http://stackoverflow.com/comment/81298225
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47172810
has text: is `wizard.excel.report.file` a TransientModel from the error odoo trying to call fields_view_get of the model that return the structur of the view but the object is None not the model instance?
score: 0

http://stackoverflow.com/q/47107549
downvote count: 0
upvote count: 1
score: 1
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81165435
has answer: http://stackoverflow.com/a/47107617
type: UnansweredQuestion
has title: Sign in with django authentication from frontend
tagged with: django
has body: I have created a view which allows the user to sign in. def signin(request): email = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=email, password=password) if user is not None: login(request, user) How should I verify that the user is signed in? Is it when the user is accessing an API that requires user to be logged in first? The documentation shows that we can use request.user.is_authenticated is True or not to verify. However, I am not using django templates but reactJS to send POST requests. How should I do it? Should I include a User attribute in json body in the POST request?
tagged with: python
has comment: http://stackoverflow.com/comment/81165423
has comment: http://stackoverflow.com/comment/81165396

http://stackoverflow.com/comment/81277882
type: Comment
type: QuestionComment
score: 0
has text: find all the prime numbers between your given number and see if there's a sum that makes up your number
comment on: http://stackoverflow.com/q/47164054

http://stackoverflow.com/q/47110056
tagged with: variables
has comment: http://stackoverflow.com/comment/81170354
has comment: http://stackoverflow.com/comment/81170319
has title: loop function 2 variables
favorite count: 0
has body: can anyone help me with python? I try to define the follow function related to both variables in a loop, but I don´t get it: x = [0.0000, 0.0125, 0.0250, 0.0500, 0.0750, 0.1000, 0.1500, 0.2000, 0.3000, 0.4000, 0.5000, 0.6000, 0.7000, 0.8000, 0.9000, 0.9500, 1.000, 0.0000, 0.0125, 0.0250, 0.0500, 0.0750, 0.1000, 0.1500, 0.2000, 0.3000, 0.4000, 0.5000, 0.6000, 0.7000, 0.8000, 0.9000, 0.9500, 1.000] z = [0.0000, 0.0221, 0.0336, 0.0518, 0.0662, 0.0782, 0.0965, 0.1090, 0.1202, 0.1178, 0.1055, 0.0868, 0.0649, 0.0421, 0.0202, 0.0105, 0.0000, 0.0000, -0.0151, -0.0186, -0.0185 , -0.0150, -0.0113, -0.0065, -0.0026, -0.0007, -0.0011, -0.0057, -0.0114, -0.0156, -0.0165, -0.0127, -0.0087, 0.0000] for i, j in (range(x), range(z)): """incluir cada valor con un indice correspondiente a la matriz""" l_hess=np.sqrt(i^2+j^2) print(l_hess) delta = np.arctan2(j/i) print(delta)
linked to: http://stackoverflow.com/q/18648626
tagged with: python
type: Question
answer count: 0
type: UnansweredQuestion
score: 1
tagged with: function
duplicate of: http://stackoverflow.com/q/18648626
downvote count: 0
upvote count: 1
tagged with: loops

http://stackoverflow.com/a/60183414
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/112981854
score: 7
answers question: http://stackoverflow.com/q/47202705
has body: I Followed @samprog (most accepted) answer on my machine running on UBUNTU VERSION="14.04.6". and was getting "standard_init_linux.go:195: exec user process caused "exec format error" None of the solution worked for me mentioned above. Fixed the error after changing my Dockerfile as follows FROM python:latest COPY capturing.py ./capturing.py CMD ["python","capturing.py"] Note: If your script import some other module then you need to modify COPY statement in your Dockerfile as follows - COPY *.py ./ Hope this will be useful for others.
type: Answer

http://stackoverflow.com/comment/81381878
comment on: http://stackoverflow.com/q/47216209
type: Comment
type: QuestionComment
score: 0
has text: `new_entry` is a list. In 5th line `new_dictionary[new_entry] = [value]` you are trying to use it as a key in dictionary. Lists are unhashable and can't be used as keys in dictionary.

http://stackoverflow.com/comment/81142361
score: 0
type: AnswerComment
has text: Problem with the pip version, trying to upgrade that it throws permission denied error and i'm not able to use sudo & not able to change the folder permission.
type: Comment
comment on: http://stackoverflow.com/a/47093980

http://stackoverflow.com/comment/81223882
comment on: http://stackoverflow.com/q/47137391
score: 1
has text: Maybe you want to use a non-word boundary - [`r"\B'([^']*)'\B"`](https://regex101.com/r/p8a4Lc/1) - for "whole non-word" searches? Or do you want to match these strings after `(` only - [`r"\('([^']*)'"`](https://regex101.com/r/p8a4Lc/2)? Can there be `"` inside `'...'`? If not, use `"""'([^"']*)'"""`
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47169146
tagged with: python
score: 1
accepted answer: http://stackoverflow.com/a/47169490
tagged with: wxwidgets
type: AnsweredQuestion
has body: I am currently trying modify the example given from the tutorial on this page That generates the GUI shown below. (You can download the example yourself on the second page of the tutorial). Tutorial Running this code with Python 2.7 with wxPython and Comtypes will open a GUI similar to that on the last page of the tutorial that gives the properties of a beam of light. import wx import wx.lib.activex import csv import comtypes.client class EventSink(object): def __init__(self, frame): self.counter = 0 self.frame = frame def DataReady(self): self.counter +=1 self.frame.Title= "DataReady fired {0} times".format(self.counter) class MyApp( wx.App ): def OnClick(self,e): rb_selection = self.rb.GetStringSelection() if rb_selection == "WinCam": data = self.gd.ctrl.GetWinCamDataAsVariant() data = [[x] for x in data] else: p_selection = self.cb.GetStringSelection() if p_selection == "Profile_X": data = self.px.ctrl.GetProfileDataAsVariant() data = [[x] for x in data]#csv.writerows accepts a list of rows where each row is a list, a list of lists elif p_selection == "Profile_Y": data = self.py.ctrl.GetProfileDataAsVariant() data = [[x] for x in data] else: datax = self.px.ctrl.GetProfileDataAsVariant() datay = self.py.ctrl.GetProfileDataAsVariant() data = [list(row) for row in zip(datax,datay)]#Makes a list of lists; X1 with Y1 in a list, X2 with Y2 in a list etc... filename = self.ti.Value with open(filename, 'wb') as fp: w = csv.writer(fp, delimiter=',') w.writerows(data) def __init__( self, redirect=False, filename=None ): wx.App.__init__( self, redirect, filename ) self.frame = wx.Frame( parent=None, id=wx.ID_ANY,size=(760,500), title='Python Interface to DataRay') #Panel p = wx.Panel(self.frame, wx.ID_ANY) #Get Data self.gd = wx.lib.activex.ActiveXCtrl(p, 'DATARAYOCX.GetDataCtrl.1') #The methods of the object are available through the ctrl property of the item self.gd.ctrl.StartDriver() self.counter = 0 sink = EventSink(self.frame) self.sink = comtypes.client.GetEvents(sel…
tagged with: user-interface
downvote count: 0
tagged with: wxpython
upvote count: 1
has title: wxpython dataray interface camera
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47169490
type: Question
tagged with: activex

http://stackoverflow.com/a/47184468
answers question: http://stackoverflow.com/q/47175078
has body: You can use Picodash - location search to search any city and set a radius and get all the latest posts, you can view heat map or cluster map any time. You can also load posts from any date range and view heatmap. You can use this Insatgram API to search posts by location: https://api.instagram.com/v1/media/search?lat=48.858844&amp;lng=2.294351&amp;access_token=ACCESS-TOKEN
has comment: http://stackoverflow.com/comment/84359544
type: Answer
has comment: http://stackoverflow.com/comment/84257544
has comment: http://stackoverflow.com/comment/84390550
score: 0

http://stackoverflow.com/comment/81374691
type: Comment
has text: @StevenRumbalski Since that would invalidate the comment.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47212307

http://stackoverflow.com/q/47184579
has title: How to use .apply() to pandas dataframe using multiprocessing?
upvote count: 3
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81319376
favorite count: 0
score: 3
tagged with: pandas
has body: I have a function that I want to apply to a pandas dataframe in parallel import multiprocessing from multiprocessing import Pool from collections import Counter import numpy as np def func1(): # do some operations in serial return word_vector_matrix # a numpy ndarray def get_vector(text): vector = np.zeroes(100,) for i in range(5): vector += word_vector_matrix[text.index(i)] return vector def apply_get_vector(data): return data['text_column'].apply(get_vector) if __name__ == '__main__': word_vector_matrix = func1() def parallelize_dataframe(data, func): num_cores = multiprocessing.cpu_count() num_partitions = num_cores # num chunks = num cores chunks_dict = {i:np.array_split(data, num_partitions)[i] for i in range(num_partitions)} pool = Pool(num_cores) word_vectors = np.concatenate(pool.map(func, [chunks_dict[i] for i in chunks_dict])) pool.close() pool.join() return word_vectors vectors = parallelize_dataframe(df, apply_get_vector) The problem is that I get an error &gt;&gt;&gt; NameError: name 'word_vector_matrix' is not defined I thought this is strange because I do define word_vector_matrix in main, but I don't explicitly give it as an argument into the get_vector function. Is there something that I am doing wrong here by not declaring variables in scope, and if so how do I correct this? I did find this question which explains how to use .apply() with multiple arguments which I feel we will need to use here, but my case is slightly different given that I am using multiprocessing. If anyone could please explain how to do this I'd greatly appreciate it. Thanks
linked to: http://stackoverflow.com/q/19914937
tagged with: multiprocessing
type: Question
answer count: 0

http://stackoverflow.com/comment/81176839
score: 1
comment on: http://stackoverflow.com/a/47113501
type: Comment
type: AnswerComment
has text: The root cause is this design decision here: https://github.com/requests/requests/blob/master/requests/sessions.py#L106-L116

http://stackoverflow.com/q/47119036
type: AnsweredQuestion
score: 0
answer count: 1
has title: Scrapy module not found for a web crawling script
tagged with: web-crawler
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/81187852
has body: I have scrapy version 1.4 and python 3. I am trying to use scrapy with python, however, whenever I run python3 script.py, I get a return error File "script.py", line 2, in &lt;module&gt; from scrapy import Spider ModuleNotFoundError: No module named 'scrapy' However, the imports are below from __future__ import absolute_import from scrapy import Spider from scrapy.selector import Selector from stack.items import StackItem class StackSpider(Spider): When I run pip show scrapy Name: Scrapy Version: 1.4.0 Summary: A high-level Web Crawling and Web Scraping framework ...
tagged with: python
accepted answer: http://stackoverflow.com/a/47119146
has answer: http://stackoverflow.com/a/47119146
has comment: http://stackoverflow.com/comment/81187810

euclidean-distance
type: Tag
tags question: http://stackoverflow.com/q/47155595
tag name: euclidean-distance
tags question: http://stackoverflow.com/q/47087087

http://stackoverflow.com/q/47165847
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/81284578
has title: OpenCV Error: Assertion failed ((mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1)) in cv::binary_op
has comment: http://stackoverflow.com/comment/81282852
has body: I've seen this question being asked, however, the answers did not help resolve my issue, so hoping someone can help me out. I'm building an adaptive skin detector, so I'm using a dataset to train a classifier on different skin colors. Then I'd like to use my webcam to be able to detect skin in the image. I'm getting the following error though when applying the predicted mask to the camera frame: OpenCV Error: Assertion failed ((mtype == CV_8U || mtype == CV_8S) &amp;&amp; _mask.sameSize(*psrc1)) in cv::binary_op, file ..\..\..\modules\core\src\arithm.cpp, line 241 Traceback (most recent call last): File "skinDetectionBetter.py", line 80, in &lt;module&gt; skin = cv2.bitwise_and(gray, gray, mask=imgLabels) cv2.error: ..\..\..\modules\core\src\arithm.cpp:241: error: (-215) (mtype == CV_8U || mtype == CV_8S) &amp;&amp; _mask.sameSize(*psrc1) in function cv::binary_op I've tried resizing my mask imgLabels to use 3 color channels (ex (480,640,3)), then tried resizing to use 1 color channel (ex (480,640,1)), however, I continue to get this error. As far as I can see, the imgLabels and frame both have shape of (480,640,3). Here's a snippet of my code. camera = cv2.VideoCapture(0) while True: # reads in the current frame # .read() returns True if frame read correctly, and False otherwise ret, frame = camera.read() if ret: # reshape the frame to follow format of training data (rows*col, 3) data = np.reshape(frame, (frame.shape[0] * frame.shape[1], 3)) predictedLabels = classifier.predict(data) # output: [2 2 2 1 1 2 2 1 ...] and shape: (480,640,3) predictedMask = (-(predictedLabels - 1) + 1) * 255 # the AND operator applies the skinMask to the image imgLabels = np.resize(predictedMask, (frame.shape[0], frame.shape[1], 3)) # ERROR HAPPENS WITH BELOW LINE skin = cv2.bitwise_and(frame, frame, mask=imgLabels) # show the skin in the image along with the mask, show images side-by-side cv2.imshow("images", np.hstack([frame, skin]))
tagged with: python
score: 2
tagged with: python-3.x
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81281495
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/47113637
has answer: http://stackoverflow.com/a/47113912
has comment: http://stackoverflow.com/comment/81177252
tagged with: python
has title: Bar Chart from Dataframe Error module 'numpy' has no attribute 'arrange'
tagged with: plot
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81177574
has comment: http://stackoverflow.com/comment/81177639
has comment: http://stackoverflow.com/comment/81177215
tagged with: pandas
has comment: http://stackoverflow.com/comment/81177504
score: 0
has comment: http://stackoverflow.com/comment/81177489
has body: I am trying to plot a bar chart from a dataframe. If I do numpy arrange I see the error module 'numpy' has no attribute 'arrange' . If I don't do arrange I see no error but the chart opens but I don't see any bars. Here's my code: data = [] for x in tracks: data.append({'Track_Name':x.title,'plays':str(x.playback_count)}) df = pd.DataFrame(data) df1 = df'Track_Name' df2 = df'plays' df1 = str(df1) df2 = str(df2) ind = np.arrange(df1) plt.bar(ind,df2) plt.show() Plot Figure:
answer count: 1
has comment: http://stackoverflow.com/comment/81177211
has comment: http://stackoverflow.com/comment/81177110
accepted answer: http://stackoverflow.com/a/47113912
type: Question
tagged with: numpy

edit-distance
type: Tag
tags question: http://stackoverflow.com/q/47156739
tag name: edit-distance

http://stackoverflow.com/q/47150674
tagged with: python
favorite count: 0
type: Question
tagged with: numpy
downvote count: 0
type: UnansweredQuestion
has body: I have a tiff image of shape (6,500,500) and I read it as numpy array &gt;&gt;&gt;type(image) &lt;type 'numpy.ndarray'&gt; &gt;&gt;&gt; image.shape (6, 500, 500) I transpose it to make (500,500,6) image = image.transpose((1, 2, 0)) &gt;&gt;&gt; image.shape (500, 500, 6) Then when I try to transform it into PIL image &gt;&gt;&gt; image = Image.fromarray(image) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/dfd/env27/local/lib/python2.7/site-packages/PIL/Image.py", line 2419, in fromarray raise TypeError("Cannot handle this data type") TypeError: Cannot handle this data type &gt;&gt; I get the above error. My array is uint8 image array([[[122, 104, 77, 255, 145, 71], [123, 102, 77, 252, 140, 71], [122, 99, 72, 249, 123, 57], [[133, 113, 90, 106, 45, 22], [129, 98, 77, 96, 36, 18], [126, 99, 77, 102, 39, 18], ..., [124, 105, 76, 255, 120, 54], [123, 104, 74, 254, 114, 51], [119, 102, 69, 8, 117, 51]]], dtype=uint8)
has title: PIL Image.fromarray complains for 6 channel tiff data
answer count: 1
has answer: http://stackoverflow.com/a/47151009
tagged with: uint8t
tagged with: python-imaging-library
upvote count: 1
score: 1

http://stackoverflow.com/a/49714644
type: Answer
answers question: http://stackoverflow.com/q/47132665
score: 0
has body: I'm inspired by Jaba's answer. If you want to get the cartesian_product of two 2-D tensors, you can do it as following: input a:[N,L] and b:[M,L], get a [N*M,L] concat tensor tile_a = tf.tile(tf.expand_dims(a, 1), [1, M, 1]) tile_b = tf.tile(tf.expand_dims(b, 0), [N, 1, 1]) cartesian_product = tf.concat([tile_a, tile_b], axis=2) cartesian = tf.reshape(cartesian_product, [N*M, -1]) cart = tf.Session().run(cartesian) print(cart.shape) print(cart)
has comment: http://stackoverflow.com/comment/115061473

http://stackoverflow.com/q/47086852
downvote count: 0
upvote count: 1
tagged with: pointers
has answer: http://stackoverflow.com/a/47088004
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81130377
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47088004
tagged with: http://stackoverflow.com/tag/c
has body: I am using ctypes in Python and I need to pass a pointer to an array of pointers to structs to some C function. This is struct: typedef struct { float x; float y; float z; float radius; } Sphere; And I have function with the following prototype: void render(Sphere** spheres); In Python I declared a class for the Sphere struct and I need to set argtypes to the render function: lib_render = ctypes.cdll.LoadLibrary('librender.so') class Sphere(ctypes.Structure): _fields_ = [('x', ctypes.c_float), ('y', ctypes.c_float), ('z', ctypes.c_float), ('radius', ctypes.c_float)] render = lib_render.render render.argtypes = [&lt;cannot find out what needs to be here&gt;] spheres = numpy.array([Sphere(1, 2.8, 3, 0.5), Sphere(4.2, 2, 1, 3.2)]) render(spheres) How to pass that array correctly?
has comment: http://stackoverflow.com/comment/81123418
type: AnsweredQuestion
tagged with: ctypes
has comment: http://stackoverflow.com/comment/81123977
has title: How can I pass a pointer to array of pointers to structs from python
has comment: http://stackoverflow.com/comment/81123493
answer count: 1

http://stackoverflow.com/comment/81360984
type: Comment
comment on: http://stackoverflow.com/q/47188727
type: QuestionComment
has text: Have you tried to set the write concern in your call or elsewhere in your code?
score: 0

http://stackoverflow.com/q/47188907
upvote count: 2
has title: Saving multi-line with variables string to html file
has comment: http://stackoverflow.com/comment/81327508
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has body: I have function in python that takes few strings and should join them with a bigger string that should be a html file. def manzy(product_name, product_image, product_price_new, product_price_before): a = """ title """ + product_name + """ Womans cloath """ + product_price_new + """ """ + product_price_before + """ """ Html_file= open("filename","w") Html_file.write(a) Html_file.close() When i get the code running, the file gets created and then I get error: UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 400: ordinal not in range(128) I have read few topics on this subject and I am worried that my error has something to do with joining function arguments with this mess of a string. However, the error does not say anything about me messing the format of the string, and maybe there is something with that?
tagged with: http://stackoverflow.com/tag/html
tagged with: python
accepted answer: http://stackoverflow.com/a/47189237
linked to: http://stackoverflow.com/q/196345
has answer: http://stackoverflow.com/a/47189237
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81327559

http://stackoverflow.com/q/47075479
has body: I have created a batch windows batch file. The batch file runs an test.exe. i have used subprocess.popen to run the batch file using python. The batch file runs in a different window and the batch file runs a test.exe. The test.exe that the batch file runs in different windows says "Press any key to continue ". Can i pass the keystrock using python import subprocess subprocess.Popen(r'start cmd /c C:\test.bat', shell=True) p.wait() print 'done'
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/81099383
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: batch-file
has comment: http://stackoverflow.com/comment/81099361
has answer: http://stackoverflow.com/a/47076975
accepted answer: http://stackoverflow.com/a/47076975
answer count: 1
has comment: http://stackoverflow.com/comment/81099607
has title: Test a windows batch file using python
type: Question
linked to: http://stackoverflow.com/q/1458636

http://stackoverflow.com/q/47135190
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/47136029
tagged with: django
tagged with: python
has body: I am working on a Django application on Leave Management, in which there are employees from different countries. I am storing the data of the time, when the leave is created, into DB. Now, I want this datetime that is being inserted into DB, to be the current local time of the location where that particular employee is working at. For example, let us suppose Mr. X is working at India and Y is working at Newyork. If X applies for a leave, I want it to be created at local time (created_at= what-so-ever time it is in India) and when Y applies for a leave, I want it to be created_at=what-so-ever time it is in Newyork. As of now, whatever I am inserting into DB, it is getting inserted as UTC time only. How to resolve this issue? I am trying to achieve something like this.. But it is always UTC. userid = employees.objects.get(emp_id=request.user.username) if employees.objects.get(emp_id=request.user.username).emp_loc == 'IND': tzone=pytz.timezone('Asia/Calcutta') elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MLA': tzone=pytz.timezone('Asia/Manila') elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MPLS': tzone=pytz.timezone('CST6CDT') timezone.activate(pytz.timezone(tzone)) tnow=timezone.localtime(timezone.now()) if request.POST['action'] == 'Save changes': new_leave = leave.objects.create(employee=employees.objects.get(emp_id = userid.emp_id), start_date=sdt, end_date=edt, ltype=ltyp, message=des, date_created=tnow) new_leave.save() Badly in need of help..... :( Thanks in advance......... :)
type: AnsweredQuestion
score: 1
tagged with: datetime
answer count: 1
has title: Django different timezones in same application
tagged with: django-models
upvote count: 1
has answer: http://stackoverflow.com/a/47136029
favorite count: 0

http://stackoverflow.com/comment/81156032
type: AnswerComment
has text: @JamesPhillips Hi James, I looked at the graph and guessed that the scale of b was around 10,000.
comment on: http://stackoverflow.com/a/47087240
type: Comment
score: 0

http://stackoverflow.com/comment/81209485
comment on: http://stackoverflow.com/q/47129770
score: 0
has text: @Shaonshaonty Yes, I want.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47201262
has comment: http://stackoverflow.com/comment/81352452
has comment: http://stackoverflow.com/comment/81355222
has comment: http://stackoverflow.com/comment/81354958
has comment: http://stackoverflow.com/comment/81354441
has comment: http://stackoverflow.com/comment/81353242
has comment: http://stackoverflow.com/comment/81351354
has comment: http://stackoverflow.com/comment/81355431
has comment: http://stackoverflow.com/comment/81360773
has comment: http://stackoverflow.com/comment/81360310
has comment: http://stackoverflow.com/comment/81360600
has comment: http://stackoverflow.com/comment/81352569
accepted answer of: http://stackoverflow.com/q/47201227
has comment: http://stackoverflow.com/comment/81351435
has comment: http://stackoverflow.com/comment/81354367
has comment: http://stackoverflow.com/comment/81354407
has comment: http://stackoverflow.com/comment/81354780
has comment: http://stackoverflow.com/comment/81361350
has comment: http://stackoverflow.com/comment/81352830
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81353402
has comment: http://stackoverflow.com/comment/81352066
has comment: http://stackoverflow.com/comment/81352166
downvote count: 0
has comment: http://stackoverflow.com/comment/81360254
has comment: http://stackoverflow.com/comment/81352164
has comment: http://stackoverflow.com/comment/81361172
has comment: http://stackoverflow.com/comment/81351958
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81353171
has comment: http://stackoverflow.com/comment/81353558
has comment: http://stackoverflow.com/comment/81352324
answers question: http://stackoverflow.com/q/47201227
has comment: http://stackoverflow.com/comment/81352223
has comment: http://stackoverflow.com/comment/81352511
has comment: http://stackoverflow.com/comment/81351647
has comment: http://stackoverflow.com/comment/81355064
has comment: http://stackoverflow.com/comment/81355170
has comment: http://stackoverflow.com/comment/81354734
has comment: http://stackoverflow.com/comment/81351626
has comment: http://stackoverflow.com/comment/81352882
has comment: http://stackoverflow.com/comment/81353511
has comment: http://stackoverflow.com/comment/81352404
has comment: http://stackoverflow.com/comment/81353005
has comment: http://stackoverflow.com/comment/81360672
has comment: http://stackoverflow.com/comment/81361219
has comment: http://stackoverflow.com/comment/81351963
has comment: http://stackoverflow.com/comment/81352705
has comment: http://stackoverflow.com/comment/81352074
has comment: http://stackoverflow.com/comment/81352320
has body: You can use select first letter by str[1] and then use value_counts: df = pandas.read_csv('a.csv') a = df['name'].str[0].value_counts().rename_axis('alph').reset_index(name='count') Another solutions with groupby by second letter: a = df['name'].groupby(df['name'].str[0]).count().reset_index(name='count') a = df['name'].groupby(df['name'].str[0]).size().reset_index(name='count')
type: Answer

http://stackoverflow.com/comment/81354109
has text: @Alasdair well spotted, thanks - added it to the answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/47202782
score: 1
type: Comment

http://stackoverflow.com/a/47117077
answers question: http://stackoverflow.com/q/47116006
downvote count: 0
type: Answer
score: 4
upvote count: 4
has body: .... Use the title() function.

http://stackoverflow.com/comment/81442210
score: 0
type: Comment
type: AnswerComment
has text: And are you still trapped in this? Here is an interesting post for more advanced topic, I'm trying to solve it. You can have a look. https://stackoverflow.com/questions/10196198/how-to-remove-convexity-defects-in-a-sudoku-square/11366549
comment on: http://stackoverflow.com/a/47133639

http://stackoverflow.com/q/47124791
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81241642
has comment: http://stackoverflow.com/comment/81254692
has comment: http://stackoverflow.com/comment/81215972
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
score: 1
has comment: http://stackoverflow.com/comment/81208205
tagged with: python
has comment: http://stackoverflow.com/comment/81346543
has title: Reading Large CSV files using pandas in chunks changing the column name?
has comment: http://stackoverflow.com/comment/81216013
tagged with: python-2.7
linked to: http://stackoverflow.com/q/25962114
tagged with: pandas
answer count: 0
downvote count: 0
upvote count: 1
has body: I am trying to read a 4GB CSV file using pandas using the code below: tp = pd.read_csv('train.csv', sep='\t', iterator=True, chunksize=10000) train = pd.concat(tp, ignore_index=True) After using this I am able to read the csv but when I used : (train.shape) it shows number of columns to be "1" but there are 24 columns. I also tried to use sep as ',' but doing that returns me the optput on console as killed. I am using GC instance with 8GB RAM so no issues from that side. Also, if I try reading the CSV using : pandas.read_csv("train.csv") this fails for that I have recommended various other questions on stackoverflow which recommended me to read data in chunks.
has comment: http://stackoverflow.com/comment/81273192
has comment: http://stackoverflow.com/comment/81203870
favorite count: 0
type: Question

http://stackoverflow.com/comment/81284507
score: 0
type: Comment
has text: I have tried to use this code but I have got a error message (see edited post above)
type: AnswerComment
comment on: http://stackoverflow.com/a/47167229

http://stackoverflow.com/comment/81342702
type: Comment
comment on: http://stackoverflow.com/q/47196329
score: 0
type: QuestionComment
has text: hmm with type(arg1,arg2,arg3) i can create any class right? so if i can create class i can create instance of it. I only wanted to be sure that there is no other ways to create instance of class then object.__new__(cls), super().__new__(cls).

http://stackoverflow.com/comment/81365527
score: 0
type: Comment
has text: The thing is I am not adding values from list. insert values comes from the original table row. I am using list only for select if i understand you right.
type: AnswerComment
comment on: http://stackoverflow.com/a/47207593

http://stackoverflow.com/q/47164054
has comment: http://stackoverflow.com/comment/81277882
downvote count: 4
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/47164272
has comment: http://stackoverflow.com/comment/81279009
favorite count: 0
tagged with: recursion
has title: Python: function which finds a prime, but also determines if the parameters entered is the sum of 2 primes
has comment: http://stackoverflow.com/comment/81277881
has body: Would appreciate some feedback on a challenge I was recently given. In an interview the challenge was to write a function which takes only one number f(n) and returns a True if the number entered meets these conditions: A prime number (which is easy enough to check) the sum of 2 prime numbers Without being able to enter a second number, there'd be a lot of recursions in the algorithm. Any pointers? An example of a True would be f(5) where 5 is a prime number and the sum of 2 and 3 (which are also prime). But 1 + 4 is also 5, which is false.
has comment: http://stackoverflow.com/comment/81277935
type: Question
tagged with: algorithm
tagged with: python
has comment: http://stackoverflow.com/comment/81278621
has comment: http://stackoverflow.com/comment/81278143
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47165576
score: -1

http://stackoverflow.com/comment/81085354
score: 1
type: QuestionComment
has text: The `where` expression has to iterate over the array several time. One to create the boolean array. Then `np.count_nonzero` quickly counts the number of `True` values. Finally `where` (actually `np.nonzero`) collects the indices of those values. The `transpose` to `argwhere` should be a minor part of the action. If `ds2` large compared to the number of True pixels, then this `where` action could dominate.
type: Comment
comment on: http://stackoverflow.com/q/47068017

http://stackoverflow.com/a/47144702
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47116894
has body: It seems I misinterpreted how to shape my data, since Im using a categorical_crossentropy loss, I had to one-hot encode my dataY with to_categorical which worked perfectly. However, when trying to train large datasets I got the very famous MemoryError. Thanks djk47463.

http://stackoverflow.com/comment/81223791
type: QuestionComment
comment on: http://stackoverflow.com/q/47136595
has text: I think my log-normal PDF is OK, at least I can match them when I use `scipy.stats.lognorm.pdf`. I simply copied the formula from Wikipedia. I suspect my problem lies within my understanding of what `scipy.signal.convolve` does (the blue dashed line in the plots).
score: 0
type: Comment

http://stackoverflow.com/q/47108981
tagged with: pandas
has title: How to apply a function which gets the dataframe sliced with sliding window as a parameter in pandas?
tagged with: sliding-window
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I've a time series data stored in pandas dataframe, which looks like this: Date Open High Low Close Volume 0 2016-01-19 22.86 22.92 22.36 22.60 838024 1 2016-01-20 22.19 22.98 21.87 22.77 796745 2 2016-01-21 22.75 23.10 22.62 22.76 573068 3 2016-01-22 23.13 23.35 22.96 23.33 586967 4 2016-01-25 23.22 23.42 23.01 23.26 645551 5 2016-01-26 23.28 23.85 23.22 23.74 592658 6 2016-01-27 23.68 23.78 18.76 20.09 5351850 7 2016-01-28 20.05 20.69 19.11 19.37 2255635 8 2016-01-29 19.51 20.02 19.40 19.90 1203969 9 2016-02-01 19.77 19.80 19.13 19.14 1203375 I want to create an applicable function, which gets a slice of the original dataset what it can aggregate by any custom defined aggregation operator. Lets say, the function is applied like this: aggregated_df = data.apply(calculateMySpecificAggregation, axis=1) where the calculateMySpecificAggregation gets a 3-sized slice of the original dataframe for each row of the original dataframe. For each row the parameter dataframe of function contains the previous and the next rows of the original dataframe. #pseudocode example def calculateMySpecificAggregation(df_slice): # I want to know which row was this function applied on (an index I would like to have here) ri= ??? # index of the row where was this function applied # where df_slice contains 3 rows and all columns return float(df_slice["Close"][ri-1] + \ ((df_slice["High"][ri] + df_slice["Low"][ri]) / 2) + \ df_slice["Open"][ri+1]) # this line will fail on the borders, but don't worry, I will handle it later... I want to have the sliding window size parametrized, access to other columns of the row and know the row index of the original line where the function was applied on. That means, in case of slidingWindow = 3, I want to have parameter dataframes: #parameter dataframe when the function is applied on row[0]: Date Open High Low Close Volume 0 2016-01-19 22.86 22.92 22.36 22.60 838024 1 2016-01-20 22.19 22.98 21.87 22.77 796745 #parameter dataframe when the function is applie…
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47110095
tagged with: numpy
score: 0

http://stackoverflow.com/comment/81102599
score: 1
type: Comment
type: QuestionComment
has text: Are you sure that's the separator? I can't see what it is in your question. Try opening it in a latin-1 encoding.
comment on: http://stackoverflow.com/q/47077096

http://stackoverflow.com/q/47148710
tagged with: numpy
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47169593
has body: I have done some googling and haven't been able to find any working solution to my problem. I am trying to write a program that will take a black and white image and store in an array whether the pixel is black or white. I have been able to open the image and read the width and height of it but am completely stuck as to how to detect if the pixel is black or white and then store that in an array for later use. I have been using the following code and any help would be great. I ideally would want to read if the pixel is white and store that as a 1 in the array map. from PIL import Image import numpy as np from scipy import misc from pandas import * ##Opens the Image im_file = Image.open('mazes/15x15.png') ##Reads the image pixel information arr = np.array(im_file) ##Sets the width, height and maze size variables width = im_file.size[0] height = im_file.size[1] size = width * height ##Defines the mapping array map = np.zeros([width, height], dtype=np.int) ##Prints maze information for debugging print ('Maze width:', width) print ('Maze height:', height) print ('Maze size:', size, '\n') ##Prints mapping array for debugging print (DataFrame(map))
tagged with: python
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81247811
has title: Python read if image pixel is black or white
type: Question

http://stackoverflow.com/a/47161122
has comment: http://stackoverflow.com/comment/81271878
has body: There are several different ways to create dialog box type UIs for python. PyQt is one of the more powerful ones. Tkinter is also handy for simple tasks. Or at least I like to use it for simple stuff. Either one should get what you need. There's probably more I missed as well. EDIT If it's a CLI you want, there are plenty of tool. Here's a neat looking one.
answers question: http://stackoverflow.com/q/47160966
has comment: http://stackoverflow.com/comment/81272785
score: 0
has comment: http://stackoverflow.com/comment/81271944
type: Answer

http://stackoverflow.com/comment/81078351
has text: What do you mean, @FabianYing?
comment on: http://stackoverflow.com/q/47064968
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81189873
comment on: http://stackoverflow.com/q/47119987
type: QuestionComment
score: 0
has text: @NimishBansal With my code? Really?
type: Comment

send
type: Tag
tags question: http://stackoverflow.com/q/47136239
tag name: send

http://stackoverflow.com/a/47206422
downvote count: 0
has body: If I understood correctly, you have to use the .loc command. So df.loc[french,'allergy (column)'] = df.loc[english,allergy ( COLUMN D)] repeat the process till you are done, and then use the drop command. df.drop('english',0,inplace=True)
upvote count: 1
answers question: http://stackoverflow.com/q/47204234
score: 1
type: Answer

http://stackoverflow.com/comment/81123810
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47086845
has text: @user8834780 Yw~ :-)
score: 0

http://stackoverflow.com/comment/81159877
has text: ... or put it in the `__init__` method of QueueWrapper.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47104627
score: 0

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/47111946
tags question: http://stackoverflow.com/q/47139873
tags question: http://stackoverflow.com/q/47212257
tags question: http://stackoverflow.com/q/47138660
tags question: http://stackoverflow.com/q/47190303
tags question: http://stackoverflow.com/q/47167331
tags question: http://stackoverflow.com/q/47179188
tags question: http://stackoverflow.com/q/47187699
tags question: http://stackoverflow.com/q/47132548
tags question: http://stackoverflow.com/q/47206529
tags question: http://stackoverflow.com/q/47109501
tags question: http://stackoverflow.com/q/47108278
tags question: http://stackoverflow.com/q/47126208
tags question: http://stackoverflow.com/q/47113620
tags question: http://stackoverflow.com/q/47137992
tags question: http://stackoverflow.com/q/47205238
tags question: http://stackoverflow.com/q/47216089
tags question: http://stackoverflow.com/q/47074632
tags question: http://stackoverflow.com/q/47182268
tags question: http://stackoverflow.com/q/47108320
tags question: http://stackoverflow.com/q/47204828
tags question: http://stackoverflow.com/q/47161830
tags question: http://stackoverflow.com/q/47146497
tags question: http://stackoverflow.com/q/47111659
tags question: http://stackoverflow.com/q/47076685
tags question: http://stackoverflow.com/q/47221517
tags question: http://stackoverflow.com/q/47135190
tags question: http://stackoverflow.com/q/47065438
tags question: http://stackoverflow.com/q/47182403
tags question: http://stackoverflow.com/q/47178340
tags question: http://stackoverflow.com/q/47193902
type: Tag
tags question: http://stackoverflow.com/q/47214594
tags question: http://stackoverflow.com/q/47097471

http://stackoverflow.com/comment/81275720
has text: When I add the password is when i get the commands ignored until end of transaction.
score: 0
comment on: http://stackoverflow.com/a/47163031
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81424260
score: 0
type: Comment
has text: It is not finding `pyximport` module. That module is not there in pip or in Debian repositories.
type: QuestionComment
comment on: http://stackoverflow.com/q/47216437

http://stackoverflow.com/comment/81116161
has text: ... with a `750` in there as well of course.
type: QuestionComment
comment on: http://stackoverflow.com/q/47083191
score: 0
type: Comment

http://stackoverflow.com/a/47096305
type: Answer
has comment: http://stackoverflow.com/comment/81142264
downvote count: 0
has comment: http://stackoverflow.com/comment/81142102
has comment: http://stackoverflow.com/comment/81142188
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47096228
has body: You can find the indices as follows idxs = self.df.index[self.df['X'].isnull()] # find all indices with None in df.X Full code: self.df['X'] = self.df['x'].apply(lambda x: my_map.get(x)) idxs = self.df.index[self.df['X'].isnull()] # find all indices with None in df.X self.df = self.df.drop(idxs)

http://stackoverflow.com/a/47105127
has body: If I am understanding you correctly, you have a function name that is being stored as a string. If that is the case, you can use solutions provided here Calling a function of a module from a string with the function&#39;s name to use that function.
has comment: http://stackoverflow.com/comment/81161555
type: Answer
answers question: http://stackoverflow.com/q/47105082
score: 0

http://stackoverflow.com/q/47109915
answer count: 1
tagged with: python
type: Question
tagged with: music21
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47426193
favorite count: 0
score: 3
upvote count: 3
downvote count: 0
has title: How can I display an empty staff using music21?
has body: I am trying to produce a quick reworking of some educational materials on music showing how it may be able to create the associated media assets (images, audio files) from "code" in a Jupyter notebook using the Python music21 package. It seems the simplest steps are the hardest. For example, how do I create an empty staff: or a staff populated by notes but without a clef at the start? If I do something like: from music21 import * s = stream.Stream() s.append(note.Note('G4', type='whole')) s.append(note.Note('A4', type='whole')) s.append(note.Note('B4', type='whole')) s.append(note.Note('C5', type='whole')) s.show() I get the following?

http://stackoverflow.com/a/47147458
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81276991
has comment: http://stackoverflow.com/comment/81276120
downvote count: 0
has comment: http://stackoverflow.com/comment/81277120
has comment: http://stackoverflow.com/comment/81277073
has body: pd.concat +ffill pd.concat([df,pd.concat([df1]*len(df)).set_index(df.index)]).sort_index().ffill() Out[1327]: GROUP_ID USER_ID USER_NAME 0 65.0 50 ABC1 0 65.0 7 BOND 1 67.0 74 ABC2 1 67.0 7 BOND 2 69.0 71 ABC3 2 69.0 7 BOND pd.concat([df,pd.concat([df1] * df.GROUP_ID.nunique().reset_index(drop=True)]).sort_index().bfill() Out[1418]: GROUP_ID USER_ID USER_NAME 0 65.0 50 ABC1 0 65.0 7 BOND 1 65.0 74 ABC2 1 69.0 7 BOND 2 69.0 71 ABC3
has comment: http://stackoverflow.com/comment/81276130
type: Answer
answers question: http://stackoverflow.com/q/47147332
has comment: http://stackoverflow.com/comment/81276663

http://stackoverflow.com/a/47144627
type: Answer
answers question: http://stackoverflow.com/q/47144190
has body: Use functions, at least one that converts an input to a tuple of indices (row and column). This function should split the input into two characters. The letter can then be converted to the row, the digit to column. These conversions can be done independently and with a few tricks (using ord() on the letter and int() on the digit plus some math) very short. The function then returns an index tuple to use on board.
score: 0

http://stackoverflow.com/q/47151194
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47151276
has body: short['SOURCE'] = None for x in range(len(short)): if (short['AMOUNT'].iloc[x] &gt; 0) &amp; (len(short['ACCOUNT'].iloc[x]) &gt;1): short['SOURCE'].iloc[x] = short['ACCOUNT'].iloc[x][1] elif short['AMOUNT'].iloc[x] &gt; 0: short['SOURCE'].iloc[x] = "Guy" else: short['SOURCE'].iloc[x] = short['MERCHANT'].iloc[x] the goal: Look at columns ACCOUNT and SOURCE. If ACCOUNT has 2 strings and source is positive, set SOURCE to the second string if ACCOUNT has 1 string, set SOURCE to that string If AMOUNT is negative, set SOURCE to column MERCHANT. This is a super ugly, super hacky, super slow solution. Is there a better one?
favorite count: 0
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47151276
has comment: http://stackoverflow.com/comment/81251978
tagged with: python
has title: using content of a pandas row to create another pandas row (help me optimize this really ugly function)
tagged with: pandas
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81276963

http://stackoverflow.com/a/47116895
type: Answer
score: 0
has body: I solved this by converting my nested dictionary into a list of tuples using list comprehension and then using heapq.nsmallest(2, myTupleList, key=itemgetter(2) ). Performance is manageable because it only takes 0.5 sec to convert the dictionary to a list for a 1 million row example.
answers question: http://stackoverflow.com/q/47102518

http://stackoverflow.com/q/47114146
tagged with: pipe
has title: Stdin and stdout don't appear to be redirected to pipe
type: Question
answer count: 0
tagged with: fork
type: UnansweredQuestion
has body: I have to run a bunch of programs in parallel, via fork(), dup2, and pipes; (programs: rgen, A1, A2 and the driver program itself A3). - A3 starts and executes rgen (via fork) with cml arguments; - rgen passes stdout to A1 (via pipe 'toA1'); - A1 needs to take stdin from rgen (via pipe 'toA1'), process that and then send stdout to A2 (via pipe 'toA2'); - A2 needs to take stdin from A1 (from pipe 'toA2'); - A2 then takes that input and sends what it got from A1 to stdout (screen), it then waits for user input from A3 (via pipe 'toA2') or for input from A1 via pipe 'toA2'; - Then the driver program needs to get stdin from the keyboard and send stdout to A2 (via pipe 'toA2'); The issue is that pipe 'toA2' doesn't appear to be working. I know that A1 sends the correct output to stdout. And I know that A2 receives input from stdin. Currently A2 receives stdin from the keyboard as noted from "std::cin >> use_input" and the fact that when I run the program it doesn't do anything else unless I input something into the command line. It should look like this in the terminal: $./A3 -s 5 -n 4 -l 5 V 8 E {&lt;0,2&gt;,&lt;0,3&gt;,&lt;0,4&gt;,&lt;1,3&gt;,&lt;4,7&gt;,&lt;5,2&gt;,&lt;5,6&gt;} s 2 4 2-0-4 where "./A3 -s 5 -n 4 -l 5" and "s 2 4" are user inputs into the command line and "V 8" and "E {...}" and "2-0-4" are all output to the screen by A2. *fyi all of the individual programs work just fine (maybe not A3 since it's the only with the potential issue), I'm more worried about getting the information from other processes. I've removed all of the code in my programs that are not to do with stdin or stdout and replaced it with "...". If it is necessary to show, let me know, I just thought it'd be easier to read this way since I know it works once I have then input. Program A3 (c++): int main(int argc, char **argv) { std::string user_input; std::vector&lt;pid_t&gt; kids; pid_t child_pid; char* empty_arg1[2]; empty_arg1[0] = "A1.py"; empty_arg1[1] = nullptr; char* empty_arg2[2]; …
tagged with: python
tagged with: c++
has comment: http://stackoverflow.com/comment/81178351
score: 0
has comment: http://stackoverflow.com/comment/81178135
has comment: http://stackoverflow.com/comment/81178164

django
tags question: http://stackoverflow.com/q/47136884
tags question: http://stackoverflow.com/q/47188197
tags question: http://stackoverflow.com/q/47177476
tags question: http://stackoverflow.com/q/47170729
tags question: http://stackoverflow.com/q/47219973
tags question: http://stackoverflow.com/q/47102090
tags question: http://stackoverflow.com/q/47119450
tags question: http://stackoverflow.com/q/47194526
tags question: http://stackoverflow.com/q/47207867
tags question: http://stackoverflow.com/q/47209122
tags question: http://stackoverflow.com/q/47162991
tags question: http://stackoverflow.com/q/47134307
tags question: http://stackoverflow.com/q/47188250
tags question: http://stackoverflow.com/q/47170853
tags question: http://stackoverflow.com/q/47219945
tags question: http://stackoverflow.com/q/47217001
tags question: http://stackoverflow.com/q/47173204
tags question: http://stackoverflow.com/q/47126641
tags question: http://stackoverflow.com/q/47141085
tags question: http://stackoverflow.com/q/47141645
tags question: http://stackoverflow.com/q/47210954
tags question: http://stackoverflow.com/q/47137152
tags question: http://stackoverflow.com/q/47167331
tags question: http://stackoverflow.com/q/47179188
tags question: http://stackoverflow.com/q/47119560
tags question: http://stackoverflow.com/q/47094002
tags question: http://stackoverflow.com/q/47124297
tags question: http://stackoverflow.com/q/47215825
tags question: http://stackoverflow.com/q/47088830
tags question: http://stackoverflow.com/q/47088458
tags question: http://stackoverflow.com/q/47201786
tags question: http://stackoverflow.com/q/47107549
tags question: http://stackoverflow.com/q/47153937
tags question: http://stackoverflow.com/q/47135969
tags question: http://stackoverflow.com/q/47177696
tags question: http://stackoverflow.com/q/47116218
tags question: http://stackoverflow.com/q/47217438
tags question: http://stackoverflow.com/q/47198497
tags question: http://stackoverflow.com/q/47076685
tags question: http://stackoverflow.com/q/47069717
tags question: http://stackoverflow.com/q/47190633
tags question: http://stackoverflow.com/q/47221517
tags question: http://stackoverflow.com/q/47111777
tags question: http://stackoverflow.com/q/47164279
tags question: http://stackoverflow.com/q/47187699
tags question: http://stackoverflow.com/q/47140951
tags question: http://stackoverflow.com/q/47075629
tags question: http://stackoverflow.com/q/47103079
tags question: http://stackoverflow.com/q/47143506
tags question: http://stackoverflow.com/q/47078101
tags question: http://stackoverflow.com/q/47145002
tags question: http://stackoverflow.com/q/47132548
tags question: http://stackoverflow.com/q/47219336
tags question: http://stackoverflow.com/q/47162217
tags question: http://stackoverflow.com/q/47156528
tags question: http://stackoverflow.com/q/47152668
tags question: http://stackoverflow.com/q/47199089
tags question: http://stackoverflow.com/q/47195512
tags question: http://stackoverflow.com/q/47065010
tags question: http://stackoverflow.com/q/47176064
tags question: http://stackoverflow.com/q/47086910
tags question: http://stackoverflow.com/q/47067202
tags question: http://stackoverflow.com/q/47218977
tags question: http://stackoverflow.com/q/47129830
tags question: http://stackoverflow.com/q/47064749
tags question: http://stackoverflow.com/q/47206569
tags question: http://stackoverflow.com/q/47199759
tags question: http://stackoverflow.com/q/47151210
tags question: http://stackoverflow.com/q/47098049
tags question: http://stackoverflow.com/q/47139509
tags question: http://stackoverflow.com/q/47130510
tags question: http://stackoverflow.com/q/47088484
tags question: http://stackoverflow.com/q/47111898
tags question: http://stackoverflow.com/q/47177485
tags question: http://stackoverflow.com/q/47135190
tags question: http://stackoverflow.com/q/47144204
tags question: http://stackoverflow.com/q/47196356
tags question: http://stackoverflow.com/q/47182403
tags question: http://stackoverflow.com/q/47132864
tags question: http://stackoverflow.com/q/47064840

http://stackoverflow.com/q/47169550
type: Question
has body: Is it possible to port this python code to work in Robot Framework? from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.action_chains import ActionChains chrome_options = Options() chrome_options.binary_location = 'C:/Program Files (x86)/MyApp.exe' driver = webdriver.Chrome('C:/Program Files (x86)/chromedriver.exe', chrome_options=chrome_options) I'm trying to create a chrome webdriver in robot that sends my selenium calls to my chromium application. Is it possible? I create a python Library see code below but it just launches my app and closes it. I want to be able to make selenium/robot calls to it. Code for myLibrary.py import selenium from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.action_chains import ActionChains from robot.libraries.BuiltIn import BuiltIn def pas_webdriver_instance(): se2lib = BuiltIn().get_library_instance('ExtendedSelenium2Library') chrome_options = Options() chrome_options.binary_location = 'C:/Program Files (x86)/myapp.exe' driver = webdriver.Chrome('C:/Program Files (x86)/chromedriver.exe', chrome_options=chrome_options)
tagged with: robotframework
tagged with: python
has title: How to launch a Chromium application using Chromedriver?
upvote count: 2
score: 2
tagged with: selenium-chromedriver
downvote count: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47188055
tagged with: selenium
has comment: http://stackoverflow.com/comment/81292486
favorite count: 0

http://stackoverflow.com/comment/81305653
score: 0
has text: @Reti43: Thanks for the benchmarking
type: Comment
comment on: http://stackoverflow.com/a/47174460
type: AnswerComment

http://stackoverflow.com/q/47207620
has title: Matplotlib scatter not able to parse datetime but plot is
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81370920
answer count: 0
linked to: http://stackoverflow.com/q/38256750
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/38256750
has comment: http://stackoverflow.com/comment/81371245
score: 1
tagged with: matplotlib
has body: For some reason matplotlib's scatter isn't able to parse datetime values but plot is. Is this a bug in matplotlib or am I doing something wrong? import datetime from decimal import Decimal import matplotlib.pyplot as plt import seaborn as sns x = [datetime.date(2016, 10, 12),datetime.date(2017, 6, 28)] y = [Decimal('618020.0000'), Decimal('442107.0000')] plt.plot(x, y) import datetime from decimal import Decimal import matplotlib.pyplot as plt import seaborn as sns x = [datetime.date(2016, 10, 12),datetime.date(2017, 6, 28)] y = [Decimal('618020.0000'), Decimal('442107.0000')] plt.scatter(x, y) My matplotlib version is 1.5.3.

http://stackoverflow.com/q/47077534
has body: I have a class in forms.py that set the ui for that form, some of which are a drop down menu populated by an (external) database class myForm(forms.Form): barcodes_list = getBarcodes(server_database) barcodes= forms.TypedChoiceField(label='Barcodes', choices=barcodes_list, widget=forms.Select(attrs={'style':'width:164px'}), initial = '' ) the barcodes_list is only ran on restart of the Django server. If the page is refreshed the barcode list stays the same even if there was a change on the database. I would like barcodes_list to be run again on refresh. I have tried adding this within the myForm class as per similar questions on SO def __init__(self, *args, **kwargs): super(myForm, self).__init__(*args, **kwargs) barcodes_list = ...
has title: Django update form values on page refresh
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: jquery
type: Question
has answer: http://stackoverflow.com/a/47077768
accepted answer: http://stackoverflow.com/a/47077768
tagged with: django
tagged with: python

http://stackoverflow.com/a/47100737
upvote count: 1
answers question: http://stackoverflow.com/q/47100474
downvote count: 0
type: Answer
has body: If you want to regex it: for i in re.findall(".+:\s*(.*)", messages): print(i) This doesn't handle the special chars you have in there though.
score: 1
accepted answer of: http://stackoverflow.com/q/47100474
type: AcceptedAnswer

http://stackoverflow.com/comment/81224204
type: AnswerComment
has text: In your solution `a1 = df.iloc[:, 1:].eq(1).sum()` how can I put the names of colums of `a1` to `Feature` and `Count`?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47137233

http://stackoverflow.com/a/47180990
score: 0
has body: This has nothing to do with how the string actually looks like; try printing it: print(a+c) It is simply a matter of how Python represents the string in an interactive session (or when repr()d). See also: Built-in Functions: repr() in the Python docs.
answers question: http://stackoverflow.com/q/47180942
type: Answer

http://stackoverflow.com/a/47176619
type: Answer
has body: Using loc + map: m = df.color.isnull() df.loc[m, 'color'] = df.loc[m, 'object'].map(df2.set_index('object').default_color) df object color 0 chair black 1 ball yellow 2 door brown 3 ball blue 4 chair white 5 chair brown 6 ball grey If you're going to be doing a lot of these replacements, you should call set_index on df2 just once and save its result.
answers question: http://stackoverflow.com/q/47176420
upvote count: 5
score: 5
downvote count: 0

http://stackoverflow.com/a/47317710
downvote count: 0
has comment: http://stackoverflow.com/comment/103416514
score: 14
has body: The pip command was actually the pip3, and the "ImportError" was happening when I used python (2.7). pip2 uninstall backports.functools_lru_cache then, pip2 install backports.functools_lru_cache fixed my problem.
type: Answer
upvote count: 14
answers question: http://stackoverflow.com/q/47179433

http://stackoverflow.com/q/47091223
linked to: http://stackoverflow.com/q/46911925
downvote count: 0
has title: Replacing QTextEdit bounding box with a line
has answer: http://stackoverflow.com/a/47092069
accepted answer: http://stackoverflow.com/a/47092069
answer count: 1
favorite count: 0
type: Question
score: 2
type: AnsweredQuestion
tagged with: pyside
tagged with: python
has body: This question is a slight modification of the bounding box example. I'm trying to understand how to draw simple shapes. I just want to replace the bounding box with a diagonal line from the upperLeft point to the lowerRight point. However, QLine() does not appear to have a show() method and viewport() has no addItem() method. So, I think the line is not being displayed. Here is my modification of the showBoxes method: def showLines(self): while self.boxes: self.boxes.pop() #self.boxes.pop().deleteLater() #Qline has no deleteLater(). Does that matter? viewport = self.edit.viewport() for start, end, ident in db: rect = self.edit.getBoundingRect(start, end) x = rect.x() y = rect.y() h = rect.height() w = rect.width() line = QLine() #QRubberBand(QRubberBand.Rectangle, viewport) line.setLine(x,y,x+w,y+h) #box.setGeometry(rect) # need to show line here? self.boxes.append(line)
tagged with: qtextedit
upvote count: 2

avx
tags question: http://stackoverflow.com/q/47068709
tag name: avx
type: Tag

http://stackoverflow.com/q/47118187
has title: Cqlsh does now work on newly installed Cassandra on Ubuntu 16.04
tagged with: cassandra-3.0
tagged with: cqlsh
tagged with: python
type: UnansweredQuestion
tagged with: ubuntu
has answer: http://stackoverflow.com/a/47118751
score: 0
answer count: 2
linked to: http://stackoverflow.com/q/13390775
has body: I am getting this error when I try cqlsh or cqlsh 127.0.0.1:9160 : Connection error: ('Unable to connect to any servers', {'127.0.0.1': error(111, "Tried connecting to [('127.0.0.1', 9042)]. Last error: Connection refused")}) I just started learning Cassandra. My machine had an installation of Cassandra for something else, so I uninstalled and installed Cassandra 3.11.1 to follow tutorials. I followed this to uninstall, I used this instruction to install. My hosts file is: 127.0.0.1 localhost My python is version 2.7.12 and some Cassandra settings are: start_rpc: false rpc_address: localhost rpc_port: 9160 Cassandra status is active, and node was up and normal when I first tried "sudo nodetool status", but now it is erroting after I changed start_rpc to true and change it back to false :( Node error message is: nodetool: Failed to connect to '127.0.0.1:7199' - ConnectException: 'Connection refused'. I read this and tried his suggestion, and it did not work. Also, ideally, I want to use python 3. Is it a bad idea?
tagged with: cassandra
has answer: http://stackoverflow.com/a/47125798
type: Question

date
tags question: http://stackoverflow.com/q/47084766
type: Tag
tags question: http://stackoverflow.com/q/47198848
tags question: http://stackoverflow.com/q/47182734
tag name: date
tags question: http://stackoverflow.com/q/47158114
tags question: http://stackoverflow.com/q/47186807
tags question: http://stackoverflow.com/q/47171944
tags question: http://stackoverflow.com/q/47130344
tags question: http://stackoverflow.com/q/47143592
tags question: http://stackoverflow.com/q/47195630
tags question: http://stackoverflow.com/q/47213158
tags question: http://stackoverflow.com/q/47095669
tags question: http://stackoverflow.com/q/47155621

http://stackoverflow.com/comment/81175072
has text: Ah I see, so what you want is the same result but rotated? So this method gives you 2 by 10, but you want 10 by 2?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47112556
score: 0

pyqt
type: Tag
tags question: http://stackoverflow.com/q/47139958
tags question: http://stackoverflow.com/q/47101280
tags question: http://stackoverflow.com/q/47102224
tags question: http://stackoverflow.com/q/47213347
tags question: http://stackoverflow.com/q/47189091
tags question: http://stackoverflow.com/q/47178890
tags question: http://stackoverflow.com/q/47067050
tags question: http://stackoverflow.com/q/47177905
tags question: http://stackoverflow.com/q/47082319
tags question: http://stackoverflow.com/q/47174683
tags question: http://stackoverflow.com/q/47079461
tags question: http://stackoverflow.com/q/47164979
tags question: http://stackoverflow.com/q/47066239
tags question: http://stackoverflow.com/q/47110432
tags question: http://stackoverflow.com/q/47147086
tags question: http://stackoverflow.com/q/47091216
tags question: http://stackoverflow.com/q/47182539
tags question: http://stackoverflow.com/q/47145117
tags question: http://stackoverflow.com/q/47165402
tags question: http://stackoverflow.com/q/47106099
tags question: http://stackoverflow.com/q/47117944
tags question: http://stackoverflow.com/q/47153250
tags question: http://stackoverflow.com/q/47214061
tags question: http://stackoverflow.com/q/47192476
tags question: http://stackoverflow.com/q/47155862
tags question: http://stackoverflow.com/q/47081772
tags question: http://stackoverflow.com/q/47076345
tags question: http://stackoverflow.com/q/47165998
tag name: pyqt
tags question: http://stackoverflow.com/q/47201539
tags question: http://stackoverflow.com/q/47125056
tags question: http://stackoverflow.com/q/47216468
tags question: http://stackoverflow.com/q/47140550
tags question: http://stackoverflow.com/q/47173791
tags question: http://stackoverflow.com/q/47123335
tags question: http://stackoverflow.com/q/47105178
tags question: http://stackoverflow.com/q/47168063
tags question: http://stackoverflow.com/q/47088724
tags question: http://stackoverflow.com/q/47120996
tags question: http://stackoverflow.com/q/47085427
tags question: http://stackoverflow.com/q/47121089
tags question: http://stackoverflow.com/q/47076370
tags question: http://stackoverflow.com/q/47144326

http://stackoverflow.com/q/47072916
tagged with: python
has comment: http://stackoverflow.com/comment/81097756
has comment: http://stackoverflow.com/comment/81120070
has body: I have a dataframe which can be simplified like this: df = pd.DataFrame(index = ['01/11/2017', '01/11/2017', '01/11/2017', '02/11/2017', '02/11/2017', '02/11/2017'], columns = ['Period','_A', '_B', '_C'] ) df.Period = [1, 2, 3, 1, 2, 3] df which looks like: Date Period _A _B _C 01/11/2017 1 NaN NaN NaN 01/11/2017 2 NaN NaN NaN 01/11/2017 3 NaN NaN NaN 02/11/2017 1 NaN NaN NaN 02/11/2017 2 NaN NaN NaN 02/11/2017 3 NaN NaN NaN And I want to apply my function to each cell Get_Y(Date, Period, Location) (where _A, _B, _C, ... are the locations). Get_Y is a complex function, that looks up data from other dataframes using the Date, Period and Location, and based on criteria gives a value for Y (a float between 0 and 1). I have managed to make this work with iterrows: for index, row in PeriodDF.iterrows(): date = index Period = row.loc[row.index[0]] LocationList = row.index[1:] print(date, Period) for Location in LocationList : PeriodDF.loc[(PeriodDF.index == date)&amp;(PeriodDF.Period == Period), Location] = Get_Y(date, Period, Location) But this takes over 1 hour. There must be a way to do this faster in pandas. I have tried creating 3 dataframes, one an array of the Period, one an array of the Location, and one of the Date, but not sure how to apply Get_Y elementwise, using the value from each dataframe.
answer count: 0
tagged with: pandas
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81098802
downvote count: 0
has comment: http://stackoverflow.com/comment/81094257
has title: Fast elementwise apply function using index and column name - pandas
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81104067
has comment: http://stackoverflow.com/comment/81099878
has comment: http://stackoverflow.com/comment/81094056
type: UnansweredQuestion

http://stackoverflow.com/comment/81217210
has text: Sorry. If you get offended. I am a new to scripting. also the code you provided did not make any changes as I wanted to have. Anyways, thank you for the information and sharing the code.
comment on: http://stackoverflow.com/a/47132729
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/47191190
has comment: http://stackoverflow.com/comment/95397051
has comment: http://stackoverflow.com/comment/81352625
has comment: http://stackoverflow.com/comment/81340567
has body: This function async def readlist(self): filename = 'employees.txt' empList = [] with open(filename) as f_obj: for line in f_obj: empList.append(line) return empList is not asynchronous. The file reading is synchronous and no other task can run while this happens. Now since file reading is blocking by default it is not easy to make it asynchronous. One way is to submit the task to a separate thread: import asyncio from concurrent.futures import ThreadPoolExecutor FileIOPool = ThreadPoolExecutor(8) # you may pass here something like 2*CPU_CORES class Mywin(wx.Frame): ... def read_file(self): filename = 'employees.txt' empList = [] with open(filename) as f_obj: for line in f_obj: empList.append(line) return empList async def readlist(self): loop = asyncio.get_event_loop() return await loop.run_in_executor(FileIOPool, self.read_file) Now readlist is truely asynchronous, other operations can run while the file is being read. This is a standard procedure when you want to apply some blocking task to asynchronous framework.
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81335305
has comment: http://stackoverflow.com/comment/81335409
accepted answer of: http://stackoverflow.com/q/47184177
answers question: http://stackoverflow.com/q/47184177
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/81118560
comment on: http://stackoverflow.com/q/47082599
score: 0
has text: You seem to need all text after the first occurrence of a `"md5": "` substring. Why not use [`re.search(r'"md5":\s*"(.*)', data, re.S)`](https://ideone.com/sVGPHA) and grab `m.group(1)` value?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81319379
comment on: http://stackoverflow.com/a/47168795
type: Comment
score: 0
has text: Keep in mind each file can a different number of customers. File 1 could have 5 customers, file 2 could have 1, file 3 could have 2, etc.
type: AnswerComment

http://stackoverflow.com/q/47086910
downvote count: 1
favorite count: 0
has title: possible to return list of dict instead of a list when using for in? django
type: Question
possible better answer: http://stackoverflow.com/a/47087057
has body: I have a code which returns a list, which looks something like this [user.name for user in Model.field.filter()] I know this would return me a list of user name but I am wondering if it would be possible to return list of dict? such as [ {'name': 'name1', 'email': 'email1'}, {'name': 'name2', 'email': 'email2'} ]
has comment: http://stackoverflow.com/comment/81123689
has answer: http://stackoverflow.com/a/47087057
tagged with: arrays
has comment: http://stackoverflow.com/comment/81151739
tagged with: django
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81125705
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47104366
tagged with: list
answer count: 2
has answer: http://stackoverflow.com/a/47104366
score: 0
upvote count: 1

http://stackoverflow.com/comment/81135410
comment on: http://stackoverflow.com/q/47090519
has text: @MadPhysicist 3=5 and not 3=2 is because 1 is already mapped to 2 and it should be a one-one mapping like i said.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47098185
has answer: http://stackoverflow.com/a/47227364
upvote count: 6
tagged with: install-requires
has body: I have a library (subx) which depends on subprocess32. The subprocess32 library is a backport for Python2.7 and provides the timeout kwarg. My library needs the timeout kwarg. I need subprocess32 only if the target platform is Python2.x. How should I define the dependency in my project? I get this error message, if I define a dependency to subprocess32 via "install_requires" (setup.py) and I am inside a python3 virtualenv: ===&gt; pip install -e git+https://github.com/guettli/subx.git#egg=subx Obtaining subx from git+https://github.com/guettli/subx.git#egg=subx Cloning https://github.com/guettli/subx.git to ./src/subx Collecting subprocess32 (from subx) Using cached subprocess32-3.2.7.tar.gz Complete output from command python setup.py egg_info: This backport is for Python 2.x only. ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-lju3nl1y/subprocess32/
possible better answer: http://stackoverflow.com/a/47103734
has answer: http://stackoverflow.com/a/47103734
type: AnsweredQuestion
downvote count: 0
tagged with: pip
favorite count: 0
has title: Dependency management: subprocess32 needed for Python2.7
tagged with: setup.py
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/47227364
tagged with: python
tagged with: dependency-management
score: 6

http://stackoverflow.com/q/47182821
tagged with: class
tagged with: object
tagged with: oop
type: Question
tagged with: http://stackoverflow.com/tag/csv
type: AnsweredQuestion
score: 0
has body: was confused about how to make objects of people with different attributes using an import from a csv file. The format of the imported file is simply a short list of names. For now I wanted it just to be able to at least display the objects created as I can't seem to progress very far with what I'm doing What I have below is all that I could think of to do, sorry if it's a stupid query! Thanks very much. class person: def __init__(self, name): self.name = name self.age = 0 self.wage = 0 self.height = 0 def getName(self): return self.name def importList(): with open('peoplenamelist.csv', 'r') as f: reader = csv.reader(f) maleList = list(reader) maleList = self.name return self.name
accepted answer: http://stackoverflow.com/a/47182899
tagged with: python
has answer: http://stackoverflow.com/a/47182899
answer count: 1
has title: Python - creating objects from csv import list

http://stackoverflow.com/a/47157866
downvote count: 0
answers question: http://stackoverflow.com/q/47157692
has body: Think it like that, the axis indicates the dimension which will be eliminated. So for the first case axis 0, so if you go through this dimension (2 entries) they will all collapse into 1. Thus it will be as following: result = [[1,1,1] + [1,1,1]] = [2,2,2] So you removed dimension 0. Now, for the second case, you will collapse axis 1 (or columns), so: result = [[1,1] + [1,1] + [1,1]] = [3,3] And the last case is you keep collapsing in order indicated in the brackets. In other words, first you eliminate the rows and then the columns: result1 = [2,2,2] result_final = 2 + 2 + 2 = 6 Hope this helps!
score: 10
upvote count: 10
type: Answer

http://stackoverflow.com/q/47079461
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81235079
upvote count: 3
has comment: http://stackoverflow.com/comment/81235111
downvote count: 0
tagged with: pyqt
answer count: 1
tagged with: signals-slots
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81228754
has comment: http://stackoverflow.com/comment/81234637
has title: PySide/PyQT5: How to emit signals from a QGraphicsItem?
score: 3
tagged with: qgraphicsitem
has comment: http://stackoverflow.com/comment/81115731
tagged with: pyside
has comment: http://stackoverflow.com/comment/81235273
has comment: http://stackoverflow.com/comment/81145058
tagged with: python
has answer: http://stackoverflow.com/a/47142635
accepted answer: http://stackoverflow.com/a/47142635
has body: I want to emit a signal from a QGraphicsItem when it is doubled-clicked, in order to change a widget in the main window. The graphics-scene/-item does not provide an emit() method, but I was just wondering if there is an alternate way to do this. The code below has a function within a QGraphicsView class that will print to the terminal when an item is double-clicked. How can I make that into a slot/signal instead (if QGraphicsItem does not support signal/slots)? import sys from PySide.QtCore import * from PySide.QtGui import * class MyFrame(QGraphicsView): def __init__( self, parent = None ): super(MyFrame, self).__init__(parent) scene = QGraphicsScene() self.setScene(scene) self.setFixedSize(500, 500) pen = QPen(QColor(Qt.green)) brush = QBrush(pen.color().darker(150)) item = scene.addEllipse(0, 0, 45, 45, pen, brush) item.setPos(0,0) def mouseDoubleClickEvent(self, event): print("Circle Clicked!") # this double click event prints to terminal but how to setup # signal/slot to update the QWidget QLabel text instead? class Example(QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): hbox = QHBoxLayout(self) top = QLabel("Double Click Green Circle (Howto change this QWidget Label with signals?)") bottom = MyFrame() splitter = QSplitter(Qt.Vertical) splitter.addWidget(top) splitter.addWidget(bottom) hbox.addWidget(splitter) self.setLayout(hbox) self.setGeometry(0, 0, 500, 600) self.show() def main(): app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main()
has comment: http://stackoverflow.com/comment/81144649
has comment: http://stackoverflow.com/comment/81228959

http://stackoverflow.com/comment/81101125
has text: `"... even if server sends back response."` How do you know that it does?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47076402

http://stackoverflow.com/comment/81310544
comment on: http://stackoverflow.com/q/47180753
type: Comment
type: QuestionComment
score: 0
has text: @TomKarzes I was trying the recursive version of gcd. I had it done using iterative function and wanted to try using recursion.

http://stackoverflow.com/comment/81107190
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47079132
has text: I actually have different range_start. In the above given sample it is all same, yeah but for 1 resource id there is 1 range_start

http://stackoverflow.com/a/47200011
score: 0
answers question: http://stackoverflow.com/q/47199303
has body: It looks as if the helpdesk urls.py includes url for login and logout, but not for resetting the password. The easiest way to include the password reset urls is to include the django.contrib.auth.urls in your project's urls.py. url('^', include('django.contrib.auth.urls')), See the Django docs for Authentication Views for more info.
type: Answer

http://stackoverflow.com/q/47114772
has answer: http://stackoverflow.com/a/59550532
downvote count: 0
answer count: 1
has title: sqlite + PyQt5 to standalone exe - Python 3.6.3 + Pyinstaller
tagged with: pyqt5
favorite count: 0
has comment: http://stackoverflow.com/comment/81193376
score: 2
has comment: http://stackoverflow.com/comment/81192740
tagged with: pyinstaller
has comment: http://stackoverflow.com/comment/81182714
has body: I would like to create an exe with Pyinstaller including a database (.db) and a picture (.png). I want everything into a single exe (--onefile). I tried to add the path of both elements directly in the spec file but it doesn't work. Here is my spec file: # -*- mode: python -*- block_cipher = None a = Analysis(['back_end.py'], pathex=['C:\\Users\\...\\site-packages\\PyQt5\\Qt\\bin', 'C:\\Users\\...\\Test_packaging'], binaries=[], datas=['C:\\Users\...\\Test_packaging\\database1.db', 'C:\\Users\...\\Test_packaging\\picture1.png'], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='back_end', debug=False, strip=False, upx=True, runtime_tmpdir=None, console=False ) Thank you
tagged with: sqlite
tagged with: python
has comment: http://stackoverflow.com/comment/81192497
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81183298
has comment: http://stackoverflow.com/comment/81192493
type: UnansweredQuestion

http://stackoverflow.com/q/47212741
has title: CSV Content in lowercase before processing?
tagged with: http://stackoverflow.com/tag/csv
score: 0
has body: Hey everyone :) I'm struggling because I have a big CSV-File where in one column the data should be considered case-insensitive, how can I fix that Python considers all rows of that column as lower (anton = ANTon)? That's what I tried: def CSV_firstnameshouldbelowered(csv_data): csv_record[First_Name] = csv_record[First_Name].lower() firstnameislowernow = { First_Name: csv_record[First_Name], Age: csv_record[Age] } return firstnameislowernow Sadly I can't use .lower() here because it's not a string. How can I change that columns content into lowercase? The part "firstnameislowernow" should be modified with the implementation before, otherwise I can't further process the data with my code :)
has answer: http://stackoverflow.com/a/47212834
tagged with: python
tagged with: lowercase
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/47212834
type: AnsweredQuestion

http://stackoverflow.com/comment/81190418
comment on: http://stackoverflow.com/q/47119748
score: 0
type: Comment
type: QuestionComment
has text: @juanpa.arrivillaga,OK got it now.Thanks Mate

http://stackoverflow.com/a/47223065
has body: dd does not output anything to stdout, however, it does output to stderr. Pass in stderr=subprocess.STDOUT to get the stderr output: Documentation here output_dd = subprocess.check_output(['dd', 'if=/dev/md0', 'of=/desktop'] stderr=subprocess.STDOUT) you will get output like b'# records in\n# records out\n# bytes transferred in # secs, (# bytes/sec) where you can use regular expressions to compare file size and the perform other operations(if that's what you want)
answers question: http://stackoverflow.com/q/47216910
type: Answer
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/comment/81117052
comment on: http://stackoverflow.com/q/47082875
score: 1
type: Comment
type: QuestionComment
has text: The decisive point is `x` in `M( x => f)`, which remains completely unused. As a result `f` in `M( f => M( x => f) )` evaluates to `f => M( x => f)` and when this partially applied function is finally applied to `foobar`, `f` becomes `foobar` and is simply returned, since `x` is ignored.

http://stackoverflow.com/a/47113595
answers question: http://stackoverflow.com/q/47113141
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: The barplot thinks your dates are categories. While one option may of course be to convert them into real dates (datetime objects) a potentially simpler solution in this case is to plot the bars in terms of integer values and set the labels accordingly. plt.barh(range(len(row_list)), row_list) plt.yticks(range(len(row_list)), month_list) It might then make sense to invert the y scale via plt.gca().invert_yaxis().
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47113141

http://stackoverflow.com/comment/81344760
has text: Simply the quotes are missing
comment on: http://stackoverflow.com/a/47194119
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47213852
possible better answer: http://stackoverflow.com/a/47219154
tagged with: scrapy
has answer: http://stackoverflow.com/a/47232117
has answer: http://stackoverflow.com/a/47219154
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
has body: I'm using round-col as the list length as there's always data in that column which tells me the size of the table. I'm scraping data to csv so all fields have to correspond but the trouble I'm facing is when the loop hits 'no data' the list index goes out of range or 'TypeError: 'NoneType' object is not sub scriptable from scrapy.selector import Selector from scrapy.spiders import Spider from bigcrawler.items import BigcrawlerItem class CrawlbotSpider(Spider): name = 'bigcrawler' allowed_domains = ['www.matchstat.com'] start_urls = ['https://matchstat.com/tennis/all-upcoming-matches'] custom_settings = { 'FEED_FORMAT': 'csv' , 'FEED_URI': 'test.csv' } def parse(self ,response): hxs = Selector(response) item = BigcrawlerItem() round_col = hxs.xpath(".//tr[contains(@class, 'match')]/td[contains(@class, 'round')]/text()").extract() event_col = hxs.xpath(".//tr[contains(@class, 'match')]/td[contains(@class, 'event-name')]/a/text()").extract() player1_col = hxs.xpath(".//tr[contains(@class, 'match')]/td[contains(@class, 'player-name')][1]/a/text()").extract() player2_col = hxs.xpath(".//tr[contains(@class, 'match')]/td[contains(@class, 'player-name')][2]/a/text()").extract() odds1_col = hxs.xpath(".//tr[contains(@class, 'match highlight')]/td[contains(@class, 'odds-td odds-0')]/a[contains(@class, 'btn btn-default virtual btn-xs btn-outcome odds')][1]/text()").extract_first() odds2_col = hxs.xpath( ".//tr[contains(@class, 'match highlight')]/td[contains(@class, 'odds-td odds-1')]/a[contains(@class, 'btn btn-default virtual btn-xs btn-outcome odds')][2]/text()").extract_first() h2h_col = hxs.xpath(".//tr[contains(@class, 'match')]/td[contains(@class, 'h2h')]/a[contains(@class, 'h2h')]/text()").extract_first() for x in range(0,len(round_col)): item['round'] = round_col[x].strip() item['event1'] = event_col[x].strip() item['player_1'] = player1_col[x].strip() item['player_2'] = player2_col[x].strip() item['player_1_odds'] = odds1_col[x].strip() item['player_2_odds'] = odds2_…
tagged with: python
tagged with: loops
accepted answer: http://stackoverflow.com/a/47232117
type: Question
has title: Python/Scrapy handle missing table data, list index out of range
upvote count: 0
downvote count: 2
score: -2
has answer: http://stackoverflow.com/a/47227657
has comment: http://stackoverflow.com/comment/81377325

http://stackoverflow.com/q/47172770
downvote count: 2
has answer: http://stackoverflow.com/a/51759467
tagged with: machine-learning
answer count: 7
has comment: http://stackoverflow.com/comment/81295474
favorite count: 0
tagged with: opencv
type: Question
tagged with: image-resizing
has answer: http://stackoverflow.com/a/49721346
has answer: http://stackoverflow.com/a/57726798
has answer: http://stackoverflow.com/a/60042154
accepted answer: http://stackoverflow.com/a/47173472
tagged with: python
tagged with: image-processing
score: 10
has answer: http://stackoverflow.com/a/47173472
has comment: http://stackoverflow.com/comment/81295290
has title: error: (-215) ssize.width > 0 && ssize.height > 0 in function resize
possible better answer: http://stackoverflow.com/a/49721346
has comment: http://stackoverflow.com/comment/81296599
has body: I am building an image processing classifier. This line is giving me an error: input_img_resize=cv2.resize(input_img,(128,128)) The error: ('error: /io/opencv/modules/imgproc/src/imgwarp.cpp:3483: error: (-215) ssize.width &gt; 0 &amp;&amp; ssize.height &gt; 0 in function resize') My code: PATH = os.getcwd() # Define data path data_path = PATH + '/data' data_dir_list = os.listdir(data_path) img_rows=128 img_cols=128 num_channel=3 num_epoch=30 num_classes = 67 img_data_list=[] for dataset in data_dir_list: img_list=os.listdir(data_path+'/'+ dataset) print ('Loaded the images of dataset-'+'{}\n'.format(dataset)) for img in img_list: input_img=cv2.imread(data_path + '/'+ dataset + '/'+ img ) input_img_resize=cv2.resize(input_img,(128,128)) img_data_list.append(input_img_resize)
has answer: http://stackoverflow.com/a/50641105
upvote count: 12
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/68908620

http://stackoverflow.com/comment/81390980
has text: You are so fast. I came here with a solution you posted one.
type: AnswerComment
score: 2
type: Comment
comment on: http://stackoverflow.com/a/47220706

http://stackoverflow.com/a/47149509
has body: Maybe you can recursively obtain all dir and make shutil.move to every dir。 import os root = "/Users/xyz/Documents/fun/test" g = os.walk(root) dirs = [] for i in g: dirs.append(i[0]) print(dirs)
answers question: http://stackoverflow.com/q/47148519
score: 0
has comment: http://stackoverflow.com/comment/81249517
has comment: http://stackoverflow.com/comment/81249560
type: Answer

http://stackoverflow.com/q/47209751
has body: I am using the default view for logging the users.So I have not made any modelForm for it.So I am not able to provide any bootstrap class to the input fields i.e username and password. So my login form is looking ugly.Is there anyway. I want to add bootstrap class form-control to the input fields username and password. Following is my HTML and URL snippets. All functions and classes used have their modules imported. urls.py url(r'^login/$', login, {'template_name': 'app/login.html'}), login.html {% csrf_token %} {% for field in form %} {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} {% endif %} {% endfor %} Remember me Sign in
downvote count: 0
answer count: 3
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81369091
has answer: http://stackoverflow.com/a/47210014
possible better answer: http://stackoverflow.com/a/47210014
has answer: http://stackoverflow.com/a/47210343
accepted answer: http://stackoverflow.com/a/47210343
favorite count: 0
has answer: http://stackoverflow.com/a/61683050
type: Question
tagged with: twitter-bootstrap
tagged with: django
tagged with: python
has title: Add Bootstrap to Inbulit Login View Django
linked to: http://stackoverflow.com/q/5827590
type: AnsweredQuestion

http://stackoverflow.com/q/47210457
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/112650329
favorite count: 0
type: Question
tagged with: python-2.7
score: 1
has comment: http://stackoverflow.com/comment/81370783
tagged with: python
has title: pyodbc executemany with tuple and python variable
downvote count: 0
has body: My tuple looks like this: test_tuple = ((1,2),(2,2),(3,5)) If I had a table with two columns, I can do: executemany("insert into mytable (col1, col2) values (?, ?);", test_tuple) Now if I wanted to insert into three columns, with the third column being a variable from Python, how can I achieve this? ran_string_var = 'foo' executemany("insert into mytable (col1, col2, col3) values (?, ?, ran_string_var);", test_tuple) Results in table: | col1 | col2 | col3 | | 1 | 2 | foo | | 2 | 2 | foo | | 3 | 5 | foo | What are some of my options? Maybe add the variables I want into the tuple? I cannot hard code the string with quotes because it will be dynamic.
answer count: 0
has comment: http://stackoverflow.com/comment/81370284
upvote count: 1

python
tags question: http://stackoverflow.com/q/47161842
tags question: http://stackoverflow.com/q/47088492
tags question: http://stackoverflow.com/q/47177533
tags question: http://stackoverflow.com/q/47113670
tags question: http://stackoverflow.com/q/47086876
tags question: http://stackoverflow.com/q/47115025
tags question: http://stackoverflow.com/q/47136595
tags question: http://stackoverflow.com/q/47088198
tags question: http://stackoverflow.com/q/47153937
tags question: http://stackoverflow.com/q/47198319
tags question: http://stackoverflow.com/q/47160934
tags question: http://stackoverflow.com/q/47135969
tags question: http://stackoverflow.com/q/47136019
tags question: http://stackoverflow.com/q/47087229
tags question: http://stackoverflow.com/q/47169037
tags question: http://stackoverflow.com/q/47177696
tags question: http://stackoverflow.com/q/47135549
tags question: http://stackoverflow.com/q/47090088
tags question: http://stackoverflow.com/q/47188835
tags question: http://stackoverflow.com/q/47111834
tags question: http://stackoverflow.com/q/47173791
tags question: http://stackoverflow.com/q/47097803
tags question: http://stackoverflow.com/q/47160502
tags question: http://stackoverflow.com/q/47176083
tags question: http://stackoverflow.com/q/47203845
tags question: http://stackoverflow.com/q/47117353
tags question: http://stackoverflow.com/q/47216436
tags question: http://stackoverflow.com/q/47100945
tags question: http://stackoverflow.com/q/47210102
tags question: http://stackoverflow.com/q/47217821
tags question: http://stackoverflow.com/q/47151298
tags question: http://stackoverflow.com/q/47105636
tags question: http://stackoverflow.com/q/47076428
tags question: http://stackoverflow.com/q/47116218
tags question: http://stackoverflow.com/q/47066063
tags question: http://stackoverflow.com/q/47090975
tags question: http://stackoverflow.com/q/47181946
tags question: http://stackoverflow.com/q/47116637
tags question: http://stackoverflow.com/q/47209163
tags question: http://stackoverflow.com/q/47217438
tags question: http://stackoverflow.com/q/47091818
tags question: http://stackoverflow.com/q/47144893
tags question: http://stackoverflow.com/q/47087338
tags question: http://stackoverflow.com/q/47127761
tags question: http://stackoverflow.com/q/47090912
tags question: http://stackoverflow.com/q/47114596
tags question: http://stackoverflow.com/q/47106830
tags question: http://stackoverflow.com/q/47103578
tags question: http://stackoverflow.com/q/47176420
tags question: http://stackoverflow.com/q/47069678
tags question: http://stackoverflow.com/q/47193228
tags question: http://stackoverflow.com/q/47187446
tags question: http://stackoverflow.com/q/47081807
tags question: http://stackoverflow.com/q/47169571
tags question: http://stackoverflow.com/q/47075440
tags question: http://stackoverflow.com/q/47129229
tags question: http://stackoverflow.com/q/47088139
tags question: http://stackoverflow.com/q/47105178
tags question: http://stackoverflow.com/q/47078050
tags question: http://stackoverflow.com/q/47176777
tags question: http://stackoverflow.com/q/47219198
tags question: http://stackoverflow.com/q/47121960
tags question: http://stackoverflow.com/q/47156119
tags question: http://stackoverflow.com/q/47140088
tags question: http://stackoverflow.com/q/47078331
tags question: http://stackoverflow.com/q/47128046
tags question: http://stackoverflow.com/q/47205923
tags question: http://stackoverflow.com/q/47202603
tags question: http://stackoverflow.com/q/47168531
tags question: http://stackoverflow.com/q/47198165
tags question: http://stackoverflow.com/q/47100559
tags question: http://stackoverflow.com/q/47215704
tags question: http://stackoverflow.com/q/47183635
tags question: http://stackoverflow.com/q/47066727
tags question: http://stackoverflow.com/q/47160328
tags question: http://stackoverflow.com/q/47210455
tags question: http://stackoverflow.com/q/47198497
tags question: http://stackoverflow.com/q/47113182
tags question: http://stackoverflow.com/q/47223071
tags question: http://stackoverflow.com/q/47203904

http://stackoverflow.com/a/47181177
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47180910
score: 1
type: Answer
has body: It is not possible, however it is some kind of a tradition in Python to append class _ to get a new identifier Use like this: class_ = "This is my string" You can read Official Documentation

http://stackoverflow.com/comment/81235079
comment on: http://stackoverflow.com/q/47079461
score: 0
type: QuestionComment
has text: import sys from PySide import QtCore, QtGui class MyFrame(QtGui.QGraphicsView): def __init__( self, parent = None ): super(MyFrame, self).__init__(parent) scene = QtGui.QGraphicsScene() self.setScene(scene) self.setFixedSize(500, 500) pen = QtGui.QPen(QtGui.QColor(QtCore.Qt.green)) brush = QtGui.QBrush(pen.color().darker(150)) item = scene.addEllipse(0, 0, 45, 45, pen, brush) item.setPos(0,0) if ( __name__ == '__main__' ): app = QtGui.QApplication([]) f = MyFrame() f.show() app.exec_()
type: Comment

http://stackoverflow.com/q/47104717
has comment: http://stackoverflow.com/comment/81161840
type: Question
tagged with: algorithm
accepted answer: http://stackoverflow.com/a/47104987
has title: Palindrome Algorithm and UnboundLocalError
tagged with: python
type: AnsweredQuestion
has body: This is my code to find the longest palindrome within a String. I get the following error message: "UnboundLocalError: local variable 'Current_Pal' referenced before assignment" I know that the variable 'Current_Pal" should be within the isPal function but if I do this the variable will be initialized to zero at every loop. def isPalindrome(s): Current_Pal = '' Longest_Pal = '' def toChars(s): s = s.lower() ans= '' for c in s: if c in 'abcdefghijklmnopqrstuvwxyz': ans = ans+ c return ans def isPal(s): if len(s) &lt;= 1: return Current_Pal + s else: if s[0] == s[-1]: Current_Pal = Current_Pal + s[0] else: if Current_Pal &gt; Longest_Pal: Longest_Pal = Current_Pal Current_Pal = '' return isPal(s[1:-1]) return isPal(toChars(s)) Palin = isPalindrome("HYTBCABADEFGHABCDEDCBAGHTFYW1234567887654321ZWETYGDE") print(Palin)
score: 0
has answer: http://stackoverflow.com/a/47104987
answer count: 1
tagged with: palindrome
has comment: http://stackoverflow.com/comment/81160037

http://stackoverflow.com/comment/81191212
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47120772
has text: Why are you using `randint` when you can use `np.random.randint`? Make a single call for 30 random numbers, and you're done.

http://stackoverflow.com/comment/81248545
comment on: http://stackoverflow.com/q/47147250
type: QuestionComment
type: Comment
score: 0
has text: I looked at the link, but I wasn't sure which problem was the relevant one for me. I now understand that it stems from insecure devices, but I'm still not sure if that is the best approach.

http://stackoverflow.com/q/47203573
linked to: http://stackoverflow.com/q/44597107
has title: How to fix "Unknown error: Chrome failed to start: exited abnormally" for running chrome in docker?
type: Question
tagged with: docker
score: 1
tagged with: python
has body: I want to use docker to run selenium tests within a jenkins instance. To test this, I am creating a docker image with the following Dockerfile: FROM python:2.7-slim WORKDIR /selenium ADD . /selenium # Install any needed packages specified in requirements.txt RUN pip install --trusted-host pypi.python.org -r requirements.txt # Install some basic stuff RUN apt-get update -qqy RUN apt-get install -y wget xvfb bzip2 zip unzip # Install all the chrome libraries... RUN apt-get install -y gconf-service libasound2 libatk1.0-0 libcairo2 libcups2 libfontconfig1 libgdk-pixbuf2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libxss1 fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils # Set firefox version and installation directory through environment variables. ENV FIREFOX_VERSION 45.0 ENV FIREFOX_DIR /usr/bin/firefox ENV FIREFOX_FILENAME $FIREFOX_DIR/firefox.tar.bz2 # Download the firefox of specified version from Mozilla and untar it. RUN mkdir -p $FIREFOX_DIR RUN wget -q --continue --output-document $FIREFOX_FILENAME "https://ftp.mozilla.org/pub/firefox/releases/${FIREFOX_VERSION}/linux-x86_64/en-US/firefox-${FIREFOX_VERSION}.tar.bz2" RUN tar -xaf "$FIREFOX_FILENAME" --strip-components=1 --directory "$FIREFOX_DIR" # Prepend firefox dir to PATH ENV PATH $FIREFOX_DIR:$PATH # Install Chrome ENV LOCALEXE /usr/local/bin ENV CHROMEDRIVERZIP=chromedriver_linux64.zip ENV CHROMEDRIVER=chromedriver RUN wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb RUN dpkg -i google-chrome-stable_current_amd64.deb; apt-get -fy install RUN wget "http://chromedriver.storage.googleapis.com/2.33/${CHROMEDRIVERZIP}" RUN unzip ${CHROMEDRIVERZIP} RUN mv ${CHROMEDRIVER} ${LOCALEXE} # Prepare the output directories RUN mkdir -p /selenium/out RUN ln -sf /dev/stdout /selenium/out/out.log RUN ln -sf /dev/stderr /selenium/out/err.log RUN Xvfb :99 -ac -screen 0 1280x1024x16 &amp; ENV DISPLAY :99 # Run app.py when the container launches CMD ["nosetests", "-s", "test1.py"] and in …
favorite count: 0
has answer: http://stackoverflow.com/a/47204124
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/25975241
answer count: 1
downvote count: 0
tagged with: selenium
upvote count: 1
tagged with: google-chrome

http://stackoverflow.com/comment/81097109
score: 3
type: Comment
comment on: http://stackoverflow.com/q/47074423
has text: The default colour cycle was changed in matplotlib 2. See [this](https://matplotlib.org/users/dflt_style_changes.html#colors-color-cycles-and-color-maps) part of the docs
type: QuestionComment

http://stackoverflow.com/q/47184906
tagged with: python
has comment: http://stackoverflow.com/comment/81443971
type: AnsweredQuestion
tagged with: rest
tagged with: api
has comment: http://stackoverflow.com/comment/81533018
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has title: Quick Rest API with Python for mocking responses
accepted answer: http://stackoverflow.com/a/47232498
has comment: http://stackoverflow.com/comment/81533576
downvote count: 1
has answer: http://stackoverflow.com/a/47232498
favorite count: 0
score: 8
type: Question
tagged with: python-3.x
has body: I am testing a C# application that make requests to another Rest API and I want to mock the server. I known basic python and I was wondering if I can write a simple API Rest server without be involved with large frameworks like Django. It would be a simple server where I receive a json through request body and I have to return another json (with the logic of the return inside, like a view). Best regards! Something simple like this: @path(/api/v1/somepath, GET) def my_function(request): json_input = request.body.json() # My logic here response.status = 200 response.body = {'some_field': 'something'} return response
upvote count: 9
has comment: http://stackoverflow.com/comment/81532468
has comment: http://stackoverflow.com/comment/81533787
has comment: http://stackoverflow.com/comment/81443898

http://stackoverflow.com/comment/81367568
has text: *Security*, what kind of security? Also keep in mind that the two codes you provided behave differently. With the first one you will have a new instance of `First` everytime `Second.second_other_function` is called.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47209205
score: 0

http://stackoverflow.com/comment/81256437
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47153385
has text: Yes, I tried: Error: `"delimiter" must be a 1-character string`.
score: 0

http://stackoverflow.com/comment/81335199
type: QuestionComment
comment on: http://stackoverflow.com/q/47187764
has text: Thank you all so much for the answers! My code runs perfectly now. Seriously can't thank you guys enough!
score: 0
type: Comment

http://stackoverflow.com/q/47156825
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
has body: This is the sample code copied from the documentation page of ldap3 http://ldap3.readthedocs.io/tutorial_searches.html#finding-entries. I am trying to make a connection to ldap but its not working for the free test ldap and even my own ldap server. testing.py from ldap3 import Server, Connection, ALL server = Server('ipa.demo1.freeipa.org', get_info=ALL) conn = Connection(server, 'uid=admin,cn=users,cn=accounts,dc=demo1,dc=freeipa,dc=org', 'Secret123', auto_bind=True) conn.search('dc=demo1,dc=freeipa,dc=org', '(objectclass=person)') print(conn.entries) For test purpose trying to connect to the testing server and this is the common error I get when trying to make the connections. Error Message Traceback (most recent call last): File "testingldap.py", line 9, in &lt;module&gt; conn = Connection(server, 'uid=admin,cn=users,cn=accounts,dc=demo1,dc=freeipa,dc=org', 'Secret123', auto_bind=True) File "/home/tara/env3/lib/python3.5/site-packages/ldap3/core/connection.py", line 278, in __init__ self.bind(read_server_info=True) File "/home/tara/env3/lib/python3.5/site-packages/ldap3/core/connection.py", line 427, in bind response = self.post_send_single_response(self.send('bindRequest', request, controls)) File "/home/tara/env3/lib/python3.5/site-packages/ldap3/strategy/sync.py", line 122, in post_send_single_response responses, result = self.get_response(message_id) File "/home/tara/env3/lib/python3.5/site-packages/ldap3/strategy/base.py", line 298, in get_response responses = self._get_response(message_id) File "/home/tara/env3/lib/python3.5/site-packages/ldap3/strategy/sync.py", line 168, in _get_response dict_response = self.decode_response(ldap_resp) File "/home/tara/env3/lib/python3.5/site-packages/ldap3/strategy/base.py", line 403, in decode_response result = bind_response_to_dict(component) File "/home/tara/env3/lib/python3.5/site-packages/ldap3/operation/bind.py", line 119, in bind_response_to_dict 'saslCreds': bytes(response['serverSaslCreds']) if response['serverSa…
tagged with: python
downvote count: 1
score: 2
tagged with: python-3.4
has title: Error connecting to freeIPA demo ldap server using python3-ldap
tagged with: python-ldap
upvote count: 3

http://stackoverflow.com/comment/81375751
comment on: http://stackoverflow.com/a/47184672
type: Comment
score: 0
type: AnswerComment
has text: thank you i mean what if someone inherited Animal class like class Cat(Animal): def __init__(self, food, n): super().__init__(name=n) self.food = food self.sound = 'meow' self.namegetter = 'namegetter'

http://stackoverflow.com/a/68273718
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47116006
has body: Just use this: turtle.screen.title("Custom title")

http://stackoverflow.com/q/47217846
has comment: http://stackoverflow.com/comment/81385583
has body: I'm trying to rename some files which all start with the same string (Vertragshandbuch_Beitrag_) in a folder using pyhton on windows. An example file-name: Vertragshandbuch_Beitrag_004_Term Sheet.docx New file-name should look like this: 4.docx My current code looks like this: import os import re for filename in os.listdir("."): m = re.match("Vertragshandbuch_Beitrag_(\d+)_(\w+(\W\w+)*)\.docx", filename) number = m.group(1) new_filename = number + ".docx" os.rename(filename, new_filename) print(new_filename) I'm getting this error: Traceback (most recent call last): File "C:(...)rename.py", line 6, in number = m.group(1) AttributeError: 'NoneType' object has no attribute 'group' I checked the regex with several filenames here: https://regex101.com/ and it was always a perfect match. I'm new to python and before asking the question I searched a long time and all the tips about normalizing the file name didn't help. I changed the script after input from blurp to: import os import re for filename in os.listdir("."): m = re.match(r'Vertragshandbuch_Beitrag_(\d+)_(\w+(\W\w+)*)\.docx', filename) number = m.group(1) new_filename = number + ".docx" os.rename(filename, new_filename) print(new_filename) Still the same error and still a match when I check the regex. To test the regex match I used now: import os import re for filename in os.listdir("."): m = re.match(r'Vertragshandbuch_Beitrag_(\d+)_(\w+(\W\w+)*)\.docx', filename) number = m.group(1) new_filename = number + ".docx" if m is not None: os.rename(filename, new_filename) print(new_filename) Still same error message. Okay, as a last resort I tried this in a folder which contained only the file Vertragshandbuch_Beitrag_003_Letter.docx: import os, sys import re for filename in os.listdir("."): m = re.match(r"Vertragshandbuch_Beitrag_(\d+)_(\w+(\W\w+)*)\.docx", filename) print(m) I got the following result: &lt;_sre.SRE_Match object; span=(0, 40), match='Vertragshandbuch_Beitrag_003_Letter.docx'> Looks like it is matchi…
has comment: http://stackoverflow.com/comment/81385539
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/81385453
downvote count: 0
accepted answer: http://stackoverflow.com/a/47218760
has comment: http://stackoverflow.com/comment/81385571
favorite count: 0
has comment: http://stackoverflow.com/comment/81385310
type: Question
has answer: http://stackoverflow.com/a/57615333
has comment: http://stackoverflow.com/comment/81385681
tagged with: python
has title: AttributeError: 'NoneType' object has no attribute 'group' while using re.match for renaming of file names
tagged with: regex
has comment: http://stackoverflow.com/comment/81385563
has answer: http://stackoverflow.com/a/47218760
has comment: http://stackoverflow.com/comment/81385533
possible better answer: http://stackoverflow.com/a/57615333

http://stackoverflow.com/a/47206017
answers question: http://stackoverflow.com/q/47205988
score: 0
has body: Well you're getting that error because of this merge_df['DEMO2']=merge_df.apply('DEMO2', axis=1) Should (probably) be this: merge_df['DEMO2']=merge_df.apply(DEMO2, axis=1)
type: Answer

http://stackoverflow.com/q/47072859
type: AnsweredQuestion
tagged with: deep-learning
has title: How to append data to one specific dataset in a hdf5 file with h5py
tagged with: h5py
score: 73
accepted answer: http://stackoverflow.com/a/47074545
upvote count: 73
tagged with: hdf5
has answer: http://stackoverflow.com/a/47074545
linked to: http://stackoverflow.com/q/25655588
favorite count: 0
type: Question
tagged with: numpy
has body: I am looking for a possibility to append data to an existing dataset inside a .h5 file using Python (h5py). A short intro to my project: I try to train a CNN using medical image data. Because of the huge amount of data and heavy memory usage during the transformation of the data to NumPy arrays, I needed to split the "transformation" into a few data chunks: load and preprocess the first 100 medical images and save the NumPy arrays to hdf5 file, then load the next 100 datasets and append the existing .h5 file, and so on. Now, I tried to store the first 100 transformed NumPy arrays as follows: import h5py from LoadIPV import LoadIPV X_train_data, Y_train_data, X_test_data, Y_test_data = LoadIPV() with h5py.File('.\PreprocessedData.h5', 'w') as hf: hf.create_dataset("X_train", data=X_train_data, maxshape=(None, 512, 512, 9)) hf.create_dataset("X_test", data=X_test_data, maxshape=(None, 512, 512, 9)) hf.create_dataset("Y_train", data=Y_train_data, maxshape=(None, 512, 512, 1)) hf.create_dataset("Y_test", data=Y_test_data, maxshape=(None, 512, 512, 1)) As can be seen, the transformed NumPy arrays are splitted into four different "groups" that are stored into the four hdf5 datasets[X_train, X_test, Y_train, Y_test]. The LoadIPV() function performs the preprocessing of the medical image data. My problem is that I would like to store the next 100 NumPy arrays into the same .h5 file into the existing datasets: that means that I would like to append to, for example, the existing X_train dataset of shape [100, 512, 512, 9] with the next 100 NumPy arrays, such that X_train becomes of shape [200, 512, 512, 9]. The same should work for the other three datasets X_test, Y_train and Y_test.
answer count: 2
possible better answer: http://stackoverflow.com/a/67334192
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/67334192

http://stackoverflow.com/comment/81239491
score: 0
comment on: http://stackoverflow.com/q/47144204
has text: it seems to be an error from `settings.py` do you have a similar import to check if everything is fine?, where is located this line?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47075296
answer count: 2
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47076089
tagged with: python
tagged with: regex
score: -1
has body: I would like to display a list containing information from some text files using Python. What I want to display : [host_name, hardware_ethernet_value, fixed_address_value] An example of a file (random examples): host name-random-text.etc { hardware ethernet 00:02:99:aa:xx:yc; fixed-address 1.3.0.155; } host name-another-again.etc { hardware ethernet 00:02:99:aa:xx:yc; fixed-address 3.5.0.115; } Someone helped me to write a code for that but it doesn't work anymore, though I know where the problem is coming from. So the code is as follows : #!/usr/bin/env python #import modules import pprint import re #open a file filedesc = open("DATA/fixed.10.3", "r") #using regex expressions to get the different informations SCAN = { 'host' : r"^host (\S+) {", 'hardware' : r"hardware ethernet (\S+);", 'fixed-adress' : r"fixed adress (\S+);" } item = [] for key in SCAN: #print(key) regex = re.compile(SCAN[key]) #print(regex) for line in filedesc: #print(line) match = regex.search(line) #print(match) #match = re.search(regex, line) #if match is not None: #print(match.group(1)) if match is not None: #print(match.group(1)) if match.group(1) == key: print(line) item += [match.group(2)] break #print the final dictionnaries pp=print(item) #make sure to close the file after using it with file.close() What should be expected : match.group(1) = host match.group(2) = name-random-text.etc But what I have is match.group(1) = name-random-text.etc so match.group(2) = nothing here. This is why the condition match.group(1) == key never works, because match.group(1) never takes the values ['host', 'hardware ethernet', 'fixed-address'].
has answer: http://stackoverflow.com/a/47083274
has title: Displaying information in a list using regex and .group()
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/81260638
score: 0
comment on: http://stackoverflow.com/q/47155173
has text: Now they could start guessing the IP address for the other side. Probably 192.168.0.{100,101,102,103}. And: it is impossible to "call functions" on another machine. It *is* possible to send messages, which *could* cause the other side to "call functions".
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47145716
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47145210
type: AcceptedAnswer
downvote count: 0
has body: You're looking for yield_per: res = session.query(MyModel).filter(MyModel.date.between(odate, cdate)).yield_per(1000)
type: Answer
answers question: http://stackoverflow.com/q/47145210
score: 4

http://stackoverflow.com/q/47152344
tagged with: dataframe
downvote count: 1
has title: How to calculate Levenshtein ratio/distance for rows in my column in python?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81255123
accepted answer: http://stackoverflow.com/a/47280100
answer count: 2
has comment: http://stackoverflow.com/comment/81255085
has comment: http://stackoverflow.com/comment/81254727
has answer: http://stackoverflow.com/a/47280100
linked to: http://stackoverflow.com/q/11437121
has comment: http://stackoverflow.com/comment/81255335
tagged with: python
tagged with: levenshtein-distance
has answer: http://stackoverflow.com/a/47468126
has comment: http://stackoverflow.com/comment/81257323
has comment: http://stackoverflow.com/comment/81254909
score: 2
has comment: http://stackoverflow.com/comment/81254852
type: AnsweredQuestion
has body: I have a dataframe with only one column , and 1000 rows in that column. I need to compare all rows and find Levenshtein distance for all rows . how Do i calculate that ratio or distance in python I have a dataframe as following: #Df StepDescription click confirm button when done you have logged on please log in to proceed click on confirm button Dolb was released successfully Enter your details validate the statement Aval was released sucessfully How to do i Calculate Levenshtein ration for all these Code I have written to iterate through loops but after iterating how to proceed. import Levenshtein import pandas as pd data_dist = pd.read_csv('path\Data_TestDescription.csv') df = pd.DataFrame(data_dist) for index, row in df.iterrows():
tagged with: pandas
upvote count: 3
possible better answer: http://stackoverflow.com/a/47468126
linked to: http://stackoverflow.com/q/47156739

http://stackoverflow.com/a/47189575
has comment: http://stackoverflow.com/comment/81390336
has body: It happens that there is an easier way. It's taken me a day or two to dig around until I was pointed toward the right method in scipy.stats. I was looking for the wrong sort of name! First, build a subclass of rv_continuous to represent one of your distributions. We know the pdf for your distributions, so that's what we define. In this case there's just one parameter. If more are needed just add them to the def statement and use them in the return statement as required. &gt;&gt;&gt; from scipy import stats &gt;&gt;&gt; param = 3/2 &gt;&gt;&gt; from math import exp &gt;&gt;&gt; class NoName(stats.rv_continuous): ... def _pdf(self, x, param): ... return param*exp(-param*x) ... Now create an instance of this object, declare the lower end of its support (ie, the lowest value that the r.v. can assume), and what the parameters are called. &gt;&gt;&gt; noname = NoName(a=0, shapes='param') I don't have an actual sample of values to play with. I'll create a pseudo-random sample. &gt;&gt;&gt; sample = noname.rvs(size=100, param=param) Sort it to make it into the so-called 'empirical cdf'. &gt;&gt;&gt; empirical_cdf = sorted(sample) The sample has 100 elements, therefore generate 100 points at which to sample the inverse cdf, or quantile function, as discussed in the paper your referenced. &gt;&gt;&gt; theoretical_points = [(_-0.5)/len(sample) for _ in range(1, 1+len(sample))] Get the quantile function values at these points. &gt;&gt;&gt; theoretical_cdf = [noname.ppf(_, param=param) for _ in theoretical_points] Plot it all. &gt;&gt;&gt; from matplotlib import pyplot as plt &gt;&gt;&gt; plt.plot([0,3.5], [0, 3.5], 'b-') [&lt;matplotlib.lines.Line2D object at 0x000000000921B400&gt;] &gt;&gt;&gt; plt.scatter(empirical_cdf, theoretical_cdf) &lt;matplotlib.collections.PathCollection object at 0x000000000921BD30&gt; &gt;&gt;&gt; plt.show() Here's the Q-Q plot that results.
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47122284
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47122284

http://stackoverflow.com/a/47135281
has comment: http://stackoverflow.com/comment/81220854
type: Answer
score: 0
has body: You have to pass the path within an array: currentFile.extractall(path, ['foo bar/'])
answers question: http://stackoverflow.com/q/47135096

http://stackoverflow.com/a/47145532
has body: As far as I can tell, the solution is to initialize each dictionary value as a list from the start. For example, initialize your dictionary as dictionary = {'dog' : ['bark'], 'cat' : ['kitten']}. Then, when you want to add new values to your dictionary keys you can use dictionary["dog"].append("speak").
score: 1
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47145305

http://stackoverflow.com/comment/81116219
type: Comment
has text: It is okay, before I have used "replace" with success but now I need something like "re.sub". The problem is in the order of "re.sub" operation.
type: QuestionComment
comment on: http://stackoverflow.com/q/47082599
score: 0

http://stackoverflow.com/comment/81210427
type: QuestionComment
has text: How is "merging two lists" defined?
score: 2
comment on: http://stackoverflow.com/q/47130325
type: Comment

http://stackoverflow.com/comment/81234731
comment on: http://stackoverflow.com/q/47141744
score: 0
type: Comment
type: QuestionComment
has text: From what I can tell, the Flask dev server is single-threaded by default, so that's one reason it might work locally and not when you deploy.

http://stackoverflow.com/comment/81276498
type: AnswerComment
comment on: http://stackoverflow.com/a/47146889
has text: I think it would be better to create a custom context processor. See this blog post: https://matthewphiong.com/django-global-template-variable
type: Comment
score: 0

http://stackoverflow.com/q/47087510
has body: I am trying to scrape data off the site below however it seems I can't seem to find a css selector where it will display a correct output. For this website, I have tried: .row:nth-child(1) span as well as other css selectors. I am yet to find a working xpath as it is not like Nth-childs to try to see if it makes any difference I've posted my full code here
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/81125568
type: Question
has comment: http://stackoverflow.com/comment/81125597
tagged with: python
has title: Not scraping correct values despite it being correct in chrome inspect
tagged with: css
tagged with: selenium-webdriver
tagged with: xpath
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47089464
accepted answer: http://stackoverflow.com/a/47089464

http://stackoverflow.com/comment/81169389
type: QuestionComment
has text: You are finding [How to arguments django signals - post_save/pre_save](https://stackoverflow.com/a/23452387/6360580). This answer is maybe what you need.
type: Comment
comment on: http://stackoverflow.com/q/47109501
score: 0

http://stackoverflow.com/q/47147265
possible better answer: http://stackoverflow.com/a/47151181
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47147753
accepted answer: http://stackoverflow.com/a/47147753
tagged with: scikit-learn
has title: How to combine numeric and text data in a scikit dataset
type: AnsweredQuestion
has body: I have some data like: name | cost ----------------- milk | 1.20 butter | 3.50 eggs | .99 I'd like to be able to group these by both name and price (e.g., "skim milk" is related to "whole milk" and five things that are $2.99 would be scored as similar) using one of SciKit's clustering modules, like kmeans. I know I have to turn the names into numbers, which I'm doing using the HashingVectorizer, which gives me a sparse matrix. However, at that point, I'm not sure how to combine that with the costs column. The examples I've seen take the output of HashingVectorizer and feed it straight into kmeans.fit. Can someone give (or point me towards) an example that uses text data + at least one other column?
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/47151181

relational-database
type: Tag
tag name: relational-database
tags question: http://stackoverflow.com/q/47129229

http://stackoverflow.com/q/47211331
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81392692
has title: os.rename per string in dir name and fileextension (lookup table)
has body: I am having trouble calling keys and values from lookup table to rename files. The task: in CWD, find each dir that ends =camID (e.g, ...=d5), then find raw_file inside =camID, then prefix all raw_file filenames (but not other filenames) with device_name. Code: for camID in config: if dir_name.endswith(camID): for filename in os.listdir(camID): if filename.endswith(config(nested(raw_file))): os.rename(filename, config(nested(cam_name)){}_{}filename) Lookup: config = { 'g7': {}, 'd5': {}, } config['g7']['cam_name'] = 'Canon-G7' config['g7']['raw_file'] = ('cr2', 'jpg', 'mp4') config['d5']['cam_name'] = 'Nikon-D5' config['d5']['raw_file'] = ('nef', 'jpg', 'avi') #'g7', 'd5' are called "camID" Tree before and after: CWD 01_camdirab=d5 /aaa/ .nef,.jpg,.avi,.wav 02_camdirxyz=g7 /bbb/ddd/ .cr2,.jpg,.mp4 04_camdire012345 / .mp4,.jpg,.avi CWD 01_camdirab=d5 /aaa/ Nikon-D5_.nef, Nikon-D5_.jpg, Nikon-D5_.avi, .wav 02_camdirxyz=g7 /bbb/ddd/ Canon-G7_.cr2, Canon-G7_.jpg, Canon-G7_.mp4 04_camdire012345 /.mp4,.jpg,.avi
answer count: 1
has comment: http://stackoverflow.com/comment/81372807
type: Question
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81393194
accepted answer: http://stackoverflow.com/a/47223396
tagged with: python
has comment: http://stackoverflow.com/comment/81375756
has answer: http://stackoverflow.com/a/47223396
has comment: http://stackoverflow.com/comment/81394203
has comment: http://stackoverflow.com/comment/81395084
tagged with: python-3.x

http://stackoverflow.com/comment/81145096
has text: Have you tried reversing the from / to values? so from would be 100 to would be 0
score: 3
comment on: http://stackoverflow.com/q/47097593
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81327199
has text: This problem has absolutely nothing to do with the use of argparse. Have you done any research at all into the error `no display name and no $DISPLAY environment variable`?
comment on: http://stackoverflow.com/q/47186962
score: 0
type: QuestionComment
type: Comment

list
tags question: http://stackoverflow.com/q/47073792
tags question: http://stackoverflow.com/q/47128907
tags question: http://stackoverflow.com/q/47101607
tags question: http://stackoverflow.com/q/47078837
type: Tag
tags question: http://stackoverflow.com/q/47077275
tags question: http://stackoverflow.com/q/47203951
tags question: http://stackoverflow.com/q/47085552
tags question: http://stackoverflow.com/q/47194543
tags question: http://stackoverflow.com/q/47212994
tags question: http://stackoverflow.com/q/47099567
tags question: http://stackoverflow.com/q/47162485
tags question: http://stackoverflow.com/q/47129403
tags question: http://stackoverflow.com/q/47209786
tags question: http://stackoverflow.com/q/47145424
tags question: http://stackoverflow.com/q/47202575
tags question: http://stackoverflow.com/q/47191365
tags question: http://stackoverflow.com/q/47065157
tags question: http://stackoverflow.com/q/47204134
tags question: http://stackoverflow.com/q/47163279
tags question: http://stackoverflow.com/q/47162758
tags question: http://stackoverflow.com/q/47113666
tags question: http://stackoverflow.com/q/47082106
tags question: http://stackoverflow.com/q/47112874
tags question: http://stackoverflow.com/q/47211939
tags question: http://stackoverflow.com/q/47149109
tags question: http://stackoverflow.com/q/47192135
tags question: http://stackoverflow.com/q/47158267
tags question: http://stackoverflow.com/q/47118470
tags question: http://stackoverflow.com/q/47119303
tags question: http://stackoverflow.com/q/47181150
tags question: http://stackoverflow.com/q/47170698
tags question: http://stackoverflow.com/q/47219993
tags question: http://stackoverflow.com/q/47120603
tags question: http://stackoverflow.com/q/47065548
tags question: http://stackoverflow.com/q/47208007
tags question: http://stackoverflow.com/q/47105572
tags question: http://stackoverflow.com/q/47081372
tags question: http://stackoverflow.com/q/47086676
tags question: http://stackoverflow.com/q/47175484
tags question: http://stackoverflow.com/q/47100868
tags question: http://stackoverflow.com/q/47189463
tags question: http://stackoverflow.com/q/47065866
tags question: http://stackoverflow.com/q/47211782
tags question: http://stackoverflow.com/q/47168660
tags question: http://stackoverflow.com/q/47080385
tags question: http://stackoverflow.com/q/47160456
tags question: http://stackoverflow.com/q/47164554
tags question: http://stackoverflow.com/q/47218675
tags question: http://stackoverflow.com/q/47106398
tags question: http://stackoverflow.com/q/47162981
tags question: http://stackoverflow.com/q/47103246
tags question: http://stackoverflow.com/q/47172769
tags question: http://stackoverflow.com/q/47182309
tags question: http://stackoverflow.com/q/47141600
tags question: http://stackoverflow.com/q/47090088
tags question: http://stackoverflow.com/q/47119593
tags question: http://stackoverflow.com/q/47120859
tags question: http://stackoverflow.com/q/47148524
tags question: http://stackoverflow.com/q/47066033
tags question: http://stackoverflow.com/q/47185315
tags question: http://stackoverflow.com/q/47214245
tags question: http://stackoverflow.com/q/47168948
tags question: http://stackoverflow.com/q/47163732
tags question: http://stackoverflow.com/q/47167972
tags question: http://stackoverflow.com/q/47166229
tags question: http://stackoverflow.com/q/47129380
tags question: http://stackoverflow.com/q/47167736
tags question: http://stackoverflow.com/q/47179055
tags question: http://stackoverflow.com/q/47080007
tags question: http://stackoverflow.com/q/47119071
tags question: http://stackoverflow.com/q/47113090
tags question: http://stackoverflow.com/q/47083816
tags question: http://stackoverflow.com/q/47082191
tags question: http://stackoverflow.com/q/47128539
tags question: http://stackoverflow.com/q/47188417
tags question: http://stackoverflow.com/q/47079367
tags question: http://stackoverflow.com/q/47084190
tags question: http://stackoverflow.com/q/47098517
tags question: http://stackoverflow.com/q/47105392

http://stackoverflow.com/comment/81118377
has text: Monday is the first day.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47084509
score: 0

http://stackoverflow.com/a/47093979
has comment: http://stackoverflow.com/comment/112280513
type: Answer
has comment: http://stackoverflow.com/comment/81145615
has body: You could try this solution: description.xpath("//img/@src")
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81137961
answers question: http://stackoverflow.com/q/47093335

http://stackoverflow.com/comment/81259798
has text: Thanks for the answer. Though it is not exactly what I want, it can be a good alternative. One question is, the above modification make it returns exactly 5000 training examples and 1000 test examples? or return only 6000 training examples?
type: Comment
comment on: http://stackoverflow.com/a/47155003
score: 0
type: AnswerComment

http://stackoverflow.com/q/47212686
favorite count: 0
has title: Why is 'isInstance' not defined?
has comment: http://stackoverflow.com/comment/81375589
type: Question
has answer: http://stackoverflow.com/a/74733021
upvote count: 5
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81375343
has comment: http://stackoverflow.com/comment/81374894
has body: I'm trying to build a little Python utility. I've built a unit test to test a basic setter, but my unit test fails with NameError: name 'isInstance' is not defined. My code: from pathlib import Path class DirectoryStructureNormalizer: def __init__(self, path): self.path = path @property def path(self): return self.__path @path.setter def path(self, path): self.__path = Path(path) And my unit test: import unittest from pathlib import Path from DirectoryStructureNormalizer import DirectoryStructureNormalizer class DirectoryStructureNormalizerTests(unittest.TestCase): def testSetterShouldSetPathToPathlibPath(self): directoryStructureNormalizer = DirectoryStructureNormalizer('.') self.assertTrue(isInstance(directoryStructureNormalizer.path, Path)) def main(): unittest.main() if __name__ == '__main__': main() And finally, my output: E ====================================================================== ERROR: testSetterShouldSetPathToPathlibPath (__main__.DirectoryStructureNormalizerTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "DirectoryStructureNormalizerTests.py", line 12, in testSetterShouldSetPathToPathlibPath self.assertTrue(isInstance(directoryStructureNormalizer.path, Path)) NameError: name 'isInstance' is not defined ---------------------------------------------------------------------- Ran 1 test in 0.002s FAILED (errors=1) I know I'm missing something super basic, but what?
answer count: 2
has comment: http://stackoverflow.com/comment/81374970
score: 2
downvote count: 3
tagged with: python-unittest
has answer: http://stackoverflow.com/a/74732957

http://stackoverflow.com/comment/81170215
comment on: http://stackoverflow.com/q/47108812
score: 0
has text: @pinkfloydx33 yes i have used it after --- using (Process process = Process.Start(start))---but it does not work
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81326694
type: AnswerComment
comment on: http://stackoverflow.com/a/47188075
score: 0
type: Comment
has text: This worked, thank you! I've since clarified the problem because when I tested it on my live data it didn't work (I didn't communicate that there is a nested dictionary.

http://stackoverflow.com/comment/81235078
type: QuestionComment
comment on: http://stackoverflow.com/q/47141645
has text: https://stackoverflow.com/questions/9462999/how-to-download-a-filefield-file-in-django-view might help
score: 0
type: Comment

http://stackoverflow.com/a/47197671
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47196719
has body: For future reference, here's the map I was using before. I actually made a mistake in the question; the data is set so that January 1960 is 1960.0, which means 1/12 must be added to each fractional component. def date_conv(d): y, frac_m = str(d).split('.') y = int(y) m = int(round((float('0.{}'.format(frac_m)) + 1/12) * 12, 0)) d = 1 try: date = datetime.datetime(year=y, month=m, day=d) except ValueError: print(y, m, frac_m) raise return date dates_series = dates_series.map(lambda d: date_conv(d)) The try/except block was just something I added for troubleshooting while writing it.

http://stackoverflow.com/comment/81337826
type: AnswerComment
has text: Hi @Marv, thanks for the solution I resolved it but now im getting one more error for sqlite3, I searched my didnt get the result, can you check this https://stackoverflow.com/questions/47194018/receiving-error-while-running-the-program-after-freezing-using-cx-freeze
type: Comment
comment on: http://stackoverflow.com/a/47155561
score: 0

http://stackoverflow.com/q/47185586
possible better answer: http://stackoverflow.com/a/47185684
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81320447
score: 1
downvote count: 1
tagged with: python
has body: I'm a data science noob and am working on the Kaggle Titanic dataset. I'm running a Logistic Regression on it to predict whether passengers in the test data set survived or died. I clean both the training and test data and run the Logistic Regression fit on the training data. All good. train = pd.read_csv('train.csv') X_train = train.drop('Survived',axis=1) y_train = train['Survived'] from sklearn.linear_model import LogisticRegression logmodel = LogisticRegression() logmodel.fit(X_train,y_train) Then I run the prediction model on the test data as such: test = pd.read_csv('test.csv') predictions = logmodel.predict(test) I then try to print the Confusion Matrix: from sklearn.metrics import classification_report, confusion_matrix print(confusion_matrix(test,predictions)) I get an error that says: ValueError: Classification metrics can't handle a mix of continuous-multioutput and binary targets What does this mean and how do I fix it? Some potential issues I see are: I'm doing something super dumb and wrong with that prediction model on the test data. The value for features "Age" and "Fare" (cost of passenger's ticket) are floats, while the rest are integers. Where am I going wrong? Thanks for your help!
has answer: http://stackoverflow.com/a/47186557
accepted answer: http://stackoverflow.com/a/47186557
favorite count: 0
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/47185684
has title: Logistic Regression - ValueError: classification metrics can't handle a mix of continuous-multi output and binary targets
tagged with: classification
tagged with: machine-learning
tagged with: scikit-learn
linked to: http://stackoverflow.com/q/47079266
tagged with: logistic-regression

http://stackoverflow.com/comment/81223653
comment on: http://stackoverflow.com/q/47135838
has text: I tried `s = u"full_" + u"我被调用了" + u".PDF"` and then `return s.encode("utf8")`, but it still output the same result. Thanks for your help anyway.
type: Comment
type: QuestionComment
score: 0

jupyter
tags question: http://stackoverflow.com/q/47145233
tags question: http://stackoverflow.com/q/47138023
type: Tag
tags question: http://stackoverflow.com/q/47103811
tags question: http://stackoverflow.com/q/47211324
tags question: http://stackoverflow.com/q/47086510
tags question: http://stackoverflow.com/q/47172525
tags question: http://stackoverflow.com/q/47114998
tags question: http://stackoverflow.com/q/47160523
tags question: http://stackoverflow.com/q/47082416
tags question: http://stackoverflow.com/q/47177397
tag name: jupyter
tags question: http://stackoverflow.com/q/47165346
tags question: http://stackoverflow.com/q/47191297

http://stackoverflow.com/comment/81172357
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47103275
type: AnswerComment
has text: @quamrana That depends on your usecase. For sophisticated ways, one might look at http://www.attrs.org/en/stable/

zeromq
tags question: http://stackoverflow.com/q/47086715
type: Tag
tag name: zeromq
tags question: http://stackoverflow.com/q/47080682

http://stackoverflow.com/comment/81158596
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47103158
has text: You can write (*i[0:4]) too shorten.
score: 2

http://stackoverflow.com/a/47091072
has body: The idea is to iterate through dictionary and the remove the found key. Here is an example: data = { "categories": { "imageData": { "Alcohol": "xyz123", "Noise Level": "average", "Music": { "dj": False }, "Attire": "casual" } } } for toDelete in ['categories.imageData.Music.dj', 'categories.imageData.Attire']: # find keys path = toDelete.split('.') # remember last item. # It is important to understand that stored value is a reference. # so when you delete the object by its key, you are modifying a referenced dictionary/object. item = data # iterate through all items except last one # we want to delete the 'dj', not 'False' which is its value for key in path[:-1]: item = item[key] del item[path[-1]] print data Result {'categories': {'imageData': {'Music': {}, 'Alcohol': 'xyz123', 'Noise Level': 'average'}}}
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47090882
upvote count: 3
score: 3

http://stackoverflow.com/comment/81364721
has text: commenting out the line that sets `charstr` to `'''^ S[SPQWR]{1}R'''` makes your regex work. Is there any significance to that part?
type: QuestionComment
comment on: http://stackoverflow.com/q/47207819
score: 1
type: Comment

http://stackoverflow.com/q/47089749
type: Question
has comment: http://stackoverflow.com/comment/81130185
has comment: http://stackoverflow.com/comment/81418567
accepted answer: http://stackoverflow.com/a/47233842
has comment: http://stackoverflow.com/comment/81130794
tagged with: python
has title: One end clamped and other end free cubic spline using scipy.interpolate.splprep and splev
has answer: http://stackoverflow.com/a/47233842
tagged with: interpolation
tagged with: numpy
has comment: http://stackoverflow.com/comment/81129444
has comment: http://stackoverflow.com/comment/81130627
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81129796
downvote count: 0
score: 1
upvote count: 1
tagged with: scipy
answer count: 1
has body: I have the following data: x_old = [ 0.00000000e+00, -5.96880765e-24, -8.04361605e-23, -2.11167774e-22, -2.30386081e-22, -7.86854147e-23, 1.17548440e-22, 1.93009272e-22, 1.49906866e-22, 9.66877465e-23, 1.48495705e-23] y_old = [ 0. , 0.03711505, 0.03780602, 0.02524459, 0.01349815, 0.00964215, 0.00972842, 0.0168793 , 0.02577024, 0.02761626, 0.02141961] z_old = [ 0. , 0.29834302, 0.59805918, 0.89773519, 1.19755092, 1.49749325, 1.79750314, 2.09741402, 2.39727031, 2.69726787, 2.99719479] I want to find the 3-D spline between these points so that the initial coordinate (0, 0, 0) remains fixed (clamped) and the other end is free. I did: from scipy.interpolate import splprep, splev import numpy as np # find the knot points tckp,u = splprep([x_old,y_old,z_old],s=3.0,k=3,nest=-1) # evaluate spline. xnew,ynew,znew = splev(np.linspace(0,1,400),tckp) Graph: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt ax.plot(xnew, ynew, znew, label='first iteration') plt.scatter(x_old, y_old, z_old, color='blue', label='given') ax.legend() plt.show() Question 1. In the above graph, the initial point is certainly not fixed. Mathematically, I know that I need to specify boundary conditions so that I get the 3-D spline I want. How can I do this in scipy?. Is there any optional arguments I can use in splprep and splev that I can specify to achieve this or do I need a completely new way to do this? Question 2 : If I wanted both ends to be clamped then how do I achieve that? Some Math : 'Clamped at the initial point' means that the first derivative at the initial point is zero and 'free at the terminal' point means that the second derivative there is zero.
favorite count: 0
has comment: http://stackoverflow.com/comment/81129252
has comment: http://stackoverflow.com/comment/81129635

http://stackoverflow.com/q/47123521
answer count: 1
tagged with: database
has comment: http://stackoverflow.com/comment/81198020
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47124446
has title: Django form field update
score: 0
has comment: http://stackoverflow.com/comment/81198482
tagged with: django-forms
type: Question
has body: I have a Django form that lets users choose a tag from multiple tag options. The problem I am facing is that even when the tag list gets updated, the model form does not get the updated tag list from database. As a result, new tags do not appear in options. Here is my code in forms.py: class EnglishTagForm(forms.Form): tag_choices = [(x.tagName, x.tagName.upper()) for x in ClassTag.objects.filter( agentId=Agent.objects.get(name='English Chowdhury'))] tag = forms.CharField(widget=forms.Select(choices=tag_choices, attrs={'class':'form-control'})) def __init__(self, *args, **kwargs): super(EnglishTagForm, self).__init__(*args, **kwargs) self.fields['tag'].choices = [(x.tagName, x.tagName.upper()) for x in ClassTag.objects.filter( agentId=Agent.objects.get(name='English Chowdhury'))] This form is being instantiated in view. My question is what changes should I do so that tag_choices gets updated from database on every instantiation. How the above form is used in views.py: ``` def complaintDetail(request, complaint_id): complaint = Complaints.objects.filter(pk=complaint_id).first() context = {} if request.method == 'POST': agent = Agent.objects.get(name="English Chowdhury") if "SubmitTag" in request.POST: englishForm = EnglishTagForm(request.POST) if englishForm.is_valid: // Complaint Delete Logic return redirect('chatbot:modComplaints') else: englishForm = EnglishTagForm() context['eForm'] = englishForm elif "SubmitBundle" in request.POST: newTagForm = NewTagForm(request.POST) if newTagForm.is_valid(): // Complaint Delete Logic complaint.delete() return redirect('chatbot:modComplaints') else: newTagForm = NewTagForm() context['newForm'] = newTagForm else: englishForm = EnglishTagForm() context['eForm'] = englishForm newTagForm = NewTagForm() context['newForm'] = newTagForm context['complaint'] = complaint return render(request, 'chatbot/complaintDetail.html', context) ``` Edit: (For future reference) I decided to modify the tag attribute and convert CharField to ModelCh…
type: UnansweredQuestion

http://stackoverflow.com/a/47115578
has comment: http://stackoverflow.com/comment/81181421
has comment: http://stackoverflow.com/comment/81181211
has comment: http://stackoverflow.com/comment/81181210
score: 2
has comment: http://stackoverflow.com/comment/81181227
upvote count: 3
has body: chars = set("!$%^&amp;*()_-+=") if any((i in chars) for i in string): points += 1
has comment: http://stackoverflow.com/comment/81181261
downvote count: 1
answers question: http://stackoverflow.com/q/47115532
has comment: http://stackoverflow.com/comment/81181302
type: Answer

http://stackoverflow.com/q/47121586
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81192893
has comment: http://stackoverflow.com/comment/81192840
has comment: http://stackoverflow.com/comment/81193028
has answer: http://stackoverflow.com/a/47122051
tagged with: python
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/81192745
answer count: 1
tagged with: calendar
downvote count: 1
has title: How do I fix my Python program
favorite count: 0
type: Question
has body: import datetime import time import locale now = datetime.datetime.now() locale.setlocale(locale.LC_ALL, 'nl_NL') geboortejaar = input("Wanneer ben je geboren? (jaar)") leeftijd = 2017 - int(geboortejaar) maand = int(input("En in welke maand? (getal)")) dag = int(input("En op welke dag? (getal)")) Weekdag = time.strftime("%d").upper() Maand = time.strftime("%m").upper() if maand &gt;= Maand and dag &gt;= Weekdag: print("Je bent dan " + str(leeftijd - 1) + " jaar oud en leeft al ongeveer " + str((leeftijd - 1) * 365) + " dagen!" ) else: print("Je bent dan " + str(leeftijd) + " jaar oud en leeft al ongeveer " + str(leeftijd * 365) + " dagen!") I live in the Netherlands and I wanted to make a Program that tells you how old you are without having to change some things everyday but by taking calendar info. Can someone help me fix this?
has comment: http://stackoverflow.com/comment/81192766

http://stackoverflow.com/comment/81201312
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47123701
has text: I have tried to implement your solution with: `num_sequence_A = input( "enter sequence A: ")` in which i receive an error. It only works when I change the input sequence to: `num_sequence_A = range(5 )`

http://stackoverflow.com/q/47124454
has title: Command line argument shows up as an empty string
answer count: 2
possible better answer: http://stackoverflow.com/a/47124588
has answer: http://stackoverflow.com/a/47124588
tagged with: python
has answer: http://stackoverflow.com/a/47124568
accepted answer: http://stackoverflow.com/a/47124568
has body: I'm attempting to pass in an argument to my script but for some reason if I specify -t for my time value, it shows up in the script as an empty string. If I specify --time, I get the correct value. Why? import sys, getopt, time def main(argv): inputfile = '' outputfile = '' sleeptime = 6 if len(sys.argv) == 1: print("No arguments supplied") print('Usage: test.py -i &lt;inputfile&gt; -o &lt;outputfile&gt; -t &lt;1-24&gt;') sys.exit() try: opts, arg = getopt.getopt(argv, "i:o:t", ["ifile=", "ofile=", "time="]) except getopt.GetoptError: print('Incorrect options.') print('Usage: test.py -i &lt;inputfile&gt; -o &lt;outputfile&gt; -t &lt;1-24&gt;') sys.exit() for opt, arg in opts: if opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg elif opt in ("-t", "--time"): print("time = ", arg) sleeptime = int(arg) else: print("Unknown arg") sys.exit() print(sleeptime) if __name__ == "__main__": main(sys.argv[1:]) I pretty much ripped the code from here: https://www.tutorialspoint.com/python/python_command_line_arguments.htm
score: 2
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81199208
downvote count: 0
has comment: http://stackoverflow.com/comment/81199214
has comment: http://stackoverflow.com/comment/81199107
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/81237253
has text: Hey, thanks for the answer. You were right about post_id not being a property of Post, checked {{ post.id }} in the template and it does have an integer value, but after changing to {% url 'view_post' post_id=post.id %} I am still getting the same error.
score: 0
comment on: http://stackoverflow.com/a/47143511
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81269285
score: 0
type: Comment
type: QuestionComment
has text: It's not clear why you are putting the response into a BytesIO object. But in any case you need to show the full traceback so that we can tell where the error is occurring.
comment on: http://stackoverflow.com/q/47159869

http://stackoverflow.com/q/47144606
has answer: http://stackoverflow.com/a/78376472
has answer: http://stackoverflow.com/a/58466226
downvote count: 0
has answer: http://stackoverflow.com/a/75720827
tagged with: python-requests
tagged with: http
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/55852421
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47144673
linked to: http://stackoverflow.com/q/15258728
has body: My question is closely related to How to tell if you&#39;re getting a 404. I'm using the Requests library to hit an HTTP endpoint. I want to check if the response is a success. I am currently doing this: r = requests.get(url) if 200 &lt;= response.status_code &lt;= 299: # Do something here! Instead of doing that ugly check for values between 200 and 299, is there a shorthand I can use?
score: 65
upvote count: 65
tagged with: python
has title: How to tell if you're getting a success message?

http://stackoverflow.com/comment/81222620
type: Comment
score: 0
has text: Calling Matlab is not an option
comment on: http://stackoverflow.com/q/47136614
type: QuestionComment

http://stackoverflow.com/comment/81111741
type: QuestionComment
comment on: http://stackoverflow.com/q/47080956
has text: @Ray The reason I have that first list is for a jump to navigation at the top of the page. It jumps to that letter if there are states within it. And the output of these lists is in a template that displays the related content. The second dictis not used currently. It is just something i've been playing around with to create the desired dict.
score: 0
type: Comment

http://stackoverflow.com/comment/81301207
score: 0
comment on: http://stackoverflow.com/a/47175087
type: Comment
has text: Thanks for your answer. This really helped me
type: AnswerComment

excel
tags question: http://stackoverflow.com/q/47076719
tags question: http://stackoverflow.com/q/47094603
tags question: http://stackoverflow.com/q/47139769
tags question: http://stackoverflow.com/q/47212831
tags question: http://stackoverflow.com/q/47175150
tags question: http://stackoverflow.com/q/47097161
tag name: excel
tags question: http://stackoverflow.com/q/47079980
tags question: http://stackoverflow.com/q/47094083
tags question: http://stackoverflow.com/q/47122752
tags question: http://stackoverflow.com/q/47177555
tags question: http://stackoverflow.com/q/47084230
tags question: http://stackoverflow.com/q/47182872
tags question: http://stackoverflow.com/q/47192659
tags question: http://stackoverflow.com/q/47156332
type: Tag
tags question: http://stackoverflow.com/q/47211869
tags question: http://stackoverflow.com/q/47158597
tags question: http://stackoverflow.com/q/47203746
tags question: http://stackoverflow.com/q/47217479
tags question: http://stackoverflow.com/q/47068734
tags question: http://stackoverflow.com/q/47073459
tags question: http://stackoverflow.com/q/47162966
tags question: http://stackoverflow.com/q/47086615
tags question: http://stackoverflow.com/q/47085618
tags question: http://stackoverflow.com/q/47222373
tags question: http://stackoverflow.com/q/47178632
tags question: http://stackoverflow.com/q/47146074
tags question: http://stackoverflow.com/q/47135655
tags question: http://stackoverflow.com/q/47197259
tags question: http://stackoverflow.com/q/47141354
tags question: http://stackoverflow.com/q/47143644
tags question: http://stackoverflow.com/q/47148345
tags question: http://stackoverflow.com/q/47066817
tags question: http://stackoverflow.com/q/47209035
tags question: http://stackoverflow.com/q/47204701
tags question: http://stackoverflow.com/q/47107510
tags question: http://stackoverflow.com/q/47085450

knapsack-problem
type: Tag
tags question: http://stackoverflow.com/q/47111513
tag name: knapsack-problem

http://stackoverflow.com/q/47113097
has title: File extension to file type checker in Python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81177455
has comment: http://stackoverflow.com/comment/81178505
has comment: http://stackoverflow.com/comment/81178161
score: 0
has comment: http://stackoverflow.com/comment/81177633
accepted answer: http://stackoverflow.com/a/47113391
answer count: 1
has answer: http://stackoverflow.com/a/47113391
has comment: http://stackoverflow.com/comment/81176505
type: Question
has body: I've created simple script to compare actual file type to extension. I don't know why I cannot search dictionary for key returned from file.read(3) . If I enter the key manualy or use sig like below, everything works fine. file_sigs = {b'\xff\xd8\xff':('JPEG','.jpg'), b'\x46\x4f\x52':('GIF','.gif')} file = open("ggg.jpg", "rb") sig = file.read(3) ext = os.path.splitext('ggg.jpg')[1] if sig in file_sigs: #print(file_sigs[sig]) if ext in file_sigs[b'\xff\xd8\xff'][1]: print('match') else: print('no match') else: print('no such signature')
has comment: http://stackoverflow.com/comment/81177955
has comment: http://stackoverflow.com/comment/81177696
has comment: http://stackoverflow.com/comment/81176876
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81176633

http://stackoverflow.com/a/47476067
type: Answer
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47121617
score: 1
upvote count: 1
has body: I'll answer my own question then: To loop through the viewports # import python maya commands import maya.cmds as cmds # Create a list of ALL viewports viewports = cmds.getPanel( all = True) # Get the current viewport vp = cmds.getPanel( withFocus = True) # current viewport current = cmds.modelEditor( vp, q = True, nurbsCurves = True) for view in viewports: if 'modelPanel' in view: # check to see if the item in lists is a viewport # is one of the model panels. # The list is quite big and we only need up to four print view # prints the current viewport #Swap the NURBS visibility around cmds.modelEditor( view, edit = True, nurbsCurves = not(current)) I hope that helped me as much as it did you. Yes it did. Thanks
answers question: http://stackoverflow.com/q/47121617

http://stackoverflow.com/q/47088484
has answer: http://stackoverflow.com/a/47203410
answer count: 4
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81130698
downvote count: 4
has answer: http://stackoverflow.com/a/47090424
upvote count: 2
has comment: http://stackoverflow.com/comment/81137502
score: -2
has body: Django documentation specify as_view method in class-based-views as_view() class method creates an instance of the class and calls its dispatch() method. I attempt to print the instance. For illustration: # urls.py from django.conf.urls import url from myapp.views import MyView urlpatterns = [ url(r'^about/$', MyView.as_view()), ] #views.py from django.http import HttpResponse from django.views import View class MyView(View): def get(self, request): # &lt;view logic&gt; return HttpResponse('result') I added a print statement to views.py: class MyView(View): print(self) def get(self, request): # &lt;view logic&gt; return HttpResponse('result') It reports NameError. How can I print the instance created by class 'View'?
accepted answer: http://stackoverflow.com/a/47324336
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47324336
has answer: http://stackoverflow.com/a/47312380
possible better answer: http://stackoverflow.com/a/47090424
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81418960
has title: Retrieve the instance created by class_based_view

http://stackoverflow.com/q/47085618
score: 2
tagged with: xlsxwriter
downvote count: 0
possible better answer: http://stackoverflow.com/a/72584187
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/47085861
tagged with: excel
has answer: http://stackoverflow.com/a/47085861
has answer: http://stackoverflow.com/a/72584187
type: AnsweredQuestion
has title: XlsxWriter conditional formatting does not recognize "icon_style" parameter
answer count: 2
upvote count: 2
has body: I'm currently trying to apply an icon style conditional format in excel to a Pandas dataframe output with XlsxWriter, and it has been giving me the following error: UserWarning: Unknown parameter 'icon_style' in conditional_formatting() param_key Based on the XlsxWriter documentation, this parameter is the correct way to set which icon set is used in the format. I've found no indication for what the correct keyword is. Any idea what the current syntax is for this?

http://stackoverflow.com/comment/81158504
type: QuestionComment
has text: Use ICAP protocol.
comment on: http://stackoverflow.com/q/47103625
score: 0
type: Comment

http://stackoverflow.com/a/47196279
type: Answer
has body: You have to filter for the agents who are in the team you want to send a team invitation. If you do not have a field which shows in which team the agent is you can not filter it. Create only one team invitation: TeamInvitation.objects.create(team='someteam') and then the agent filters: agent = Agent.objects.get(pk=somepk) teaminv = TeamInvitation.objects.filter(team=agent.team) With that way you can show the agent if he was invited. But I do not know why you want to create an team invitation for each agent. A team invitation should only be created once and the agent checks if he was invited. Normally you would make an invitation for the hole team and everyone who is in the team gets the invitation. I hope it is clear what I mean. So you should think about your structure.
score: 0
answers question: http://stackoverflow.com/q/47190960
has comment: http://stackoverflow.com/comment/81357296

http://stackoverflow.com/comment/81350275
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47200853
type: Comment
has text: Ok, it worked. Thanks... although I am now getting a MemoryError (might be to do with the amount of data that is going through!

http://stackoverflow.com/comment/81335436
has text: @Robᵩ can u explain why 81.0 % 1.0 in my python console is 0.0 but dont break my while loop?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47190264

http://stackoverflow.com/comment/81105016
has text: @JohnGordon running which python returns /usr/bin/python
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47078101
score: 0

http://stackoverflow.com/q/47197748
score: 1
has comment: http://stackoverflow.com/comment/81345774
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81347992
tagged with: scipy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81361366
has title: Rotate with scipy without interpolation
has comment: http://stackoverflow.com/comment/81347766
has comment: http://stackoverflow.com/comment/81346670
type: UnansweredQuestion
has body: I'm trying to rotate without interpolation my 3D stack (3D numpy array) on the (x,y) plane (around the z axis). To do this, I'm using the rotate function from the package Scipy as follows: ske_rotate = scipy.ndimage.rotate(stack, angle, (1, 0), False, None, 0, 'constant', 0.0, False) The issue is that I obtain a distorted rotated 3D stack as showed in my two figures. Before: After: Here are the constructed 3D skeletons of the 3D stacks before and after rotation. One can remark that the skeletons are different (points are added on the skeleton after rotation) which means that (in a quantitative way) the shape was modified after rotation. 3D Skeleton before rotation 3D Skeleton after rotation For 2D analysis, I extract the 39 slice from the two stacks. The two stacks have the same size (stack.shape=(120,120,120)). Note that if we remove the option in the line code, the stacks will have different sizes. The degree of rotation is 10° Original stack: slice 39 Rotated stack: slice 39 With the interpolation method : ske_rotate = scipy.ndimage.rotate(stack, angle) The 3D skeleton becomes as in the following figure (as if new shape is added..): 3D skeleton after a rotation with interpolation How can I obtain free distorted rotated 3D stack ?
has comment: http://stackoverflow.com/comment/81344524
tagged with: python
has comment: http://stackoverflow.com/comment/81349222
has comment: http://stackoverflow.com/comment/81347571
has comment: http://stackoverflow.com/comment/81345948
has comment: http://stackoverflow.com/comment/81348249
has comment: http://stackoverflow.com/comment/81348099
has comment: http://stackoverflow.com/comment/94358391
answer count: 0

http://stackoverflow.com/comment/81231481
score: 0
comment on: http://stackoverflow.com/q/47099370
type: Comment
has text: yep. Oh-- and I don't think it listed a line number, but it seems it fails when it tries to use the invertlaplace() function.
type: QuestionComment

http://stackoverflow.com/a/64466524
type: Answer
answers question: http://stackoverflow.com/q/47216476
score: 0
has body: I did a video on how to use wheel encoders and calculate the robot linear and angular speeds. (https://youtu.be/ktZTN5aUYPY) If you follow the video you will see that in the project doc folder, there is a ppt file with all the formulas. (https://github.com/gusbots/mark01/tree/v3.1/doc) Here is a snapshot of it: where vr and vl are the angular velocities in rad/s, R is the radius of the wheel and L is the distance between the wheels.

http://stackoverflow.com/comment/81326789
has text: I have just tested it. When using a smaller vocabulary size, the network stops improving already around epoch 15
comment on: http://stackoverflow.com/q/47163477
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47121089
type: AnsweredQuestion
score: 0
has title: Python - how to use the value of a variable inside a function that is called when a button is clicked
tagged with: pyqt
tagged with: function
answer count: 1
accepted answer: http://stackoverflow.com/a/47121720
tagged with: signals-slots
has answer: http://stackoverflow.com/a/47121720
type: Question
tagged with: python
has body: I have a piece of python code like this: class MainWindow(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) --snip-- self.ui.pushButton.clicked.connect(self.selectFile) someParameter = someFunction(self.filename) # (1) def selectFile(self): self.ui.lineEdit.setText(QtGui.QFileDialog.getOpenFileName()) self.filename = self.ui.lineEdit.text() # I want to use "filename" variable in (1) --snip-- I want to catch the name of the file which is selected by QFileDialog and do two things; firstly, show the address of the file in a lineEdit widget and secondly, store the address of the file in a variable so I can use it later on the rest of the process. How should I do that, and what is the proper way?

http://stackoverflow.com/comment/106699202
has text: @Elliptica You can check [this](https://stackoverflow.com/questions/60262432/service-account-not-authorized-to-access-this-resource-api-while-trying-to-acces/60262433#60262433) answer for a Python solution
score: 0
comment on: http://stackoverflow.com/q/47208425
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47064768
favorite count: 0
has comment: http://stackoverflow.com/comment/81077776
has comment: http://stackoverflow.com/comment/81080190
has answer: http://stackoverflow.com/a/47102561
type: Question
has comment: http://stackoverflow.com/comment/81116438
has comment: http://stackoverflow.com/comment/81077786
has comment: http://stackoverflow.com/comment/81079667
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/47099183
has comment: http://stackoverflow.com/comment/81146436
has title: Efficient design to store lookup table for files in directories
has body: Let's say I have three directories dir1, dir2 &amp; dir3, with thousands of files in each. Each file has a unique name with no pattern. Now, given a filename, I need to find which of the three directories it's in. My first thought was to create a dictionary with the filename as key and the directory as the value, like this: {'file1':'dir1', 'file2':'dir3', 'file3':'dir1', ... } But seeing as there are only three unique values, this seems a bit redundant and takes up space. Is there a better way to implement this? What if I can compromise on space but need faster lookup?
has answer: http://stackoverflow.com/a/47099183
tagged with: lookup
tagged with: file-search
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81319775
has comment: http://stackoverflow.com/comment/81078690
answer count: 2
score: 1
has comment: http://stackoverflow.com/comment/81078522
has comment: http://stackoverflow.com/comment/81078194
has comment: http://stackoverflow.com/comment/81112919
has comment: http://stackoverflow.com/comment/81116234
downvote count: 0
possible better answer: http://stackoverflow.com/a/47102561
upvote count: 1
has comment: http://stackoverflow.com/comment/81078705
has comment: http://stackoverflow.com/comment/81283940

http://stackoverflow.com/comment/81120281
comment on: http://stackoverflow.com/q/47085156
type: Comment
score: 0
type: QuestionComment
has text: Are you talking about this: https://en.wikipedia.org/wiki/Cutting_stock_problem

http://stackoverflow.com/comment/81304685
has text: `mysql.connector` is for MySQL. `psycopg2` is for Postgres. Which database are you using? If Postgres, the default port is 5432 so make sure that your firewall has that port open. Did you try using the `psql` client?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47175388

http://stackoverflow.com/a/47113893
downvote count: 0
has comment: http://stackoverflow.com/comment/81180394
has body: To do this task it is recommended to use QStackedWidget, for this I assumed that the widget associated with that area can be accessed through self.widget: class OperatorGUI(MainBase, MainUI): def __init__(self, parent=None): super(OperatorGUI, self).__init__(parent) self.setupUi(self) self.comboBox.activated[str].connect(self.choose_widget) self.widget.setLayout(QVBoxLayout()) self.stacked = QtGui.QStackedWidget() self.widget.layout().addWidget(self.stacked) self.textWidget = TextWidget() self.calendarWidget = CalendarWidget() self.stacked.addWidget(self.textWidget) self.stacked.addWidget(self.calendarWidget) def choose_widget(self, choice): # Set the widget accorging to the choice if choice == "Option 1": self.stacked.setCurrentWidget(self.textWidget) elif choice == "Option 2": self.stacked.setCurrentWidget(self.calendarWidget)
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/47110432
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81180746
has comment: http://stackoverflow.com/comment/81180474
has comment: http://stackoverflow.com/comment/81180862
type: Answer
answers question: http://stackoverflow.com/q/47110432
has comment: http://stackoverflow.com/comment/81179926
has comment: http://stackoverflow.com/comment/81180501

http://stackoverflow.com/comment/81136888
type: QuestionComment
has text: @Hackaholic Read my question again understand the problem I am facing.
comment on: http://stackoverflow.com/q/47093661
score: 0
type: Comment

http://stackoverflow.com/comment/81396639
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47223071
type: QuestionComment
has text: @RaghuramVadapalli there is no typo in the last two raws? Shouldn't be they like first 2?

http://stackoverflow.com/q/47142968
has comment: http://stackoverflow.com/comment/81237378
has answer: http://stackoverflow.com/a/47143366
has comment: http://stackoverflow.com/comment/81236691
has comment: http://stackoverflow.com/comment/81238506
has comment: http://stackoverflow.com/comment/81236318
has body: BLUF: Why is the decode() method on a bytes object failing to decode ç? I am receiving a UnicodeDecodeError: 'utf-8' codec can't decode by 0xe7 in position..... Upon tracking down the character, it is the ç character. So when I get to reading the response from the server: conn = http.client.HTTPConnection(host = 'something.com') conn.request('GET', url = '/some/json') resp = conn.getresponse() content = resp.read().decode() # throws error I am unable to get the content. If I just do content = resp.read() it is successful, I can write to file using wb but then whever the ç is, it is replaced with 0xE7 in the file upon writing. Even if I open the file in Notepad++ and set the encoding to UTF-8, the character only shows as the hex version. Why am I not able to decode this UTF-8 character from an HTTPResponse? Am I not correctly writing it to file either?
type: Question
has comment: http://stackoverflow.com/comment/81236243
has comment: http://stackoverflow.com/comment/81236870
has comment: http://stackoverflow.com/comment/81236328
has comment: http://stackoverflow.com/comment/81279607
has comment: http://stackoverflow.com/comment/81236586
answer count: 1
has comment: http://stackoverflow.com/comment/81236744
accepted answer: http://stackoverflow.com/a/47143366
tagged with: python
has comment: http://stackoverflow.com/comment/81236495
has comment: http://stackoverflow.com/comment/81236733
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81237343
score: 0
has comment: http://stackoverflow.com/comment/81236720
has comment: http://stackoverflow.com/comment/81237260
has title: UnicodeDecodeError (UTF-8) for JSON

http://stackoverflow.com/comment/81310913
type: QuestionComment
has text: Verify that `c:\users\hell\envs\my_env\lib\site-packages\src\package_name\config\config.ini` exists. Show us the config.
comment on: http://stackoverflow.com/q/47180075
score: 0
type: Comment

http://stackoverflow.com/q/47203904
tagged with: text
score: 0
has answer: http://stackoverflow.com/a/47204089
tagged with: python
tagged with: twitter
has body: I'm super desperate. I imported a long list of tweets that looks like this for each line: [29.5912325, -98.370464330000004] 6 2011-08-28 19:02:31 @AyLaTayLa let me guess wing stop lol" Each section in the tweet is separated by a tab (\t). Printing (d) and printing (x) works but the moment that I attempt to return dictlist, there's a string out of range error originating at line: if line[0] == '[': I've tried indenting at different points but I either get another error or dictlist just returns the first tweet. Help! from datetime import datetime dictlist = [] def make_tweets(): file_name = open('/users/s/Desktop/project/all_tweets.txt', 'r') file_name = file_name.readlines() file_name = [x.strip() for x in file_name] for line in file_name: if line[0] == '[': d ={} x = line.split("\t") x[0] = x[0].split(" ") x[0][0] = float(x[0][0].strip(",""[")) x[0][1] = float(x[0][1].strip("]")) x[2] = datetime.strptime('2011-08-28 19:02:28', '%Y-%m-%d %H:%M:%S') x[3] = x[3].lower() #print(x) d['latitude'] = x[0][0] d['longitude'] = x[0][1] d['time'] = x[2] d['text'] = x[3] dictlist.append(dict(d)) #printing d works but anything beyond that return dictlist make_tweets() When I print d, dictionaries look like this: {'latitude': 39.99230957, 'longitude': -75.13111973, 'time': datetime.datetime(2011, 8, 28, 19, 2, 28), 'text': '@_tweetthis what dorm r you in?'} {'latitude': 54.10410612, 'longitude': 28.33601993, 'time': datetime.datetime(2011, 8, 28, 19, 2, 28), 'text': '@andykozik круто !!!'} {'latitude': 19.47690987, 'longitude': -71.34471434, 'time': datetime.datetime(2011, 8, 28, 19, 2, 28), 'text': '@ninosh_flow jajajaj mi hermanasoooo'} SEE FOR ERROR IMAGE
has comment: http://stackoverflow.com/comment/81356395
type: Question
has comment: http://stackoverflow.com/comment/81356697
type: UnansweredQuestion
answer count: 1
has title: String index out of range on otherwise fine code (dictionary of tweets) - python

http://stackoverflow.com/q/47169151
accepted answer: http://stackoverflow.com/a/47169704
upvote count: 3
has answer: http://stackoverflow.com/a/47169704
answer count: 1
downvote count: 0
has body: I am trying to allow the user of my script to prompt users to enter the correct password if they have entered an invalid one. I am not sure whether this a psql configuration or if its done by using error handling with python. Which one do I use and how? My current code is as follows: backup_ps = subprocess.Popen( ['pg_dump','-h', ORIGIN_DB, '-U', ORIGIN_DB_USER, ORIGIN_DB_NAME, '-f', destination, '-c', '-t', 'table1', '-Fp', '--inserts'], stdout=subprocess.PIPE ) output = backup_ps.communicate()[0] # if password incorrect, prompt for correct password.
favorite count: 0
type: Question
has title: Multiple Password attempts pg_dump python
tagged with: python
tagged with: postgresql-9.3
type: AnsweredQuestion
tagged with: pg-dump
score: 3

http://stackoverflow.com/a/47948410
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47120509
has body: I have recently come across a very similar issue and from my personal experience I am pretty confident I was able to infer the answer to what you are asking even though I am not 100% sure. List item the shape changes because different data types have different lengths when encoded as byte lists and since a float16 has half the length of a float32 the same byte list can either be read as a sequence of n float32 values or as twice as many float16 values. In other words the byte list you are trying to decode doesn't change when you change data type but what does change is the partitions you make of this array list. You should check the data type of the the data you use to generate the tfrecord file with and use the same datatype to decode the byte_list when reading it (you can check the data type of a numpy array with the .dtype attribute). None that I can see but I may be wrong.
answers question: http://stackoverflow.com/q/47120509
type: Answer
has comment: http://stackoverflow.com/comment/82903581
score: 4
has comment: http://stackoverflow.com/comment/110851522
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47146718
has comment: http://stackoverflow.com/comment/81243765
has comment: http://stackoverflow.com/comment/81244299
has comment: http://stackoverflow.com/comment/81243748
has answer: http://stackoverflow.com/a/47146775
has comment: http://stackoverflow.com/comment/81244197
accepted answer: http://stackoverflow.com/a/47146792
has answer: http://stackoverflow.com/a/47146827
upvote count: 1
has answer: http://stackoverflow.com/a/47147395
has comment: http://stackoverflow.com/comment/81244257
favorite count: 0
has comment: http://stackoverflow.com/comment/81243783
type: Question
linked to: http://stackoverflow.com/q/10995172
possible better answer: http://stackoverflow.com/a/47146775
has comment: http://stackoverflow.com/comment/81243851
has comment: http://stackoverflow.com/comment/81243854
score: -3
has answer: http://stackoverflow.com/a/47146792
tagged with: python
tagged with: dictionary
has title: Function to check if N number of keys exist in a dictionary
has body: I am looking to create a function that will check if multiple keys are present in a dictionary and return a value that indicates which keys were present. I know I could write something like: def param_checker(parameters): if 'foo' in parameters: if 'bar' in parameters: if 'qux' in parameters: return 0 else: return 1 elif 'baz' in parameters: if 'qux' in parameters: return 2 else: return 3 else: return 4 elif 'quxx' in parameters: if 'bar' in parameters: return 5 elif 'qux' in parameters: if 'baz' in parameters: return 6 else: return 7 else: return 8 else: return 9 However, the above example is both messy and clunky. The complexity also scales with the number of parameters you need to check to return a value. For example, I needed 3 layers of if conditions to check the keys foo, bar, and qux. I know I could chain the if conditions inline, but it is still messy and clunky. This is somewhat similar to Python check if list of keys exist in dictionary. The big difference here is that instead of checking if they all exist or not, I am looking to return a value indicating what combination of keys exist. Note: I did not write out all possible combinations in the provided sample code, as that would be tedious when I am just trying to illustrate the problem. Below is a example of invoking the function to check which keys are present. d = dict() d['foo'] = 'blah' d['bar'] = 'blah' val = param_checker(d) # val represents a unique value indicating which keys are present in dictionary d I will know ahead of time what keys could be in the dictionary, so I can have some sort of list of possible keys, like: keys = ["foo", "bar", "baz", "qux", "quxx"] I am hoping to build a function that can check N keys and return a unique value indicating which ones where present. How can I efficiently do this?
answer count: 4
has comment: http://stackoverflow.com/comment/81244585
type: AnsweredQuestion
downvote count: 4

http://stackoverflow.com/a/47104770
accepted answer of: http://stackoverflow.com/q/47104354
has body: We can avoid creating the heavy meshgrids by directly working on the 1D arrays as a performance measure with array-initialization for the two output arrays and then broadcasted assignments for assigning the input arrays once as they are along the even-numbered places and flipped along the odd numbered ones. This gives us the zig-zag ordering. The implementation would be - def create_zigzag_grids(a,b): m,n = len(b), len(a) out1 = np.empty((m,n,2),dtype=int) out1[:,:,1] = b[:,None] out1[::2,:,0] = a out1[1::2,:,0] = a[::-1] out2 = np.empty((n,m,2),dtype=int) out2[:,:,0] = a[:,None] out2[::2,:,1] = b out2[1::2,:,1] = b[::-1] return out1.reshape(-1,2), out2.reshape(-1,2) Sample run - 1) Input and output : In [748]: a,b = np.array([1,2,3,4]), np.array([5,6,7]) ...: out1, out2 = create_zigzag_grids(a,b) ...: 2) Create meshgrid to verify our results : In [749]: xv, yv = np.meshgrid(a,b) In [750]: xv Out[750]: array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) In [751]: yv Out[751]: array([[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7]]) 3) Verify results : In [752]: out1 Out[752]: array([[1, 5], [2, 5], [3, 5], [4, 5], [4, 6], [3, 6], [2, 6], [1, 6], [1, 7], [2, 7], [3, 7], [4, 7]]) In [753]: out2 Out[753]: array([[1, 5], [1, 6], [1, 7], [2, 7], [2, 6], [2, 5], [3, 5], [3, 6], [3, 7], [4, 7], [4, 6], [4, 5]]) Runtime test Other approach(es) - def Psidom(a,b): # @Psidom's stack based soln xv, yv = np.meshgrid(a,b) xv[1::2] = xv[1::2,::-1] out1 = np.stack((xv, yv), axis=-1).reshape(-1, 2) yv[:,1::2] = yv[::-1, 1::2] out2 = np.stack((xv.T, yv.T), axis=-1).reshape(-1, 2) return out1, out2 Timings - In [829]: a = np.arange(100) ...: b = np.arange(100)+100 In [830]: %timeit Psidom(a,b) ...: %timeit create_zigzag_grids(a,b) 10000 loops, best of 3: 133 µs per loop 10000 loops, best of 3: 25.1 µs per loop In [831]: a = np.arange(1000) ...: b = np.arange(1000)+1000 In [832]: %timeit Psidom(a,b) ...: %timeit create_zigzag_grids(a,b) 10 loops, best of 3: 23.8 ms per loop 100 loops, best of 3…
upvote count: 3
score: 3
type: Answer
answers question: http://stackoverflow.com/q/47104354
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/81291703
has text: @MartinBeckett Is that feasible with openCV.. I am a bit doubtful.
type: Comment
comment on: http://stackoverflow.com/q/47154989
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81177455
has text: You mean `if ext in file_sigs[file.read(3)]: print('Matching extension:', ext)`. That works as well for me. I updated my answer
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47113097

http://stackoverflow.com/q/47087848
favorite count: 0
type: Question
tagged with: aggregation
score: -2
tagged with: python
type: AnsweredQuestion
has title: categorical data to be dummified and aggregated
tagged with: pandas
has body: I have the following dataset where X1 is the date of test done, X2 is the results of tests having 45 levels and x3 is the test name X1 X2 X3 20.04.2017 AA 1256(NB) 20.04.2017 AA 1257(NB) 20.04.2017 AA 1258(LM) 20.04.2017 LL 1257(NB) 23.07.2017 LL 1256(NB) 23.07.2017 LL 1258(LM) I am trying to transform the above data to Date X3 AA LL 20.04.2017 1256(NB) 1 1 20.04.2017 1257(NB) 1 1 20.04.2017 1258(LM) 1 0 23.07.2017 1258(LM) 0 1 I was able to create the dummy columns for AA &amp; LL using 'pd.get_dummies' but the aggregation on the basis of X3 column is not happening.
upvote count: 0
downvote count: 2
accepted answer: http://stackoverflow.com/a/47087971
answer count: 1
has answer: http://stackoverflow.com/a/47087971

http://stackoverflow.com/a/47189104
answers question: http://stackoverflow.com/q/47189031
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
has body: The most straightforward way is to use np.vstack: In [9]: arr = np.array([1,2,3]) In [10]: x = np.arange(20, 23) In [11]: arr = np.vstack([arr, x]) In [12]: arr Out[12]: array([[ 1, 2, 3], [20, 21, 22]]) Note, your entire approach has major code smell, doing the above in a loop will give you quadratic complexity. Perhaps you should work with a list and then convert to an array at the end (which will at least be linear-time). Or maybe rethink your approach entirely. Or, as you imply, you could pre-allocate your array: In [18]: result = np.zeros((10, 3)) In [19]: result Out[19]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]]) In [20]: result[0] = x In [21]: result Out[21]: array([[ 20., 21., 22.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])
accepted answer of: http://stackoverflow.com/q/47189031
type: Answer

http://stackoverflow.com/a/47208712
upvote count: 1
has comment: http://stackoverflow.com/comment/81369142
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47208509
has body: This is because you're replacing a with b first...so you have "bbb" and then replacing b with ab, so you get "ababab" here's the code you need: SRS = { 'a':'b', 'b':'ab'} script = "aba" script_replaced = "" for character in script: script_replaced += SRS[character] print(script) print(script_replaced) Note that we loop over each character in the string and replace with a match in the dictionary
downvote count: 0

http://stackoverflow.com/a/47114848
upvote count: 1
answers question: http://stackoverflow.com/q/47114800
score: 1
type: Answer
has body: Following one line should work for you tdf['Counterfeit_Weight'].fillna(p)
downvote count: 0

http://stackoverflow.com/a/63780771
upvote count: 4
downvote count: 0
has body: This would be more a more robust solution, as it can be used with Generic Views hassle free. Also, the checks in render() can be easily altered as per the needs (Eg., handling no-2XX in this solution). from rest_framework.renderers import JSONRenderer class CustomRenderer(JSONRenderer): def render(self, data, accepted_media_type=None, renderer_context=None): status_code = renderer_context['response'].status_code response = { "status": "success", "code": status_code, "data": data, "message": None } if not str(status_code).startswith('2'): response["status"] = "error" response["data"] = None try: response["message"] = data["detail"] except KeyError: response["data"] = data return super(CustomRenderer, self).render(response, accepted_media_type, renderer_context)
answers question: http://stackoverflow.com/q/47173483
type: Answer
score: 4

http://stackoverflow.com/q/47102954
has comment: http://stackoverflow.com/comment/81156356
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81156843
score: 0
has comment: http://stackoverflow.com/comment/81156472
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/47103123
type: Question
possible better answer: http://stackoverflow.com/a/47103125
answer count: 2
has answer: http://stackoverflow.com/a/47103123
has answer: http://stackoverflow.com/a/47103125
tagged with: python
has title: How can I write a zero-array in a csv file in python?
has body: I would like to write a csv file in Python 3 with the following format: "index, 0". E.g.: 0, 0 1, 0 2, 0 3, 0 ... I have written the following: csv_file_object = csv.writer(open('file.csv', 'w', newline='')) Y=np.zeros(2508, dtype=int) for index, y_aux in enumerate(Y): csv_file_object.writerow([index, y_aux]) However, when I have opened the csv file, I can see: 0 1 2 3 ... How can I solve this? Thank you.

http://stackoverflow.com/comment/81197371
type: AnswerComment
comment on: http://stackoverflow.com/a/47123654
score: 0
has text: This is what I needed! Thanks for the quick, simple, and working answer!
type: Comment

http://stackoverflow.com/a/47116893
has comment: http://stackoverflow.com/comment/81183951
has body: You can try this: firstList = ['Product1,item,,description,price|', 'Product2,item,,description,price|','Product3,item,,description,price|'] secondList = secondList = 'Product4,item,,description,price' final_list = ''.join(firstList+[secondList[0]+"|"]) if isinstance(secondList, list) else ''.join(firstList+[secondList+"|"]) Output: 'Product1,item,,description,price|Product2,item,,description,price|Product3,item,,description,price|Product4,item,,description,price|'
has comment: http://stackoverflow.com/comment/81184793
has comment: http://stackoverflow.com/comment/81184179
type: Answer
has comment: http://stackoverflow.com/comment/81184739
has comment: http://stackoverflow.com/comment/81183970
accepted answer of: http://stackoverflow.com/q/47116871
score: 2
has comment: http://stackoverflow.com/comment/81184107
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81184130
answers question: http://stackoverflow.com/q/47116871
type: AcceptedAnswer

http://stackoverflow.com/a/47107916
downvote count: 0
has body: As others have said, that's a dictionary comprehension, which isn't available in Python 2 until version 2.7. In Python 2.5 and later you can use a generator expression inside the dict constructor: self._sensitive_ids = dict((xmr, self.parser.get_id(xmr)) for xmr in self.sensitive) In Python 2.4, you can use a list comprehension inside the dict constructor: self._sensitive_ids = dict([(xmr, self.parser.get_id(xmr)) for xmr in self.sensitive]) Actually, you can also use the generator expression version in Python 2.4. I'm a little hazy, it's a while since I used 2,4. ;) You can read about list comprehensions in the official tutorial.
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81166302
type: Answer
accepted answer of: http://stackoverflow.com/q/47107818
answers question: http://stackoverflow.com/q/47107818
type: AcceptedAnswer

http://stackoverflow.com/comment/81323407
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47187069
has text: @AbdurahmanHijazi don't use `\n` as well, `line` is already stripped of `\n` I think

http://stackoverflow.com/a/47196950
score: 0
type: Answer
type: AcceptedAnswer
has body: Why not plot directly in matplotlib? import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.DataFrame(np.random.randn(120), columns=list('A')) data['sig'] = np.NaN data['sig'] = np.where((data['A'] &gt; 1), data['A'], data['sig'] ) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(data["A"]) ax.scatter(data.index, data["sig"])
accepted answer of: http://stackoverflow.com/q/47196669
answers question: http://stackoverflow.com/q/47196669

http://stackoverflow.com/a/47157659
answers question: http://stackoverflow.com/q/47091374
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: When you use Start Process, each argument that you would use on a command line needs to be an argument in robot. For example, if you would type appium -p 4723 on the command line, then in robot you would do: Start process appium -p 4723 (note: there are two spaces between "process", "appium", "-p", and "4723") When you do this, robot will look through the folders in your PATH environment variable in order to find a program named "appium" (or "appium.exe" on windows). If you get the error "cannot find the file specified" that usually means that the program you're trying to run isn't in a folder in your PATH. It could also mean that the program isn't installed, or that you misspelled the app name, but I'm assuming neither of those are true in this case. The simplest solution is to find where the appium executable is, and then use the full and complete path as the first argument to Run Process (eg: Run Process C:/the/path/to/appium.exe -p 4723)

http://stackoverflow.com/q/47144092
has comment: http://stackoverflow.com/comment/81238244
favorite count: 0
type: Question
tagged with: django
tagged with: python
has title: Django BooleanField doesn't work on edit form
has comment: http://stackoverflow.com/comment/81254165
has body: My situation: Models.py class Box(models.Model): is_empty = models.BooleanField(default=False) upload_date = models.DateTimeField(auto_add_now=True) Forms.py class BoxForm(forms.ModelForm): class Meta: model = Box fields = (is_empty,) Views.py def edit_box(request, pk): box = get_object_or_404(Box, pk=pk) if request.method == 'POST': form = BoxForm(request.POST, instance=box) if form.is_valid(): form.save() return redirect('home') else: form = BoxForm(instance=box) return render(request, 'form.html', {'form': form}) The problem is that when I enter into the template form and I want to change checkbox value I can't do it, it seems disabled and I dan't know why. EDIT Template.html ... {% csrf_token %} {% render_field form.is_empty class="form-control" %} Is empty? Save ...
has comment: http://stackoverflow.com/comment/81238297
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/47160606
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81242450

http://stackoverflow.com/comment/81228304
type: Comment
type: QuestionComment
score: 0
has text: ([None,None,None,3],[None,5]) and (tf.TensorShape([None,None,None,3]),tf.TensorShape([None,5])) results in a TypeError. Seems it tries to treat entries as int and if that fails it expects int64 and not list or TensorShape.
comment on: http://stackoverflow.com/q/47103249

http://stackoverflow.com/comment/81286821
comment on: http://stackoverflow.com/q/47168022
type: Comment
type: QuestionComment
has text: I have not. I thought about using the html5 one or lxml. do you have any suggestions on which would be best to employ here?
score: 0

http://stackoverflow.com/comment/81332850
has text: I spent the day rewritting my code and somehow the problem was fixed. The memory problem is gone, even though I don't know what I did that fixed it...
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47169253

http://stackoverflow.com/comment/81335698
has text: Packages don't necessarily have an `__init__.py` file, and modules aren't necessarily `.py` files.
type: Comment
type: AnswerComment
score: 6
comment on: http://stackoverflow.com/a/47193123

http://stackoverflow.com/comment/97867997
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47072050
type: QuestionComment
has text: As suggested in https://github.com/tensorflow/tensorflow/issues/1962#issuecomment-211505577, try to use `write_meta_graph=False` while saving

boto3
tags question: http://stackoverflow.com/q/47182750
tag name: boto3
tags question: http://stackoverflow.com/q/47194919
tags question: http://stackoverflow.com/q/47210957
tags question: http://stackoverflow.com/q/47146493
tags question: http://stackoverflow.com/q/47088045
tags question: http://stackoverflow.com/q/47208770
tags question: http://stackoverflow.com/q/47206395
tags question: http://stackoverflow.com/q/47147780
tags question: http://stackoverflow.com/q/47111787
type: Tag
tags question: http://stackoverflow.com/q/47100393
tags question: http://stackoverflow.com/q/47078310
tags question: http://stackoverflow.com/q/47214812

http://stackoverflow.com/comment/81116650
score: 0
comment on: http://stackoverflow.com/q/47083655
type: Comment
type: QuestionComment
has text: I don't believe it is. However I don't want to download the image. I just want the url to be exported to a file and all url's need to go to a file

http://stackoverflow.com/q/47065429
tagged with: python
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81079370
has answer: http://stackoverflow.com/a/47075578
tagged with: sqlalchemy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81089662
has title: SQLAlchemy Expression Language first or one
has body: I'm using the sqlalchemy expression language (i.e. Core). I'm trying to build a query that should only return one result. I want to do query = select([table]).where(cond).one() or query = select([table]).where(cond).first() but that only yields AttributeError: 'Select' object has no attribute 'one' The closest I have come is query = select([table]).where(cond).limit(1) but that is not entirely satisfactory because I get a list of results where I want a single result. I can work around by inserting extra logic but I'd be much happier to find a way to do this cleanly. I also would prefer not to use plain text queries. Any ideas? Much appreciated.
type: UnansweredQuestion

numpy
tags question: http://stackoverflow.com/q/47160523
tags question: http://stackoverflow.com/q/47138318
tags question: http://stackoverflow.com/q/47113979
tags question: http://stackoverflow.com/q/47216388
tags question: http://stackoverflow.com/q/47139917
tags question: http://stackoverflow.com/q/47094930
tags question: http://stackoverflow.com/q/47138133
tags question: http://stackoverflow.com/q/47100903
tags question: http://stackoverflow.com/q/47202016
tags question: http://stackoverflow.com/q/47082071
tags question: http://stackoverflow.com/q/47085374
tags question: http://stackoverflow.com/q/47097607
tags question: http://stackoverflow.com/q/47071235
tags question: http://stackoverflow.com/q/47208361
tags question: http://stackoverflow.com/q/47119332
tags question: http://stackoverflow.com/q/47210256
tags question: http://stackoverflow.com/q/47121741
tags question: http://stackoverflow.com/q/47065677
tags question: http://stackoverflow.com/q/47188932
tags question: http://stackoverflow.com/q/47135132
tags question: http://stackoverflow.com/q/47089645
tags question: http://stackoverflow.com/q/47146768
tags question: http://stackoverflow.com/q/47167678
tags question: http://stackoverflow.com/q/47124007
tags question: http://stackoverflow.com/q/47213847
tags question: http://stackoverflow.com/q/47088896
tags question: http://stackoverflow.com/q/47208473
tags question: http://stackoverflow.com/q/47220616
tags question: http://stackoverflow.com/q/47110235
tags question: http://stackoverflow.com/q/47108981
tags question: http://stackoverflow.com/q/47115025
tags question: http://stackoverflow.com/q/47091818
tags question: http://stackoverflow.com/q/47100559
tags question: http://stackoverflow.com/q/47223071
tags question: http://stackoverflow.com/q/47186313
tags question: http://stackoverflow.com/q/47189031
tags question: http://stackoverflow.com/q/47147647
tags question: http://stackoverflow.com/q/47135539
tags question: http://stackoverflow.com/q/47085925
tags question: http://stackoverflow.com/q/47123602
tags question: http://stackoverflow.com/q/47186962
tags question: http://stackoverflow.com/q/47178086
tags question: http://stackoverflow.com/q/47106112
tags question: http://stackoverflow.com/q/47129819
tags question: http://stackoverflow.com/q/47166551
tags question: http://stackoverflow.com/q/47142323
tags question: http://stackoverflow.com/q/47073936
tags question: http://stackoverflow.com/q/47163732
tags question: http://stackoverflow.com/q/47165446
tags question: http://stackoverflow.com/q/47066197
tags question: http://stackoverflow.com/q/47119693
tags question: http://stackoverflow.com/q/47087099
tags question: http://stackoverflow.com/q/47181660
tags question: http://stackoverflow.com/q/47144096
tags question: http://stackoverflow.com/q/47179799
tags question: http://stackoverflow.com/q/47155550
tags question: http://stackoverflow.com/q/47121045
tags question: http://stackoverflow.com/q/47175128
tags question: http://stackoverflow.com/q/47112308
tags question: http://stackoverflow.com/q/47104306
tags question: http://stackoverflow.com/q/47080410
tags question: http://stackoverflow.com/q/47171944
tags question: http://stackoverflow.com/q/47120159
tags question: http://stackoverflow.com/q/47077290
tags question: http://stackoverflow.com/q/47106678
tags question: http://stackoverflow.com/q/47196133
tags question: http://stackoverflow.com/q/47108441
tags question: http://stackoverflow.com/q/47218811
tags question: http://stackoverflow.com/q/47104354
tags question: http://stackoverflow.com/q/47139515
tags question: http://stackoverflow.com/q/47207243
tags question: http://stackoverflow.com/q/47114360
tags question: http://stackoverflow.com/q/47162048
tags question: http://stackoverflow.com/q/47110381
tags question: http://stackoverflow.com/q/47207023
tags question: http://stackoverflow.com/q/47167305
type: Tag
tags question: http://stackoverflow.com/q/47188054
tags question: http://stackoverflow.com/q/47141980
tags question: http://stackoverflow.com/q/47068468

http://stackoverflow.com/comment/81399282
type: Comment
comment on: http://stackoverflow.com/a/47223353
type: AnswerComment
score: 0
has text: Yes, this is the desirable result.

http://stackoverflow.com/a/47124352
score: 0
has body: Your previous question and code: Fully customized Python Help Usage With import par as pp, the all variables, classes and functions defined in that module have to be accessed with the pp. prefix. Thus pp.parser is the parser object that was created on import. pp.preq is one of the argument groups. pp.USAGEformat is the custom formatter class. But a formatter, an object of this class is not created when the parser is created nor when par is imported. A formatter is created from the specified class when you ask for help or usage ('-h', pp.parser.print_help()). (edit) This was wrong: This formatter will take globals variables like version and prog from the current namespace (the importing one), not the pp one. The formatter still takes version from the imported namespace. But I can change that with: pp.version = '3.0' (see my edit in https://stackoverflow.com/a/47118317/901925) You can test this behavior in pre itself by changing version at the end of the file and doing a new print_help(). You'll see a change in the display. pp.parser on the other hand is created on import. You could modify pp.parser.description, the attribute that was set on creation. Setting or changing pp.description doesn't do it. When you do parser.print_help(), it calls parser.format_help, which in turn calls parser._get_formatter. That method uses parser.formatter_class to create a formatter object, which is then 'filled' and 'executed'. There's a lot of flexibility in this approach, but it can be confusing.
type: Answer
answers question: http://stackoverflow.com/q/47119468

http://stackoverflow.com/q/47190746
has body: I want to create 2 GMapPlots in the same plot (HTML) object on separate Tab Panes, but when I click on my second tab then no Google Map nor my little circles are displayed. The whole area of the plot is grey and the "Google" logo is displayed in the bottom-left corner, but there is no Map. My title of my tab-plots are change correctly when I click on the tabs, and the hover objects are displayed correctly on both plots. I created the 2 plots in a for cycle using the same data source, so all the code is the same, expect the data values (GPS coordinates) that differ. I have a column that can only have 2 values that define the exact data source (the rows) of each plot. If I filter out the rows of my first plot in the line of for cycle code, then my "original second" plot appears correctly. So in this case I have only 1 tab, that has actually the "second" plot of my original 2-tab plot and it is displayed correctly in this case (without an other map on other tab). So it looks like that GMapPlot can be used only for 1 plot in the same plot (HTML) object. Is it true? 1) Of course, if I make the separate bokeh HTML objects (without Tab Panes) then both Maps (and the circles) are displayed correctly. 2) If I create e.g. 2 bar charts in the same plot object (same HTML file) on separate Tab Panes then both charts are displayed correctly. So does anybody know what the problem could be and how to solve it? Thank you!!!
type: Question
tagged with: google-maps
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: widget
accepted answer: http://stackoverflow.com/a/47206173
answer count: 1
has title: Python bokeh GMapPlot on Tab Pane widgets
has answer: http://stackoverflow.com/a/47206173
tagged with: bokeh

http://stackoverflow.com/q/47085527
has comment: http://stackoverflow.com/comment/81121784
tagged with: api
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81123622
has comment: http://stackoverflow.com/comment/81122044
has body: I've got a strange problem. I'm using one of EBI SOAP services and I'm running three iterations. At first iteration I have no problem in running my code because variable 'selectedHits' is empty. At the end of first iteration I update variable 'selectedHits' and then change it to binary form and then to base64 format (because this variable must be in base64 format). This is a part of my code: jobID=''; selectedHits='' for e in range(1,4): inputparam = client.factory.create('InputParameters') inputparam.scores=5 inputparam.alignments=5 inputparam.previousjobid = jobID inputparam.selectedHits = selectedHits response = client.service.run('Info@gmail.com',name,inputparam) jobID=response selectedHits=str(base64.b64encode(bytes(selectedHits, 'utf-8')),'utf-8') #print(selectedHits) #print(response) Imagine that our new selectedHits is as follows: b'U1A6RlJEQ19FQ09MSQpTUDpGUkRDX1NISURTClRSOkQyVE1CM19DSVRSSQpTUDpGUkRDX1NBTFRZClRSOkQ0QkZKMV85RU5UUgo=' when I use this new 'selectedHits' at the second iteration, instead of getting the result I get 'Info@gmail.com' repeatedly!!! when I manually eliminate character 'b' at the first part of this new 'selectedHits', I'll get result. When I try to eliminate character 'b' automatically by different ways (here by using the following code): selectedHits=str(base64.b64encode(bytes(selectedHits, 'utf-8')),'utf-8') , I mostly don't get the result and I'll get error (In summary as follows): ValueError: invalid literal for int() with base 16: b'' http.client.IncompleteRead: IncompleteRead(0 bytes read) raise IncompleteRead(b''.join(value)) http.client.IncompleteRead: IncompleteRead(5228 bytes read) I'm confused and don't know exactly what to do. When I eliminate 'b' automatically, I don't get the result. When I retain this 'b' character, I don't get the result too!! just by eliminating the character by hand and using the following value for selectedHits, I'll get the answer: 'U1A6RlJEQ19FQ09MSQpTUDpGUkRDX1NISURTClRSOkQyVE1CM19DSVRSSQpTUDpGUk…
has answer: http://stackoverflow.com/a/47094095
tagged with: base64
tagged with: python
has comment: http://stackoverflow.com/comment/81122919
has comment: http://stackoverflow.com/comment/81121437
has comment: http://stackoverflow.com/comment/81121682
score: 0
has comment: http://stackoverflow.com/comment/81123106
has comment: http://stackoverflow.com/comment/81121578
has comment: http://stackoverflow.com/comment/81123244
answer count: 1
has comment: http://stackoverflow.com/comment/81121534
tagged with: soap
has comment: http://stackoverflow.com/comment/81123387
has comment: http://stackoverflow.com/comment/81121996
has comment: http://stackoverflow.com/comment/81123755
has title: Geting rid of extra 'b' in changing binary format to base64
has comment: http://stackoverflow.com/comment/81121857
type: Question
has comment: http://stackoverflow.com/comment/81123292
tagged with: binary

http://stackoverflow.com/q/47104898
has comment: http://stackoverflow.com/comment/81160351
has comment: http://stackoverflow.com/comment/81160402
tagged with: python
tagged with: continue
has comment: http://stackoverflow.com/comment/81160505
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81160326
has comment: http://stackoverflow.com/comment/81160469
has answer: http://stackoverflow.com/a/47105018
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81160531
has title: Python with 2 continue in a while
has comment: http://stackoverflow.com/comment/81160357
favorite count: 0
has body: I tried exception handling and got stuck in my first program, in this program my first continue in while is working but 2nd one is not continuing the loop print("hello to divide") o = "y" while o == "y": try: x = int(input("enter first no. = ")) y = int(input("enter second no. = ")) except: print("please enter numeric value") continue try: z = x/y print(str(x) +"/"+str(y)+"="+str(z)) except: print("please do not divide with 0(zero)") continue finally: o = input("do you want to do it again (y/n)? = ") The second except is working fine but after printing message it jumps to finally statement please help ???
type: Question
has comment: http://stackoverflow.com/comment/81160339
tagged with: while-loop
accepted answer: http://stackoverflow.com/a/47105018
tagged with: exception

http://stackoverflow.com/a/47075690
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47074894
score: 2
has body: Here's one using the correlation defintion with NumPy tools meant for performance with corr2_coeff_rowwise - pd.Series(corr2_coeff_rowwise(dfa.values,dfb.values)) Sample run - In [74]: dfa Out[74]: a b c d 0 2.0 6.0 8.0 12.0 In [75]: dfb Out[75]: a b c d 0 2 6 8 12 1 1 3 4 6 2 -1 -3 -4 -6 In [76]: pd.Series(corr2_coeff_rowwise(dfa.values,dfb.values)) Out[76]: 0 1.0 1 1.0 2 -1.0 dtype: float64 Runtime test Case #1 : Large number of rows in dfb and 4 columns - In [77]: dfa = pd.DataFrame(np.random.randint(1,100,(1,4))) In [78]: dfb = pd.DataFrame(np.random.randint(1,100,(30000,4))) # @sera's soln In [79]: %timeit dfb.corrwith(dfa.iloc[0], axis=1) 1 loop, best of 3: 4.09 s per loop In [80]: %timeit pd.Series(corr2_coeff_rowwise(dfa.values,dfb.values)) 1000 loops, best of 3: 1.53 ms per loop Case #2 : Decent number of rows in dfb and 400 columns - In [83]: dfa = pd.DataFrame(np.random.randint(1,100,(1,400))) In [85]: dfb = pd.DataFrame(np.random.randint(1,100,(300,400))) In [86]: %timeit dfb.corrwith(dfa.iloc[0], axis=1) 10 loops, best of 3: 44.8 ms per loop In [87]: %timeit pd.Series(corr2_coeff_rowwise(dfa.values,dfb.values)) 1000 loops, best of 3: 635 µs per loop

http://stackoverflow.com/a/48216678
downvote count: 0
type: Answer
score: 19
has body: Yes, you can use the plutil command to check the syntax of property list files. In your case: $ plutil test.plist test.plist: Encountered unknown tag Key on line 14 That means your Key tag should be lowercase, so it should be key.
upvote count: 19
answers question: http://stackoverflow.com/q/47124312
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47124312

http://stackoverflow.com/q/47156126
has comment: http://stackoverflow.com/comment/81261875
has comment: http://stackoverflow.com/comment/81261591
has comment: http://stackoverflow.com/comment/81261695
has title: Get all strings with same beginning and end and any number of the same letter in between
type: UnansweredQuestion
score: -3
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/81261688
tagged with: pandas
upvote count: 0
has body: I want to search in text for words that have the same start and end letter and any number of the same letter in between (should also be case-insensitive) e.g. lol, lool, Loool, loooooool etc. should all be captured. I want to filter a Pandas dataframe for these words. e.g. df[df.message.str.contains('lol', case=False)]
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/47156325
has comment: http://stackoverflow.com/comment/81261735
has comment: http://stackoverflow.com/comment/81261619
favorite count: 0
type: Question

http://stackoverflow.com/comment/81375784
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47213086
has text: Did you try going back to the beginning of `matrix_reader`?

http://stackoverflow.com/comment/81158954
comment on: http://stackoverflow.com/q/47101836
has text: @ImportanceOfBeingErnest Thank you for the links. The first one is new to me. I will check it out. The second one I have found as well but it did not help me. However, I will look at it again. So far, anything I have tried didn't satisfy at least one of the requirements mentioned in my updated question.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81204477
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/47127112
has text: `df.iloc[0]` is a better way to get the first row of a dataframe, because it gets the first row by position. By contrast, `df.loc[0]` gets the row with an index of 0, which happens to be the first row in the question, but it won't work in general.

http://stackoverflow.com/comment/94068825
type: AnswerComment
comment on: http://stackoverflow.com/a/47158368
type: Comment
has text: How did you do that?
score: 0

http://stackoverflow.com/q/47120247
tagged with: path
downvote count: 0
answer count: 1
has title: Use linux style path when calling python on Windows with bash
has body: I'm using git bash to run a python script that calls some Linux tools (scp, ssh) on Windows. My python script takes a path as a parameter. However, when calling os.path.join to do some operation on that path, the returned value is a windows-formatted path (back slashes). Passing that path to the scp or ssh tools fails or does not behave properly. Is there any easy way to 'force' Linux path style in python 3 ?
tagged with: bash
type: AnsweredQuestion
tagged with: windows
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/47120353
type: Question
upvote count: 2
score: 2
has answer: http://stackoverflow.com/a/47120353

http://stackoverflow.com/comment/81169183
comment on: http://stackoverflow.com/q/47109319
type: Comment
score: 0
has text: And if you do, walking over the csv file won't bring much...
type: QuestionComment

http://stackoverflow.com/a/47069581
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47069525
type: Answer
answers question: http://stackoverflow.com/q/47069525
has body: In django id field is by default the pk hence you can use both. Difference: But you can manually set pk and then it may not be id field
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/47211186
has answer: http://stackoverflow.com/a/47212404
type: AnsweredQuestion
tagged with: api
score: 0
tagged with: web-scraping
answer count: 1
has title: Getting the buy price amount and only the buy price amount from Coinbase API
type: Question
has comment: http://stackoverflow.com/comment/81371900
tagged with: coinbase-api
tagged with: python
has comment: http://stackoverflow.com/comment/81372292
has comment: http://stackoverflow.com/comment/81374210
accepted answer: http://stackoverflow.com/a/47212404
has body: I am messing around with Coinbase's API using Python. When trying to print out the buy price for BTC, I write: client.get_buy_price() Which is great, but it returns: "amount": "7272.19", "base": "BTC", "currency": "USD" Is there anyway that I can just get the amount only (7272.19)?

http://stackoverflow.com/q/47142536
has body: I want create a snake game. My first objective is to create an asterisk which can move from top to bottom without pressing any key, simulating the snake 'moving'. What should I add in my code so that * moves in the console without printing the number of times loop runs. My code so far is: import time i=0 while (i&lt;5): print "*" time.sleep(0.5) i+=1
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: linux
has title: How to clear screen at previous point in python 2 program creating snake game?
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/81235789
accepted answer: http://stackoverflow.com/a/47143116
answer count: 1
has answer: http://stackoverflow.com/a/47143116
upvote count: 1

http://stackoverflow.com/q/47151241
type: Question
type: AnsweredQuestion
tagged with: python
tagged with: debian
has answer: http://stackoverflow.com/a/47151353
accepted answer: http://stackoverflow.com/a/47151353
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has title: How to exclude a specific message from stdout when using apt in python script?
has body: I get this message: "WARNING: apt does not have a stable CLI interface. Use with caution in scripts." In a simple script that does process = subprocess.Popen(['apt', 'upgrade', '-y'], stdout=subprocess.PIPE) How can I remove that annoying warning when running apt from python subprocess? I don't mind the rest of the output, I only want to get rid of the warning. Edit: I'm iterating though the output so that I can get live output from apt. How can I remove it from there? with open('test.log', 'w') as f: process = subprocess.Popen(['apt', 'upgrade', '-y'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) for line in iter(process.stdout.readline, ''): sys.stdout.write(line) f.write(line)
favorite count: 0

http://stackoverflow.com/q/47097293
has answer: http://stackoverflow.com/a/67673377
has comment: http://stackoverflow.com/comment/81145767
has comment: http://stackoverflow.com/comment/81145792
has comment: http://stackoverflow.com/comment/81145360
type: AnsweredQuestion
score: 36
downvote count: 0
has comment: http://stackoverflow.com/comment/81150663
has comment: http://stackoverflow.com/comment/81145290
has answer: http://stackoverflow.com/a/52910576
has answer: http://stackoverflow.com/a/47098446
has comment: http://stackoverflow.com/comment/81145172
has comment: http://stackoverflow.com/comment/81146075
answer count: 4
favorite count: 0
type: Question
has title: Django: Best way to merge migrations conflicts
upvote count: 36
has comment: http://stackoverflow.com/comment/81150840
has answer: http://stackoverflow.com/a/62810889
tagged with: django-migrations
possible better answer: http://stackoverflow.com/a/62810889
has comment: http://stackoverflow.com/comment/81145980
accepted answer: http://stackoverflow.com/a/52910576
tagged with: django
has body: I'm currently working on a dev branch and I will need to merge it to master one day. I have up to 20 migrations files on my dev branch and about the same number on master at the moment. I needed to make migrations on both branches which will result in migrations having the same prefix, (ex 0003_auto) In other words, if you have migrations files generated by makemigrations with the same prefix, what is the best/secure way of handling this. Here are two ways I have figured myself (maybe entirely wrong): Deleting all migrations files, merge the code and then running a fresh makemigrations and migrate which will result in only one migration file. Using the --merge flag to let django make the merge: makemigrations --merge Now, knowing all this I'd like to know what is the best way of handling this. In general, what should I use that will correctly merge conflicts and get me a fresh version of my project with every model updates. EDIT I think providing a step by step solution would be ideal for me and future users since there exists tons of informations on the subject but not one seems to be concise and clear.
tagged with: python
has comment: http://stackoverflow.com/comment/81150700

http://stackoverflow.com/q/47165783
has body: I have come across this example from Python hitchhikers guide: def create_multipliers(): return [lambda x, i=i : i * x for i in range(5)] The example above is the solution to some issues caused with late binding, where variables used in closures are looked up at the time the inner function is called. What does the i=i mean and why is it making such difference?
linked to: http://stackoverflow.com/q/7546285
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/12423614
answer count: 2
has comment: http://stackoverflow.com/comment/81281818
score: 5
linked to: http://stackoverflow.com/q/1132941
has comment: http://stackoverflow.com/comment/81286543
has comment: http://stackoverflow.com/comment/81281337
has comment: http://stackoverflow.com/comment/81281911
has comment: http://stackoverflow.com/comment/81281999
downvote count: 0
tagged with: lambda
favorite count: 0
has title: What does i=i mean, when creating a lambda in python?
type: Question
has comment: http://stackoverflow.com/comment/81282006
linked to: http://stackoverflow.com/q/2295290
has comment: http://stackoverflow.com/comment/81282019
possible better answer: http://stackoverflow.com/a/47165862
upvote count: 5
accepted answer: http://stackoverflow.com/a/47166432
tagged with: python
has answer: http://stackoverflow.com/a/47165862
has answer: http://stackoverflow.com/a/47166432

http://stackoverflow.com/q/47106218
tagged with: odoo
score: 1
tagged with: odoo-8
has answer: http://stackoverflow.com/a/53062541
has comment: http://stackoverflow.com/comment/81164090
possible better answer: http://stackoverflow.com/a/47107963
has comment: http://stackoverflow.com/comment/81163990
has comment: http://stackoverflow.com/comment/81166439
has answer: http://stackoverflow.com/a/47107963
has comment: http://stackoverflow.com/comment/81164039
favorite count: 0
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81172742
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81164005
has comment: http://stackoverflow.com/comment/81164065
has title: AttributeError: 'bool' object has no attribute '_fields' - Odoo v8
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/53062541
has comment: http://stackoverflow.com/comment/81164020
has body: I'm just adding some related fields to my model, some other fields work, but for this model they just won't, these are my models: class book_block(models.Model): _name = 'book.block' name = fields.Char(string="Name") code = fields.Char(string="Code", size=11) size_code = fields.Many2one('bsi.book.block.size', string="Size") text_paper = fields.Many2one('text.paper', string="Text Paper") n_pages_one_color = fields.Integer(string="N° of pages 1 color") adnl_n_pages_one_color = fields.Integer(string="Additional N° of pages one color") class mrp_worksheet_contract(models.Model): _name = 'mrp.worksheet.contract' @api.model def create(self, vals): if vals.get('name', 'New') == 'New': vals['name'] = self.env['ir.sequence'].next_by_code('mrp.worksheet.contract') or '/' return super(mrp_worksheet_contract, self).create(vals) name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New') date = fields.Date(string="Date") book_block = fields.Many2one('book.block', string="Book Block") n_pages_one_color = fields.Integer(string="N of pages one color", related="book_block.n_pages_one_color") adnl_n_pages_one_color = fields.Integer(string="Additional N° of pages one color", related="book_block.adnl_n_pages_one_color") The book_block field is okay, the issue comes with n_pages_one_color and adnl_n_pages_one_color fields, it throws me: Traceback (most recent call last): File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 546, in _handle_exception File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 583, in dispatch File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 319, in _call_function File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\service\model.py", line 118, in wrapper File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 316, in checked_call File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", lin…
has comment: http://stackoverflow.com/comment/81164129
has comment: http://stackoverflow.com/comment/81504402

http://stackoverflow.com/comment/81294412
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47172373
has text: https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences
score: 0

http://stackoverflow.com/comment/81311308
has text: It gives `sre_constants.error: bad character range`
type: Comment
comment on: http://stackoverflow.com/a/47181204
type: AnswerComment
score: 0

http://stackoverflow.com/q/47212459
answer count: 3
type: UnansweredQuestion
downvote count: 0
has title: Automating Comparison of Word Documents Using Python
has answer: http://stackoverflow.com/a/53421731
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/53707123
tagged with: win32com
upvote count: 5
tagged with: pywin32
tagged with: python
has body: I am trying to use win32com(pywin32) and Microsoft Word's Object Model to Compare two Word Documents(Automating the task of Comparing two documents in Microsoft word under Review->Compare). Following is the code I have written for this: import win32com.client Application=win32com.client.gencache.EnsureDispatch("Word.Application") Document=Application.Documents.Add() Application.CompareDocuments("Original.docx","Revised.docx") But I am getting the following error: Traceback (most recent call lastFile "&lt;pyshell#9&gt;", line 1, in &lt;module&gt; Application.CompareDocuments("Original.docx","Revised.docx") File "C:\Python36\lib\site-packages\win32com\gen_py\00020905-0000-0000-C000-000000000046x0x8x6\_Application.py", line 79, in CompareDocuments , CompareFields, CompareComments, CompareMoves, RevisedAuthor, IgnoreAllComparisonWarnings File "C:\Python36\lib\site-packages\win32com\client\__init__.py", line 466, in _ApplyTypes_ return self._get_good_object_(self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),user, resultCLSID) TypeError: The Python instance can not be converted to a COM object I am not able to understand why this error is being thrown. I really want to resolve this issue.Please help. Thanks in Advance
has answer: http://stackoverflow.com/a/49115304
tagged with: ms-word
score: 5

http://stackoverflow.com/comment/81138441
type: AnswerComment
comment on: http://stackoverflow.com/a/47093980
has text: Same as in my project but i copy pasted like this.
type: Comment
score: 0

http://stackoverflow.com/comment/81241085
comment on: http://stackoverflow.com/q/47144624
score: 0
has text: Don't use the system Python for this. You should be using [Virtualenv](https://virtualenv.pypa.io/en/stable/) to create isolated Python environments.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47143836
downvote count: 0
has answer: http://stackoverflow.com/a/75111767
score: 89
answer count: 6
possible better answer: http://stackoverflow.com/a/54406915
accepted answer: http://stackoverflow.com/a/47144000
has answer: http://stackoverflow.com/a/76940599
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47144000
has answer: http://stackoverflow.com/a/54406915
tagged with: pandas
has body: Hi: I am trying to use the Pandas DataFrame.to_csv method to save a dataframe to a csv file: filename = './dir/name.csv' df.to_csv(filename) However I am getting the error: IOError: [Errno 2] No such file or directory: './dir/name.csv' Shouldn't the to_csv method be able to create the file if it doesn't exist? This is what I am intending for it to do.
tagged with: python
upvote count: 89
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/68328949
has answer: http://stackoverflow.com/a/77144783
has title: Pandas DataFrame.to_csv raising IOError: No such file or directory

http://stackoverflow.com/comment/81176966
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47069667
has text: I'd use `strace` to trace system calls to see which terminfo directory it actually tried using.
score: 0

http://stackoverflow.com/q/47089368
has title: Python Script Errors
downvote count: 0
has comment: http://stackoverflow.com/comment/81128046
score: 1
upvote count: 1
has body: I am doing a simple Python script in Maya, and I'm constantly getting syntax errors. What needs to be changed in my script? select = ls(sl) if (len(sel) == 0): error("Nothing was selected.") else: rotate - relative 1 2 3 scale - relative 4 5 6 translate - relative 7 8 9
has comment: http://stackoverflow.com/comment/81128018
tagged with: maya
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47090127
has comment: http://stackoverflow.com/comment/81128204
type: UnansweredQuestion
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81129684

http://stackoverflow.com/comment/81161164
type: Comment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/158196/discussion-between-offeltoffel-and-prokhozhii).
type: AnswerComment
comment on: http://stackoverflow.com/a/47096657
score: 0

http://stackoverflow.com/a/47172838
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/81320239
has body: Url you trying to load (http://kivy.org/logos/kivy-logo-black-64.png) redirects on url with https protocol (just load it in browser to see). To load urls with https on Android you should build your apk with OpenSSL support. On Python 2 it can be achieved with adding openssl in buildozer's requirements. I'm not sure if it'll work with python3crystax.
answers question: http://stackoverflow.com/q/47168094
downvote count: 0
has comment: http://stackoverflow.com/comment/81296637

http://stackoverflow.com/q/47199782
has comment: http://stackoverflow.com/comment/81348128
has answer: http://stackoverflow.com/a/47199933
has comment: http://stackoverflow.com/comment/81350822
answer count: 1
tagged with: os.system
has comment: http://stackoverflow.com/comment/81350941
has comment: http://stackoverflow.com/comment/81348120
downvote count: 1
has comment: http://stackoverflow.com/comment/81348769
favorite count: 0
has title: Don't save a file, using a .format()
type: Question
has body: I'm trying to use os.system() and a .format() for a program that hides Archive in Image. I don't understand , why the OUTPUT.jpg doesn't save in a current directory. Also, I have a GUI for it, it's easy enough to use. But Can't get an output file. It doesn't just create. Please, can you help? Here is a code: import tkinter as tk import tkinter.filedialog as f import os def access(event): global arch arch = f.askopenfilename() txt['text'] = 'Choose a picture' btn_1.destroy() btn_2.grid(row=1, column=1) def access2(event): global img img = f.askopenfilename() btn_2.destroy() os.system('copy {} + {} {}/OUTPUT.jpg'.format(img, arch, os.getcwd())) txt['text'] = 'Ready.' root = tk.Tk() txt = tk.Label(root, text='Choose archive') btn_1 = tk.Button(root, text='Выбрать') btn_2 = tk.Button(root, text='Выбрать') txt.grid(row=0, column=1) btn_1.grid(row=1, column=1) btn_1.bind('&lt;Button-1&gt;', access) btn_2.bind('&lt;Button-1&gt;', access2) root.mainloop()
has comment: http://stackoverflow.com/comment/81349604
has comment: http://stackoverflow.com/comment/81355068
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81348671
tagged with: python
has comment: http://stackoverflow.com/comment/81348484
score: -1
has comment: http://stackoverflow.com/comment/81348336

http://stackoverflow.com/comment/81226168
score: 0
type: Comment
type: QuestionComment
has text: @MarkSetchell creating a directory is not a solution. I updated the question: Required feature: If one process dies, then the lock/semaphore should get released by the operating system.
comment on: http://stackoverflow.com/q/47136965

http://stackoverflow.com/comment/96763559
type: AnswerComment
has text: It can be done using the browser, but if you're using a web based client you need to make sure it uses SocketIO, and not some other implementation. One I have found that works for is http://amritb.github.io/socketio-client-tool/
score: 3
type: Comment
comment on: http://stackoverflow.com/a/47085343

http://stackoverflow.com/comment/81246460
comment on: http://stackoverflow.com/a/47148078
has text: 100GB is still pretty big, especially if you haven't implemented any restart logic. Based on my, rather limited, experience, I would suggest splitting the file into sizes you can fit in memory (and buy lots of memory <wink>).
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47085328
favorite count: 0
type: Question
has body: I'm trying to implement a TCP socket via stunnel but not sure how to capture the server response. My stunnel configuration file is exactly like this: [Coinbase] client = yes accept = 127.0.0.1:4197 connect = fix.gdax.com:4198 verify = 4 CAfile = /etc/fix.gdax.com.pem And the Python code I have is: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("127.0.0.1", 4197)) msg = b'GET / HTTP/1.1\nHost: www.google.com\n\n' # ping google as a means of testing s.send(msg) print(s.recv(1024)) Whatever the message I send over the socket (including those that the server located at fix.gdax.com would expect) the result of that print statement is always just an empty string in byte form: b'' The stunnel log is as follows: 2017.11.02 20:49:58 LOG5[7]: Service [Coinbase] accepted connection from 127.0.0.1:65205 2017.11.02 20:49:58 LOG5[7]: s_connect: connected 52.86.60.82:4198 2017.11.02 20:49:58 LOG5[7]: Service [Coinbase] connected remote server from 192.168.0.14:65206 2017.11.02 20:49:58 LOG5[7]: Certificate accepted at depth=0: C=US, ST=California, L=San Francisco, O="Coinbase, Inc.", CN=*.gdax.com 2017.11.02 20:50:06 LOG3[7]: readsocket: Connection reset by peer (WSAECONNRESET) (10054) 2017.11.02 20:50:06 LOG5[7]: Connection reset: 37 byte(s) sent to TLS, 0 byte(s) sent to socket My interpretation of that is that the message is going out fine and the certificate is valid etc, but I can't work out how to receive data sent back by the server... any help greatly appreciated! I'm quite new to TCP &amp; SSL so apologies if any of the terminology is wrong.
has answer: http://stackoverflow.com/a/47087252
tagged with: sockets
has title: How do you use a Python socket with stunnel?
tagged with: ssl
tagged with: python
upvote count: 2
tagged with: stunnel
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/47087252
downvote count: 0
tagged with: tcp
answer count: 1

http://stackoverflow.com/q/47191930
has answer: http://stackoverflow.com/a/47227738
score: 1
answer count: 2
has title: Subsetting 2-D latitudes, longitudes and data from a big dataset in Python (IMS snowcover)
downvote count: 0
tagged with: matplotlib-basemap
favorite count: 0
type: Question
tagged with: numpy
has body: I have a "simple" objective in mind which turned out to be quite difficult to achieve. I have three 2-Dimensional arrays lat, lon and data all with dimensions (24576, 24576). The first two are latitudes and longitudes coordinates of the variable data which I'm trying to plot over a map. I'm reading all these data from a combination of binary files and text files so that any pre-processing operation is practically impossible and need to be done in the Python script. Given the dimensionality of the array it is virtually impossible, because of the memory constraints, to directly plot the data even when choosing a basemap projection on a small area over the globe. I've already tried that and getting a memory error when trying to plot with basemap.contourf. Thus, I need to subset the array BEFORE passing it to the contour function. I've tried many things, but nothing seems to work. My idea was to do something like this lat_bnds, lon_bnds = [35, 50], [5, 20] condition=((lats &gt; lat_bnds[0]) &amp; (lats &lt; lat_bnds[1])) &amp; (lons &gt; lon_bnds[0]) &amp; (lons &lt; lon_bnds[1]) Where lats and lons are the 2-D coordinate arrays. This yields a 2-D boolean array which has the same dimension as lats (or equivalently lons) that I can then use to mask the original data but not to subset it. Using the same condition in numpy.where produces an array shaped (2, 2564856) which I cannot use. I think the problem here is that there are multiple conditions that need to be satisfied in every point of the 2-D array and there is no guarantee that this will lead to a contiguous rectangular submatrix. However for the sake of plotting those data I really need to subset them, or to find another method to elaborate them. Am I missing something obvious? Is there any other smart way to plot the original data without encountering any error? Sources of the data: http://nsidc.org/data/G02156 Brief script to read the data in assumed that you downloaded the necessary files: import numpy as np imp…
tagged with: arrays
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/47193766
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47227738
has answer: http://stackoverflow.com/a/47193766

http://stackoverflow.com/a/55106031
has body: The accepted answer by John Zwinck is actually false (I just figured this out the hard way!). The problem in the question is a combination of doing "l-value indexing" with numpy's fancy indexing. The following doc explains exactly this case https://scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html in the section "But fancy indexing does seem to return views sometimes, doesn't it?" Edit: To summarize the above link: Whether a view or a copy is created is determined by whether the indexing can be represented as a slice. Exception: If one does "fancy indexing" then always a copy is created. Fancy indexing is something like a[[1,2]]. Exception to the exception: If one does l-value indexing (i.e. the indexing happens left of the = sign), then the rule for when a view or a copy are created doesn't apply anymore (though see below for a further exception). The python interpreter will directly assign the values to the left hand side without creating a copy or a view. To prove that a copy is created in both cases, you can do the operation in two steps: >>> a = np.arange(12).reshape(3, 4) >>> b = a[0:3:2, :][:, [0, 2]] >>> b[:] = 100 >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) and >>> b = a[:, [0, 2]][0:3:2, :] >>> b[:] = 0 >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) Just as an aside, the question by the original poster is the exact problem stated at the end of the scipy-cookbook link above. There is no solution given in the book. The tricky thing about the question is that there are two indexing operations done in a row. Exception to the exception to the exception: If there are two indexing operations done in a row on the left hand side (as is the case in this question), the direct assignment in l-value indexing only works if the first indexing operation can be represented as a slice. Otherwise a copy has to be created even though it is l-value indexing.
score: 32
downvote count: 0
upvote count: 32
type: Answer
has comment: http://stackoverflow.com/comment/138782592
answers question: http://stackoverflow.com/q/47181092

http://stackoverflow.com/comment/81204403
comment on: http://stackoverflow.com/q/47120191
type: Comment
type: QuestionComment
has text: No, *you* need to explain what your problem is, such that other people can help you solve it. Does the plot not show the minimum? The minimum of *what* actually? What do you want to see? Please reword your question to clearly state in how far what you obtain is not what you expect and what exactly hinders you to obtain the desired plot. Also read [ask] and [mcve].
score: 0

http://stackoverflow.com/a/47120943
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47120859
has body: If it is what you want, use a dictionary comprehension. For converting the list to string, use the join() function after mapping each element to a string. population = [[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [1], [0]], [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]], [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]], [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [3], [3]]] d = {", ".join(map(str,i[0])):i[1][0] for i in population} print(d) Output: {'0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0': 4, '1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0': 3, '0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1': 3, '0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1': 1}
answers question: http://stackoverflow.com/q/47120859
type: Answer
has comment: http://stackoverflow.com/comment/81191593
upvote count: 2

http://stackoverflow.com/comment/81331722
type: Comment
type: AnswerComment
has text: Hi Pedro, yes, you'll need to host your Python code on a server that will be called by Dialogflow's fulfilment.
comment on: http://stackoverflow.com/a/47165392
score: 0

http://stackoverflow.com/comment/81195832
score: 0
comment on: http://stackoverflow.com/q/47123035
type: QuestionComment
has text: In a Python shell, what is the result of `import numpy as np`, `np` and `type(np)`?
type: Comment

http://stackoverflow.com/comment/81280919
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47160723
has text: @rogerdpack Yes, it can recieve, but can it recieve continuously ? (generating results accordingly

http://stackoverflow.com/q/47210957
has answer: http://stackoverflow.com/a/47211081
answer count: 2
tagged with: amazon-ec2
tagged with: amazon-web-services
type: Question
accepted answer: http://stackoverflow.com/a/47211343
type: AnsweredQuestion
has title: Starting multiple EC2 instances using Boto3
has answer: http://stackoverflow.com/a/47211343
has comment: http://stackoverflow.com/comment/81372035
has body: I'm getting the list of instances using the code below def list_instances_by_tag_value(self, tagkey, tagvalue): ec2client = boto3.client('ec2') response = ec2client.describe_instances( Filters=[ { 'Name': 'tag:'+tagkey, 'Values': [tagvalue] } ] ) instancelist = [] for reservation in (response["Reservations"]): for instance in reservation["Instances"]: instancelist.append(instance["InstanceId"]) return instancelist Now the method list_instances_by_tag_value returns a List. Now I need to start the list of EC2 instances. So I'm doing something like below def start_ec_instances(self, instanceids): response = ec2client.start_instances(InstanceIds=instanceids) return where instanceids is the list returned from the first method. However ec2client.start_instances only accepts String and not a List. I know I can convert the list to String and then parse it. I need to append (') in front of the instanceID and also append comma (,) between each instance ID. question is, is there any easy easy way to do this rather than convert list to string and performing some append operation? It needs to look something like 'i-XXXXXX', 'i-XXXXX', 'i-XXXXXXX' EDIT: When I pass the list to start_instances from the first method it says Invalid type for parameter InstanceIds[0], value: ['i-ssss', 'i-YYYY', 'i-ZZZZ', 'i-KKKK'], type: &lt;class 'list'&gt;, valid types: &lt;class 'str'&gt;
tagged with: python
tagged with: boto3
possible better answer: http://stackoverflow.com/a/47211081
score: 0

http://stackoverflow.com/comment/83259180
has text: fisrt thanks for the improvement, but is there a possibility to simply make the cursor only moving when clicking, like its handeld in my example?
type: Comment
comment on: http://stackoverflow.com/a/47168359
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81292916
type: Comment
comment on: http://stackoverflow.com/a/47171648
score: 0
type: AnswerComment
has text: I didn't really look at what you're trying to do, but generally using a loop with numpy methods is an anti pattern.

http://stackoverflow.com/q/47146128
favorite count: 0
type: Question
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/47147886
tagged with: python
has body: What is the most efficient way to feed data from multiple TFRecord files for purposes of training a Tensorflow model? With my current process, I iterate over the examples from TFRecords, separately extracting examples into Python variables, but I don't believe this is the proper way to do this. I am migrating from Keras to Tensorflow hoping to see some speed improvements in my workflow. Towards that end, I've moved my data into TFRecord, and now I am trying to understand how to run basic linear regression models with a directory of TFRecord files. I have gotten to the point where I can read the TFRecord out into a Tensor and train in batches like so (code is taken from the Tensorflow getting started example and then modified): # Model parameters W = tf.Variable([.1], dtype=tf.float32) b = tf.Variable([.1], dtype=tf.float32) # Model input and output x = tf.placeholder(tf.float32) linear_model = W*x + b y = tf.placeholder(tf.float32) # loss loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares # optimizer optimizer = tf.train.GradientDescentOptimizer(0.1) train = optimizer.minimize(loss) # Transforms a scalar string `example_proto` into a pair of a scalar string and # a scalar integer, representing an image and its label, respectively. def _parse_function(example_proto): keys_to_features = { "X": tf.FixedLenFeature([40], tf.float32), "Y": tf.FixedLenFeature([10], tf.float32) } example = tf.parse_single_example(example_proto, keys_to_features) return example["X"][0], example["Y"][0] filenames = tf.placeholder(tf.string, shape=[None]) dataset = tf.data.TFRecordDataset(filenames, "ZLIB") dataset = dataset.map(_parse_function) dataset = dataset.repeat() dataset = dataset.batch(1024) iterator = dataset.make_initializable_iterator() next_element = iterator.get_next() # training loop init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) # reset values to wrong sess.run(iterator.initializer, feed_dict = { filenames: training_filenames })…
accepted answer: http://stackoverflow.com/a/47147886
upvote count: 3
answer count: 1
downvote count: 0
tagged with: tfrecord
has title: Integrating directory of TFRecord examples into model training
tagged with: tensorflow

http://stackoverflow.com/comment/81232322
has text: In the context of displaying it, or simply saving the file somewhere? If it's for display, why do you need to display so much data in the first place?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47141242
score: 0

http://stackoverflow.com/q/47178802
has body: Using Django 1.11.6, python 3.6.2 Short summary: static files are collected correctly on server but only one app's sub directory is served, the admin's static files return as 404. Running the local development server everything works as expected. After deploying to my EB instance none of the static files for the admin app load. If i run eb ssh and look around on the server I can see the collected static folder, along with all the different app's subfolders. The files are all there where I'd expect. The links produced on the django front-end map in a sensible way to these paths, it's just that anything in static/admin returns a 404, while the files in static/entities work fine. Testing paths on the front end: /static/admin/css/base.css (404) /static/entities/style.css (works) On server, all collected files in static look fine: /opt/python/current/app/static/admin/css /opt/python/current/app/static/entities No idea why one sub directory is server fine but the others return 404s. From my django.config option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "spf.settings" "PYTHONPATH": "/opt/python/current/app:$PYTHONPATH" "ALLOWED_HOSTS": ".elasticbeanstalk.com" "aws:elasticbeanstalk:container:python": WSGIPath: spf/wsgi.py NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "static/" ... 03_collectstatic: command: "source /opt/python/run/venv/bin/activate &amp;&amp; python manage.py collectstatic --noinput" Running the collectstatic command locally produces the correct static folder with the same subdirectories for each app too.
has comment: http://stackoverflow.com/comment/81306643
downvote count: 0
tagged with: django
upvote count: 1
has title: Elastic beanstalk Django admin css not loading
has answer: http://stackoverflow.com/a/47220477
type: AnsweredQuestion
score: 1
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47220477
tagged with: amazon-elastic-beanstalk
favorite count: 0
type: Question

http://stackoverflow.com/comment/81198941
comment on: http://stackoverflow.com/q/47124143
has text: Possible duplicate of [Getting the mean of multiple axis of a numpy array](https://stackoverflow.com/questions/17397231/getting-the-mean-of-multiple-axis-of-a-numpy-array) Specifically, see answer https://stackoverflow.com/a/17403375/8033585
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52758244
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47140259
answers question: http://stackoverflow.com/q/47140259
type: Answer
score: 2
has body: Seems like you need to add the b (binary mode) to the open call: From the docs: 'b' appended to the mode opens the file in binary mode: now the data is read and written in the form of bytes objects. This mode should be used for all files that don’t contain text. @shared_task def process_upload(path): with default_storage.open(path, 'rb') as file: # Rest of your code goes here.
upvote count: 2

http://stackoverflow.com/comment/81111716
has text: The ID key inside the nested dictionary is missing
type: AnswerComment
comment on: http://stackoverflow.com/a/47081111
score: 0
type: Comment

http://stackoverflow.com/comment/81283472
has text: You have to store `obs` in a list. The answer to this question is "No, you can not!" However, giving you a hint, you can store `obs` in file and load it in chunk if memory is a concern, that is fast enough. You have an up-vote from me and better delete the [old question](https://stackoverflow.com/questions/47146905/turning-a-generator-of-pairs-into-a-pair-of-generators) that talks about this.
comment on: http://stackoverflow.com/q/47166701
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81214226
score: 0
has text: @juanpa.arrivillaga OK Dude :) , using a `dict` with a defined, defaulted values- goes without saying, I was curious to know if there is another way. TNX !
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47132049

http://stackoverflow.com/comment/81257525
comment on: http://stackoverflow.com/a/47153929
score: 0
type: Comment
has text: Not sure if the reduction to a one-liner is worth the loss of readability, but this is a neat trick.
type: AnswerComment

http://stackoverflow.com/comment/81340004
type: Comment
type: QuestionComment
has text: You're trying to unpack: `self.name, self.author = ('Python',)`. Make sure that the input is what you're expecting... check `len(args)` first.
score: 2
comment on: http://stackoverflow.com/q/47195540

http://stackoverflow.com/comment/81167271
type: Comment
score: 0
type: AnswerComment
has text: I can help you... Tomorrow, its very late atm for me
comment on: http://stackoverflow.com/a/47108160

http://stackoverflow.com/comment/81656613
type: Comment
has text: It **should** be a similarity matrix. Sorry there was ambiguity in my last comment, basically scikit uses negative Euclidean distances so that larger values indicate values are closer.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47163581

http://stackoverflow.com/comment/81099849
has text: you are right. This class is not available for windows. But then what is available for windows ?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47075664
type: AnswerComment

django-database
type: Tag
tag name: django-database
tags question: http://stackoverflow.com/q/47124297

http://stackoverflow.com/q/47172172
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/47172380
has answer: http://stackoverflow.com/a/47172385
score: 2
answer count: 2
upvote count: 2
tagged with: pandas
downvote count: 0
tagged with: multi-index
has body: Say I have a multiindex mi as follows: Serial No. Date A B A B 0 816292 934609 27/01/17 27/01/17 1 983803 683858 25/01/17 26/01/17 2 596573 493741 27/01/17 28/01/17 3 199203 803515 28/01/17 28/01/17 A and B are two parts such that the multiindex contains information about the serial number and build date of multiple instances of the two parts. I have a dataframe df containing test information for part A, as follows: A Test 1 Test 2 Test 3 0 816292 0.934609 0.475035 0.822712 1 983803 0.683858 0.025861 0.691112 2 596573 0.493741 0.397398 0.489101 3 199203 0.803515 0.679537 0.308588 I would like to be able to merge these two and yield something like Serial No. Date Tests A B A B Test 1 Test 2 Test 3 0 816292 934609 27/01/17 27/01/17 0.934609 0.475035 0.822712 1 983803 683858 25/01/17 26/01/17 0.683858 0.025861 0.691112 2 596573 493741 27/01/17 28/01/17 0.493741 0.397398 0.489101 3 199203 803515 28/01/17 28/01/17 0.803515 0.679537 0.308588 My initial attempt was mi = mi.merge(df,left_on=('Serial No.','A'),right_on='A',how='inner') but that yields ValueError: len(right_on) must equal len(left_on). I have tried adding an additional column index 'Tests' to df and then doing mi = mi.merge(df,left_on=('Serial No.','A'),right_on=('Tests','A'),how='inner') but that yields KeyError: 'A'
favorite count: 0
has answer: http://stackoverflow.com/a/47172380
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47172385
has title: Merge multiindex with multiple column levels and dataframe

http://stackoverflow.com/comment/81161745
type: Comment
type: QuestionComment
has text: @grovina The reason why I don't do it is because I wish to reuse the same function multiple times without having to reassign it manually every single time. This is especially bothersome if I wish to do it for multiple variables (say, not just 2 like in this example, but maybe 30 different ones). Having a simple solution would be more beneficial. The second solution Brett suggested solved my issue thankfully.
score: 0
comment on: http://stackoverflow.com/q/47105166

http://stackoverflow.com/a/47155482
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81317068
accepted answer of: http://stackoverflow.com/q/47155256
has body: Your code seems good, so the problem you encounter is probably due to a bad import. You really should avoid to name your python script like "standard" modules (serial.py, string.py...), because by doing this, you expose yourself to accidentally import those files instead of the correct one (probably what happened to you). If you need to be sure of what you're importing, try this : import serial print serial.__file__ # this will tell you the position of the file you've imported and help you to be sure of what you're using. # in case you're not importing a module, only a class... try this : help(serial) # even without any help, it will give you at the end the path where this object is defined :)
has comment: http://stackoverflow.com/comment/81316507
has comment: http://stackoverflow.com/comment/81274430
type: Answer
answers question: http://stackoverflow.com/q/47155256
score: 1

pandas
tags question: http://stackoverflow.com/q/47184345
tags question: http://stackoverflow.com/q/47179215
tags question: http://stackoverflow.com/q/47216564
tags question: http://stackoverflow.com/q/47132838
tags question: http://stackoverflow.com/q/47150020
tags question: http://stackoverflow.com/q/47204234
tags question: http://stackoverflow.com/q/47102258
tags question: http://stackoverflow.com/q/47148342
tags question: http://stackoverflow.com/q/47111829
tags question: http://stackoverflow.com/q/47119965
tags question: http://stackoverflow.com/q/47084949
tags question: http://stackoverflow.com/q/47067228
tags question: http://stackoverflow.com/q/47098429
tags question: http://stackoverflow.com/q/47113370
tags question: http://stackoverflow.com/q/47220744
tags question: http://stackoverflow.com/q/47209301
tags question: http://stackoverflow.com/q/47164176
tags question: http://stackoverflow.com/q/47089960
tags question: http://stackoverflow.com/q/47159996
tags question: http://stackoverflow.com/q/47194806
tags question: http://stackoverflow.com/q/47128009
tags question: http://stackoverflow.com/q/47129131
tags question: http://stackoverflow.com/q/47087451
tags question: http://stackoverflow.com/q/47191675
tags question: http://stackoverflow.com/q/47126285
tags question: http://stackoverflow.com/q/47189831
tags question: http://stackoverflow.com/q/47135533
tags question: http://stackoverflow.com/q/47121397
tags question: http://stackoverflow.com/q/47082237
tags question: http://stackoverflow.com/q/47078250
tags question: http://stackoverflow.com/q/47222866
tags question: http://stackoverflow.com/q/47186040
tags question: http://stackoverflow.com/q/47213579
tags question: http://stackoverflow.com/q/47212791
tags question: http://stackoverflow.com/q/47086468
tags question: http://stackoverflow.com/q/47176420
tags question: http://stackoverflow.com/q/47092512
tags question: http://stackoverflow.com/q/47152923
tags question: http://stackoverflow.com/q/47087614
tags question: http://stackoverflow.com/q/47078331
tags question: http://stackoverflow.com/q/47213852
tags question: http://stackoverflow.com/q/47164362
tags question: http://stackoverflow.com/q/47206034
tags question: http://stackoverflow.com/q/47118820
tags question: http://stackoverflow.com/q/47187359
tags question: http://stackoverflow.com/q/47191791
tags question: http://stackoverflow.com/q/47065193
tags question: http://stackoverflow.com/q/47220773
tags question: http://stackoverflow.com/q/47126129
tags question: http://stackoverflow.com/q/47142864
tags question: http://stackoverflow.com/q/47214780
tags question: http://stackoverflow.com/q/47106305
tags question: http://stackoverflow.com/q/47105560
tags question: http://stackoverflow.com/q/47087506
tags question: http://stackoverflow.com/q/47164950
tags question: http://stackoverflow.com/q/47135539
tags question: http://stackoverflow.com/q/47189212
tags question: http://stackoverflow.com/q/47123666
tags question: http://stackoverflow.com/q/47086896
tags question: http://stackoverflow.com/q/47143631
tags question: http://stackoverflow.com/q/47160153
tags question: http://stackoverflow.com/q/47113813
tags question: http://stackoverflow.com/q/47161057
tags question: http://stackoverflow.com/q/47126567
tags question: http://stackoverflow.com/q/47142840
tags question: http://stackoverflow.com/q/47148381
tags question: http://stackoverflow.com/q/47073936
tags question: http://stackoverflow.com/q/47216757
tags question: http://stackoverflow.com/q/47095375
tags question: http://stackoverflow.com/q/47084641
tags question: http://stackoverflow.com/q/47092567
tags question: http://stackoverflow.com/q/47073066
tags question: http://stackoverflow.com/q/47133250
tags question: http://stackoverflow.com/q/47079717
tags question: http://stackoverflow.com/q/47150399
tags question: http://stackoverflow.com/q/47099819
tags question: http://stackoverflow.com/q/47161550
tags question: http://stackoverflow.com/q/47146358
tags question: http://stackoverflow.com/q/47170311
tags question: http://stackoverflow.com/q/47087099

http://stackoverflow.com/q/47185461
tagged with: python
has comment: http://stackoverflow.com/comment/81319984
has body: I have a 4D array of shape (1948, 60, 2, 3) which tells the difference in end effector positions (x,y,z) over 60 time steps. The number 1948 indicates the number of samples, 60 is the number of time steps, 2 is for left_arm and right_arm, 3 denotes the x,y,z positions. a sample of how it looks is below: array([[[ 3.93048840e-05, 7.70215296e-04, 1.13865805e-03], [ 1.11679799e-04, -7.04810066e-04, 1.83552688e-04]], [[ -6.26468389e-04, 6.86668923e-04, 1.57112482e-04], [ 3.68164582e-04, 7.98948528e-04, 4.50642200e-04]], [[ 2.51472961e-04, -2.48105983e-04, 7.52486843e-04], [ 8.99905240e-05, 1.70473461e-04, -3.09927572e-04]], [[ -7.52414330e-04, 5.46782063e-04, -3.76679264e-04], [ -3.12531026e-04, -3.36585211e-04, 5.79075595e-05]], [[ 7.69968002e-04, -1.95524291e-03, -8.65666619e-04], [ 2.37583215e-04, 4.59415986e-04, 6.07292643e-04]], [[ 1.41795261e-03, -1.62364401e-03, -8.99673829e-04], I want to normalize this data as I need tot rain on a neural netowrk. How do I go about normalizing a 4D array I have an intuition for images. Can I normalize each example data or should the normalization be there for the entire 4D array?
has comment: http://stackoverflow.com/comment/81322386
has comment: http://stackoverflow.com/comment/81323267
favorite count: 0
tagged with: numpy
has comment: http://stackoverflow.com/comment/81323157
tagged with: normalization
has answer: http://stackoverflow.com/a/47187160
tagged with: deep-learning
has answer: http://stackoverflow.com/a/47186645
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: neural-network
has comment: http://stackoverflow.com/comment/81320031
accepted answer: http://stackoverflow.com/a/47187160
possible better answer: http://stackoverflow.com/a/47186645
has comment: http://stackoverflow.com/comment/81323082
has title: How to normalize 4D array ( not an image)?
type: Question
has comment: http://stackoverflow.com/comment/81319983
has comment: http://stackoverflow.com/comment/81319956
has comment: http://stackoverflow.com/comment/81320270

http://stackoverflow.com/q/47207713
has comment: http://stackoverflow.com/comment/81365506
tagged with: python
has comment: http://stackoverflow.com/comment/81424858
has answer: http://stackoverflow.com/a/47243098
has title: python pandas: A value is trying to be set on a copy of a slice from a DataFrame
type: Question
has comment: http://stackoverflow.com/comment/81366815
tagged with: python-3.x
linked to: http://stackoverflow.com/q/20625582
has comment: http://stackoverflow.com/comment/81364598
upvote count: 3
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47243098
has comment: http://stackoverflow.com/comment/81365841
has comment: http://stackoverflow.com/comment/81435415
has body: Could you please advise how the following lines should be re-written based on http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy df.drop('PACKETS', axis=1, inplace=True) produces See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy df.drop('PACKETS', axis=1, inplace=True) /home/app/ip-spotlight/code/app/ipacc/plugin/ix.py:74: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame df.replace(numpy.nan, "", inplace=True) produces See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy df.replace(numpy.nan, "", inplace=True) /home/app/ip-spotlight/code/app/ipacc/plugin/ix.py:68: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame On the other hand, the following is an example of how it was re-written based on the above principle df.loc[:, ('SRC_PREFIX')] = df[ ['SRC_NET', 'SRC_MASK'] ].apply(lambda x: "/".join(x), axis=1) But i am unable to figure out how to re-write the cases 1 and 2 ? EDIT: the code so far it looks like this (df is the dataframe of interest). So initially the is some kind of casting: df = pandas.DataFrame(data['payload'], columns=sorted(data['header'], key=data['header'].get)) df = df.astype({ 'SRC_AS' : "object", 'DST_AS' : "object", 'COMMS' : "object", 'SRC_COMMS' : "object", 'AS_PATH' : "object", 'SRC_AS_PATH' : "object", 'PREF' : "object", 'SRC_PREF' : "object", 'MED' : "object", 'SRC_MED' : "object", 'PEER_SRC_AS' : "object", 'PEER_DST_AS' : "object", 'PEER_SRC_IP' : "object", 'PEER_DST_IP' : "object", 'IN_IFACE' : "object", 'OUT_IFACE' : "object", 'SRC_NET' : "object", 'DST_NET' : "object", 'SRC_MASK' : "object", 'DST_MASK' : "object", 'PROTOCOL' : "object", 'TOS' : "object", 'SAMPLING_RATE' : "uint64", 'EXPORT_PROTO_VERSION' : "object", 'PACKETS' : "object", 'BYTES' : "uint64", }) Then the calculate functio…
has comment: http://stackoverflow.com/comment/81365675
favorite count: 0
has comment: http://stackoverflow.com/comment/81364389
type: AnsweredQuestion
score: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/81365287
has comment: http://stackoverflow.com/comment/81365892

http://stackoverflow.com/a/68953182
has comment: http://stackoverflow.com/comment/127302093
type: Answer
score: 1
downvote count: 1
has body: This answer fixes issues in the current accepted answer. The major issue there is that the condition to remove a directory has to be not filenames and not dirnames. import os def remove_empty_directories(root): for dirpath, dirnames, filenames in os.walk(root): if not filenames and not dirnames: os.rmdir(dirpath)
upvote count: 2
answers question: http://stackoverflow.com/q/47093561

http://stackoverflow.com/a/47206650
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47205195
has body: If your thread only changes a's value once, at the end of its life, then you can use .join() to wait for the thread to terminate. import threading import time class example: def __init__(self): self.a = 0 self.temp = threading.Thread(target=self.valchange) self.temp.start() self.notifier() def valchange(self): time.sleep(5) self.a = 1 def notifier(self): self.temp.join() print("the value of a has changed") example() If the thread might change a's value at any point in its lifetime, then you can use one of the threading module's more generalized control flow objects to coordinate execution. For instance, the Event object. import threading import time class example: def __init__(self): self.a = 0 self.event = threading.Event() temp = threading.Thread(target=self.valchange) temp.start() self.notifier() def valchange(self): time.sleep(5) self.a = 1 self.event.set() def notifier(self): self.event.wait() print("the value of a has changed") example() One drawback to this Event approach is that the thread target has to explicitly call set() whenever it changes the value of a, which can be irritating if you change a several times in your code. You could automate this away using a property: import threading import time class example(object): def __init__(self): self._a = 0 self._a_event = threading.Event() temp = threading.Thread(target=self.valchange) temp.start() self.notifier() @property def a(self): return self._a @a.setter def a(self, value): self._a = value self._a_event.set() def valchange(self): time.sleep(5) self.a = 1 def notifier(self): self._a_event.wait() print("the value of a has changed") example() Now valchange doesn't have to do anything special after setting a's value.
has comment: http://stackoverflow.com/comment/81363612
has comment: http://stackoverflow.com/comment/81366402

http://stackoverflow.com/comment/81094953
has text: You can use df1.append(df2) since the dataframe structure is same. or df = pd.concat([df1, df2],axis=0)
comment on: http://stackoverflow.com/q/47073066
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51839169
score: 68
answers question: http://stackoverflow.com/q/47065438
type: Answer
has body: Open urls.py and replace: django.contrib.auth.views.login with django.contrib.auth.views.LoginView django.contrib.auth.views.logout with django.contrib.auth.views.LogoutView
upvote count: 68
downvote count: 0

http://stackoverflow.com/a/47155003
has body: Filtering the dataset exactly 10% per class can be a bit hairy, but if your goal is just to try ResNet on a smaller dataset, the simplest way is to skip 90% of the dataset, which will reduce each class approximately to 10%. If this is ok for you, simply add skip after the shuffle call: ... dataset = dataset.shuffle(buffer_size=_SHUFFLE_BUFFER) dataset = dataset.skip(54000) ... .. which will cause the dataset to skip 90% of 60000 examples and return only 6000.
has comment: http://stackoverflow.com/comment/81259949
has comment: http://stackoverflow.com/comment/81260659
answers question: http://stackoverflow.com/q/47149764
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/81259798
type: Answer
upvote count: 1

neo4j
tags question: http://stackoverflow.com/q/47167014
tags question: http://stackoverflow.com/q/47126947
tag name: neo4j
tags question: http://stackoverflow.com/q/47116400
type: Tag
tags question: http://stackoverflow.com/q/47133423
tags question: http://stackoverflow.com/q/47088560
tags question: http://stackoverflow.com/q/47118349

http://stackoverflow.com/comment/81137787
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47094142
has text: Yes it is empty at all.I think

subprocess
tags question: http://stackoverflow.com/q/47166174
tags question: http://stackoverflow.com/q/47132966
tags question: http://stackoverflow.com/q/47184031
tags question: http://stackoverflow.com/q/47118721
tag name: subprocess
type: Tag
tags question: http://stackoverflow.com/q/47166453
tags question: http://stackoverflow.com/q/47065051
tags question: http://stackoverflow.com/q/47097363
tags question: http://stackoverflow.com/q/47067013
tags question: http://stackoverflow.com/q/47129012
tags question: http://stackoverflow.com/q/47147857
tags question: http://stackoverflow.com/q/47146886
tags question: http://stackoverflow.com/q/47124169
tags question: http://stackoverflow.com/q/47199225
tags question: http://stackoverflow.com/q/47194600
tags question: http://stackoverflow.com/q/47134453
tags question: http://stackoverflow.com/q/47132791
tags question: http://stackoverflow.com/q/47118121
tags question: http://stackoverflow.com/q/47153842
tags question: http://stackoverflow.com/q/47108955
tags question: http://stackoverflow.com/q/47117780
tags question: http://stackoverflow.com/q/47205292
tags question: http://stackoverflow.com/q/47090982
tags question: http://stackoverflow.com/q/47196230
tags question: http://stackoverflow.com/q/47094142
tags question: http://stackoverflow.com/q/47158315
tags question: http://stackoverflow.com/q/47189986
tags question: http://stackoverflow.com/q/47120873
tags question: http://stackoverflow.com/q/47187642
tags question: http://stackoverflow.com/q/47137586
tags question: http://stackoverflow.com/q/47169037
tags question: http://stackoverflow.com/q/47066063
tags question: http://stackoverflow.com/q/47205923

http://stackoverflow.com/comment/81320123
score: 0
type: Comment
has text: yeah i got slice part but what does len(df) // len(v) + 1 this code means ? Is it a division or something else. So it will divide 1704/5 then add 1 ?
type: AnswerComment
comment on: http://stackoverflow.com/a/47185435

http://stackoverflow.com/comment/81343424
comment on: http://stackoverflow.com/q/47197187
type: QuestionComment
has text: @ Steve Haigh wow that was very fast. Thank you very very much. I changed it the way it is in my skript now. It could be that the indentation is wrong ;) (I am new to python and web scraping as well). I will have a look at the API. Perhaps this will be the better answer to my Problems.
score: 0
type: Comment

http://stackoverflow.com/a/47202104
answers question: http://stackoverflow.com/q/47201984
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
has body: you have to convert your elements using a element to key function so you can use comparison not of the element itself but of a transformed data suiting your needs. I would do this as a generic solution: def insertionSort(arr, n, keyfunc=lambda x:x): for i in range(1, n): key = arr[i] j = i - 1 while j &gt;= 0 and keyfunc(arr[j]) &gt; keyfunc(key): arr[j+1] = arr[j] j = j - 1 arr[j+1] = key return ' '.join(arr) so by default, the key is just the element itself, but if you call your function like this: insertionSort(arr, len(arr), keyfunc=int) the key function is now "conversion to integer", and sorting works as expected on a list of integers as strings. (note that the built-in sort method works that way, by allowing to provide a key function). of course you can drop the whole keyfunc idea and just hardcode int here: while j &gt;= 0 and int(arr[j]) &gt; int(key):
accepted answer of: http://stackoverflow.com/q/47201984
downvote count: 0

http://stackoverflow.com/comment/81394962
score: 0
has text: @KaranGupta Try this? `df.to_dict('i')`
type: Comment
comment on: http://stackoverflow.com/a/47216885
type: AnswerComment

http://stackoverflow.com/q/47210236
answer count: 1
linked to: http://stackoverflow.com/q/13649664
has body: I configed my logging in below config file, where I have a "filelog" to write the logging info into a file by using: flog = logging.getLogger(__file__) flog.info('write!') However, I want to specify a different file to log to everytime I run. Now I can only write to C:/record.log How can I pass in a paramter to indicate which file I want to write to? [loggers] keys: root, file [formatters] keys: detailed,simple [handlers] keys: console,filelog [formatter_simple] format: %(asctime)s-%(name)s-%(levelname)s: %(message)s [formatter_detailed] format: %(asctime)s-%(name)s-%(levelname)s-%(lineno)d: %(message)s [handler_console] class: StreamHandler args: [] formatter: detailed [handler_filelog] class: handlers.RotatingFileHandler args: ('C:/record.log','a', 1000000, 5) formatter: detailed [logger_root] level: DEBUG handlers: console [logger_file] level: INFO qualname: file handlers: filelog
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: python logging: how to pass in a parameter to a logging config file
tagged with: logging
score: 2
has answer: http://stackoverflow.com/a/65104600
has comment: http://stackoverflow.com/comment/81370523
downvote count: 0

http://stackoverflow.com/q/47221056
has comment: http://stackoverflow.com/comment/81392068
score: 1
has title: Python: How to make sparql queries to extract data from Dbpedia?
tagged with: python
has body: I want to extract data of Swiss cities from Dbpedia using sparql in python. import rdflib sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery(""" PREFIX dbpedia-owl: &lt;http://dbpedia.org/ontology/&gt; PREFIX dbpedia: &lt;http://dbpedia.org/resource&gt; PREFIX dbpprop: &lt;http://dbpedia.org/property&gt; SELECT DISTINCT ?citylabel ?countrylabel ?pop ?country WHERE{ ?city rdf:type dbpedia-owl:City. ?city rdfs:label ?citylabel. ?city dbpedia-owl:populationTotal ?pop. ?city dbpedia-owl:country ?country. ?country rdfs:label ?countrylabel. FILTER ( ?country = dbpedia:Switzerland) } """) sparql.setReturnFormat(JSON) results = sparql.query().convert() But it results contains no values. Why?
has comment: http://stackoverflow.com/comment/81392388
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81392323
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: sparql
has comment: http://stackoverflow.com/comment/81392431

observers
tags question: http://stackoverflow.com/q/47122821
type: Tag
tag name: observers

http://stackoverflow.com/comment/81282526
comment on: http://stackoverflow.com/q/47166301
score: 0
type: Comment
type: QuestionComment
has text: Please don't tag questions with things they don't relate to. MySQL has nothing to do with Postgres and/or Python in this case.

datarow
tags question: http://stackoverflow.com/q/47073066
type: Tag
tag name: datarow

http://stackoverflow.com/comment/81362297
type: Comment
comment on: http://stackoverflow.com/a/47206673
has text: @MatiasCicero he can, that's not an issue I think
type: AnswerComment
score: 1

http://stackoverflow.com/a/47157785
has body: The problem is caused by the way that you import the tkinter module: from PIL import Image,ImageTk from tkinter import * The second import will replace any existing names of variables, classes etc. with those contained in the tkinter module. It just so happens that there is an Image class defined in tkinter (that doesn't have an open() method), so it will replace the one that was already imported from PIL. &gt;&gt; from tkinter import * &gt;&gt;&gt; Image &lt;class 'tkinter.Image'&gt; This is a demonstration of why it is preferable not to use import *, although it is common to do so with Tkinter. One way to fix this is to swap the order of your imports so that PIL.Image replaces tkinter.Image, but that now prevents you from using tkinter.Image if you had wanted to use both in the same namespace. So, you can import using as to define your own name for items imported from the module: from PIL import ImageTk, Image as PILImage and use PILImage instead of Image when you require a PIL.Image.
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47157579

http://stackoverflow.com/a/50228663
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47210530
has body: I found @SergioLucero's answer too incomplete to answer the question, the code sample is not working. However, with code and answer created by @ifearthenight (from this question: Lining up labels with the nodes on a Bokeh figure generated from a NetworkX graph) I was able to produce a working example. from bokeh.io import show, output_notebook from bokeh.plotting import figure from bokeh.models import ColumnDataSource, LabelSet from bokeh.models.graphs import from_networkx output_notebook() G = nx.karate_club_graph() plot = figure(title="Karate Club Graph", tools="", x_range=(-1.5, 1.5), y_range=(-1.5, 1.5), toolbar_location=None) graph = from_networkx(G, nx.spring_layout) plot.renderers.append(graph) x, y = zip(*graph.layout_provider.graph_layout.values()) node_labels = nx.get_node_attributes(G, 'club') source = ColumnDataSource({'x': x, 'y': y, 'club': [node_labels[i] for i in range(len(x))]}) labels = LabelSet(x='x', y='y', text='club', source=source, background_fill_color='white') plot.renderers.append(labels) show(plot)
score: 5
has comment: http://stackoverflow.com/comment/127043015
upvote count: 5

http://stackoverflow.com/comment/81349695
has text: This is what I was looking for. Thanks;)
type: Comment
comment on: http://stackoverflow.com/a/47200614
score: 0
type: AnswerComment

http://stackoverflow.com/a/47075924
type: Answer
has comment: http://stackoverflow.com/comment/81103707
downvote count: 0
upvote count: 1
score: 1
has body: Looking at both of your code blocks its pretty much evident both will have identical effects. Through wait = WebDriverWait(driver, 10) we are creating an instance of WebDriverWait with the intended webdriver instance i.e. driver and the timespan as 2 arguments. This wait doesn't comes into force until &amp; unless you explicitly use them in your code as : wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "some_selector"))) So, where ever you invoke the instance of the WebDriverWait i.e wait, the intended function is performed/executed irrespective of its position in the code block. In this case the function is searching for expected_conditions as presence_of_element_located. Moreover, once you create an instance of WebDriverWait, e.g. wait, you can also use them as many times you wish (considering the arguments i.e webdriver instance and timespan are similar) in your code block as follows: wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "some_selector"))) #some code for some task wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "some_other_selector"))) #some other code for some other task wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "some_selector_else")))
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47075280
answers question: http://stackoverflow.com/q/47075280

http://stackoverflow.com/comment/81114442
score: 0
comment on: http://stackoverflow.com/q/47082410
type: QuestionComment
type: Comment
has text: its my intetion to create a new dict of all the other dicts. to save myself for some extra trouble i just make the number of contests fixed (10 contests). but when i compare for example dict1 and dict2, and some players participated in both, but with different scores, how to put the higehst score in the new dict?

http://stackoverflow.com/a/59288726
downvote count: 1
has comment: http://stackoverflow.com/comment/108810826
has comment: http://stackoverflow.com/comment/108794403
type: Answer
has comment: http://stackoverflow.com/comment/108742064
score: 14
has body: The easiest way that I found to fix this is to uninstall everything then install a specific version of tensorflow-gpu: uninstall tensorflow: pip uninstall tensorflow uninstall tensorflow-gpu: (make sure to run this even if you are not sure if you installed it) pip uninstall tensorflow-gpu Install specific tensorflow-gpu version: pip install tensorflow-gpu==2.0.0 pip install tensorflow_hub pip install tensorflow_datasets You can check if this worked by adding the following code into a python file: from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import tensorflow as tf import tensorflow_hub as hub import tensorflow_datasets as tfds print("Version: ", tf.__version__) print("Eager mode: ", tf.executing_eagerly()) print("Hub Version: ", hub.__version__) print("GPU is", "available" if tf.config.experimental.list_physical_devices("GPU") else "NOT AVAILABLE") Run the file and then the output should be something like this: Version: 2.0.0 Eager mode: True Hub Version: 0.7.0 GPU is available Hope this helps
upvote count: 15
has comment: http://stackoverflow.com/comment/135872963
has comment: http://stackoverflow.com/comment/108805498
answers question: http://stackoverflow.com/q/47068709
has comment: http://stackoverflow.com/comment/108742055
has comment: http://stackoverflow.com/comment/135384301

http://stackoverflow.com/comment/117044990
type: AnswerComment
comment on: http://stackoverflow.com/a/47138314
score: 0
has text: I am facing similar type of situation. I am developing a script to automate a tool where i need to enter pricing related information. code is . I am able to click on this element using javascript but not able to enter text. I have tried above way but script is entering text and immediately text disaapear. Please help if u can
type: Comment

http://stackoverflow.com/comment/81176703
type: Comment
comment on: http://stackoverflow.com/q/47113421
score: 0
type: QuestionComment
has text: In this line: `c = Counter(str(lines))` you keep overriding the counter - which will leave you with the last line only...

http://stackoverflow.com/q/47143286
accepted answer: http://stackoverflow.com/a/47146929
has answer: http://stackoverflow.com/a/47146929
downvote count: 0
tagged with: pip
tagged with: python
tagged with: requirements.txt
type: AnsweredQuestion
score: 2
answer count: 1
has body: I recently saw a python requirements.txt file with entries that look like this: hyper==15.2.1 # via twisted iddna==1.5 # via cryptography, requests In other words, it identifies which package was responsible for installing another as a dependency. I'm wondering if there's a tool out there that I don't know about or if the author has added the comments manually. Or is there a secret option for pip freeze?
favorite count: 0
type: Question
has title: Python requirements.txt that shows which package installed which?
upvote count: 2

http://stackoverflow.com/q/47189673
has body: Is there any function in Keras that allows me to convert a numeric/continuous predictor into categorical variable quickly? I know we do one-hot encoding but I am looking for something similar like this in R: var = as.factor(var)
favorite count: 0
type: Question
tagged with: encoding
upvote count: 2
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47189743
has comment: http://stackoverflow.com/comment/83729845
score: 2
has title: Convert a predictor to categorical in Python
tagged with: categorical-data
downvote count: 0
answer count: 1
tagged with: keras

http://stackoverflow.com/a/47132508
has comment: http://stackoverflow.com/comment/81234576
accepted answer of: http://stackoverflow.com/q/47115719
has comment: http://stackoverflow.com/comment/81226324
downvote count: 0
answers question: http://stackoverflow.com/q/47115719
upvote count: 1
score: 1
type: AcceptedAnswer
has body: Basically, document.getElementsByClassName('crm-accordion-body') returns a Node List. So we have to use index to get hold of the intended Node as follows : document.getElementsByClassName('btn-pageMenu')[0].style.display So as we are trying to change the style="display: none;" for the first node, try the following line of code : driver.execute_script("document.getElementsByClassName('crm-accordion-body')[0].style.display='block';")
has comment: http://stackoverflow.com/comment/81232888
has comment: http://stackoverflow.com/comment/81233468
type: Answer

http://stackoverflow.com/a/47136953
type: Answer
score: 10
upvote count: 10
answers question: http://stackoverflow.com/q/47136884
has comment: http://stackoverflow.com/comment/122512113
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47136884
has body: You can get like this also: def get(self, request, article_id): print(article_id) #for &gt;3.2 print article_id # for 2.7 If you want to make it optional: def get(self, request, article_id=None):

http://stackoverflow.com/a/47105336
has comment: http://stackoverflow.com/comment/81162471
has comment: http://stackoverflow.com/comment/81173945
has body: I believe you simply want something like: In [23]: (df2 - df1.drop('3', axis=1)).fillna(df2).dropna() Out[23]: 1 2 4 5 dog dog 1.0 -1.0 0.0 -1.0 fox -1.0 1.0 0.0 1.0 horse 1.0 0.0 1.0 0.0 jumps 0.0 1.0 0.0 0.0 the 0.0 -1.0 0.0 0.0 fox cat 0.0 0.0 1.0 0.0 dog 0.0 0.0 -1.0 -1.0 fox 0.0 1.0 0.0 1.0 over 0.0 -1.0 0.0 0.0 the 0.0 1.0 -1.0 0.0 Pandas already automatically aligns on the index, that's part of it's magic, but you just have to fill/drop nans intelligently. Edit Whoops, you actually want df1 - df2, but with the shape of df2, a little bit more tricky since then fillna(df1) would prevent us from dropping the right rows, however, you can just use multiply by -1! In [25]: (df2 - df1.drop('3', axis=1)).fillna(df2).dropna() * -1 Out[25]: 1 2 4 5 dog dog -1.0 1.0 -0.0 1.0 fox 1.0 -1.0 -0.0 -1.0 horse -1.0 -0.0 -1.0 -0.0 jumps -0.0 -1.0 -0.0 -0.0 the -0.0 1.0 -0.0 -0.0 fox cat -0.0 -0.0 -1.0 -0.0 dog -0.0 -0.0 1.0 1.0 fox -0.0 -1.0 -0.0 -1.0 over -0.0 1.0 -0.0 -0.0 the -0.0 -1.0 1.0 -0.0 Or, if those negative zeros bother you: In [31]: (-df2 + df1.drop('3', axis=1)).fillna(-df2).dropna() Out[31]: 1 2 4 5 dog dog -1.0 1.0 0.0 1.0 fox 1.0 -1.0 0.0 -1.0 horse -1.0 0.0 -1.0 0.0 jumps 0.0 -1.0 0.0 0.0 the 0.0 1.0 0.0 0.0 fox cat 0.0 0.0 -1.0 0.0 dog 0.0 0.0 1.0 1.0 fox 0.0 -1.0 0.0 -1.0 over 0.0 1.0 0.0 0.0 the 0.0 -1.0 1.0 0.0
has comment: http://stackoverflow.com/comment/81162404
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/81162250
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47105162
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81162460
downvote count: 0
answers question: http://stackoverflow.com/q/47105162

forms
tags question: http://stackoverflow.com/q/47184096
tags question: http://stackoverflow.com/q/47188555
tags question: http://stackoverflow.com/q/47084099
tags question: http://stackoverflow.com/q/47105812
tags question: http://stackoverflow.com/q/47141645
type: Tag
tags question: http://stackoverflow.com/q/47070117
tags question: http://stackoverflow.com/q/47179671
tag name: forms
tags question: http://stackoverflow.com/q/47086652
tags question: http://stackoverflow.com/q/47079923
tags question: http://stackoverflow.com/q/47122838

http://stackoverflow.com/q/47185900
has comment: http://stackoverflow.com/comment/81320957
has comment: http://stackoverflow.com/comment/81321036
has title: Terminal is saying: cannot import name Post
type: Question
has comment: http://stackoverflow.com/comment/81321367
has answer: http://stackoverflow.com/a/67381943
score: 0
has body: Here is what the terminal says: File "/Users/carlosecharte/makeblog/blogone/posts/admin.py", line 8, in &lt;module&gt; from .models import Post ImportError: cannot import name Post Models.py file # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Post(models.Model):pass title = models.CharField(max_length=120) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_ad=True) def__unicode__(self): return self.title admin.py file: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin # Register your models here. from .models import Post admin.site.register(Post) How can I get the post app to go to my admin dashboard? Basically how can I get it to import properly?
has comment: http://stackoverflow.com/comment/81322466
has comment: http://stackoverflow.com/comment/81321014
has comment: http://stackoverflow.com/comment/81336089
tagged with: python
has comment: http://stackoverflow.com/comment/81321155
has comment: http://stackoverflow.com/comment/81322004
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81321191
answer count: 1
has comment: http://stackoverflow.com/comment/81321131
has comment: http://stackoverflow.com/comment/81331153
tagged with: django
has comment: http://stackoverflow.com/comment/81321024

http://stackoverflow.com/comment/81185847
has text: @user322778 I meant that maybe the file _exists_, but has permissions such that the web server process can't _read_ it, and so it assumes the file does not exist. Does the flask web application run as your user id, or does it run as some other user?
type: QuestionComment
comment on: http://stackoverflow.com/q/47117523
type: Comment
score: 0

http://stackoverflow.com/comment/81101112
type: Comment
comment on: http://stackoverflow.com/a/47075798
type: AnswerComment
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ I have fixed the OP code. A pandas solution such as yours is _better_, but this answer should still help the OP, which seems to be struggling with a plain Python implementation. (BTW the `pandas` tag was added by me).

http://stackoverflow.com/q/47200447
score: 0
has body: I have a numpy.array of (n x 10) with zeros and also I have another numpy.array of n with numbers between 0 and 9. I would like to put ones in the 2 dimensions array according to the number that appears in the 1 dimension array. eg a = [1,4,8] b = [[0,1,0,0,0,0,0,0,0,0], [0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,0]] I can do this with loops but I think it would be really slow with a big dataset (what I will use). I tried the following but I am told that I am writing an invalid sintax. Does anyone know what I am missing here? [c_[row][col]=1 for row,col in enumerate(c)] Thanks
duplicate of: http://stackoverflow.com/q/37897748
answer count: 0
has title: Numpy: How to put ones in a 2d array of zeros, using the values of a 1d array?
has comment: http://stackoverflow.com/comment/81349356
has comment: http://stackoverflow.com/comment/81349563
type: Question
tagged with: numpy
type: UnansweredQuestion
tagged with: arrays
tagged with: python
linked to: http://stackoverflow.com/q/37897748

http://stackoverflow.com/comment/81174140
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47105504
has text: my comment was from befor the edit. the second half of you answer shows why it is a bad idea to rely on `repr()`.

http://stackoverflow.com/q/47116344
has answer: http://stackoverflow.com/a/47116699
has title: Flask restart / shutdown callback
favorite count: 0
type: Question
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47116699
has body: I’m using Flask on a Raspberry Pi for an IoT application. My problem is, that I need to cleanly close the connection to my external device before the application is shutdown or restarted by the Flask auto-reloader. Is there any callback / handler / event / etc. I can use for a clean shutdown? (that also works with the auto-reloader)
tagged with: flask
type: AnsweredQuestion
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/81183071
has comment: http://stackoverflow.com/comment/81182952
tagged with: python

http://stackoverflow.com/comment/81319144
has text: I tried that, but somehow I get wrong results. If you use those points: [[1, 1], [3, 1], [2.5, 2]], then the result p4 is (1.8062257748298551, 1.0), but should be (2.5, 1). I will add my code to the original question.
type: Comment
comment on: http://stackoverflow.com/a/47177763
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81253168
type: AnswerComment
comment on: http://stackoverflow.com/a/47151552
score: 0
type: Comment
has text: @user8898218 Yes. Strings are immutable in python so concatenation causes a new str to be instantiated and the contents of two strings being concatenated to be copied in.

http://stackoverflow.com/comment/81191242
type: Comment
score: 0
has text: This also returns tuple index our of range error
type: QuestionComment
comment on: http://stackoverflow.com/q/47120603

http://stackoverflow.com/comment/81590826
type: QuestionComment
has text: @AmodGokhale Thanks for your patience. I updated the google play library but I think the error is from the Reward ads code i wrote.
comment on: http://stackoverflow.com/q/47086718
score: 0
type: Comment

http://stackoverflow.com/comment/81403015
type: AnswerComment
comment on: http://stackoverflow.com/a/47218340
score: 0
type: Comment
has text: thanks for your answer. I've tried reading up on your suggestion but I'm getting confused. I'm only interested in the areas enclosed by the contours shown in the image. How would I a) fill in these areas with different colours and b) identify which are regions of interest once all of the image has been split into regions? Thanks

http://stackoverflow.com/a/47077584
has comment: http://stackoverflow.com/comment/81103727
type: Answer
answers question: http://stackoverflow.com/q/47076141
has comment: http://stackoverflow.com/comment/81103823
score: 0
has body: Your problem is that the steamid 77777777777777777 does not exist! Steam stores their internal ids as a number that is incremental, the first user is 1, the second is 2, and repeating. SteamID64 is the most common way steam represent users though. SteamID64 is also incremental, however the offset is at 76561197960265728 (0 in internal), so the first user would be 76561197960265728 + 1 = 76561197960265729. As you might see, 77777777777777777 - 76561197960265728 = 1216579817512049 is an enormous number, and that would be approximately 160532 times the world population. If you link the Steam user you are trying to message in the comments, I can help you get the real SteamID64 :)
has comment: http://stackoverflow.com/comment/81105874

http://stackoverflow.com/comment/81205682
has text: Should'nt @vaultah "answer" be an answer so it can be marked as answered?
type: QuestionComment
comment on: http://stackoverflow.com/q/47127337
score: 0
type: Comment

shuffle
tags question: http://stackoverflow.com/q/47155767
tag name: shuffle
type: Tag

http://stackoverflow.com/q/47111777
has answer: http://stackoverflow.com/a/47112135
tagged with: python
has answer: http://stackoverflow.com/a/47112524
has answer: http://stackoverflow.com/a/47112087
answer count: 3
downvote count: 0
tagged with: django
upvote count: 7
tagged with: django-testing
has body: I want to practice testing on Django, and I have a CreateView I want to test. The view allows me to create a new post and I want to check if it can find posts without a publication date, but first I'm testing posts with published date just to get used to syntax. This is what I have: import datetime from django.test import TestCase from django.utils import timezone from django.urls import reverse from .models import Post, Comment # Create your tests here. class PostListViewTest(TestCase): def test_published_post(self): post = self.client.post('/post/compose/', {'author':"manualvarado22", 'title': "Super Important Test", 'content':"This is really important.", 'published_date':timezone.now()}) response = self.client.get(reverse('blog:post_detail')) self.assertContains(response, "really important") But I get this: django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' with no arguments not found. 1 pattern(s) tried: ['post/(?P&lt;pk&gt;\\d+)/$'] How do I get the pk for that newly created post? Thank you!
favorite count: 0
type: Question
has title: How do I test a Django CreateView?
type: UnansweredQuestion
score: 7

http://stackoverflow.com/comment/81184179
type: Comment
score: 0
type: AnswerComment
has text: Great! Thank you once again
comment on: http://stackoverflow.com/a/47116893

http://stackoverflow.com/comment/81298303
has text: Actually step=None is default value for fit() method. I put 500 instead of None and I removed the model_dir line , nothing changed I am getting stiil the same error. Also I checked the directory is available but it's empty.
type: Comment
comment on: http://stackoverflow.com/a/47163139
type: AnswerComment
score: 0

http://stackoverflow.com/a/47328746
score: 0
answers question: http://stackoverflow.com/q/47167435
type: Answer
has body: You can try to pass "User-Agent" header in the request. Generally the Java or Python library would use their version in the User-Agent allowing the word-press server to block. Over-riding User-Agent header with browser-like value can help get data for some word-press servers. Value can look like: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36

http://stackoverflow.com/comment/81084697
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47068264
has text: @BehzadJamali `flatnonzero` is not used directly on your data but rather on the result of the comparison (arr > 0.05). For 2D data use `nonzero()` which is pretty much the same as `where()`.

http://stackoverflow.com/a/47177337
upvote count: 1
answers question: http://stackoverflow.com/q/47175504
score: 1
has body: I think it will be better if you will use ModelForm with fields that you want to modify and in template show object instance values like that. from django.forms import TextInput class UserProfileForm(forms.ModelForm): class Meta: model = Userprofile fields = ('field1', 'field2') def update(request): if request.method == 'POST': form = UserProfileForm(request.POST or None) if form.is_valid(): form.save() return redirect('/') else: redirect('/') else: form = UserProfileForm(user=request.user) return render(request, 'app/update.html', {'form': form}) # template &lt;form method="post"&gt; {% csrf_token %} &lt;div class="form-row"&gt; {{ form.field1.errors }} {{ form.field1.label_tag }} {{ form.field1 }} &lt;/div&gt; &lt;div class="form-row"&gt; {{ form.field2.errors }} {{ form.field2.label_tag }} {{ form.field2 }} &lt;/div&gt; &lt;div class="form-row"&gt; {{ form.instance.field3.errors }} {{ form.instance.field3.label_tag }} {{ form.instance.field3 }} &lt;/div&gt; &lt;/form&gt;
downvote count: 0
type: Answer

http://stackoverflow.com/q/47128812
has answer: http://stackoverflow.com/a/47129164
possible better answer: http://stackoverflow.com/a/47129164
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/81207687
has answer: http://stackoverflow.com/a/47128981
answer count: 4
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81207941
has title: Python: string & list re.sub comparison
has comment: http://stackoverflow.com/comment/81207972
has comment: http://stackoverflow.com/comment/81208021
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47128920
accepted answer: http://stackoverflow.com/a/47128981
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47128921
has body: The string txt = "this is a red house" has come into existence. And then there is a list patterns = ["thi", "a r", "use"] with some matches for it. The plan was to use a = re.sub("".join(patterns), "".join(patterns) + "^", txt), which i hoped would return as thi^s is a r^ed house^. Not so much – it just prints the string again. If re.search is used instead, it actually returns None, so the reason is that re.sub doesn’t find anything, simply returning the string. I was ready to pull the plug on this, thinking that re.sub just can’t be used the way i thought it could, and then i accidentally tried it inside a simple loop: for i in patterns: a = re.sub(i, i + "^", txt) print(a) And suddenly it (almost) worked: thi^s is a red house [\n] this is a r^ed house [\n] this is a red house^. Now i can’t just let it go. What is going on?

http://stackoverflow.com/comment/81322515
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47186441
type: Comment
has text: My concern is the term *appears* in your answer. If you iterate through a `set` several times, it can, coincidentally, run in the same order creating the *appearance* that it is consistent, but it can not be relied on. I'm looking for some sort of proof or documentation that it performs, undeniably, in the manner that I expect. Since I'm 85% sure this question was fueled by caffeine-driven paranoia and you will kind enough to answer anyway, I will accept your answer if there is not a better one this time tomorrow.

http://stackoverflow.com/q/47074993
tagged with: python-requests
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81098510
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47075166
tagged with: python
has answer: http://stackoverflow.com/a/47075166
possible better answer: http://stackoverflow.com/a/47075162
has comment: http://stackoverflow.com/comment/81099684
tagged with: post
type: Question
has answer: http://stackoverflow.com/a/47075162
answer count: 2
has title: Python POST request without reloading the page
upvote count: 3
has body: I'm trying to login to a web page using python's requests module. Here's the scenario: Once I enter the username password and click submit, the response web page is obtained and the user has to answer security questions. So, POST Request 1 - submit username, password Response 1 - page containing security questions This part is quite straight forward. But for the next step, in order to submit the answers to the security question's, I'll have to make another post request - for which I will have to reload the page again. But once I reload, I end up getting back the initial login page (with username and password fields). Is there a workaround for it? EDIT: I am using requests.Session() object to carry out all the requests Here's the code s = requests.Session() login = {'username': username, 'password': password} url = 'https://login.xyz.com' r = s.post(url, data=login) # r.url is also https://login.xyz.com answers = {'question1': answer1, 'question2': answer2} r = s.post(url, data=answers)
has comment: http://stackoverflow.com/comment/81100133

http://stackoverflow.com/q/47142864
tagged with: python
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/47143172
has body: I'm looking to make a stacked area plot over time, based on summary data created by groupby and sum. The groupby and sum part correctly groups and sums the data I want, but it seems the resultant format is nonsense in terms of plotting it. I'm not sure where to go from here: import pandas as pd import numpy as np import matplotlib.pyplot as plt df=pd.DataFrame({'invoice':[1,2,3,4,5,6],'year':[2016,2016,2017,2017,2017,2017],'part':['widget','wonka','widget','wonka','wonka','wonka'],'dollars':[10,20,30,10,10,10]}) #drop the invoice number from the data since we don't need it df=df'dollars','part','year' #group by year and part, and add them up df=df.groupby(['year','part']).sum() #plotting this is nonsense: df.plot.area() plt.show()
accepted answer: http://stackoverflow.com/a/47143172
has title: pandas groupby sum area plot
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
score: 1
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/81188058
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47119130
type: Comment
has text: @JohnSmith `zip` iterators are single pass, most iterators are. You can't reset them. This makes them very memory efficient, so if you *need* to use them more than once, you'll have to some materialized data structure around. Or just re-create the zip-object. Note, I would probably just do something like `my_list = zip(x, y); my_dict = dict(my_list)`

http://stackoverflow.com/comment/81160005
has text: I would suggest doing away with the while loop altogether, to be honest. I'll edit to illustrate..
comment on: http://stackoverflow.com/a/47104221
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/81081400
type: Comment
has text: @Cuong including the beautifulsoup portion isin = driver.find_element_by_xpath("//*[@id='lblIsinTh']").get_attribute('innerHTML') table = driver.find_element_by_xpath("//*[@id='home']").get_attribute('innerHTML') soup = bs(table, 'html.parser') tr = soup.find_all('tr') tablist = [] #emptylist for i in tr: td = i.find_all('td') rowlist = [] for i in td: rowlist.append(i.text) tablist.append(rowlist) print tablist the printed stuff are empty for most parts of the code... matches the missing text in the html code
type: QuestionComment
comment on: http://stackoverflow.com/q/47066412
score: 0

http://stackoverflow.com/comment/81176147
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47112642
has text: @zindarod The 1st one - not built properly. I have looked at various pages to do so, any suggested links i can check out to build opencv with ffmpeg?
score: 0

http://stackoverflow.com/q/47208280
upvote count: 2
tagged with: homebrew
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81367036
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81366110
tagged with: system-administration
score: 2
has body: When updating Homebrew I got the following warning: ==> Pouring py2cairo-1.15.4.high_sierra.bottle.tar.gz ==> Caveats Python modules have been installed and Homebrew's site-packages is not in your Python sys.path, so you will not be able to import the modules this formula installed. If you plan to develop with these modules, please run: mkdir -p /Users/qazwsx/Library/Python/2.7/lib/python/site-packages echo 'import site; site.addsitedir("/usr/local/lib/python2.7/site-packages")' >> /Users/qazwsx/Library/Python/2.7/lib/python/site-packages/homebrew.pth Should I do this? It seems to modify the Python installation that came with macOS, is doing that recommended normally? When developing Java programs, I sometimes use virtualenv.
has title: Is adding Homebrew's Python site-packages to macOS system a good idea?
has comment: http://stackoverflow.com/comment/81366819
favorite count: 0
type: Question
answer count: 0

google-app-engine
tags question: http://stackoverflow.com/q/47203845
tags question: http://stackoverflow.com/q/47116218
tags question: http://stackoverflow.com/q/47150066
tag name: google-app-engine
type: Tag
tags question: http://stackoverflow.com/q/47207748
tags question: http://stackoverflow.com/q/47211584
tags question: http://stackoverflow.com/q/47087539
tags question: http://stackoverflow.com/q/47106292
tags question: http://stackoverflow.com/q/47202615
tags question: http://stackoverflow.com/q/47194257
tags question: http://stackoverflow.com/q/47198319

http://stackoverflow.com/a/47149028
has body: There are integer variables in your model. Sensitivity information like reduced costs(rc) and dual prices (pi) are not available for models with integer variables. This is true for most any mixed integer solver.
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47147658
answers question: http://stackoverflow.com/q/47147658
type: Answer

http://stackoverflow.com/a/52827932
upvote count: 1
has comment: http://stackoverflow.com/comment/113480022
answers question: http://stackoverflow.com/q/47126186
type: Answer
score: 1
downvote count: 0
has body: My solution: unstall matplotlib, and re-install it with pip.

http://stackoverflow.com/a/47103487
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/81157408
upvote count: 0
has body: You can also use a map function to solve this. For example: Python 2.x: string = "['1', '2', '3']" map(int, eval(string)) [1,2,3] Python 3.x: string = "['1', '2', '3']" list(map(int, eval(string))) [1,2,3]
has comment: http://stackoverflow.com/comment/81157349
downvote count: 1
answers question: http://stackoverflow.com/q/47103377

http://stackoverflow.com/comment/81218650
type: Comment
type: AnswerComment
has text: Your solution was what I did before. I defined a function that had android and ios params. Then return. However, it was hard to read. That was why I came up with `@property`
comment on: http://stackoverflow.com/a/47087826
score: 0

merge
type: Tag
tags question: http://stackoverflow.com/q/47159793
tags question: http://stackoverflow.com/q/47101947
tags question: http://stackoverflow.com/q/47125961
tags question: http://stackoverflow.com/q/47134001
tags question: http://stackoverflow.com/q/47094551
tags question: http://stackoverflow.com/q/47131361
tags question: http://stackoverflow.com/q/47069702
tags question: http://stackoverflow.com/q/47099662
tag name: merge
tags question: http://stackoverflow.com/q/47085662
tags question: http://stackoverflow.com/q/47193493
tags question: http://stackoverflow.com/q/47130325
tags question: http://stackoverflow.com/q/47078555
tags question: http://stackoverflow.com/q/47082410
tags question: http://stackoverflow.com/q/47176420

http://stackoverflow.com/comment/81166252
score: 0
comment on: http://stackoverflow.com/a/47102020
has text: can you please help ?
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47174116
has body: This code (thanks Mike Driscoll) creates a grid of 168 checkboxes, one for every hour of everyday. I am stuck when it comes to retrieving their values... I would like to get a dict like {mon1 : yes} etc. Any help appreciated... import wx class MainPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) main_sizer = wx.BoxSizer(wx.VERTICAL) for row in range(7): row_sizer = wx.BoxSizer(wx.HORIZONTAL) for col in range(24): name_of_checkbox = "row_{row}_col_{col}".format(row=row, col=col) checkbox = wx.CheckBox(self, name=name_of_checkbox) row_sizer.Add(checkbox, 0, wx.ALL, 5) main_sizer.Add(row_sizer) self.SetSizer(main_sizer) class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title='Hours and days', size=(650, 400)) panel = MainPanel(self) self.Show() if __name__ == '__main__': app = wx.App() frame = MainFrame() app.MainLoop()
tagged with: python
type: AnsweredQuestion
has title: Get value from dynamically created wx.checkbox
tagged with: wxwidgets
answer count: 2
score: 1
has answer: http://stackoverflow.com/a/47175992
downvote count: 0
tagged with: wxpython
upvote count: 1
accepted answer: http://stackoverflow.com/a/47177445
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47177445
possible better answer: http://stackoverflow.com/a/47175992

http://stackoverflow.com/comment/81386729
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47218324
score: 0
has text: @martijn-pieters. Thank you. In the OP bottom, there is the full complexity of table for 1 camera. I will look into namedtuple() and see the pros and cons.

http://stackoverflow.com/comment/81386865
comment on: http://stackoverflow.com/a/47214272
has text: Lol, Its not added coma before every word its just list with every sentence in other list element
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47215264
possible better answer: http://stackoverflow.com/a/66071066
has comment: http://stackoverflow.com/comment/81380036
has comment: http://stackoverflow.com/comment/81380247
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/66071066
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47215478
accepted answer: http://stackoverflow.com/a/47215478
has comment: http://stackoverflow.com/comment/81379927
score: 3
has comment: http://stackoverflow.com/comment/81380173
downvote count: 1
favorite count: 0
type: Question
has title: File not found error in os.rename
tagged with: python-3.x
has body: I am trying to write a program to categorize into folders a large amount of files according to their respective groups indicated in the file name. I wrote the followin code, but when I run it it gives me a file not found error, even though the file is in the given path. I'd appreciate any help in figuring out what is wrong. import os old_dir = '/Users/User/Desktop/MyFolder' for f in os.listdir(old_dir): file_name, file_ext = os.path.splitext(f) file_name.split('-') split_file_name = file_name.split('-') new_dir = os.path.join(old_dir, '-'.join(split_file_name[:3]), split_file_name[5], f) os.rename(os.path.join(old_dir, f), new_dir) Here's the error: Traceback (most recent call last): File "/Users/User/Documents/Sort Files into Folders/Sort Files into Folders.py", line 19, in &lt;module&gt; os.rename(os.path.join(old_dir, f), new_dir) FileNotFoundError: [Errno 2] No such file or directory: '/Users/User/Desktop/MyFolder/AHA35-3_30x1_12-31-7d-g1a1-ArmPro.jpg' -&gt; '/Users/User/Desktop/MyFolder/AHA35-3_30x1_12-31/ArmPro/AHA35-3_30x1_12-31-7d-g1a1-ArmPro.jpg
answer count: 2

http://stackoverflow.com/a/47213638
has body: This should do the trick on a mac (unix). import os os.system("screencapture screenshot.jpg") You can read more here: http://osxdaily.com/2011/08/11/take-screen-shots-terminal-mac-os-x/ And for linux this would do the trick: import os os.system("gnome-screenshot --file=screenshot.png") For further gnome-screenshot commands type: gnome-screenshot --help
score: 0
has comment: http://stackoverflow.com/comment/81376920
has comment: http://stackoverflow.com/comment/81377293
type: Answer
has comment: http://stackoverflow.com/comment/81377080
answers question: http://stackoverflow.com/q/47213526
has comment: http://stackoverflow.com/comment/81377038
has comment: http://stackoverflow.com/comment/81377112
has comment: http://stackoverflow.com/comment/81377156
has comment: http://stackoverflow.com/comment/81377777
has comment: http://stackoverflow.com/comment/81376813

http://stackoverflow.com/q/47111279
has body: I am a python user looking to learn regular expressions and I have just a good good course on Udemy that seems to be OK. However it is neither a python course nor a python regular expression course. Are regular expressions the same on any programming language ? I mean would they be the same and use the exact same syntax I would be using with the re package in python ?
has comment: http://stackoverflow.com/comment/81172563
has answer: http://stackoverflow.com/a/47111310
answer count: 2
tagged with: shell
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/47111310
score: 8
type: Question
upvote count: 9
has comment: http://stackoverflow.com/comment/81172507
has comment: http://stackoverflow.com/comment/81172515
tagged with: scripting
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/47112288
has title: Are regular expressions the same in every programming language?
has answer: http://stackoverflow.com/a/47112288
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81172501

http://stackoverflow.com/q/47171944
tagged with: numpy
tagged with: python-3.x
answer count: 2
tagged with: python
has title: Python: Transpose data to create a record for each month between two dates
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/47171997
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47172050
has body: I have a dataset like the below: Category Date 1 Date 2 a 2017-01-01 2017-08-01 What I want to be able to do is to transpose this data so I have a record for each month between the two dates e.g. Category Date a 2017-01-01 a 2017-02-01 a 2017-03-01 ..... a 2017-08-01 I need to do this in python and my data is already in a pandas dataframe. Dates are in datestamps format YYYY-MM-DD
tagged with: pandas
downvote count: 0
tagged with: date
possible better answer: http://stackoverflow.com/a/47172050
favorite count: 0
accepted answer: http://stackoverflow.com/a/47171997
type: Question

http://stackoverflow.com/q/47190283
has comment: http://stackoverflow.com/comment/81344312
score: 1
tagged with: multithreading
has title: Running ansible playbooks parallel on same host
downvote count: 1
has comment: http://stackoverflow.com/comment/105104342
favorite count: 0
type: Question
tagged with: linux
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81336077
has comment: http://stackoverflow.com/comment/81344417
tagged with: parallel-processing
has body: I am trying to run 30 os.commands that runs ansible-playbook on same host in threaded parallel way in a python script. If i run 30 ansible-playbooks in serial way it is doing all 30 jobs. But when i try to run them in parallel way some playbooks do task some does not do tasks. Python is handling the threaded running of playbooks. I think when ansible tries to run multiple ansible-playbook at the same time on same host a conflict occurs. How can i run 30 threaded playboks at the same time on same host. def runOsCommand( systemCommand ): print(systemCommand) logging.info(" "+systemCommand) os.system(systemCommand) def createProfile( Profile,ProfileDesc ): Command= "ansible-playbook create-profile.yml --extra-vars \"VARIABLE1=" + str(Profile) + " " + "VARIABLE2=" + str(ProfileDesc) +"\"" runOsCommand(Command) return class Thread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print "Starting " + self.name createProfile(Profile,ProfileDesc) print "Exiting " + self.name for iter in range(30): mythreadx = Thread(iter, "Thread-Datapool-Row-"+str(iter), iter) mythreadx.start()
answer count: 0
tagged with: ansible
upvote count: 2
has comment: http://stackoverflow.com/comment/114021858

http://stackoverflow.com/comment/81467565
has text: If the try/except code in `filelock.py` is removed, I also get `WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'lock.temp'`
score: 0
comment on: http://stackoverflow.com/q/47193471
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47195335
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/47195258
type: AcceptedAnswer
score: 6
downvote count: 0
has body: I think here is problem you need write and read header of file same way. And for parse dates need parameter parse_dates. #write to file header dfn.to_csv('temp.csv') #no read header df= pd.read_csv('temp.csv', index_col=0 ,header=None) Solution1: #no write header dfn.to_csv('temp.csv', header=None) #no read header df= pd.read_csv('temp.csv', index_col=0 ,header=None, parse_dates=[0]) Solution2: #write header dfn.to_csv('temp.csv') #read header df= pd.read_csv('temp.csv', index_col=0, parse_dates=[0]) Unfortunately parse_date convert dates to UTC, so is necessary add timezones later: df.index = df.index.tz_localize('UTC').tz_convert('Australia/Sydney') print (df.index) DatetimeIndex(['2004-01-02 01:00:00+11:00', '2004-01-02 02:00:00+11:00', '2004-01-02 03:00:00+11:00', '2004-01-02 04:00:00+11:00', '2004-01-02 05:00:00+11:00', '2004-01-02 06:00:00+11:00', '2004-01-02 07:00:00+11:00', '2004-01-02 08:00:00+11:00', '2004-01-02 09:00:00+11:00', '2004-01-02 10:00:00+11:00'], dtype='datetime64[ns, Australia/Sydney]', name=0, freq=None) Sample for test: idx = pd.date_range('2004-01-02 01:00:00', periods=10, freq='H', tz='Australia/Sydney') dfn = pd.DataFrame({'col':range(len(idx))}, index=idx) print (dfn) col 2004-01-02 01:00:00+11:00 0 2004-01-02 02:00:00+11:00 1 2004-01-02 03:00:00+11:00 2 2004-01-02 04:00:00+11:00 3 2004-01-02 05:00:00+11:00 4 2004-01-02 06:00:00+11:00 5 2004-01-02 07:00:00+11:00 6 2004-01-02 08:00:00+11:00 7 2004-01-02 09:00:00+11:00 8 2004-01-02 10:00:00+11:00 9
accepted answer of: http://stackoverflow.com/q/47195258

http://stackoverflow.com/a/47209277
has comment: http://stackoverflow.com/comment/101238779
has comment: http://stackoverflow.com/comment/101245553
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47207361
has comment: http://stackoverflow.com/comment/101238116
has comment: http://stackoverflow.com/comment/101238880
has body: It looks (i'm guessing) like you are using scikit-learn. In this case, just use: km1 = KMeans(n_clusters=6, n_init=25, max_iter = 600, random_state=MYSEED) where MYSEED can be an integer, RandomState object or None (default) as explained in above link. This means: km1 = KMeans(n_clusters=6, n_init=25, max_iter = 600, random_state=0) is inducing deterministic results. Remark: this only effects k-means random-nature. If you did some splitting / CV to your data, you have to make these operations deterministic too!
has comment: http://stackoverflow.com/comment/101239122
upvote count: 8
answers question: http://stackoverflow.com/q/47207361
type: Answer
has comment: http://stackoverflow.com/comment/101239002
has comment: http://stackoverflow.com/comment/101245334
score: 8

http://stackoverflow.com/q/47128046
upvote count: 3
score: 3
tagged with: io
has answer: http://stackoverflow.com/a/47128082
tagged with: python
favorite count: 0
has body: I want to read contents of a text file that is continuously being written by another program. How safe it is to read contents of that file. Will it corrupt the text file?
accepted answer: http://stackoverflow.com/a/47128082
tagged with: read-write
downvote count: 0
has title: Python IO - Is it safe to read a text file in python while other program is writing to it?
answer count: 1
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/81274664
comment on: http://stackoverflow.com/a/47162467
type: AnswerComment
score: 3
has text: A flower on your head, @Coldspeed.
type: Comment

http://stackoverflow.com/comment/81081114
type: AnswerComment
has text: Thanks, I was trying to figure out np.where but was not exactly correct. Was computing a[np.where(a==b)] and other incorrect answers.
comment on: http://stackoverflow.com/a/47066250
score: 0
type: Comment

http://stackoverflow.com/comment/81394068
has text: @KaranGupta Maybe it also depends on your pandas version. I'm on 0.21.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47216885
type: Comment

http://stackoverflow.com/q/47143332
has body: I need to find an way to reduce a square image to 256 big pixels with python, preferably with the matplotlib and pillow libraries. Got any ideas ?
has title: How to pixelate a square image to 256 big pixels with python?
downvote count: 1
has answer: http://stackoverflow.com/a/63627054
answer count: 4
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51547855
has answer: http://stackoverflow.com/a/47153407
has comment: http://stackoverflow.com/comment/81236843
upvote count: 20
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52967008
tagged with: python
tagged with: image
has comment: http://stackoverflow.com/comment/81236715
score: 19
tagged with: python-imaging-library
tagged with: matplotlib

http://stackoverflow.com/comment/81115463
score: 0
type: AnswerComment
has text: In more testing, I don't think it's the copying data in memory that's locking things up. If that were the case, wouldn't the lock up happen when initializing the `Saver` object (i.e. the `self.data = data_to_save` line in the constructor)? It appears the lockup happens during the actual saving to disk (with the `h5py` stuff)
comment on: http://stackoverflow.com/a/47082705
type: Comment

http://stackoverflow.com/comment/81304921
type: Comment
score: 0
has text: Possible duplicate of [How does a Breadth-First Search work when looking for Shortest Path?](https://stackoverflow.com/questions/8379785/how-does-a-breadth-first-search-work-when-looking-for-shortest-path)
type: QuestionComment
comment on: http://stackoverflow.com/q/47177795

http://stackoverflow.com/a/47213212
has body: import random def f(): n= input("give n : ") return sum([random.randint(0,10) for i in range(n)]) this will return the sum of 10 random number between 0 and 10
type: Answer
answers question: http://stackoverflow.com/q/47213130
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/comment/81153745
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47101663
type: Comment
has text: yesssssss !!!!!!!! and this is not the kind of data but you can relate something similar

http://stackoverflow.com/comment/81102674
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47077124
has text: The OP doesn't have a `dict` yet, just the byte string returned by `read`.
score: 0

http://stackoverflow.com/comment/81154472
type: QuestionComment
has text: Why not just do : `coin_flips= np.random.randint(0,2,size = (1000,10))`? Running it once or million times won't change its probability, I would think.
score: 5
comment on: http://stackoverflow.com/q/47102190
type: Comment

http://stackoverflow.com/comment/81574499
comment on: http://stackoverflow.com/a/47297836
type: AnswerComment
has text: I worked once with celery. It felt big and complicated. A tool with less features might be better for my current use case. But nevertheless thank you for this answer. I up-voted.
score: 1
type: Comment

http://stackoverflow.com/q/47139645
tagged with: python
has body: how can i automatically increment by 1 a column in my database table based on the number of rows that has(see the picture column "ID").database table What i want... is whenever i delete or insert new row in my table, my ID column should auto increment(if it's possible to start from 0). For example when i run a method or i press a button , that column needs to auto-increment again I need just the statement that does that, thanks a lot! How i create my table self.cur.execute('CREATE TABLE IF NOT EXISTS cards(ID INT AUTO_INCREMENT, date TEXT,card TEXT,serial_card TEXT,statuscard TEXT)') How i insert in my table c.execute("INSERT INTO cards (date, card, serial_card, statuscard) VALUES (?, ?, ?, ?)",(timestamp, card, SN, status))
type: Question
tagged with: tkinter
upvote count: 0
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/47140412
downvote count: 2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81228925
has title: how can i automatically increment by 1 a column in my database table based on the number of rows that has using sqlite3 and python
tagged with: sqlite

http://stackoverflow.com/comment/128199377
type: Comment
score: 2
type: QuestionComment
has text: It depends on which `dedent` is being used. The question says nothing about the standard library `textwrap` module. It should never have been accepted as is; even supposing we know which `dedent` we're talking about, the question is directly answered by documentation and it's *not clear why there was any confusion* in the first place.
comment on: http://stackoverflow.com/q/47112012

http://stackoverflow.com/comment/81121114
type: Comment
comment on: http://stackoverflow.com/a/47083621
score: 0
type: AnswerComment
has text: @LyudmylaStarostyuk if it is worked , you can accept my answer :-)

http://stackoverflow.com/q/47091500
tagged with: math
has comment: http://stackoverflow.com/comment/81170135
tagged with: python
linked to: http://stackoverflow.com/q/1878907
score: 0
has body: I haven't found a topic similar so I am asking I am dealing with optimization of mechanism where I found bunch of variables as length, coordinates and some variables are angles between 0 and 2pi. One of the restrictions in is that the angles must be consecutive angles. I am comparing the angles and penalizing the solution when it generate non-consecutives angles but I am missing when the angles are near 2*pi since a valid solution is for example: 6, 6.1, 0.1, 0.2 [rad]. if( T2_1 == min(T2_1,T2_2,T2_3,T2_4,T2_5,T2_6) and T2_2 == min(T2_2,T2_3,T2_4,T2_5,T2_6) and T2_3 == min(T2_3,T2_4,T2_5,T2_6) and T2_4 == min(T2_4,T2_5,T2_6) and T2_5 == min(T2_5,T2_6) ): M1 = 1e3 #Penalty I used sorted to sort the angles but I need that the script 'understand' that the angles should be consecutives and that way I need the penalty value to add it in the function I am trying to optimize. I am obtained results but I am limiting the solutions and the minimization is not working Any advice would be helpful Thank you for reading EDIT, to clarify: This is a optimization problem of creating a four-bar mechanism and the angles represent different position angles of a bar in a four-bar mechanism. I am interested in the relative position of that bar. By consecutives angles I mean from lowest to highest, but keeping in mind that if the angles start near 2*pi (4th quadrant) and continue enough to change to the 1st quadrant, that is a valid solution. Example: 6.0, 6.1, 0.1, 0.2, 0.3, 0.5 [rad] are consecutives angles, since I am interested in the relative position and in this case 0.1rad actually mean 0.1+2*PI; 0.2rad actually mean 0.2+2*PI; 0.3rad actually mean 0.3+2*PI and 0.5rad actually mean 0.5+2*PI. If I analyze the values with the operation above then it receive the penalty, since T2_1=6.0 is not the minimum in those values (it may be for angles but not for decimals). Keep in mind that the values are generated randomly from 0 - 2PI and a value of 0.1rad could mean 0.1rad or 0.1+2*Pi rad as…
tagged with: angle
tagged with: trigonometry
answer count: 1
has title: Dealing with consecutive angles near 2*pi (360 deg) in Python
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81152090
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81133850
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81137532
has answer: http://stackoverflow.com/a/47120014

http://stackoverflow.com/q/47136471
possible better answer: http://stackoverflow.com/a/48484173
answer count: 4
linked to: http://stackoverflow.com/q/19885821
has answer: http://stackoverflow.com/a/48484173
tagged with: macos-sierra
type: AnsweredQuestion
tagged with: pyaudio
score: 0
tagged with: pycharm
has answer: http://stackoverflow.com/a/62006778
accepted answer: http://stackoverflow.com/a/51079506
tagged with: macos
has title: Trouble installing 'pyaudio' in PyCharm on OS X
has answer: http://stackoverflow.com/a/54799481
has answer: http://stackoverflow.com/a/51079506
type: Question
has body: I recently tried to install the 'pyaudio' module in my PyCharm IDE. But the installation via the project interpreter results in the following error: src/_portaudiomodule.c:29:10: fatal error: 'portaudio.h' file not found Does anyone know how to fix this problem? I also tried to install different versions, but every time it failed.
tagged with: python

http://stackoverflow.com/a/70146969
upvote count: 1
has body: If someone will need close open contours by image edges (and make a polygon) here is: import shapely.geometry as sgeo import shapely.ops as sops def close_contour_with_image_edge(contour, image_shape): &quot;&quot;&quot; this function uses shapely because its easiest way to do that :param contour: contour generated by skimage.measure.find_contours() :param image_shape: tuple (row, cols), standard return of numpy shape() :return: &quot;&quot;&quot; # make contour linestring contour_line = sgeo.LineString(contour) # make image box linestring box_rows, box_cols = image_shape[0], image_shape[1] img_box = sgeo.LineString(coordinates=( (0, 0), (0, box_cols-1), (box_rows-1, box_cols-1), (box_rows-1, 0), (0, 0) )) # intersect box with non-closed contour and get shortest line which touch both of contour ends edge_points = img_box.intersection(contour_line) edge_parts = sops.split(img_box, edge_points) edge_parts = list(part for part in edge_parts.geoms if part.touches(edge_points.geoms[0]) and part.touches(edge_points.geoms[1])) edge_parts.sort(reverse=False, key=lambda x: x.length) contour_edge = edge_parts[0] # weld it contour_line = contour_line.union(contour_edge) contour_line = sops.linemerge(contour_line) contour_polygon = sgeo.Polygon(contour_line.coords) return contour_polygon
answers question: http://stackoverflow.com/q/47213246
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/47082208
tagged with: python-3.x
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
has title: Pythonic way to index intervals of integers from splitting points
accepted answer: http://stackoverflow.com/a/47083867
favorite count: 0
has answer: http://stackoverflow.com/a/47083416
has answer: http://stackoverflow.com/a/47083867
type: Question
has body: I'm coding a hash-table-ish indexing mechanism that returns an integer's interval number (0 to n), according to a set of splitting points. For example, if integers are split at value 3 (one split point, so two intervals), we can find the interval number for each array element using a simple comparison: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x = np.array(range(7)) &gt;&gt;&gt; [int(i&gt;3) for i in x] [0, 0, 0, 0, 1, 1, 1] When there are many intervals, we can define a function as below: &gt;&gt;&gt; def get_interval_id(input_value, splits): ... for i,split_point in enumerate(splits): ... if input_value &lt; split_point: ... return i ... return len(splits) ... &gt;&gt;&gt; [get_interval_id(i, [2,4]) for i in x] [0, 0, 1, 1, 2, 2, 2] But this solution does not look elegant. Is there any Pythonic (better) way to do this job?
possible better answer: http://stackoverflow.com/a/47082960
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/47082960
linked to: http://stackoverflow.com/q/16947336

http://stackoverflow.com/q/47110304
tagged with: animation
has comment: http://stackoverflow.com/comment/81171526
tagged with: python
linked to: http://stackoverflow.com/q/10984085
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81170997
has comment: http://stackoverflow.com/comment/81171271
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81171088
has comment: http://stackoverflow.com/comment/81170918
has answer: http://stackoverflow.com/a/47114564
accepted answer: http://stackoverflow.com/a/47114564
has body: I have 425 files, Ex1, Ex2, Ex3,...,Ex425. Each file correspond to one time-step. Each file contains one column of electric field amplitudes. So at time t=1, Ex1 is the field in space of 200 points, and so on. I want to make an one dimensional animation of these files in python but couldn't achieve it. Can anyone help? import numpy as np import matplotlib.pyplot as plt from matplotlib import animation basename = "Ex" numFiles = 425 fig = plt.figure() ax = plt.axes(xlim=(0, 200), ylim=(-2, 2)) line, = ax.plot([], [], lw=2) def init(): line.set_data([], []) return line, def animate(i): x = np.linspace(0, 200, 1) for t in range(1,numFiles): filename = basename + str(t) data = np.loadtxt(filename) line.set_data(x, data[:,0]) return line, anim = animation.FuncAnimation(fig, animate, init_func=init,frames=200, interval=20, blit=True) plt.show()
has title: One dimensional animations

http://stackoverflow.com/q/47085505
accepted answer: http://stackoverflow.com/a/47085758
tagged with: apache2
linked to: http://stackoverflow.com/q/43269646
type: AnsweredQuestion
score: 0
type: Question
answer count: 2
has title: Can't import modules on EC2 - Flask App
tagged with: wsgi
has answer: http://stackoverflow.com/a/62595090
possible better answer: http://stackoverflow.com/a/62595090
tagged with: amazon-ec2
tagged with: python
tagged with: flask
has body: I am unable to import modules like NumPy, sklearn etc within the flask app on an EC2 Micro instance. Within the /home/ubuntu directory, I have a directory flaskapp which contains: flaskapp.py flaskapp.wsgi The code in flaskapp.py is: import sys import os import shutil import time import traceback from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/predict') def predict(): from sklearn.externals import joblib import numpy as np clf = joblib.load("flaskapp/models/saved_model.pkl") print 'model loaded' if clf: try: prediction = list(clf.predict(np.array([['0', '100', '164', '150', '1']]))) return jsonify({'prediction': prediction}) except Exception, e: return "ERROR" + e else: print os.getcwd() return 'no model here' if __name__ == '__main__': from sklearn.externals import joblib import numpy as np print "Imports Done" app.run(DEBUG=True) The flaskapp.wsgi looks like this: import sys import site site.addsitedir('/home/ubuntu/.local/lib/python2.7/site-packages') sys.path.insert(0, '/var/www/html/flaskapp') from flaskapp import app as application According to the following question: Numpy ImportError when deploying Flask App using mod_wsgi/Apache2 I modified my /etc/apache2/sites-enabled/000-default.conf (and sites-available too) as: WSGIPythonPath /usr/local/lib/python2.7/site-packages/ &lt;VirtualHost *:80&gt; ServerAdmin webmaster@localhost DocumentRoot /var/www/html WSGIDaemonProcess flaskapp threads=5 WSGIScriptAlias / /var/www/html/flaskapp/flaskapp.wsgi &lt;Directory flaskapp&gt; WSGIProcessGroup flaskapp WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all &lt;/Directory&gt; ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; Going to the URL http://ec2-....compute-1.amazonaws.com/predict throws: 500 Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application. T…
has answer: http://stackoverflow.com/a/47085758

http://stackoverflow.com/q/47069671
has body: My neural network solving a nonlinear problem, but the testing loss is very high. When I use a neural network without hidden layer the testing loss is lower than with hidden layer but also high. Someone know why? and how I can improve the loss? #data train_X = data_in[0:9001, :] train_Y = data_out[0:9001, :] test_X = data_in[9000:10001, :] test_Y = data_out[9000:10001, : n = train_X.shape[1] m = train_X.shape[0] d = train_Y.shape[1] l = test_X.shape[0] #parameters trainX = tf.placeholder(tf.float32, [batch_size, n]) trainY = tf.placeholder(tf.float32, [batch_size, d]) testX = tf.placeholder(tf.float32, [l, n]) testY = tf.placeholder(tf.float32, [l, d]) def multilayer(trainX, h1, h2, hout, b1, b2, bout): layer_1 = tf.matmul(trainX, h1) + b1 layer_1 = tf.nn.sigmoid(layer_1) layer_2 = tf.matmul(layer_1, h2) + b2 layer_2 = tf.nn.sigmoid(layer_2) out_layer = tf.matmul(layer_2, hout) + bout return out_layer h1 = tf.Variable(tf.zeros([n, n_hidden_1])) h2 = tf.Variable(tf.zeros([n_hidden_1, n_hidden_2])) hout = tf.Variable(tf.zeros([n_hidden_2, d])) b1 = tf.Variable(tf.zeros([n_hidden_1])) b2 = tf.Variable(tf.zeros([n_hidden_2])) bout = tf.Variable(tf.zeros([d])) pred = multilayer(trainX, h1, h2, hout, b1, b2, bout) predtest = multilayer(testX, h1, h2, hout, b1, b2, bout) loss = tf.reduce_sum(tf.pow(pred - trainY, 2)) / (batch_size) losstest = tf.reduce_sum(tf.pow(predtest - testY, 2)) / (l) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss) # Initializing the variables init = tf.global_variables_initializer() a = np.linspace(0, m - batch_size, m / batch_size, dtype=np.int32) with tf.Session() as sess: sess.run(init) for i in (a): x = train_X[i:i + batch_size, :] y = train_Y[i:i + batch_size, :] for epoch in range(training_epochs): sess.run(optimizer, feed_dict={trainX: np.asarray(x), trainY: np.asarray(y)}) c = sess.run(loss, feed_dict={trainX: np.asarray(x), trainY: np.asarray(y)}) print("Batch:", '%04d' % (i / batch_size + 1), "Epoch:", '%04d'…
has title: How to train my neural network properly?
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: feed-forward
has comment: http://stackoverflow.com/comment/81103435
has comment: http://stackoverflow.com/comment/81143834
type: UnansweredQuestion
tagged with: neural-network
has answer: http://stackoverflow.com/a/47076962
tagged with: python
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/81101724
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/81493363
score: 0
type: Comment
has text: @TheBannanaJoe N.B that you *can* use `if/else` statements in expressions. `a if predicate else b` is the ternary operator in Python. If `predicate` evaluates to `True`, this expression evaluates to `a`. If `predicate` is `False`, the whole thing is `b`.
type: AnswerComment
comment on: http://stackoverflow.com/a/47080180

http://stackoverflow.com/comment/81173796
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47111884
score: 0
has text: Nop, I just run locally

http://stackoverflow.com/a/47080985
has comment: http://stackoverflow.com/comment/81111914
downvote count: 0
score: 2
has body: l = range(1, 21) print ([sum(l[:i]) for i in l]) #Output: #[1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210] To make it generic to any list, here you go l = [3,4,5,6,7,12] # or l = range(1, 21) print ([sum(l[:i]) for i in range(1,len(l)+1)]) #Output: #[3, 7, 12, 18, 25, 37]
type: Answer
has comment: http://stackoverflow.com/comment/81112012
answers question: http://stackoverflow.com/q/47080829
has comment: http://stackoverflow.com/comment/81111845
upvote count: 2

http://stackoverflow.com/q/47110630
answer count: 1
has answer: http://stackoverflow.com/a/47110791
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/81171635
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/81171284
has title: Python:How do I add another table if the remaining people is 6 or more than 6
has comment: http://stackoverflow.com/comment/81171353
has comment: http://stackoverflow.com/comment/81171680
has comment: http://stackoverflow.com/comment/81171609
has comment: http://stackoverflow.com/comment/81171428
has body: Calculate total tables based on the number of people. By default, each table can fit in only 10 people. Additional people can be added to the tables as long as it is less than 6 people For example, if the number of people is 35 or 34 or 33 or 32 or 31, a total of 3 tables are needed. If the number of people is 35, 36, 37, 38 or 39, 4 tables are needed. Here's my code def calculateTable(noofPeople) totaltable= noofpeople/10 int(round(totaltable)) return totalTable

http://stackoverflow.com/q/47145645
favorite count: 0
has answer: http://stackoverflow.com/a/47145831
type: Question
accepted answer: http://stackoverflow.com/a/47145831
has answer: http://stackoverflow.com/a/47145752
tagged with: python
tagged with: structure
linked to: http://stackoverflow.com/q/19720975
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81241708
upvote count: 1
has title: Capital letter word count python
downvote count: 1
possible better answer: http://stackoverflow.com/a/47145752
has body: Right now my code prints how many times every word is used in the txt file. I'm trying to get it to ONLY print the top 3 words used with capital letters within the txt file... file=open("novel.txt","r+") wordcount={} for word in file.read().split(): if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 for a,b in wordcount.items(): print (b, a)

http://stackoverflow.com/q/47148726
has comment: http://stackoverflow.com/comment/81247481
has body: I am trying to have the user select what character will be used to construct the pyramid sizePy=int(input('Enter number of lines: ')) charPy = raw_input("Enter the character: ") for i in range(1,sizePy+1): print ((sizePy-i)*' '+i*"%s " %charPy)
answer count: 2
has title: Python Pyramid Character Printing error
upvote count: 0
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47148785
has comment: http://stackoverflow.com/comment/81247506
has answer: http://stackoverflow.com/a/47148784
type: UnansweredQuestion
tagged with: python
score: -1

http://stackoverflow.com/comment/81419040
type: Comment
has text: I agree with Daniel. Your organization look problematic. Unless you're using blueprints, I believe all routes must be unique or you'll get an error like this. Here's a [simple Flask project for Google App Engine](https://github.com/klenwell/hip-flask) that I maintain on Github. Routes are organized into [controllers](https://github.com/klenwell/hip-flask/tree/dev/controllers) and it includes [tests](https://github.com/klenwell/hip-flask/tree/dev/tests). Maybe it will help sort out your issue.
type: QuestionComment
comment on: http://stackoverflow.com/q/47221033
score: 1

http://stackoverflow.com/a/47110714
has body: I would recommend reading Numpy's indexing documentation: https://docs.scipy.org/doc/numpy/user/basics.indexing.html Numpy is good at bulk operations. Your example could simply be translated to: import scipy l = 10 Y1 = scipy.zeros((l, l)) y_test = scipy.zeros((l, l)) y_score = scipy.random.rand(l, l) v = scipy.random.randint(0, 2, (l, l)) Y1[y_score &gt;= 0.1] = 1 y_test[(Y1 == 1) &amp; (v == 1)]
has comment: http://stackoverflow.com/comment/81172129
score: 0
has comment: http://stackoverflow.com/comment/81171453
answers question: http://stackoverflow.com/q/47110284
type: Answer

recursion
type: Tag
tags question: http://stackoverflow.com/q/47103319
tags question: http://stackoverflow.com/q/47211563
tags question: http://stackoverflow.com/q/47126172
tags question: http://stackoverflow.com/q/47144132
tags question: http://stackoverflow.com/q/47098953
tags question: http://stackoverflow.com/q/47110639
tags question: http://stackoverflow.com/q/47082875
tags question: http://stackoverflow.com/q/47066139
tags question: http://stackoverflow.com/q/47086424
tags question: http://stackoverflow.com/q/47146838
tags question: http://stackoverflow.com/q/47212943
tags question: http://stackoverflow.com/q/47087178
tags question: http://stackoverflow.com/q/47114464
tags question: http://stackoverflow.com/q/47082490
tags question: http://stackoverflow.com/q/47161712
tag name: recursion
tags question: http://stackoverflow.com/q/47124512
tags question: http://stackoverflow.com/q/47068867
tags question: http://stackoverflow.com/q/47118379
tags question: http://stackoverflow.com/q/47188706
tags question: http://stackoverflow.com/q/47164054
tags question: http://stackoverflow.com/q/47111513
tags question: http://stackoverflow.com/q/47188305
tags question: http://stackoverflow.com/q/47115692
tags question: http://stackoverflow.com/q/47139258
tags question: http://stackoverflow.com/q/47183844
tags question: http://stackoverflow.com/q/47184733

http://stackoverflow.com/comment/81125336
has text: @Rionic I understand that very well and my "solution" was sarcastic, but you have shown no code, no search, no effort whatsoever to solve your problem.
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/47087846
type: Comment

http://stackoverflow.com/comment/81238558
type: Comment
type: AnswerComment
has text: Your answer is close but its not correct. The link you have shared suggests using $.toJSON() method which doesn't really exist.
score: 0
comment on: http://stackoverflow.com/a/47143560

http://stackoverflow.com/comment/81329663
score: 1
type: Comment
has text: It looks like it's an np.int16. One can use `np.fromstring(input_data, dtype=np.int16)` to read it
type: AnswerComment
comment on: http://stackoverflow.com/a/47189899

http://stackoverflow.com/q/47209611
has body: I was wondering if there was a way to remove the space separator from a tuple in Python 3.6. For example, if I were to have: t1 = (x,y) print(t1) The output would be (x, y) but I want it to be (x,y) without the space that separates the indices. Is there a way to do this? EDIT: Thanks for the helpful answers so far, I believe I was not specific enough however. I want to consider the following class: class Example(object): def __str__(self): return '({0},{1})'.format(self.x, self.y) def __sub__(self, other): return self.x - other.x, self.y - other.y Which is then called and executed in the same file (I know classes should be in separate files but bear with me here) with the following code: if __name__ == 'main': ex1 = Example(0,12) ex2 = Example(5,10) print('ex1 - ex2 =', str(ex1-ex2)) How can I accomplish the initial problem (removing the space from the tuple), without altering any of the code below if __name__ == 'main'?
tagged with: tuples
has comment: http://stackoverflow.com/comment/81368358
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47209899
has answer: http://stackoverflow.com/a/47209680
has answer: http://stackoverflow.com/a/47209669
score: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47210110
has title: Removing Space Separator From Tuple
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47209680
accepted answer: http://stackoverflow.com/a/47210110
tagged with: python
answer count: 4

http://stackoverflow.com/q/47127421
linked to: http://stackoverflow.com/q/47116080
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47128323
tagged with: sequences
answer count: 2
has comment: http://stackoverflow.com/comment/81205139
has comment: http://stackoverflow.com/comment/81205187
has comment: http://stackoverflow.com/comment/81205430
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/81205412
has comment: http://stackoverflow.com/comment/81205169
has comment: http://stackoverflow.com/comment/81205053
has comment: http://stackoverflow.com/comment/81205483
accepted answer: http://stackoverflow.com/a/47128323
has comment: http://stackoverflow.com/comment/81205517
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81205092
has comment: http://stackoverflow.com/comment/81205407
downvote count: 3
possible better answer: http://stackoverflow.com/a/47127785
upvote count: 1
tagged with: math
has title: How to write mathematical sequences in python
has answer: http://stackoverflow.com/a/47127785
has body: I'm completely stuck on a task in one of the exercises we've been given however and was hoping someone could help me with it. The following is the actual task: Consider the sequence: x(n+1)= 0.2x(n)−α(x(n)^2−5) with x(0)= 1 for α successively equal to -0.5, +0.5, -0.25, +0.25. Check the convergence; if the sequence converges, print the message Sequence converged to x= (the value you got) otherwise print No convergence detected Check whether there are negative elements in the sequence (Hint: If |xn−xn−1| &lt; 10−9 consider a sequence to be convergent) I'm not sure how to do sequences in python though and haven't found anything that explains how via googling so have been unsuccessful in trying to do it so far. After numerous attempts, I'm completely stuck. This is the code I've done: conv = [-0.5, 0.5, -0.25, 0.25] b=0 a=conv[b] c=0 for x in conv: x1=0.2*x-a*((x**2)-5) if abs(x1 - x) &lt; 1.e-9: c += 1 x = x1 b += 1 if c &gt; 0: print('Sequence converged to x=' + x) if c === 0: print('No converge detected')
has comment: http://stackoverflow.com/comment/81205466

http://stackoverflow.com/a/47294549
has body: You can use DyTB (dynamic training bench): this tool allows you to focus only on the hyperparameter search, using tensorboard to compare the measured stats of the varisous trained model. DyTB creates for you a unique name associated with the current set of hyperparameters and use it as a log dir. Creating different log directories allows the use of Tensorboard for an easy comparison. For instance, you can train VGG on Cifar10 with this single line (both VGG and Cifar10 are some of predefined model &amp; dataset available): import tensorflow as tf from dytb.inputs.predefined import Cifar10 from dytb.train import train from dytb.models.predefined.VGG import VGG # Instantiate the model vgg = VGG() # Instantiate the CIFAR-10 input source cifar10 = Cifar10.Cifar10() # 1: Train VGG on Cifar10 for 50 epochs # Place the train process on GPU:0 device = '/gpu:0' with tf.device(device): info = train( model=vgg, dataset=cifar10, hyperparameters={ "epochs": 50, "batch_size": 50, "regularizations": { "l2": 1e-5, "augmentation": { "name": "FlipLR", "fn": tf.image.random_flip_left_right, # factor is the estimated amount of augmentation # that "fn" introduces. # In this case, "fn" doubles the training set size # Thus, an epoch is now seen as the original training # training set size * 2 "factor": 2, } }, "gd": { "optimizer": tf.train.AdamOptimizer, "args": { "learning_rate": 1e-3, "beta1": 0.9, "beta2": 0.99, "epsilon": 1e-8 } } }) During the training of this model, you can monitor the loss trend and the accuracy value using tensorboard. A new folder is created for you, using some of the representative hyperparameters used: tensorboard --logdir "log/VGG/CIFAR-10_Adam_l2=1e-05_fliplr/" as you can see, a folder for the model is created and the hyperparameter used to train it are added next, as subfolder. This means that if you change the Optimizer (from ADAM to MomentumOptimizer) or you add a comment, or you change the l2 regularization parameter, ecc, DyTB creates a subfolder into th…
score: 3
type: Answer
answers question: http://stackoverflow.com/q/47127962
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/47205055
has body: I'm having some troubles getting my for loop working, which is supposed to create a number of labels in a window. Here is the code snippet: import tkinter as tk root = tk.Tk() #Frame 1: components frame1 = tk.Frame(root).grid(row=0) items = ['REED', 'PIR', 'VIBR', 'REED', 'PIR'] for r in items: tk.Label(frame1, text=items[r]).grid(row=r,column=0) #Frame 2: statusList frame2 = tk.Frame(root).grid(row=1) status = [[True, False, True, False], ['14:00:00', '13:24:31', '15:58:32', '08:33:01']] for r in status: for s in status[r]: tk.Label(frame2, text=status[r][s]).grid(row=s,column=r) root.mainloop() It outputs the Error TypeError: list indices must be integers or slices, not str Which indicated me that my usage of the for-loop is wrong. I've looked up some information and found that I can certainly loop over a list and have it go through each item and for example print that item, but as of yet I don't know how to implement that idea when there's an encapsulated list that I want to loop through.
answer count: 3
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/47205284
has answer: http://stackoverflow.com/a/47205091
possible better answer: http://stackoverflow.com/a/47205091
has comment: http://stackoverflow.com/comment/81365908
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47205203
tagged with: for-loop
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47205203
type: AnsweredQuestion
has title: Incrementing over a list in a list (encapsulated list)
tagged with: list

http://stackoverflow.com/a/47110164
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47109842
has body: Assuming that each data part isn't that large (because copying is necessary for the solution) it can be done this way (shown in interactive shell): &gt;&gt;&gt; import pickle &gt;&gt;&gt; import ctypes &gt;&gt;&gt; b = (ctypes.c_double * 5)(1.0, 2.0, 3.0, 4.0, 5.0) # Arbitrary data &gt;&gt;&gt; d = pickle.dumps(bytes(b)) &gt;&gt;&gt; c = pickle.loads(d) &gt;&gt;&gt; a = (ctypes.c_double * 5).from_buffer_copy(c) &gt;&gt;&gt; a &lt;__main__.c_double_Array_5 object at 0x02F6C9E0&gt; &gt;&gt;&gt; list(a) [1.0, 2.0, 3.0, 4.0, 5.0]
accepted answer of: http://stackoverflow.com/q/47109842
type: Answer
has comment: http://stackoverflow.com/comment/81174381
has comment: http://stackoverflow.com/comment/81172555
downvote count: 0

turtle-graphics
tags question: http://stackoverflow.com/q/47131902
tags question: http://stackoverflow.com/q/47144177
tag name: turtle-graphics
tags question: http://stackoverflow.com/q/47204447
tags question: http://stackoverflow.com/q/47066552
type: Tag
tags question: http://stackoverflow.com/q/47155399
tags question: http://stackoverflow.com/q/47116006
tags question: http://stackoverflow.com/q/47106291
tags question: http://stackoverflow.com/q/47160561
tags question: http://stackoverflow.com/q/47110352
tags question: http://stackoverflow.com/q/47168796

http://stackoverflow.com/q/47150962
type: UnansweredQuestion
tagged with: apache
tagged with: http-redirect
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47151275
tagged with: flask
favorite count: 0
type: Question
tagged with: reverse-proxy
tagged with: python
score: 2
has body: My server admin is using Apache to provide a public address by reverse proxying my Flask backend server. Now I don't have much knowledge about ProxyPass but he's provided me with this address: http://www.example.com/resources/myproject My Flask server is using @login_required decorator to redirect the user to login page when the user hits home without any session. This works well in the local network where 192.168.1.10:5000 is redirected to 192.168.1.10:5000/login. But when accessing through the above public address, the user get redirected to: http://www.example.com/login instead of http://www.example.com/resources/myproject/login which in turn, gives a 404 error. I also logged to see if I was receiving any X-Forwarded-For headers so that I can use this to fix the problem, but I don't receive any such header from Apache.
has title: Flask login redirect behind Apache reverse proxy with subpath
upvote count: 2

http://stackoverflow.com/comment/81124763
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47085752
has text: No, pip is installed (that's why code = "pip install setuptools" works OK. Thanks for responding though.

http://stackoverflow.com/comment/81239232
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47123938
has text: yes but its about running the window or not via a command line Option like python my_app.py --console
score: 0

http://stackoverflow.com/comment/81409085
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47131231
has text: Try a very simple straight line equation like "y = 2 * x + 1" so that the result is simple. In that equation, an X value of 5 should give "y = 2 * 5 + 1" which equals 11.

http://stackoverflow.com/comment/81112731
has text: Apparently removing the beginning underscore for those other two solves the problem, though I have no idea why.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47080417

http://stackoverflow.com/comment/81290365
type: QuestionComment
score: 0
type: Comment
has text: `&` and `^` are bitwise operators. `i%-3&-4` goes `0, -4, -4` repeating, while `i%-5&8^12` goes `12, 4, 4, 4, 4` repeating. Note how the starting slice index repeats its pattern every three, while the ending index repeats every five.
comment on: http://stackoverflow.com/q/47170263

summary
tags question: http://stackoverflow.com/q/47131231
tags question: http://stackoverflow.com/q/47121953
tag name: summary
type: Tag

http://stackoverflow.com/comment/81078005
has text: This isn't Java code. Did you by chance mean to use `python` tag?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47064885
score: 2

http://stackoverflow.com/comment/81212963
comment on: http://stackoverflow.com/q/47131615
score: 3
has text: Sure. But any competent script kiddie could just use the browser dev tools to change the validation rules. You must always validate on the backend too.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47722017
type: Answer
upvote count: 2
type: AcceptedAnswer
has body: General points: SymPy stats module has some room for improvement. In particular, the documentation acknowledges that the CDF returned for normal random variables "needs some help" from simplify to become usable. Floating point numbers, especially those that are not represented precisely in binary system, are poison for SymPy. You think you are passing in 0.1, but it's really 3602879701896397/36028797018963968 and a symbolic integration routine is having a fit. Concerning the first point; the following example shows that cdf(x)(t) is a risky proposition. &gt;&gt;&gt; x = Normal('x', 1, 1) &gt;&gt;&gt; cdf(x)(1) nan The problem is that unsimplified cdf has division by _z-1. Better approach: &gt;&gt;&gt; simplify(cdf(x))(1) 1/2 Concerning the second: since the CDF is computed by symbolic integration, passing floating point numbers as parameters can make the life of integrator hard enough that it hits some deeply hidden bug using Meijer G-functions for integration. Use Rational(1, 10) or S(1)/10 to create a rational number 1/10 instead of decimal 0.1. &gt;&gt;&gt; from sympy import S &gt;&gt;&gt; x = Normal("x", 10, S(1)/10) &gt;&gt;&gt; simplify(cdf(x))(10) 1/2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47218740
score: 2
answers question: http://stackoverflow.com/q/47218740

http://stackoverflow.com/q/47145055
has comment: http://stackoverflow.com/comment/81240621
has title: How to retrieve the word before space from text widget of tkinter each time space is pressed
upvote count: 0
has comment: http://stackoverflow.com/comment/81240692
has body: I am trying to retrieve the word before everytime space is entered. For example, If a user types " iam a" i want to retrieve "iam" and then if user types "iam a girl" i want to retrieve "a" . Following is my code: import tkinter as tk import time class ExampleApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) lsum = tk.Label(self,borderwidth=2,text="suggestions") lsum.grid(row=2, column=5, sticky=tk.W) def func3(): contents = self.text.get("1.0", tk.END) lsum["text"] = contents def func4(): self.text.bind("&lt;space&gt;",func3()) self.text= tk.Text(self, height=5, width=30,borderwidth=2) self.text.pack(side=tk.RIGHT) self.text.grid(row=0, column=4) self.text.insert(tk.END, "") self.v = tk.IntVar() self.d = tk.IntVar() self.e = tk.IntVar() self.radio1=tk.Radiobutton(self, text="آيک گرآم مآڈل ", variable=self.v, value=1,command=func2).grid(column=0,row=1,columnspan=2) self.radio2=tk.Radiobutton(self, text="دو گرآم مآڈل ", variable=self.d, value=2,command=func3).grid(column=0,row=2,columnspan=2) self.radio3=tk.Radiobutton(self, text="تین گرآم مآڈل", variable=self.e, value=3).grid(column=0,row=3,columnspan=2) if __name__ == '__main__': run = ExampleApp() run.mainloop() Kindly Help please.
tagged with: user-interface
answer count: 1
tagged with: textbox
favorite count: 0
type: Question
tagged with: tkinter
downvote count: 2
has answer: http://stackoverflow.com/a/47158973
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/81240649
has comment: http://stackoverflow.com/comment/81240586
tagged with: python

http://stackoverflow.com/comment/81226700
type: Comment
has text: Yes, I agree. I create only better solution for your problem. Nice day!
type: AnswerComment
comment on: http://stackoverflow.com/a/47118728
score: 0

http://stackoverflow.com/a/47070051
answers question: http://stackoverflow.com/q/47069970
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81088102
has comment: http://stackoverflow.com/comment/81087999
has comment: http://stackoverflow.com/comment/81088051
type: Answer
accepted answer of: http://stackoverflow.com/q/47069970
score: 1
has body: Use str.find() to get two indices, and adjust for the length of the first one. Also don't forget corner cases, eg where the substrings overlap.

http://stackoverflow.com/comment/81193028
has text: Sorry, but this is the first time I post something. I started like a month a go and most of the time my teacher helped me so I kinda don't know how t ask something on a forum. My excuses!
comment on: http://stackoverflow.com/q/47121586
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47199406
has body: using pandas is definitely the way to go to handle this kind of data. groupby().plot() returns one or several Axes objects. You can simply iterate over them to alter their aspect: axs = data_df.groupby('ID').plot('var1','var2') for ax in axs.values(): ax.set_ylabel('whatever') ...
accepted answer of: http://stackoverflow.com/q/47197949
has comment: http://stackoverflow.com/comment/81348909
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47197949
downvote count: 0
has comment: http://stackoverflow.com/comment/81349074
has comment: http://stackoverflow.com/comment/81394484
has comment: http://stackoverflow.com/comment/81349483
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/81390643

http://stackoverflow.com/comment/81134053
score: 0
type: AnswerComment
has text: The goal here was to store data in redis and not modify it along the fly. i knew tat you can use reJson to do so.Just gave an alternative :)
type: Comment
comment on: http://stackoverflow.com/a/47088242

http://stackoverflow.com/comment/81171931
has text: Variables were Turkish, I did mistake when I was translating English. So, It's still don't work.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47081576

http://stackoverflow.com/q/47097267
tagged with: python-3.x
tagged with: opencv
tagged with: python
has comment: http://stackoverflow.com/comment/81144102
has comment: http://stackoverflow.com/comment/81144324
score: 0
has title: Overlaying a rotated image in opencv
has comment: http://stackoverflow.com/comment/81144496
answer count: 0
type: UnansweredQuestion
has body: I'm trying to overlay an image on top of a background after rotating it which works but because I used a region of image to place the overlay after rotating it the corners of where the overlay was are left out pointer = rotatePointer(pointer, point2, point1, pointerNo) rows, cols, channels = pointer.shape x = int(point2[0]) y = int(point2[1]) roi = background[int(y - (rows/2)):int(y + (rows / 2)), int(x - (cols/2)):int(x + (cols/2)) ] # Create a mask of pointer as well as it's inverse' foreGrey = cv2.cvtColor(pointer,cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(foreGrey, 10, 255, cv2.THRESH_BINARY_INV) inverseMask = cv2.bitwise_not(mask) #Black out area of pointer in roi backgroundBlackOut = cv2.bitwise_and(roi,roi,mask = inverseMask) #Take the pointer without alpha channel pointerForeground = cv2.bitwise_and(pointer,pointer, mask = mask) cv2.imshow('Mask', pointerForeground) #Put the pointer into the ROI dst = cv2.add(backgroundBlackOut, pointerForeground) background[int(y - (rows/2)):int(y + (rows / 2)), int(x - (cols/2)):int(x + (cols/2)) ] = dst return background
has comment: http://stackoverflow.com/comment/81144192
upvote count: 1
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/81392443
has text: hey thanks for your reply! when I indent it like that I get an error message for line 9 and line 321 (which i dont understand) and it says: nicodeDecodeError: 'utf-8' codec can't decode byte 0x87 in position 27: invalid start byte
comment on: http://stackoverflow.com/a/47207502
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47217907
type: Answer
answers question: http://stackoverflow.com/q/47217151
score: 0
has comment: http://stackoverflow.com/comment/81386028
has body: I think that you need a TimeDistributed layer after a LSTM with return_sequences=True layer2= LSTM(128, dropout=0.2, recurrent_dropout=0.2,return_sequences=True) layer3= TimeDistributed(Dense(1, activation='sigmoid')))

http://stackoverflow.com/q/47112878
has answer: http://stackoverflow.com/a/47123198
tagged with: python
has body: test.py import kivy kivy.require('1.10.0') from kivy.app import App from kivy.uix.button import Button from kivy.uix.dropdown import DropDown from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder from kivy.core.window import Window class CustDrop(DropDown): def __init__(self, **kwargs): super(CustDrop, self).__init__( **kwargs) self.select('') class ExampleApp(App): def build(self): self.root = Builder.load_file('test.kv') return self.root if __name__ =='__main__': ExampleApp().run() test.kv BoxLayout: orientation: 'vertical' #spacing : 10 BoxLayout: #spacing : 10 canvas.before: Rectangle: pos: self.pos size: self.size #Color: #rgb: (70,70,70) size_hint_y:1 Button: spacing : 10 text: 'test1' size : (60,30) size_hint : (None, None) background_color: 90 , 90, 90, 90 color: 0, 0.517, 0.705, 1 Button: text: 'test2' size: (60, 30) size_hint: (None, None) background_color: 90 , 90, 90, 90 color: 0, 0.517, 0.705, 1 Button: id: btn text: 'test3' size: (60, 30) size_hint: (None, None) on_release: dropdown.open(self) #size_hint_y: None #height: '40dp' background_color: 90 , 90, 90, 90 color: 0, 0.517, 0.705, 1 CustDrop: id: dropdown Button: text: 'Sub menu1 Test3' size_hint_y: None height: '30dp' #on_release: dropdown.select('') on_release: app.root.test background_color: 90 , 90, 90, 90 color: 0, 0.517, 0.705, 1 Button: text: 'Sub menu2 Test3' size_hint_y: None height: '30dp' on_release: dropdown.select('') background_color: 90 , 90, 90, 90 color: 0, 0.517, 0.705, 1 Button: text: 'Sub menu3 Test3' size_hint_y: None height: '30dp' on_release: dropdown.select('') background_color: 90 , 90, 90, 90 color: 0, 0.517, 0.705, 1 Button: text: 'Fourth' size_hint_y: None height: '30dp' on_release: dropdown.select('') background_color: 90 , 90, 90, 90 color: 0, 0.517, 0.705, 1 BoxLayout: canvas.before: Rectangle: pos: self.pos size: self.size Color: rgb: (1,1,1) AsyncImage source: '2.jpg' AsyncImage source: '4.jpg' AsyncImage source: '2.jpg' Label: size_hint_x: 22 Label…
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: kivy
has title: remove border and add multilevel submenu
type: Question
accepted answer: http://stackoverflow.com/a/47121049
tagged with: kivy-language
answer count: 2
possible better answer: http://stackoverflow.com/a/47123198
has answer: http://stackoverflow.com/a/47121049

http://stackoverflow.com/q/47213315
has body: I've been looking around for a while to find the answer but unfortunately no luck today. I'm trying to get the contents off this webpage and save it to a variable. (Link to the website) Any help would be great, if you are confused what I am meaning drop a question in the comments, because personally I'm not sure how to word this well. Please don't let me down stackoverflow, I know you can do it ;)
score: 4
has comment: http://stackoverflow.com/comment/81376359
has comment: http://stackoverflow.com/comment/81376759
answer count: 2
has title: How to save webpage data to a variable in Python
has comment: http://stackoverflow.com/comment/81376611
has comment: http://stackoverflow.com/comment/81376514
has comment: http://stackoverflow.com/comment/81376575
has answer: http://stackoverflow.com/a/47213801
linked to: http://stackoverflow.com/q/15138614
has comment: http://stackoverflow.com/comment/81376277
downvote count: 0
tagged with: web
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/63394660
favorite count: 0
has comment: http://stackoverflow.com/comment/81376640
type: Question
upvote count: 4
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81376843
has answer: http://stackoverflow.com/a/63394660
accepted answer: http://stackoverflow.com/a/47213801
has comment: http://stackoverflow.com/comment/81376859
tagged with: rss
tagged with: python
has comment: http://stackoverflow.com/comment/81547247

http://stackoverflow.com/comment/81359554
comment on: http://stackoverflow.com/a/47205199
score: 0
type: AnswerComment
has text: @harshi I have added the explanation. Please go through it and ask if still not understanding. Also, if this helped you consider upvoting/accepting the answer.
type: Comment

http://stackoverflow.com/comment/81117583
comment on: http://stackoverflow.com/q/47084045
type: Comment
score: 0
has text: I only wan't a binary output of whether or not there is horizontal or vertical adjacency.
type: QuestionComment

http://stackoverflow.com/comment/81114968
comment on: http://stackoverflow.com/q/47082785
has text: ValueError: could not convert string to float: C @yklsga
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81290468
score: 1
has text: @PatrickHaugh. Backticks are a deprecated way to spell `repr(i)` - so the code in the question is python2.
type: Comment
comment on: http://stackoverflow.com/a/47170354
type: AnswerComment

http://stackoverflow.com/comment/81305487
type: AnswerComment
score: 0
has text: Thx, will test that!
type: Comment
comment on: http://stackoverflow.com/a/47177763

http://stackoverflow.com/q/47065932
favorite count: 0
score: 8
type: Question
linked to: http://stackoverflow.com/q/11058464
answer count: 2
linked to: http://stackoverflow.com/q/3207219
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47066074
has title: How to get file path + file name into a list?
accepted answer: http://stackoverflow.com/a/47065979
duplicate of: http://stackoverflow.com/q/3207219
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47065979
upvote count: 8
has body: I am trying to get a list of strings with the file path and the file name. At the moment I only get the file names into the list. Code: hamFileNames = os.listdir("train_data\ham") Output: ['0002.1999-12-13.farmer.ham.txt', '0003.1999-12-14.farmer.ham.txt', '0005.1999-12-14.farmer.ham.txt'] I would want an output similar to this: ['train_data\ham\0002.1999-12-13.farmer.ham.txt', 'train_data\ham\0003.1999-12-14.farmer.ham.txt', 'train_data\ham\0005.1999-12-14.farmer.ham.txt']
possible better answer: http://stackoverflow.com/a/47066074
tagged with: directory-listing

http://stackoverflow.com/q/47191226
has comment: http://stackoverflow.com/comment/81332910
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81332043
answer count: 3
tagged with: if-statement
accepted answer: http://stackoverflow.com/a/47191322
has body: Here's what I'm trying to do (in a single list comprehension): 1. Compare the the relation of 2 bool-integer lists using logical operators 2. Return a list of bool-int values where: - 1 is returned when both a,b values are 1 (1,1) - 0 is returned when a==1 and b==0 (1,0) - other cases are skipped, as in (0,0 &amp; 0,1) Example Logic: A = [1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,0] B = [1,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0] L = [] for i in range(len(B)): if A[i] + B[i] == 2: L.append(1) elif A[i]==1 and B[i]==0: L.append(0) Expected Output for print(L): [1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1] My Attempt: (syntaxError points to the 'for')(and it's a bit long) L = [1 if x+y == 2 else 0 if x-y == 1 for x,y in zip(A, B)] Best Answer by Wander Nauta (Pythonic and fast) L = [y for x, y in zip(A, B) if x] . Couple of My Reference Points: - add-sum-of-values-of-two-lists-into-new-list - if-else-in-a-list-comprehension - elif-in-list-comprehension-conditionals Use Cases: - Comparing lists representing the set of features (un)desired by a user/customer, and (un)available for a given product/service - The returned 1's would represent desires_met and 0's would represent desires_unmet - Further derivatives/analysis could easily be done on the boolean list returned.
has comment: http://stackoverflow.com/comment/81332939
downvote count: 3
has answer: http://stackoverflow.com/a/47191322
score: -1
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/81333623
favorite count: 0
has title: Boolean-logical Comparison of Lists Using List Comprehension
type: Question
linked to: http://stackoverflow.com/q/14050824
possible better answer: http://stackoverflow.com/a/47191482
has comment: http://stackoverflow.com/comment/81333004
upvote count: 2
linked to: http://stackoverflow.com/q/9987483
linked to: http://stackoverflow.com/q/4406389
has answer: http://stackoverflow.com/a/47191482
tagged with: python
has comment: http://stackoverflow.com/comment/84803591
has answer: http://stackoverflow.com/a/47191563
tagged with: boolean-logic
has comment: http://stackoverflow.com/comment/81332070

http://stackoverflow.com/q/47205180
score: 4
has answer: http://stackoverflow.com/a/47205881
has body: I have a set of images over which polygons are drawn. I have the points of those polygons and I draw these using Shapely and check whether certain points from an eye tracker fall into the polygons. Now, some of those images are mirrored but I do not have the coordinates of the polygons drawn in them. How can I flip the polygons horizontally? Is there a way to do this with Shapely?
upvote count: 4
type: AnsweredQuestion
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81359250
accepted answer: http://stackoverflow.com/a/47205881
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/54860362
possible better answer: http://stackoverflow.com/a/54860362
has title: How can I mirror a polygon using Python?
tagged with: shapely
tagged with: python

http://stackoverflow.com/a/47123498
has body: You have to call pygame.event.pump() at least once before using pygame.key.get_pressed() so that pygame can check what keys have been pressed.
answers question: http://stackoverflow.com/q/47121824
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47121824
upvote count: 4
downvote count: 0
type: Answer
score: 4

http://stackoverflow.com/comment/81100374
comment on: http://stackoverflow.com/q/47074909
score: 0
has text: Not sure it is possible - see https://stackoverflow.com/questions/32760888/pyspark-dataframes-way-to-enumerate-without-converting-to-pandas?noredirect=1&lq=1 ; and from the [`monotonically_increasing_id` docs](http://spark.apache.org/docs/2.2.0/api/python/pyspark.sql.html#pyspark.sql.functions.monotonically_increasing_id), "The generated ID is guaranteed to be monotonically increasing and unique, but not consecutive."
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81374970
type: QuestionComment
has text: @MarkDickinson That works! However, I'm still confuzzled as to why `isInstance` is not defined in that context? Is this expected? Why?
comment on: http://stackoverflow.com/q/47212686
score: 1
type: Comment

http://stackoverflow.com/a/47103579
has comment: http://stackoverflow.com/comment/81157676
upvote count: 0
has body: You can use this code s1 = "['1', '2', '3']" print(sum([int(x) for x in list(s1) if x.isnumeric()])) that will output 6
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/81157821
answers question: http://stackoverflow.com/q/47103377
score: -1

http://stackoverflow.com/a/47204659
answers question: http://stackoverflow.com/q/47204260
type: Answer
has comment: http://stackoverflow.com/comment/81357951
has comment: http://stackoverflow.com/comment/81359490
score: 5
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47204260
upvote count: 5
has comment: http://stackoverflow.com/comment/81357967
has body: Or we can using melt pd.DataFrame(dict([ (k,pd.Series(v)) for k,v in d.items() ])).melt().dropna() Out[51]: variable value 0 A 2017-01-02 1 A 2017-01-03 4 B 2017-02-02 5 B 2017-02-03 6 B 2017-02-04 7 B 2017-02-05 8 C 2016-02-02 A way inspired by piR pd.Series(d).apply(pd.Series).melt().dropna() Out[142]: variable value 0 0 2017-01-02 1 0 2017-02-02 2 0 2016-02-02 3 1 2017-01-03 4 1 2017-02-03 7 2 2017-02-04 10 3 2017-02-05

http://stackoverflow.com/comment/81284279
type: Comment
has text: It says that I have python2.7.13 (???).
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47112902

http://stackoverflow.com/comment/81246037
comment on: http://stackoverflow.com/a/47147578
type: Comment
score: 0
type: AnswerComment
has text: I think this is the cleanest approach, with the most straight-forward intent and least magic. Thanks!

http://stackoverflow.com/q/47087671
score: 2
tagged with: lag
has answer: http://stackoverflow.com/a/47087737
tagged with: pandas
has comment: http://stackoverflow.com/comment/81125264
downvote count: 0
answer count: 1
tagged with: shift
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has body: I have a pandas dataframe. LAG_VAL presented below is how my result should look like. A DT VAL LAG_VAL 1 2017-01-10 1 nan 1 2018-01-10 2 1 2 2017-01-10 1 nan 2 2018-01-10 2 1 2 2019-01-10 3 2 I run the code below, but it is giving me all nan values. df['LAG_VAL'] = df.groupby(['A','DT'])['VAL'].shift(1) I have made sure that the data type of DT is datetime64[ns]. I have also made sure that the dataframe is sorted before shifting. df.sort(['A,'DT], inplace=True)
tagged with: python
has title: Lagging by date in Pandas
linked to: http://stackoverflow.com/q/26280345

http://stackoverflow.com/q/47208929
type: Question
tagged with: python
tagged with: distributed-computing
has title: A library for distributed ad-hoc state sharing?
has answer: http://stackoverflow.com/a/47212519
score: 0
has body: Generally I want to be able to synchronize order of parallel execution: to set walls and current state between unknown and chand (always more than one) amount of geterogenious workers: whlie state != "end": if state == "blah": doX() waitAll() if master == True: state = "x" waitAll() if state == "x": doZ() waitAll() if master == True: state = "end" waitAll() Generally I look for a way to share a state of an application in ad-hoc distributed master-slave menner. I want to have same script for master and slaves (alike in MPI model). Master have a public IP known to all slaves. Generally I see how one could implement it in ZMQ yet wonder if there is some known dedicated library for it?
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/81555233
type: AnswerComment
has text: Do you _need_ the `armhf/python` image or does the official one work? If you _need_ a different image, we need to search for a new image that supports your infrastructure and has python installed.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47280363

http://stackoverflow.com/comment/81317388
type: Comment
comment on: http://stackoverflow.com/q/47184099
type: QuestionComment
score: 0
has text: what is the language?

protege
type: Tag
tags question: http://stackoverflow.com/q/47111939
tag name: protege

http://stackoverflow.com/a/47095546
downvote count: 0
has body: You need to extend both to 3D, keeping the first axis aligned and introducing new axes along the last one for points and second last one for L1 and then subtract - points[:,:,None] - L1[:,None,:] # or points[...,None] - L1[:,None]
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47095482
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81141520
type: Answer
accepted answer of: http://stackoverflow.com/q/47095482

http://stackoverflow.com/comment/81381463
has text: @piRSquared Thank you!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47215877
type: Comment

http://stackoverflow.com/a/47147192
has body: You'll notice that if you want to do what you did to 39 to 27, you'll be repeating code. This is a case where recursion can help (calling the function in itself): def persistence(num): if num &lt; 10: return 0 # Only one digit. Can't iterate over it num_str = str(num) total = 1 for i in num_str: total = total * int(i) return 1 + persistence(total) # We do 1 + because we just did an iteration Let's imagine the input was 39: 39 is not less than 10 so we go to the next stage. We do the same code you provided to get the total of multiplying the digits We now have a new number (27) allocated at total. We repeat the code above by calling the function again, but instead of passing 39, we pass through 27. 27 is not less than 10 so we go to the next stage We get the multiplication of digits We repeat until we get a total of 4 (1*4). We call persistence(4), but it returns 0 because 4 &lt; 10. No iteration has been done for the number 4 (hence we return 0) At this point, recursion has stopped. Python now backtracks through all previous calls. It adds 0 + 1 + 1 + 1 to give 3. Recursion is a little tricky to wrap your head around at first, but basically it's a function which calls itself, but it has "base cases" to stop the function running indefinitely. In this case, our base case is if the number is less than 10 (it has one digit). No iterations take place on this number.
answers question: http://stackoverflow.com/q/47147136
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81244842
score: 3
accepted answer of: http://stackoverflow.com/q/47147136
type: Answer

http://stackoverflow.com/comment/81462829
has text: You are welcome @rajiv, but which one worked for you?
type: AnswerComment
comment on: http://stackoverflow.com/a/47225409
type: Comment
score: 0

http://stackoverflow.com/q/47072285
has comment: http://stackoverflow.com/comment/128990019
has comment: http://stackoverflow.com/comment/81094338
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 2
has comment: http://stackoverflow.com/comment/81094019
downvote count: 0
has comment: http://stackoverflow.com/comment/81094836
has answer: http://stackoverflow.com/a/47073633
possible better answer: http://stackoverflow.com/a/47073633
linked to: http://stackoverflow.com/q/52369572
favorite count: 0
has body: I'm new to Python and I'm having trouble using lists. I expose my problem, as you can see, I have a datos.csv file with the following structure. 1,4.0,?,?,none,? 2,2.0,3.0,?,none,? 2,2.5,2.5,?,tc,39 Using this function I store the data on a list. def main(): lista = [] with open('datos.csv','r') as f: for line in f: lista.append(line.strip().split(',')) determinar_tipo(lista) if __name__ == '__main__': main() Up to this point, I have no problem. However the problem comes when I have to determine the type of the elements. Using this code, I can organize my list in columns for columna in itertools.izip(*lista): This code allows me to treat the data as columns, as indicated, here is an example of what I receibe from this 'for': {'1','2','2'} {'4.0','2.0','2.5'} . . . As you can see is the same data from my csv file but structure by columns. Ok, here is my problem. I have to determine the type of each of the columns based on their argument, that is, suppose that the first column {'1', '2', '3'}, check the first element and that element is the type of that column, in this case the type of this column would be int. Another example with {'4.0', '2', '2.5'}, I check the type of the primary element and determine that it is float. For the case {'?', '?' , '?'} the type would be "indeterminate". However, the problem comes with the signs '?', If I get a symbol of these, I have to check the next element of the column, it would be the element called 'word', {'?', 'Word', '5'}, so the type of the column woulb be string. This is the code I developed to verify it, but I did not finish determining the types correctly. def determinar_tipo(lista): b = 0 aux = [] for columna in itertools.izip(*lista): if columna[0] != "?": #If it's a number or string I save it aux.append(columna[0]) print columna[0] else: #If it's '?' if len(columna) &gt; b: b = b + 1 if columna[b] != "?": aux.append(columna[b]) b = 0 else: b = b + 1 print b #Correct code for x in aux: try: var_type = type(int(x)) excep…
type: Question
has comment: http://stackoverflow.com/comment/81093888
has comment: http://stackoverflow.com/comment/81094209
tagged with: for-loop
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/47073621
accepted answer: http://stackoverflow.com/a/47073621
has comment: http://stackoverflow.com/comment/81094484
tagged with: python
has comment: http://stackoverflow.com/comment/81094777
has title: Determine data type from CSV - Python
has comment: http://stackoverflow.com/comment/81093683

http://stackoverflow.com/a/75774121
score: 0
has body: It's also possible to do the task with a combination of melt and pivot. The idea is to df = df.melt('col1').pivot(index='variable', columns='col1', values='value') or set_index and unstack twice: df = df.set_index('col1').unstack().unstack() If the variable column needs to be a column instead of an index, then use reset_index(): df.set_index('col1').unstack().unstack().reset_index(names='Variable').rename_axis(columns=None)
type: Answer
answers question: http://stackoverflow.com/q/47139203

http://stackoverflow.com/q/47111884
has answer: http://stackoverflow.com/a/47112442
type: Question
has comment: http://stackoverflow.com/comment/81174259
upvote count: 0
has comment: http://stackoverflow.com/comment/81173815
has body: I have installed python 3.6.2, Mysql 6.3 and pyMySQL 0.7.11 When running the following scrip import pymysql import mysql.connector class Crud: def __init__(self): self.db = pymysql.connect('localhost', 'dnsmonitor', 'test', 'DNSMON') self.cursor = self.db.cursor() I get the following error File "demo.py", line 1, in &lt;module&gt; import pymysql ModuleNotFoundError: No module named 'pymysql' What could be the root cause of this issue? I'm running on windows 10
tagged with: pymysql
has comment: http://stackoverflow.com/comment/81173788
has title: Python cannot recognize PyMySQL
has comment: http://stackoverflow.com/comment/81173796
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81173747
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81173775
tagged with: python
tagged with: mysql
accepted answer: http://stackoverflow.com/a/47112442
favorite count: 0
score: -1
tagged with: python-3.x

http://stackoverflow.com/comment/81597204
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47198793
has text: Actual I've file - Not a string. The file contains some unicode characters and the format is 'UTF-8 Unicode C program text, with CRLF line terminators'. Also it has some variables to replace at run-time. So, I'm using pyratemp module to replace the variables.temp_sql = pyratemp.Template(filename=sourceFile, data=data_hash, encoding='UTF-8')"
type: Comment

http://stackoverflow.com/comment/81378863
score: 0
comment on: http://stackoverflow.com/q/47214664
has text: What is an "underscore string", where is it coming from, and why are you using it?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81123320
has text: @LyudmylaStarostyuk by using excel I got the same this is the formula =LOG10((1/3)+2.718281)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47083621

http://stackoverflow.com/comment/81342920
type: Comment
type: AnswerComment
score: 0
has text: This is naive approach, also you cant pass int value to datetime.date()
comment on: http://stackoverflow.com/a/47196612

http://stackoverflow.com/comment/81315794
type: QuestionComment
has text: Python does not guarantee order of items in the dictionary. Also you call your variable `my_list`, but it is referring to a dictionary
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47183377

http://stackoverflow.com/a/47171485
answers question: http://stackoverflow.com/q/47171076
score: 0
has body: If I were to guess, I would say that you are probably getting that error because the element isn't loaded when your code runs. It's probably a slower loading page. You should try adding a wait and see if that helps. You can also simplify your locator by using a CSS selector and only scraping the page once. price = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#flight_MU5401 span.base_price02")).text
type: Answer
has comment: http://stackoverflow.com/comment/81297382

http://stackoverflow.com/a/47220561
answers question: http://stackoverflow.com/q/47219973
has body: You could use IP adress, but that could be confusing / multiple people could share one. So my suggestion would be to use Django's built-in session framework. Pulling from this stackoverflow answer, you'll see that you can gather the current session key from the request object. Then it's just a matter of changing your Cart model : from django.contrib.sessions.models import Session class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True) session = models.ForeignKey(Session, null=True, blank=True) products = models.ManyToManyField(Product, through=CartProduct) class Meta: verbose_name = 'Cart' verbose_name_plural = 'Cart' def __str__(self): if self.user : return self.user.username # For for authenticated users else if self.session : return self.session.session_key else : return "Anonymous" And of course, you'll need to make sure that you add the request.session to your Cart object when you create it. Finally, it seems the session object can still be empty sometimes, so you should look at force-saving it if you really don't want an "Anonymous" line in your admin. This answer makes force-saving the session quite simple : if not request.session.session_key: request.session.save() session_id = request.session.session_key
accepted answer of: http://stackoverflow.com/q/47219973
type: Answer
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/47070372
score: 1
accepted answer of: http://stackoverflow.com/q/47068293
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Everything you want to be done on Ansible controller is done by action plugins (they are module's companions). Take a look at some very simple plugin/module here. You want to execute module, inspect it's result for your custom message, use display.v or display.warning or anything else to display this message and then return module's result back to Ansible core. For this very reason debug is an action plugin, and it's module only contains documentation, because all the work is done by plugin itself.
type: Answer
answers question: http://stackoverflow.com/q/47068293

http://stackoverflow.com/comment/81079740
has text: Is `ID_potential` actually a numpy array? Try `np.where(np.array(ID_potential) == ID_target)`...
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47065677
type: QuestionComment

http://stackoverflow.com/comment/81304292
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47177476
has text: try reinstalling chrome
score: 0

http://stackoverflow.com/comment/81196738
comment on: http://stackoverflow.com/q/47122770
score: 1
type: Comment
type: QuestionComment
has text: What's the structure of `a_lis`? Its `len`, and the `len` of all sublists? Of `shape` of the elements if they are arrays.

http://stackoverflow.com/comment/81282615
has text: Great thanks worked..
comment on: http://stackoverflow.com/q/47166028
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47207526
answers question: http://stackoverflow.com/q/47207495
score: 3
upvote count: 3
downvote count: 0
type: Answer
has body: You can try this: d = {'M': ['Name1', 'Name2', 'Name3'], 'F': ['Name1','Name2','Name3']} for a, b in d.items(): for i in b: print("{}, {}".format(a, i)) Output: M, Name1 M, Name2 M, Name3 F, Name1 F, Name2 F, Name3

http://stackoverflow.com/a/47068973
has comment: http://stackoverflow.com/comment/81086122
has comment: http://stackoverflow.com/comment/81087950
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81086477
has comment: http://stackoverflow.com/comment/81086441
accepted answer of: http://stackoverflow.com/q/47068935
score: 1
has comment: http://stackoverflow.com/comment/81086918
type: Answer
has comment: http://stackoverflow.com/comment/81086291
has comment: http://stackoverflow.com/comment/81086067
has body: If need substract 0 window with 1 window use set_index + unstack first and then sub: data = data.set_index(['user_id', 'feat', 'type', 'window'])['norm'].unstack().fillna({1:0}) print (data) window 0 1 user_id feat type user1 all true 0.110000 0.322 all1 null NaN 0.100 user2 all1 null 0.232110 0.200 user3 all2 true 0.324234 0.300 user4 all null 0.323120 0.000 df = data[0].sub(data[1]).reset_index(name='result_norm') print (df) user_id feat type result_norm 0 user1 all true -0.212000 1 user1 all1 null NaN 2 user2 all1 null 0.032110 3 user3 all2 true 0.024234 4 user4 all null 0.323120
has comment: http://stackoverflow.com/comment/81087908
answers question: http://stackoverflow.com/q/47068935

http://stackoverflow.com/comment/81375869
has text: the user enters a number and then the program needs to put out that many random numbers
comment on: http://stackoverflow.com/q/47213130
type: QuestionComment
score: 1
type: Comment

http://stackoverflow.com/q/47100024
has title: unsupported operand type(s) for -: 'NoneType' and 'int'
tagged with: nonetype
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81166394
tagged with: python
has body: I wrote rock-paper-scissor game with python and I have error which I can't solve. please help. import random p1 = random.randint(0, 2) def choosing(): p = int(input("Rock: 0; Paper: 1; scissor: 2:")) if p &lt; 0 or p &gt; 2: print("\nPlease enter valid value") choosing() else: return int(p) p2 = choosing() print ("\n" + str(p1)) if p1 == p2: print("DRAW!!") elif p2 - p1 == 1 or p1 - p2 == 2: print("YOU WON!!") elif p1 - p2 == 1 or p2 - p1 == 2: print("YOU LOSE!!") Error says &gt; Traceback (most recent call last): File "python", line 15, in &lt;module&gt; TypeError: unsupported operand type(s) for -: 'NoneType' and 'int' and error comes only when I input valid value after entering invalid value
has answer: http://stackoverflow.com/a/47100594
tagged with: typeerror
answer count: 3
score: 1
tagged with: types
has answer: http://stackoverflow.com/a/47100056
downvote count: 1
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81150032
has answer: http://stackoverflow.com/a/47100089
has comment: http://stackoverflow.com/comment/81150005

http://stackoverflow.com/comment/81247270
comment on: http://stackoverflow.com/a/47148593
score: 0
type: Comment
has text: Can you add more of an explanation please
type: AnswerComment

http://stackoverflow.com/q/47200088
tagged with: backwards-compatibility
linked to: http://stackoverflow.com/q/36620168
has answer: http://stackoverflow.com/a/47239445
has body: In Python 2.7 ConfigParser.ConfigParser interpolates pattern %(__name__)s as name of the section. In Python 3.6 (as well as 3.3) configparser.ConfigParser fails at the same interpolation with InterpolationMissingOptionError exception. When has the behaviour of the interpolation changed? What is the rationale of the decision (as it is harming backward-compatibility)? In contrast to how to interpolate the section-name with configparser I am not asking how can I get that interpolation in Python 3.x.
answer count: 1
tagged with: configparser
type: Question
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/47239445
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has title: When (and why) has been `__name__` magic variable removed from `ConfigParser` interpolation?

http://stackoverflow.com/comment/81117691
type: QuestionComment
has text: please show us your attempt
score: 5
comment on: http://stackoverflow.com/q/47084190
type: Comment

http://stackoverflow.com/q/47196719
answer count: 2
downvote count: 0
tagged with: pandas
upvote count: 1
has title: Pandas: Convert fractional months to datetime
favorite count: 0
type: Question
score: 1
has answer: http://stackoverflow.com/a/47196831
tagged with: datetime
accepted answer: http://stackoverflow.com/a/47196831
tagged with: python
possible better answer: http://stackoverflow.com/a/47197671
has body: I have some monthly data with a date column in the format: YYYY.fractional month. For example: 0 1960.500 1 1960.583 2 1960.667 3 1960.750 4 1960.833 5 1960.917 Where the first index is June, 1960 (6/12=.5), the second is July, 1960 (7/12=.583) and so on. The answers in this question don't seem to apply well, though I feel like pd.to_datetime should be able to help somehow. Obviously I can use a map to split this into components and build a datetime, but I'm hoping for a faster and more rigorous method since the data is large.
has answer: http://stackoverflow.com/a/47197671
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46858090

http://stackoverflow.com/q/47086497
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/47086845
accepted answer: http://stackoverflow.com/a/47086845
type: Question
has title: Pandas get data in first DataFrame but not in second (equivalent of left join where null in SQL)
tagged with: python
has body: In SQL I do the following to get data that is in the first table, but not in the second table: select a.contactId from #t1 a left join #t2 b on a.contactId=b.contactId where b.contactId is null I tried doing the same in Pandas, but can't seem to get it to work.. I referenced the main comparison doc of pandas.pydata.org/pandas-docs/stable/comparison_with_sql.html but wasn't able to mimic desired output. This is what I tried: final_df = pd.merge(t_df1'contactId', t_df2.set_index('contactId'), left_on='contactId', right_index=True, how='left').t_df2['contactId'].isna() The final output should be just contactId from table t_df1 (none of contactId in t_df2 should appear). How would you write it? Thank you!

http://stackoverflow.com/a/71257796
downvote count: 0
answers question: http://stackoverflow.com/q/47144311
score: 3
type: Answer
has body: Building off @khawaja-fahad-shafi's answer, I created the following pattern, where data is a pandas DataFrame and text is a field of strings. I originally posted this as a comment not an answer, but the formatting was off. Hope it's helpful for someone. import pandas import spacy nlp = spacy.load("en_core_web_md") (data["text"] .apply(lambda text: " " .join(token.lemma_ for token in nlp(text) if not token.is_punct and not token.is_currency and not token.is_digit and not token.is_oov and not token.is_space and not token.is_stop and not token.like_num and not token.pos_ == "PROPN")))
has comment: http://stackoverflow.com/comment/133390530
upvote count: 3
has comment: http://stackoverflow.com/comment/133383246

http://stackoverflow.com/comment/81328032
score: 0
comment on: http://stackoverflow.com/q/47166563
type: Comment
type: QuestionComment
has text: yes i am looking for the sql. I want to search for the nextday in the sql as if the `program_start_date` show `20171108150000`, the nextday should be `20171109150000`, so I want to fetch that data to the 10 next data which it should be `20171109150000`, `20171109154500`, `20171109163000`, `20171109171500`, `20171109180000`, `20171109183000`, `20171109190000`, `20171109193000` and `20171109200000`. I hope that is clear?

http://stackoverflow.com/comment/81337325
comment on: http://stackoverflow.com/q/47193892
type: QuestionComment
score: 0
has text: style="background-color:#3C9770; is succeeded to 17 text element
type: Comment

http://stackoverflow.com/a/47208358
type: Answer
has body: You probably have empty lines in your file, resulting in empty items-list: dict = {} with open(selection, 'r') as lines: for line in lines: items = line.split() if items: key, values = items[0], items[1:] dict[key] = values
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47208285
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47208285

http://stackoverflow.com/q/47195785
linked to: http://stackoverflow.com/q/7961363
favorite count: 0
has body: How to remove duplicate elements from the list. I have list=[1,2,1,2,3,1,3,4] and I want to drop repeated items. That is, if an item in the list comes two or more times then it is exclude from the list completely. The final list should look like this: new_list=[4] In this example 1, 2 and 3 occur at least two time and therefore all these elements are removed from the list list=[1,2,1,2,3,1,3,4] new_list = [i for i in set(list)] # wrong; how do I fix this? print new_list Please note this is different from set(list) because set keeps all items in the list.
has answer: http://stackoverflow.com/a/47195972
has comment: http://stackoverflow.com/comment/81340381
type: Question
has comment: http://stackoverflow.com/comment/81340375
tagged with: python-3.x
linked to: http://stackoverflow.com/q/12897374
type: UnansweredQuestion
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/81340767
has comment: http://stackoverflow.com/comment/81340304
upvote count: 1
score: -4
has comment: http://stackoverflow.com/comment/81340463
answer count: 1
has title: how to remove all duplicate items from list including that item

http://stackoverflow.com/comment/81176986
type: QuestionComment
has text: `class MyView(BaseView):` should be `class MyModelView(ModelView):` and then use `admin.add_view(MyModelView(User, db.session))` and `admin.add_view(MyModelView(Post, db.session))`. Try that it should work
comment on: http://stackoverflow.com/q/47080031
score: 0
type: Comment

http://stackoverflow.com/comment/81085882
type: Comment
type: QuestionComment
has text: I'm guessing you're using openpyxl? Then `sheet.max_row` should work. Perhaps that cell isn't really empty (any kind of formatting change, perhaps?). See also https://bitbucket.org/openpyxl/openpyxl/issues/514/cell-max_row-reports-higher-than-actual
comment on: http://stackoverflow.com/q/47068734
score: 0

http://stackoverflow.com/a/47115969
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47115745
score: 1
upvote count: 1
has body: Instead of import pyplot as plt use from matplotlib import pyplot as plt as the module name is matplotlib, not pyplot.
answers question: http://stackoverflow.com/q/47115745
type: Answer

http://stackoverflow.com/comment/81143993
comment on: http://stackoverflow.com/a/47095421
has text: Ok I understand that it needs to be `d_excg = {'ExterCond': {'TA': 1, 'Gd': 1, 'Ex': 1, 'Po': 0, 'Fa': 0}}` and then `all_data['ExterCond_Good'] = all_data['ExterCond'].replace(d_excg)`. Thanks for help. This is kinda tricky, at least for a beginner like me.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47124007
has comment: http://stackoverflow.com/comment/81197988
tagged with: numpy
has answer: http://stackoverflow.com/a/47124040
type: AnsweredQuestion
has title: How to sum appearances in columns with pandas without lambda
has body: I have the following dataframe a b c d e 0 0 0 -1 1 -1 1 0 1 -1 1 -1 2 -1 0 -1 1 1 3 -1 1 1 -1 1 4 1 0 1 -1 1 5 1 0 0 0 1 6 1 1 0 0 -1 7 1 1 -1 0 0 For each numbers that appears in a,b,c,d,e, I want to sum and store in a column the amount of times that it appears in a row, so the result should be something like this: a b c d e Sum1 Sum0 Sum_1 0 0 0 -1 1 -1 1 2 2 1 0 1 -1 1 -1 2 1 2 2 -1 0 -1 1 1 2 1 2 3 -1 1 1 -1 1 3 0 2 4 1 0 1 -1 1 3 1 1 5 1 0 0 0 1 2 3 0 6 1 -1 0 0 -1 1 2 2 7 1 1 -1 -1 0 2 1 2 So in the first row, the number "1" appears once in a,b,c,d,e, so we store that in Sum1 column. Then, number "0" appears two times, and we store that in Sum0, and number "-1" appears 2 times and we store it in Sum_1. How could this columns be calculated, without using lambda functions (to get better performance)? I guess that numpy is involved here but I don't get how to do it
answer count: 3
downvote count: 0
upvote count: 1
tagged with: lambda
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47124032
has comment: http://stackoverflow.com/comment/81198027
has answer: http://stackoverflow.com/a/47124065
tagged with: pandas
has answer: http://stackoverflow.com/a/47124032
score: 1
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/47124040

http://stackoverflow.com/comment/81264326
score: 0
type: AnswerComment
has text: You need to post your whole program, or an equivalent whole test program, to get the best help.
comment on: http://stackoverflow.com/a/47141970
type: Comment

http://stackoverflow.com/q/47116558
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47144942
has body: In tensorflow, you could use the following code to run train_step 1000 times: train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss=loss) for _ in range(1000): sess.run(train_step) Is there a way to do this using tensorflow's while loop? I tried using the while loop below, but nothing gets trained: i = tf.constant(0) c = lambda i: tf.less(i, 1000) def body(i): with tf.control_dependencies([train_step]): return i+1 r = tf.while_loop(c, body, [i]) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) result = sess.run(r)
tagged with: python
has title: Running the training operation multiple times in Tensorflow
score: 1
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47144942
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/a/47207120
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47203965
upvote count: 1
has comment: http://stackoverflow.com/comment/81369848
type: Answer
accepted answer of: http://stackoverflow.com/q/47203965
has body: find takes as an argument a list of directories to search. You provided what appears to be regular expression. Because there is no directory named (literally) .*[^_].py, find returns an error. Below I have revised your script to correct that mistake (if I understand your intention). Because I see so many ill-written shell scripts these days, I've taken the liberty of "traditionalizing" it. Please see if you don't also find it more readable. Changes: use #!/bin/sh, guaranteed to be on an Unix-like system. Faster than bash, unless (like OS X) it is bash. use lower case for variable names to distinguish from system variables (and not hide them). eschew braces for variables (${var}); they're not needed in the simple case do not pipe output to /usr/bin/true; route it to dev/null if that's what you mean rm -f by definition cannot fail; if you meant || true, it's superfluous put then and do on separate lines, easier to read, and that's how the Bourne shell language was meant to be used Let &amp;&amp; and || serve as line-continuation, so you can see what's happening step by step Other changes I would suggest: Use a subshell when changing the working directory temporarily. When it terminates, the working directory is restored automatically (retained by the parent), saving you the cd .. step, and errors. Use set -e to cause the script to terminate on error. For expected errors, use || true explicitly. Change grep .py to grep '\.py$', just for good measure. To avoid Tilting Matchstick Syndrome, use something other than / as a sed substitute delimiter, e.g., sed 's://:/:g'. But sed could be avoided altogether with awk -F '/+' '{print $2}'. Revised version: #! /bin/sh src_dir=lambdas build_dir=bin mkdir -p $build_dir/lambdas rm -rf $build_dir/*.zip cp -r $src_dir/* $build_dir/lambdas # # The sed is a bit complicated to be osx / linux cross compatible : # ( .//run.sh vs ./run.sh # cd $build_dir/lambdas &amp;&amp; for L in $(find . -exec grep -l '.*[^_].py' {} + | sed 's/\/\//\//…

http://stackoverflow.com/q/47082973
tagged with: bit-manipulation
answer count: 1
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81115315
tagged with: byte
has title: Reading 'binary' bytes from a file in Python
has body: Consider a file that contains binary data represented as bytes: with open('foo', 'rb') as f: bs = f.read() print(bs) # b'\x00\x01\x00\x01\x00\x01'... The bytes can only have either 0 or 1 values. What is the most performant way to take a group of 32 bit/bytes and parse them into a (32-bit) integer? The struct module is probably what I need but I couldn't find an immediate way to do this. Alternative methods that involve casting bytes into chars and then parsing the integer from a bitstring e.g. int('01010101...', 2) don't perform as fast as I need them to for my use case.
has comment: http://stackoverflow.com/comment/81115244
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47083415
has comment: http://stackoverflow.com/comment/81115378
accepted answer: http://stackoverflow.com/a/47083415

http://stackoverflow.com/comment/81206453
type: QuestionComment
has text: python 2.7.14, matplotlib 2.1.0
comment on: http://stackoverflow.com/q/47128166
score: 0
type: Comment

http://stackoverflow.com/comment/81184718
type: Comment
score: 0
type: AnswerComment
has text: Can you specify your requirements in a bit detail please?
comment on: http://stackoverflow.com/a/47106979

http://stackoverflow.com/q/47108441
favorite count: 0
type: Question
tagged with: numpy
has body: I'm trying to adapt the example from http://cs231n.github.io/neural-networks-case-study/#together to make a neural network for a numeric target variable so it will be a neural network with regression. I surely do something wrong in the derivation part because my loss function in insanely growing. Here is the code: h = neurons # size of hidden layer D = X[0].size K = 1 W = 0.01 * np.random.randn(D,h) b = np.zeros((1,h)) W2 = 0.01 * np.random.randn(h,K) b2 = np.zeros((1,K)) # some hyperparameters step_size = 1 #learning rate reg = 0.001 # regularization strength loss_vec = [] # gradient descent loop num_examples = X.shape[0] for i in xrange(1000): # evaluate class scores, [N x K] hidden_layer = np.maximum(0, np.dot(X, W) + b) # note, ReLU activation scores = np.dot(hidden_layer, W2) + b2 loss = np.power(y - scores,2) #if i % 50 == 0: loss_vec.append(np.mean(np.abs(loss))) print "iteration %d: loss %f" % (i, np.mean(np.abs(loss))) # compute the gradient on scores dscores = 2*(y-scores) # here I am not sure is correct # backpropate the gradient to the parameters # first backprop into parameters W2 and b2 dW2 = np.dot(hidden_layer.T, dscores) db2 = np.sum(dscores, axis=0, keepdims=True) # next backprop into hidden layer dhidden = np.dot(dscores, W2.T) # backprop the ReLU non-linearity dhidden[hidden_layer <= 0] = 0 # finally into W,b dW = np.dot(X.T, dhidden) db = np.sum(dhidden, axis=0, keepdims=True) # add regularization gradient contribution dW2 += reg * W2 dW += reg * W # perform a parameter update W += -step_size * dW b += -step_size * db W2 += -step_size * dW2 b2 += -step_size * db2 Code output: iteration 0: loss 5786.021888 iteration 1: loss 24248543152533318464172949461134213120.000000 iteration 2: loss 388137710832824223006297769344993376570435619092
accepted answer: http://stackoverflow.com/a/47113953
has answer: http://stackoverflow.com/a/47113953
tagged with: neural-network
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: backpropagation
tagged with: loss-function
answer count: 1
upvote count: 1
has title: Can somebody help me to correctly derive the loss function?
downvote count: 1

http://stackoverflow.com/comment/81289038
score: 0
type: AnswerComment
has text: Ok, Thanks so much
comment on: http://stackoverflow.com/a/47168981
type: Comment

http://stackoverflow.com/comment/81383869
type: Comment
has text: what do you means "personal hash"?
type: AnswerComment
comment on: http://stackoverflow.com/a/47200367
score: 0

http://stackoverflow.com/q/47086605
type: UnansweredQuestion
has body: I have been trying to extract certain data from an XML response. I am able to get certain tags, but the information I need is within a different format that I haven't had any luck with. I have the following XML stored as a variable itemspecifics. What I need is the value for Manufacturer Part Number which is 90105-MV9-003. What I don't understand is how to extract this data because the tag name repeats. >>> print itemspecifics Brand Honda ItemSpecific Country/Region of Manufacture Japan ItemSpecific Manufacturer Part Name BOLT, DISK (8X24) (TSUKIBOSHI) ItemSpecific Manufacturer Part Number 90105-MV9-003 ItemSpecific Placement on Vehicle Rear ItemSpecific Retail Price $20.96 ItemSpecific Type rear rotor bolt set ItemSpecific >>> >>> print(type(itemspecifics)) <class 'bs4.element.Tag'>
tagged with: python
has title: Extracting data from XML Name Value List with Python
tagged with: http://stackoverflow.com/tag/xml
score: 0
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/47089374
tagged with: beautifulsoup

http://stackoverflow.com/comment/81278950
has text: @pashute You don't need apply and lambdas. You just need to use .loc[rowindex, colindex]. Since your rowindex is multiindex, it looks a bit strange analyze.loc[('aa','2015/1/1'),['o_x','o_y']), the first argument is a tuple for the multiindex, the second argument is list for two columns.
type: Comment
comment on: http://stackoverflow.com/a/47163476
score: 0
type: AnswerComment

http://stackoverflow.com/q/47182183
has body: If you worked in python with pandas you already know the chained_assignment warning when working on slices of dataframes (as e.g. described here). I found the option pandas.options.mode.chained_assignment which can be set to None, ignoring the warning "warn", printing a warning message "raise", raising an exception compare with documentation I included a minimal example, triggering this warning within a try..except..else block for exception handling. I expect an exception to be triggered only with the setting pandas.options.mode.chained_assignment = "raise", as shown in Example 3 below. In this minimal example, the behaviour is as expected, so that Example 2, with pandas.options.mode.chained_assignment = "warn" only causes a warning message to be printed, but no exception is raised. However in a larger framework, I see an exception being raised even though the parameter is set to pandas.options.mode.chained_assignment = "warn", checked with a print before like in the minimal example (see Example 4) Is there any other pandas parameter influencing the behavior of this warning message concerning exception raising? Here is a minimal example of code, setting/printing the pd.options.mode.chained_assignment parameter and showing the behaviour in a try..catch..except block. import pandas as pd # set the chained_assignment option pd.options.mode.chained_assignment = "raise" # raises exception in case of warning pd.options.mode.chained_assignment = "warn" # prints warning in case of warning, no exception is raised pd.options.mode.chained_assignment = None # no warning message and no exception is raised print "pd.options.mode.chained_assignment :", pd.options.mode.chained_assignment # create a default pandas dataframe with two columns A,B df = pd.DataFrame({"A" : [0, 1, 2], "B" : [3, 4, 5]}) print df # exctract a slice of the given pandas dataframe df2 = df[df["A"] &gt; 0] # exception handling try : # try to modify the slice, triggering the pandas warning df2["C"] = 2 except :…
linked to: http://stackoverflow.com/q/37841525
upvote count: 12
tagged with: exception
tagged with: python
score: 12
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47184039
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/47184039
type: Question
has title: pandas chained_assignment warning exception handling

http://stackoverflow.com/a/47099220
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/47097006
downvote count: 0
has body: Evaluate an algorithm using pseudo code. Identify important concepts and create functions with parameters. Give meaningful names. Run iteration with pencil and paper. If it works, refine algorithm. Identify data structures supporting your use case. The current code is not made for human eyes, but you are asking humans for help.
type: Answer

http://stackoverflow.com/q/47126186
has title: matplotlib can't load ft2font on Windows 10
has answer: http://stackoverflow.com/a/52827932
has answer: http://stackoverflow.com/a/48531978
has answer: http://stackoverflow.com/a/64217853
has answer: http://stackoverflow.com/a/56120903
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81203569
tagged with: python
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/81207887
has answer: http://stackoverflow.com/a/59164440
tagged with: freetype
has answer: http://stackoverflow.com/a/57687360
tagged with: anaconda
linked to: http://stackoverflow.com/q/24251102
tagged with: matplotlib
downvote count: 0
has answer: http://stackoverflow.com/a/63492710
favorite count: 0
type: Question
answer count: 8
has body: I'm using Anaconda 5.0.1 with Python 2.7.14. When I open a jupyter notebook and try to run the following: %matplotlib inline I get the following error: ImportError Traceback (most recent call last) C:\toolkits.win\anaconda2\envs\dlc\lib\site-packages\matplotlib\font_manager.py in &lt;module&gt;() 56 57 import matplotlib ---&gt; 58 from matplotlib import afm, cbook, ft2font, rcParams, get_cachedir 59 from matplotlib.compat import subprocess 60 from matplotlib.fontconfig_pattern import ( ImportError: DLL load failed: The specified procedure could not be found. When I try to drill into the error, the problem is with ft2font: In [1]: from matplotlib import ft2font --------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-1-a32e7826851f&gt; in &lt;module&gt;() ----&gt; 1 from matplotlib import ft2font ImportError: DLL load failed: The specified procedure could not be found. I double-checked and made sure freetype is installed: (dlc) C:\Users\Larry&gt;conda install freetype Fetching package metadata ............. Solving package specifications: . # All requested packages already installed. # packages in environment at C:\toolkits.win\anaconda2\envs\dlc: # freetype 2.8 vc9hf582001_0 [vc9] Any ideas?
has answer: http://stackoverflow.com/a/65456738

http://stackoverflow.com/comment/81143639
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47096797
has text: Yes, I want to apply ignore case
score: 0

http://stackoverflow.com/comment/81316195
comment on: http://stackoverflow.com/q/47182872
score: 0
type: Comment
has text: What errors did you get when you tried the def ws_f way? And how did you call the function?
type: QuestionComment

http://stackoverflow.com/q/47181719
has comment: http://stackoverflow.com/comment/81312594
has comment: http://stackoverflow.com/comment/81312544
has answer: http://stackoverflow.com/a/47182258
tagged with: python
has title: searching a specific line of a text file, but with an annoying twist
tagged with: python-3.6
tagged with: search
has body: So, my python file needs to be able to delete lines of a text file. Easy right? There are loads of answered questions on this website on this topic, unfortunately, they don't include if two line have the same series of characters inside of the string E.G: datafile.txt: LMNO:ABCD:UVWX ABCD:EFGH:IJKL BABC:DEFG:HIJK If I wanted to delete line two, I would have to search for it, The way my system works means that you will only know the first section before the colon. E.G: LMNO: ABCD: BABC: So, if I wanted to delete the line containing ABCD or even ABCD:, it would return line 1. This is my current code: import fileinput, sys def searchFiles(searchPrompt): with open("testfile.txt") as f: for num, line in enumerate(f, 1): if searchPrompt in line: return(num) def deleteLine(lineNumber): for lineNumber, line in enumerate(fileinput.input('testfile.txt', inplace=1)): if lineNumber == 0: continue else: sys.stdout.write(line) searchPrompt = input("Enter username to delete: ") searchPrompt = (searchPrompt+":") print(searchPrompt) lineNumber = searchFiles(searchPrompt) deleteLine(lineNumber)
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81312527
answer count: 2
has answer: http://stackoverflow.com/a/47182438
has comment: http://stackoverflow.com/comment/81312357
has comment: http://stackoverflow.com/comment/81313011
type: Question
possible better answer: http://stackoverflow.com/a/47182438
has comment: http://stackoverflow.com/comment/81312551
accepted answer: http://stackoverflow.com/a/47182258

http://stackoverflow.com/comment/81078100
comment on: http://stackoverflow.com/q/47064885
score: 0
type: QuestionComment
type: Comment
has text: @downshift that seems to work however when it prints I get 28 14 9 7 5 4 4 3 3 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1

graphics
tag name: graphics
tags question: http://stackoverflow.com/q/47180690
type: Tag
tags question: http://stackoverflow.com/q/47200326

http://stackoverflow.com/q/47086545
has title: HttpError 500 - Internal Error when training ML in Google Cloud Platform
tagged with: google-cloud-platform
type: UnansweredQuestion
has body: I am building my trainer package manually with setuptools and upload the distribution (.tar.gz) to a bucket in GCP (as instructed here). I then created a service account and give ML Engine Developer and Storage Object Admin roles. I tried to run the trainer package by calling the API from my python code. The code followed exactly what was written here. However, I received an error message: HttpError 500 - Internal error encountered. Unfortunately, the error is too generic that does not allow me to debug and the ML job is not created in the console. from oauth2client.client import GoogleCredentials from oauth2client.service_account import ServiceAccountCredentials from googleapiclient import discovery training_inputs = {'scaleTier': 'STANDARD_1', 'packageUris': ['gs://mybucket/trainerPackage-0.1.tar.gz'], 'pythonModule': 'trainer.task', 'args': ['--data-dir', 'gs://mybucket/data/evaluate_data.csv', '--job-dir', 'gs://mybucket/output', '--epochs', '10' ], 'region': 'asia-east1', 'jobDir': 'gs://mybucket/output', 'runtimeVersion': '1.2'} job_spec = {'jobId':'ml_test', 'trainingInput':training_inputs} project_name = 'test-proj' project_id = 'projects/{}'.format(project_name) credentials_dict = {my_cred_from_json} credentials = ServiceAccountCredentials.from_json_keyfile_dict(credentials_dict) cloudml = discovery.build('ml', 'v1', credentials=credentials) request = cloudml.projects().jobs().create(body=job_spec, parent=project_id) try: response = request.execute() except Exception as err: print('There was an error creating the training job.' ' Check the details:') print(err._get_reason()) print(str(err)) Here is the structure of my trainer package: trainerPackage - trainer - __init__.py - task.py - setup.py and here is my setup.py: from setuptools import setup, find_packages REQUIRED_PACKAGES = [ 'tensorflow &gt;= 1.2', 'pandas &gt;= 0.20.3', 'numpy &gt;= 1.13.3' ] setup( name = 'trainerPackage', version = '0.1', install_requires = REQUIRED_PACKAGES, packages = find_pack…
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: google-cloud-ml
has comment: http://stackoverflow.com/comment/81126760
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81258860
has comment: http://stackoverflow.com/comment/81275353
type: Question
has comment: http://stackoverflow.com/comment/81159374
answer count: 0

http://stackoverflow.com/q/47066314
tagged with: python
type: Question
answer count: 2
upvote count: 1
type: UnansweredQuestion
tagged with: random-forest
downvote count: 1
has answer: http://stackoverflow.com/a/47066811
tagged with: machine-learning
has title: why model is giving high accuracy of 84% but very low AUC 13%?
favorite count: 0
has answer: http://stackoverflow.com/a/47236204
score: 0
has body: I have built model which gives me 84% accuracy for random forest and support vector machine but giving very low auc of 13% only. I am building this in python and I am new to machine learning and data science. I am predicting 0 and 1 labels on dataset. My overall dataset is having records of 30744. Label 1 - 6930 Label 0 - 23814 Could you please advise if this is fine? Is model is getting overfitted? Appreciate any suggestion on improving auc?

http://stackoverflow.com/q/47132523
upvote count: 2
has body: Consider df Cost Store 1 22.5 Store 1 ......... Store 2 ... To convert these the dots to nan, I can use: df.replace('^\.+$', np.nan, regex=True) Cost Store 1 22.5 Store 1 NaN Store 2 NaN What I don't understand is why the following pattern also works: df.replace('^.+$', np.nan, regex=True) Cost Store 1 22.5 Store 1 NaN Store 2 NaN Note that, in this case, I haven't escaped the ., so it should be treated as a matchall character, resulting in every single row being converted to NaN... but it isn't.... only the .... rows are matched... even though I used the matchall character. Contrast this with: import re re.sub('^.+$', '', '22.5') '' Which returns an empty string. So what's going on?
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47132524
accepted answer: http://stackoverflow.com/a/47132524
type: AnsweredQuestion
score: 2
tagged with: pandas
has title: Pandas inconsistency with regex "." dot metacharacter?
tagged with: python
tagged with: regex
favorite count: 0
type: Question

http://stackoverflow.com/a/47166594
has comment: http://stackoverflow.com/comment/81283322
accepted answer of: http://stackoverflow.com/q/47166454
score: 2
answers question: http://stackoverflow.com/q/47166454
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81285317
upvote count: 2
has comment: http://stackoverflow.com/comment/81283999
downvote count: 0
type: Answer
has body: You should use a loop. for x in range(14): a = translate[x] aa = values[a] print(aa+16) This is a very basic structure in computer science, and I recommend you develop a stronger command of fundamental programming ideas before taking on a big project. Try a site like codecademy and you may find that you no longer need to ask simple questions like this. Though for the record: word = input() #the word you read in for x in range(len(word)): #this will allow you to read words of arbitrary length a = translate[x] aa = values[a] print(aa+16)

http://stackoverflow.com/a/47217763
answers question: http://stackoverflow.com/q/47217273
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81387484
has comment: http://stackoverflow.com/comment/81387646
has comment: http://stackoverflow.com/comment/81390167
has comment: http://stackoverflow.com/comment/81387018
has comment: http://stackoverflow.com/comment/81386520
type: Answer
has body: connectionSocket.send('\nHTTP/1.1 200 OK\n\n') The leading \n at the start of the HTTP header is definitely wrong. Apart from that the line delimiter should be \r\n not \n. connectionSocket.send('\HTTP/1.1 404 Not Found \n\n'); This should be HTTP/1.1... and not \HTTP/1.1.... And the line delimiter is wrong too. I have no idea where your (insufficient) understanding of HTTP comes from. But if you want to implement a server I recommend to not just have a look at a few packet captures or similar but actually study the standard which is more complex than you might imagine. That's what standards are for.
has comment: http://stackoverflow.com/comment/81386136
has comment: http://stackoverflow.com/comment/81389346
has comment: http://stackoverflow.com/comment/81386913
has comment: http://stackoverflow.com/comment/81389972
score: 1

http://stackoverflow.com/comment/81306790
type: Comment
has text: I forgot to mention I've also tried this method and got another error. I think it has to do with some type of aggregation being done with missing values in the dataset. Editing question
type: QuestionComment
comment on: http://stackoverflow.com/q/47178861
score: 0

http://stackoverflow.com/comment/81197663
comment on: http://stackoverflow.com/q/47123809
has text: Your code does not run, the indentation is off.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81132795
type: AnswerComment
has text: Thanks, your explenation fixed it for me, really interesting, haven't really worked a lot with `__init__` yet, definitely something I want to look further into now. Also I didn't know yet that you could make your own fields. Thanks for these interesting solutions.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47091553

http://stackoverflow.com/q/47198002
tagged with: python
has title: Pulling data from heroku for django website
has body: I made a website on django and hosted it on heroku. It uses the default sqlite3 database. When adding some entry on the website, the heroku db is updated. I am unable to pull that entry on my local db. When I push any changes to the heroku, all those entries that were added from the website are deleted. How can I pull those entries from heroku?
type: UnansweredQuestion
answer count: 1
tagged with: django
tagged with: git
has answer: http://stackoverflow.com/a/47198606
type: Question
has comment: http://stackoverflow.com/comment/81344585
tagged with: heroku
score: 0

http://stackoverflow.com/comment/81091516
type: QuestionComment
has text: Please make a full code example, as there seems to be something missing. You say you have lists `list_1` to `list_n`, but I don't see them in your code. Also it is not obvious what `index_all` represents. Why do you need any indices in a list, if you just want to concatenate the lists? Is that the list where you want to append all the contents of the other lists?
score: 1
comment on: http://stackoverflow.com/q/47071450
type: Comment

http://stackoverflow.com/a/47067651
has comment: http://stackoverflow.com/comment/81123946
has comment: http://stackoverflow.com/comment/108854526
score: 3
answers question: http://stackoverflow.com/q/47066858
has comment: http://stackoverflow.com/comment/81120958
type: Answer
has body: This has to do with the precision of floating point arithmetic; not all numbers can be represented exactly. If you want to set pandas to display numbers to 5 decimal places, you can do pd.set_options('display.float_format','{:.5f}') but the internal representation will stay the same (which after reading your post closely, will not solve your issues with the csv). If you want to change the internal representation, you need to use a Decimal data type: from decimal import Decimal df.round(5).astype(Decimal) FYI, you can reproduce your problem like this: import numpy as np np.float64(1.08496)
upvote count: 3
downvote count: 0

http://stackoverflow.com/a/54248496
downvote count: 0
has body: For your purpose, I would go for sklearn sample generator make_blobs: from sklearn.datasets import make_blobs centers = [(-5, -5), (5, 5)] cluster_std = [0.8, 1] X, y = make_blobs(n_samples=100, cluster_std=cluster_std, centers=centers, n_features=2, random_state=1) plt.scatter(X[y == 0, 0], X[y == 0, 1], color="red", s=10, label="Cluster1") plt.scatter(X[y == 1, 0], X[y == 1, 1], color="blue", s=10, label="Cluster2") You can generate multi-dimensional clusters with this. X yields data points and y is determining which cluster a corresponding point in X belongs to. This might be too much for what you try to achieve in this case, but generally, I think it's better to rely on more general and better-tested library codes that can be used in other cases as well.
has comment: http://stackoverflow.com/comment/112524910
type: Answer
answers question: http://stackoverflow.com/q/47115025
upvote count: 9
score: 9

http://stackoverflow.com/q/47102564
tagged with: python
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/47102818
score: 4
upvote count: 4
downvote count: 0
answer count: 1
tagged with: interactive
has title: How to set interact arguments programmatically?
favorite count: 0
type: Question
type: UnansweredQuestion
has body: Suppose I have function, that accepts list of arguments. List can be of variable length and function is ok with it. For example: import math import numpy as np import matplotlib.pyplot as plt from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets %matplotlib inline def PlotSuperposition(weights): def f(x): y = 0 for i, weight in enumerate(weights): if i==0: y+=weight else: y += weight*math.sin(x*i) return y vf = np.vectorize(f) xx = np.arange(0,6,0.1) plt.plot(xx, vf(xx)) plt.gca().set_ylim(-5,5) PlotSuperposition([1,1,2]) shows I can hardcode interact for given number of arguments, like here interact(lambda w0, w1, w2: PlotSuperposition([w0,w1,w2]), w0=(-3,+3,0.1), w1=(-3,+3,0.1), w2=(-3,+3,0.1)) which shows But how can I make number of sliders defined programmatically? I tried n_weights=10 weight_sliders = [widgets.FloatSlider( value=0, min=-10.0, max=10.0, step=0.1, description='w%d' % i, disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', ) for i in range(n_weights)] interact(PlotSuperposition, weights=weight_sliders) but got error TypeError: 'FloatSlider' object is not iterable inside PlotSuperposition saying that interact doesn't pass a list of values to the function. How to accomplish?

http://stackoverflow.com/comment/81199491
type: Comment
has text: You can check the test case in the edited question, sorry it took so long
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47124169

http://stackoverflow.com/q/47156179
has title: Scraping the core-text of webpages in python
downvote count: 4
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81261987
score: -4
tagged with: web-scraping
tagged with: python
has answer: http://stackoverflow.com/a/47156860
tagged with: phantomjs
answer count: 1
has body: Is there a module that can be used to get the core-text of a webpage? Something the will remove the headers / menus / social links? Thank you
favorite count: 0
type: Question

http://stackoverflow.com/comment/81235634
has text: @Parfait I will try that, can you confirm the arguments I need to pass with example, like where do I pass my username, server etc. is this right ("mssql+pyodbc://my_user_name:my_password@my_server/my_database", echo=False) and then mydataframe.to_sql('my_database', con=engine, if_exists='replace') I want my database and table name to be same
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47142514

http://stackoverflow.com/a/47141428
answers question: http://stackoverflow.com/q/47122561
score: 1
type: Answer
has body: I found the solution to the problem. I need to @app.route("/user-A-input", methods=['GET', 'POST']) method in Route.py instead of CallResponse.py It's probably because it is using the instance of flask object which was created in the Route.py. I still need to look into detail, like how can I make it work by keeping the UserAInput method in CallResponse.py
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47122561
type: AcceptedAnswer

http://stackoverflow.com/a/47126670
has body: pip is a command to use at the Windows Command Line prompt (the C:\ prompt), not for use in the python shell. (So don't start Python first. Just open a command prompt and type "pip install pygame" at the C: prompt.)
answers question: http://stackoverflow.com/q/47126645
score: 2
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/81240787
type: Comment
comment on: http://stackoverflow.com/a/47145126
type: AnswerComment
has text: [Miguel Grinberg also recommends putting a copy of current_user into `g.user`.](https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins)
score: 0

http://stackoverflow.com/a/47177793
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47175484
has body: I didn't clearly get your criteria with the example of the expected output however. You may apply the following: Values = [11.7, 8.5, 11.3, 11.2, 10.8, 1.05] First you determine the positions of change in the list (The if condition here is my understanding of 5% change you might want to change this according to your needs) ChangePosition = [ Ind+1 for Ind,Pair in enumerate(zip(Values,Values[1:])) if ((Pair [0] - Pair [1]) / Pair [0] &gt; -0.05) ] Then you add the beginning and the end of the possible positions. ChangePosition = [0] + ChangePosition + [len(Values)] Finally you slice the Values according to these positions: GroupedValues = [ Values[Start:Finish] if (Finish-Start)&gt; 1 else Values[Start] for Start,Finish in zip(ChangePosition ,ChangePosition [1:])]
type: Answer

http://stackoverflow.com/comment/81180978
type: AnswerComment
comment on: http://stackoverflow.com/a/47115589
score: 0
has text: You beat me to the answer. :)
type: Comment

http://stackoverflow.com/q/47222467
type: Question
has answer: http://stackoverflow.com/a/47222824
has answer: http://stackoverflow.com/a/47222597
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47222668
tagged with: python
has comment: http://stackoverflow.com/comment/81394744
has title: How do I get only one specific aspect of the JSON answer
has body: so I have the following block of JSON: b'{"data":[{"categories":[{"id":"IAB3","label":"Business","parent":"IAB3","score":"0.223819028028717559","confident":true}],"url":"megatel.de"}]}' I need only a String with the content of the first label field.
score: -1
answer count: 3
has comment: http://stackoverflow.com/comment/81394842
upvote count: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/81394839
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81291498
type: Comment
score: 0
type: AnswerComment
has text: I've solved it like this: `b.config(command=lambda b=b: b.config(text=self.ground_data_values[self.values_list_box.get(tk.ACTIVE)]))`. Yeah, that was the problem. Geez, this closure detail is really hard to remember. Thank you!
comment on: http://stackoverflow.com/a/47170894

tensorflow
tags question: http://stackoverflow.com/q/47203019
type: Tag
tags question: http://stackoverflow.com/q/47211666
tags question: http://stackoverflow.com/q/47132345
tags question: http://stackoverflow.com/q/47081900
tags question: http://stackoverflow.com/q/47086606
tags question: http://stackoverflow.com/q/47104617
tags question: http://stackoverflow.com/q/47148804
tags question: http://stackoverflow.com/q/47179126
tags question: http://stackoverflow.com/q/47192887
tags question: http://stackoverflow.com/q/47151562
tags question: http://stackoverflow.com/q/47196299
tags question: http://stackoverflow.com/q/47123960
tags question: http://stackoverflow.com/q/47100998
tags question: http://stackoverflow.com/q/47085859
tags question: http://stackoverflow.com/q/47103581
tags question: http://stackoverflow.com/q/47159215
tags question: http://stackoverflow.com/q/47169313
tags question: http://stackoverflow.com/q/47172525
tags question: http://stackoverflow.com/q/47097616
tags question: http://stackoverflow.com/q/47069671
tags question: http://stackoverflow.com/q/47162541
tags question: http://stackoverflow.com/q/47173198
tags question: http://stackoverflow.com/q/47160937
tags question: http://stackoverflow.com/q/47075719
tags question: http://stackoverflow.com/q/47153182
tags question: http://stackoverflow.com/q/47192902
tags question: http://stackoverflow.com/q/47205378
tags question: http://stackoverflow.com/q/47091726
tags question: http://stackoverflow.com/q/47115946
tags question: http://stackoverflow.com/q/47215317
tags question: http://stackoverflow.com/q/47163658
tags question: http://stackoverflow.com/q/47074590
tags question: http://stackoverflow.com/q/47167409
tags question: http://stackoverflow.com/q/47086810
tags question: http://stackoverflow.com/q/47190556
tags question: http://stackoverflow.com/q/47187768
tags question: http://stackoverflow.com/q/47149254
tags question: http://stackoverflow.com/q/47167630
tags question: http://stackoverflow.com/q/47179545
tags question: http://stackoverflow.com/q/47131497
tags question: http://stackoverflow.com/q/47132665
tags question: http://stackoverflow.com/q/47088007
tags question: http://stackoverflow.com/q/47148664
tags question: http://stackoverflow.com/q/47069667
tags question: http://stackoverflow.com/q/47191897
tags question: http://stackoverflow.com/q/47220133
tags question: http://stackoverflow.com/q/47218034
tags question: http://stackoverflow.com/q/47126907
tags question: http://stackoverflow.com/q/47106830
tags question: http://stackoverflow.com/q/47141359
tags question: http://stackoverflow.com/q/47153601
tags question: http://stackoverflow.com/q/47122697
tags question: http://stackoverflow.com/q/47212464
tags question: http://stackoverflow.com/q/47143435
tags question: http://stackoverflow.com/q/47179655
tags question: http://stackoverflow.com/q/47176400
tags question: http://stackoverflow.com/q/47127962
tags question: http://stackoverflow.com/q/47087475
tags question: http://stackoverflow.com/q/47092750
tags question: http://stackoverflow.com/q/47205160
tags question: http://stackoverflow.com/q/47132557
tags question: http://stackoverflow.com/q/47172108
tags question: http://stackoverflow.com/q/47127554
tags question: http://stackoverflow.com/q/47203530
tags question: http://stackoverflow.com/q/47149764
tags question: http://stackoverflow.com/q/47109343
tags question: http://stackoverflow.com/q/47214251
tags question: http://stackoverflow.com/q/47178371
tags question: http://stackoverflow.com/q/47199553
tags question: http://stackoverflow.com/q/47120637
tags question: http://stackoverflow.com/q/47163477
tags question: http://stackoverflow.com/q/47131248
tags question: http://stackoverflow.com/q/47114212
tags question: http://stackoverflow.com/q/47214001
tags question: http://stackoverflow.com/q/47214508
tags question: http://stackoverflow.com/q/47129071
tags question: http://stackoverflow.com/q/47200662
tags question: http://stackoverflow.com/q/47070348
tags question: http://stackoverflow.com/q/47205248

multidimensional-array
tags question: http://stackoverflow.com/q/47209612
tags question: http://stackoverflow.com/q/47193665
type: Tag
tags question: http://stackoverflow.com/q/47175707
tags question: http://stackoverflow.com/q/47166551
tags question: http://stackoverflow.com/q/47165446
tags question: http://stackoverflow.com/q/47162048
tags question: http://stackoverflow.com/q/47167305
tag name: multidimensional-array
tags question: http://stackoverflow.com/q/47084045
tags question: http://stackoverflow.com/q/47157692
tags question: http://stackoverflow.com/q/47211128

http://stackoverflow.com/comment/81185291
has text: I suggest you remove or qualify the comment that these are equivalent in many other languages. In C, for example, `a = b` assigns the value of `b` to `a` (converted as necessary and appropriate), but `a = a = b` has undefined behavior (because it is illegal to modify an object twice between sequence points).
type: AnswerComment
score: 3
comment on: http://stackoverflow.com/a/47117575
type: Comment

http://stackoverflow.com/q/47118820
has comment: http://stackoverflow.com/comment/81187452
has comment: http://stackoverflow.com/comment/81187426
favorite count: 0
type: Question
tagged with: python-3.x
score: 5
upvote count: 5
answer count: 1
has answer: http://stackoverflow.com/a/47118831
linked to: http://stackoverflow.com/q/37804702
tagged with: python
has body: There must be an obvious answer but I could neither find it in the sort_values()'s docs nor in related questions posts* by in df.sort_values() accept columns labels, but How do I sort using the columns' position ? I came up with this cumbersome code df.iloc[df.iloc[:,1].sort_values().index] to sort on the second column. I was thinking that something like df.sort_values(by=1,axis=1) would exist. So what is syntacticly simple and correct way to do that ? *Related questions: 1, 2, 3, 4, 5, 5, 6
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/17618981
downvote count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/45736127
linked to: http://stackoverflow.com/q/46584016
linked to: http://stackoverflow.com/q/37287938
tagged with: dataframe
has title: How to sort Pandas df columns' values based on its position not labels?
accepted answer: http://stackoverflow.com/a/47118831

http://stackoverflow.com/comment/81291998
has text: Your table has some information saved?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47170838

http://stackoverflow.com/q/47213335
has comment: http://stackoverflow.com/comment/81376255
type: AnsweredQuestion
tagged with: pandas
has body: I am trying to split a string in a Pandas DF and add the resulting list as a new column. For example the string: "A;B;C;D" Would be stored in a new column as: ['A','B','C','D'] Currently trying this code: df['SplitList'] = [re.split(";",i) for i in df['List']] But getting this error: File "C:\Python27\lib\re.py", line 171, in split return _compile(pattern, flags).split(string, maxsplit) TypeError: expected string or buffer
score: 1
accepted answer: http://stackoverflow.com/a/47213466
answer count: 1
downvote count: 0
upvote count: 1
tagged with: string
has answer: http://stackoverflow.com/a/47213466
has title: Splitting a String in Pandas DF and Adding a Column with the Resulting List of Values
favorite count: 0
type: Question
tagged with: split
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/81376332

http://stackoverflow.com/q/47167139
has comment: http://stackoverflow.com/comment/81323190
has title: How to use getpass() to hide a users password as it is entered
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/81284283
has body: I am trying to make a small program which checks the strength of the user password. When the user is prompted to enter their password I want the input to show as asterisks or dots instead of the text input. Is there a way of hiding this input. I have used getpass to try and hide the input without success. from getpass import getpass passwd = getpass('Please enter your password') This gives me the following warning message: Warning (from warnings module): File "C:\Program Files (x86)\Python36-32\lib\getpass.py", line 100 return fallback_getpass(prompt, stream) GetPassWarning: Can not control echo on the terminal. Warning: Password input may be echoed. Please enter your password: this_is_my_password The password is entered on the line but instead of coming up with astrisks it comes up with the original characters. As the program will check the strength of the password I need to have something that does not save the password as the asterisks but as its original characters. As well as this is there any way of incorporating a way of showing the user password if they perform an action. I was considering using a button but that is an area in Python I am not confident with so could I program in another way with a specific key. Sudo code for project. userPass = hidden(input("Please enter your password ")) if showPassword selected: show the password else: move on with the rest of the program
linked to: http://stackoverflow.com/q/35805078
accepted answer: http://stackoverflow.com/a/47263175
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/47263175
possible better answer: http://stackoverflow.com/a/47167229
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/81284624
has comment: http://stackoverflow.com/comment/81285365
has answer: http://stackoverflow.com/a/47167229
has comment: http://stackoverflow.com/comment/81286669
duplicate of: http://stackoverflow.com/q/38878741
downvote count: 3

http://stackoverflow.com/a/47106327
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47106300
answers question: http://stackoverflow.com/q/47106300
type: AcceptedAnswer
upvote count: 1
downvote count: 1
has body: type which python3instead that should work

http://stackoverflow.com/q/47098063
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81145882
tagged with: python
has comment: http://stackoverflow.com/comment/81146003
type: UnansweredQuestion
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47098893
has body: I have two images. For some specific points I know their coordinates on the two images, how can I draw lines between those points and plot a figure showing the two images along with the matching lines? I actually didn't know where to start here. That's why I didn't show any code yet. Would matplotlib benefit me in this case? EDIT This is an example of what I'm expecting (the image is taken from, here): Thanks.
linked to: http://stackoverflow.com/q/17543359
type: Question
has title: Drawing lines between specific points in two images
has comment: http://stackoverflow.com/comment/81147403
duplicate of: http://stackoverflow.com/q/17543359

http://stackoverflow.com/q/47122088
type: Question
upvote count: 4
has title: Image to numpy array to Image and finally again to array resulting in wrong array
has answer: http://stackoverflow.com/a/47122168
has comment: http://stackoverflow.com/comment/81193839
accepted answer: http://stackoverflow.com/a/47122212
has answer: http://stackoverflow.com/a/47122269
has body: I converted an image to numpy array using: arr = np.array(PIL.Image.open('1.jpg')) Then I modified part of the array: arr[0][0][0] = 128 and converted the array back to an image: img = PIL.Image.fromarray(np.uint8(arr)) im.save('2.jpg') Then, I converted the 2.jpg image into numpy array and checked value of arr: arr = np.array(PIL.Image.open('2.jpg')) print(arr) I am getting a completely different array than I got before. Why is this happening?
tagged with: python
has comment: http://stackoverflow.com/comment/81193954
possible better answer: http://stackoverflow.com/a/47122168
type: AnsweredQuestion
score: 4
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47122212
favorite count: 0

http://stackoverflow.com/q/47210115
has answer: http://stackoverflow.com/a/47224176
tagged with: list
has body: I am trying to build an NLTK corpus using information from Pubmed. In my first attempt, I successfully built a small function to retrieve the data using the Entrez package, got the retrieved article titles (a list of strings, i.e. the titles) into a corpus of files (each title as a new file) and created a corpus using each 'fileid' (i.e. the filename) as the category of the document. Now I have to step up the game: each document of the corpus needs to have a title, an abstract and the respective MeSH terms (these last need to define the categories of the corpus, instead of those being defined by the name of the document). So now I have a few problems that I don't really see how to resolve. I will start backwards, as it may be easier to understand: 1) My corpus reader goes as follows: corpus = CategorizedPlaintextCorpusReader(corpus_root, file_pattern, cat_pattern=r'(\w+)_.*\.txt') where 'cat_pattern' is a regular expression for extracting the category names from the fileids arguments, i.e. the names of the files. But now I need to get these categories from the MeSH terms within the file, which leads to the next problem: 2) the Pubmed query retrieves a batch of information, from where I first took only the titles (the ones that I would use to generate the corpus), but now I need to retrieve the titles, the abstract, and the MeSH terms. The pseudo-code would be something as follows: papers = [] 'Papers' is a list containing all the articles retrieved, as well as all the information related to the articles. Let's say I then have: out = [] for each in range(0, len(papers)): out.append(papers[each]['TI']) out.append(papers[each]['AB']) out.append(papers[each]['MH']) That last part of the list, the ['MH'] (the list of MeSH terms), is what I need to use to define the categories of the corpus. 3) After I build the corpus with these 3 pieces of information, to be able to use my classifier, I also need to somehow transform all this batch of information into this: # X: a list …
has comment: http://stackoverflow.com/comment/81379352
answer count: 1
linked to: http://stackoverflow.com/q/10463898
tagged with: nltk
has comment: http://stackoverflow.com/comment/81393944
type: AnsweredQuestion
score: 0
tagged with: python
has title: NLTK Corpus categories from lists
accepted answer: http://stackoverflow.com/a/47224176
tagged with: nlp
type: Question

http://stackoverflow.com/comment/81283086
type: Comment
comment on: http://stackoverflow.com/q/47164099
has text: And Should I do something more. Or this in the code example is enough?
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81293315
comment on: http://stackoverflow.com/a/47168321
has text: @corsiKa it doesn't work for that, actually. `add_century(6, 1964) = 1906`
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81283055
comment on: http://stackoverflow.com/a/47164899
score: 0
has text: This works !! But the result is displayed as coordinates according to your code. I just need the numerical value in the form of `'-387.7', '0.0', '0.0', '-1.0', '0.0', '0.0'`
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81337233
score: 0
type: Comment
has text: Hi,Jerry, does the object here mean instance or just class object ?
type: AnswerComment
comment on: http://stackoverflow.com/a/47193790

http://stackoverflow.com/comment/81267320
has text: Hmmm, `col2 = dataf['overall']` means get original column `overall` to `col2` variable. Do you need something else?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47152987

http://stackoverflow.com/a/47207325
type: Answer
answers question: http://stackoverflow.com/q/47206730
type: AcceptedAnswer
has body: def reverse_number(x): return x[::-1] try: number_of_sums = int(input()) for i in range(number_of_sums): s1 = input().split() if len(s1) &gt; 0: print(int(reverse_number(s1[0])) + int(reverse_number(s1[1]))) except ValueError: print("Invalid Input") Now, if you run the program and submit it will throw error stating "Invalid Input". Apart from adding the try block, also included the condition check for s1 as you might encounter an "Index out of range" error if not given proper input.
score: 0
accepted answer of: http://stackoverflow.com/q/47206730

curve-fitting
tags question: http://stackoverflow.com/q/47106576
tag name: curve-fitting
tags question: http://stackoverflow.com/q/47116977
tags question: http://stackoverflow.com/q/47148803
tags question: http://stackoverflow.com/q/47110254
tags question: http://stackoverflow.com/q/47085244
type: Tag

http://stackoverflow.com/q/47192887
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47192983
has title: Why do these two ways of doing an embedding lookup give a different answer?
has body: Suppose I have the following matrix: So, if I want to lookup the second row, I should get [3 4]. This is how I implemented the lookup mechanism using tensorflow operations: import tensorflow as tf import numpy as np from tensorflow.python.estimator.model_fn import EstimatorSpec def model_fn_1(features, labels, mode): x = tf.constant([[1]]) labels = tf.constant([[10.]]) with tf.name_scope('Embedding_Layer'): m = np.array([[1, 2], [3, 4]], np.float32) lookup = tf.nn.embedding_lookup(m, x, name='embedding_matrix_1') lookup = tf.Print(lookup, [lookup]) preds = tf.keras.layers.Dense(1)(lookup) loss = tf.reduce_mean(labels - preds) train_op = tf.train.GradientDescentOptimizer(0.01).minimize(loss, tf.train.get_global_step()) eval_metric_ops = {'accuracy': tf.metrics.accuracy(labels, preds)} return EstimatorSpec(mode=mode, loss=loss, train_op=train_op, eval_metric_ops=eval_metric_ops) model_1 = tf.estimator.Estimator(model_fn_1) model_1.train(input_fn=lambda: None, steps=1) As expected, the output from lookup while training is: 2017-11-08 21:17:49.010728: I C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\36\tensorflow\core\kernels\logging_ops.cc:79] [[[3 4]]] The problem is I do not get the same output when i try to implement the embedding lookup using Keras layers: import tensorflow as tf import numpy as np from tensorflow.python.estimator.model_fn import EstimatorSpec def model_fn(features, labels, mode): x = tf.constant([[1]]) labels = tf.constant([[10.]]) m = np.array([[1, 2], [3, 4]], np.float32) with tf.name_scope('Embedding_Layer'): n = tf.keras.layers.Embedding(2, 2, weights=[m], input_length=1, name='embedding_matrix_1', trainable=False) lookup = n(x) lookup = tf.Print(lookup, [lookup]) preds = tf.keras.layers.Dense(1)(lookup) loss = tf.reduce_mean(labels - preds) train_op = tf.train.GradientDescentOptimizer(0.01).minimize(loss, tf.train.get_global_step()) eval_metric_ops = {'accuracy': tf.metrics.accuracy(labels, preds)} return EstimatorSpec(mode=mode, loss=loss…
score: 2
has answer: http://stackoverflow.com/a/52566623
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/a/47098430
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47098270
has comment: http://stackoverflow.com/comment/81146627
has body: there are a few things that I see missing in the code provided but I think I can understand what you want to do. What I would like to tell you is to be sure to put proper columns names and index so you don't get confused and, as mentioned by @Paula Livingstone , I would also be sure that it is returning something. That said, the best way to do something like that is to use the isin function, for example: data = df[df[header[0]].isin(list[0])] Hope it helped.
downvote count: 0

http://stackoverflow.com/q/47176888
type: Question
has title: Pyspark: Is it required to pass additional modules as --py-files argument in a project
tagged with: pyspark
tagged with: project-structure
tagged with: python
has answer: http://stackoverflow.com/a/47177705
has body: I am creating a pyspark application which is modular in nature. My code struture is like: ├── main.py ├── src │ ├── __init__.py │ ├── jobs │ │ ├── __init__.py │ │ └── logic.py │ └── utils │ ├── __init__.py │ └── utility.py My start script is main.py which in turn call logic function in the logic.py file. I am running my project like spark-submit main.py My question is do i need to mention other .py files in the spark-submit command or they automaticlly get imported. I come accross a post which mention to zip the src folder and pass it as argument in --py-files. Which is the right way? Should i keep the current structure and run code from main.py like i do.? Is there any difference in these two ways? (logical and performance wise)
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47177612
answer count: 2
tagged with: apache-spark
possible better answer: http://stackoverflow.com/a/47177705
has answer: http://stackoverflow.com/a/47177612
tagged with: modular

http://stackoverflow.com/comment/81326953
score: 0
comment on: http://stackoverflow.com/q/47183033
has text: can you post your wsgi.py?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47211211
answers question: http://stackoverflow.com/q/47210861
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: Add button: self.button = QtWidgets.QPushButton(self) Subscribe to clicked event: self.button.clicked.connect(self.button_clicked) Add click handler: def button_clicked(self, *args): pixmap = QtGui.QPixmap(new_image_path) self.lbl.setPixmap(pixmap) new_image_path here is path to new image

http://stackoverflow.com/a/47087412
type: Answer
score: 1
answers question: http://stackoverflow.com/q/47087099
downvote count: 0
upvote count: 1
has body: You don't necessarily need pandas, though it is maybe faster. I don't know. I put the explanation in the code as comments: array = [1, 4, 5, 10, 20, 30, 40, 15, 17, 19, 2, 5, 3, 100, 200, 300, 400] def f(array): if len(array) == 1: return [array] # Special case for singleton array if len(array) == 2: return [[array[0]], [array[1]]] # Special case for pair results = [] index = 2 while index &lt; len(array): # This will look back by 2, so if the array is too small, apply special cases delta = array[index] - array[index - 1] # Difference between current and last element if delta == array[index - 1] - array[index - 2]: # If the three elements are all equal results.append(array[index - 2:index + 1]) # Append the group of the current three elements index += 1 # Go forward one while index &lt; len(array) and delta == array[index] - array[index - 1]: # Keep adding until the list is exhausted or the next element is no longer part of this group results[-1].append(array[index]) # Add the current element index += 1 else: # If the three elements don't have the same deltas results.append([array[index - 2]]) # Append the element and keep going index += 1 return results print(f(array)) You can try it online <a href="https://tio.run/##dVPBjtMwED3HXzESB1qRRU27CFHRAxISQhzhFvngjSeNta4dbIe2X1/GdsK2JXtwFI9f3rz3xunPobNmc7kI58QZdlBXJTyW8KGEalXCmtaG1iOtKtY@0vpE9YTYRFBCJVjCrThjEltoF4lxuWWFakGjGfew20G1BYdhcAbqVOTwBn722CihoREeobUOvDJ7jcEaSJgZmvULTeapV5yXI2ddcT7L2wvlWOHQDzr4aJgTtZF4ovc1K46d0gi58Pmq4Za4fnXKw1FpDdraZ3gSDT3OMQxvgeSFDrNYIFywFvxBaF2C6Ht9Bn@lxLOikKiDoKZZburI4eF6S7sqeviq2hYdmgbhCcMR0UAzOCoEEEaCFj4AajxQgXhJyEi9@5/snn/No7HvWXvoHOLE5AlJdsgs/h6EJuIptPfkB41c3DFt89s7arMkzi8JlHj3zg492NxkUn7bLNKP39P9oM@/2Tito3ASrMF4/NpkUgZzjufSjG5/IPYgpKQLBoMJSiddWlGKNDc8dWLwAamvSwcGT//ijQBjafxmj/EquZBtUTmZjDqnmOqHis9ElcOR8iaMl@ldx0Bb1B5fn5C05m2ATvzBdOrFAXMSfmZc9f3k78c0eYx5PseM9pYiYreKxj9u5Gasd8qExfS3Ly@Xvw" rel="nofollow noreferrer">here and that also makes reading comments easier since it's wide enough to f…

http://stackoverflow.com/comment/81171088
type: Comment
type: QuestionComment
has text: I saw those tutorials, but n0ne of them tell how to animate from importing data. More over, when I am reading data using data = np.loadtxt(filename), pythons makes an array, so it makes hard to plot.
comment on: http://stackoverflow.com/q/47110304
score: 0

http://stackoverflow.com/comment/81177674
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47113836
has text: Can one test if the number is a valid decimal and assign it to a variable in one step or will one have to run `num = float(s)` separately?

http://stackoverflow.com/q/47080561
tagged with: sockets
tagged with: .net
answer count: 1
has comment: http://stackoverflow.com/comment/81188683
downvote count: 0
upvote count: 1
has title: TCPClient "Only one usage of each socket address and linger option
favorite count: 0
tagged with: c#
tagged with: network-programming
has answer: http://stackoverflow.com/a/47081241
has comment: http://stackoverflow.com/comment/81120557
tagged with: python
has body: I have strange error in my app: "Only one usage of each socket" address.I saw many sockets in CLOSE_WAIT status in the tcpview. and I set linger timeout. but it doesn work. code below server: TcpListener listener = new TcpListener(IPAddress.Any, 7874); TcpClient client; listener.Start(); while (true) { client = listener.AcceptTcpClient(); ThreadPool.QueueUserWorkItem(ThreadProc, client); } private static void ThreadProc(object obj) { var client = (TcpClient)obj; client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 0)); var stream = client.GetStream(); using(client){ using (MemoryStream ms = new MemoryStream()) { int numBytesRead; byte[] data = new byte[1024]; try { while ((numBytesRead = stream.Read(data, 0, data.Length)) &gt; 0) { ms.Write(data, 0, numBytesRead); } }catch(Exception ex) {} var str = Encoding.ASCII.GetString(ms.ToArray(), 0, (int)ms.Length); } } } client: while (true) { try { using (TcpClient client = new TcpClient(obj.ToString(), 7874)) { client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 0)); var stream = client.GetStream(); { stream.Write(bytes, 0, bytes.Length); } Thread.Sleep(timeSleep); //just trying all possible close client.Client.Shutdown(SocketShutdown.Both); client.Client.Close(0); client.Close(); } }catch(Exception ex) { Console.WriteLine(ex); } } but python client work normally: while True: s = socket.socket( socket.AF_INET, socket.SOCK_STREAM) try: s.connect((addr, 7874)) l_onoff = 1 l_linger = 0 s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', l_onoff, l_linger)) s.send(b'test') while True: data =s.recv(1024) break except Exception as ex: print(str(datetime.datetime.now())+'NS FAIL') finally: s.close() looks like .NET tcpclient ignore set linger option. same result with: client.LingerState = new LingerOption(true, 0);
type: Question
type: UnansweredQuestion
score: 1

http://stackoverflow.com/q/47113670
type: AnsweredQuestion
tagged with: algorithm
score: 1
tagged with: count
tagged with: python
tagged with: global-variables
type: Question
accepted answer: http://stackoverflow.com/a/47119208
has title: Count work for Merge_Sort Algorithm
downvote count: 0
upvote count: 1
answer count: 1
tagged with: mergesort
has body: All, I would like to count how close an array is being sorted by using Merge Sort Algorithm. I am able to use Merge Sort to arrange the array but I have trouble to keep counting how many inversion I need during the process. For example, when input [9,4,8,3], I want to get the output [3,4,8,9] and 4 inversions. The definition of inversion is: if b in B , c in C and we have b>c then inversion is needed (the order of B,C matter). First, I will get two parts ([4,9],1) and ([3,8],1) which indicate one inversion individually. Then, when they merge again, there are another two inversions: choosing 3 instead of 4, choosing 8 instead of 9. My main question might not relate to the algorithm itself. It is about how to keep one of my variable evolve within function loop of a function. (I have using Merge_Sort function within Merge_Sort function) def Merge_Sort(a): n = len(a) if n==1: if not 'total_rev' in vars(): total_rev = 0 else: total_rev += rev_ind return a , total_rev else: m = math.floor(n/2) b , rev_ind_b = Merge_Sort(a[:m]) if not 'total_rev' in vars(): total_rev = 0 else: total_rev += rev_ind_b c , rev_ind_c = Merge_Sort(a[m:]) if not 'total_rev' in vars(): total_rev = 0 else: total_rev += rev_ind_c a_sort , rev_ind = Merge(b,c) if not 'total_rev' in vars(): total_rev = 0 total_rev += rev_ind else : total_rev += rev_ind return a_sort , total_rev def Merge(b,c): p = len(b) q = len(c) d = [] reverse_ind = 0 while len(b)!=0 or len(c)!=0 : if (len(b)*len(c) != 0) : b0 = b[0] c0 = c[0] if b0 &lt;= c0 : d.append(b0) b.remove(b[0]) else : reverse_ind += 1 d.append(c0) c.remove(c[0]) else : d.extend(b) b=[] d.extend(c) c=[] return d,reverse_ind The Merge function can work well. The only question is I cannot keep the variable "total_inv" update as I wish. I try to define "total_inv" whenever it is not defined. Not sure if it is a good way because it made my code messy. I also try to use global variable but it cannot work well. Thank you!
favorite count: 0
has answer: http://stackoverflow.com/a/47119208

http://stackoverflow.com/a/47107073
upvote count: 0
type: Answer
score: -1
has body: Used a factory approach with metaclasses, as such: class ObjectFactory: def __new__(cls, class_name, parents, attributes): attributes['__tablename__'] = class_name attributes['uid'] = Column(Integer, Sequence(class_name + '_id_seq'), primary_key=True) attributes['name'] = Column(String) class EntryFactory: def __new__(cls, class_name, parents, attributes): attributes['__tablename__'] = class_name attributes['uid'] = Column(Integer, Sequence(class_name + '_id_seq'), primary_key=True) attributes['foo'] = Column(Integer, ForeignKey('foo.uid'), nullable=False) attributes['entity_id'] = Column(Integer, ForeignKey(class_name[:-5]), nullable=False) class Thing(Base, metaclass=ObjectFactory): pass class ThingEntry(Base, metaclass=EntryFactory): pass class Quu(Base, metaclass=ObjectFactory): description = Column(String) class QuuEntry(Base, metaclass=EntryFactory): pass
downvote count: 1
answers question: http://stackoverflow.com/q/47106071

http://stackoverflow.com/comment/81184933
type: Comment
has text: An earlier version of my code used `value = [(rowIndex, colIndex, colData, recording_id)]`. Instead, remove the brackets, as above. (You might have to refresh your web page.) I think that should fix the error.
type: AnswerComment
comment on: http://stackoverflow.com/a/47117046
score: 0

http://stackoverflow.com/a/47066792
has body: Looks like the Ratings in iTunes are not stored in the ID3 tags of the MP3s. Look at the discussion here https://discussions.apple.com/thread/256205?start=0&amp;tstart=0 So there is no way Mutagen would be able to retrieve it.
answers question: http://stackoverflow.com/q/47065812
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/81081773

http://stackoverflow.com/comment/81189676
score: 0
comment on: http://stackoverflow.com/a/47119021
has text: A simple question. My database contains a column named as published_date but I want the header (Fieldname)to be as "Published Date". I tried and it is throwing an error.Is it possible to get the desired header?
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81104281
score: 0
has text: def opt(x0): bd0 = (0,100) bd1 = (0,0.100) bd2 = (2,8) bnds = (bd0, bd1, bd2) minimizer_kwargs = {"method":"Nelder-Mead", "bounds":bnds} res = basinhopping(rmse, x0, minimizer_kwargs=minimizer_kwargs,T=1.0, stepsize=1.0, niter=10) print(res.x) return res.x # go. def main(): x0 = ([50.0, 0.50, 5.0]) # initial guess opt(x0) if __name__ == "__main__": main()
type: Comment
comment on: http://stackoverflow.com/q/47072143
type: QuestionComment

http://stackoverflow.com/comment/81248298
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47148989
has text: @0TT0 its a csv

http://stackoverflow.com/a/47084917
type: Answer
has body: You can traverse relationships with the double underscore: queryset = A.objects.prefetch_related('aa','aa__bb').all() It becomes clearer without using related names: class A(models.Model): name = models.CharField() class B(models.Model): a = models.ForeignKey(A) name = models.CharField() class C(models.Model): b = models.ForeignKey(B) name = models.CharField() A.prefetch_related('b_set','b_set__c_set').all() Example from the documentation: &gt;&gt;&gt; Restaurant.objects.prefetch_related('pizzas__toppings') Where Pizza has a Many-to-Many relationship with Toppings.
answers question: http://stackoverflow.com/q/47084818
accepted answer of: http://stackoverflow.com/q/47084818
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2

http://stackoverflow.com/comment/81303651
has text: Sorry, I had not meant to leave that additional `pack` in there.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47176891

celery
tags question: http://stackoverflow.com/q/47178187
tags question: http://stackoverflow.com/q/47173574
tags question: http://stackoverflow.com/q/47075629
tags question: http://stackoverflow.com/q/47162217
tags question: http://stackoverflow.com/q/47094751
type: Tag
tags question: http://stackoverflow.com/q/47188219
tags question: http://stackoverflow.com/q/47106592
tags question: http://stackoverflow.com/q/47100339
tags question: http://stackoverflow.com/q/47178983
tags question: http://stackoverflow.com/q/47212737
tag name: celery
tags question: http://stackoverflow.com/q/47100781
tags question: http://stackoverflow.com/q/47137592
tags question: http://stackoverflow.com/q/47151975
tags question: http://stackoverflow.com/q/47141842
tags question: http://stackoverflow.com/q/47073276
tags question: http://stackoverflow.com/q/47161489

http://stackoverflow.com/q/47165343
has title: New and stuck on IndentationError: expected an indented block
tagged with: error-handling
has answer: http://stackoverflow.com/a/47165486
favorite count: 0
tagged with: python-3.x
downvote count: 4
has body: I'm new to Python and Programming in general. I'm trying to get a head start for College come Summer Term. I'm trying to learn from this beginner's book and it cites the following code exactly as I'm putting it... I tried changing the space indent every which way but I still get this message. I understand I'm probably missing something here but I would appreciate the advice as to how I should proceed. Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] &gt;&gt;&gt; # Ghost Game ... from random import randint &gt;&gt;&gt; print('Ghost Game') Ghost Game &gt;&gt;&gt; feeling_brave = True &gt;&gt;&gt; score = 0 &gt;&gt;&gt; while feeling_brave: ... ghost_door = randint(1, 3) File "&lt;stdin&gt;", line 2 ghost_door = randint(1, 3) ^ IndentationError: expected an indented block &gt;&gt;&gt; ghost_door= randint(1, 3) &gt;&gt;&gt; while feeling_brave: ... ghost_door= randint(1, 3) File "&lt;stdin&gt;", line 2 ghost_door= randint(1, 3) ^ IndentationError: expected an indented block &gt;&gt;&gt; while feeling_brave: ... ghost_door = randint(1, 3) File "&lt;stdin&gt;", line 2 ghost_door = randint(1, 3) ^ IndentationError: expected an indented block &gt;&gt;&gt; while feeling_brave: ... ghost_door = randint(1,3) File "&lt;stdin&gt;", line 2 ghost_door = randint(1,3) ^ IndentationError: expected an indented block &gt;&gt;&gt; while feeling_brave: ... ghost_door =randint(1,3) File "&lt;stdin&gt;", line 2 ghost_door =randint(1,3)
answer count: 2
has answer: http://stackoverflow.com/a/47165403
upvote count: 1
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81280811
has comment: http://stackoverflow.com/comment/81280367
score: -3
duplicate of: http://stackoverflow.com/q/45621722
type: Question
has comment: http://stackoverflow.com/comment/81280372
has comment: http://stackoverflow.com/comment/81280617
tagged with: indentation
has comment: http://stackoverflow.com/comment/81280544

http://stackoverflow.com/comment/81123180
comment on: http://stackoverflow.com/q/47086721
has text: Probably a `\n` character problem: try `grades4 = assignment_list[7].strip()`
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/47149685
tagged with: python
has title: AttributeError: 'Point' object has no attribute 'point'
has body: I am transforming a point from source frame to target frame using tf2. Below is the code snippet: import tf2_ros import tf2_geometry_msgs transform = tf_buffer.lookup_transform(target_frame, source_frame, rospy.Time(0), rospy.Duration(1.0)) pose_transformed = tf2_geometry_msgs.do_transform_point(point_wrt_kinect, transform) print pose_transformed The code throws following error: Traceback (most recent call last): File "q1.py", line 29, in &lt;module&gt; pose_transformed = tf2_geometry_msgs.do_transform_point(point_wrt_kinect, transform) File "/opt/ros/indigo/lib/python2.7/dist-packages/tf2_geometry_msgs/tf2_geometry_msgs.py", line 59, in do_transform_point p = transform_to_kdl(transform) * PyKDL.Vector(point.point.x, point.point.y, point.point.z) AttributeError: 'Point' object has no attribute 'point' The tf_geometry_msgs.py can be seen online at here. This seems silly as they are calling point.point.x. Which point are they talking about? I believe it should be geometry_msgs/Point, which I declared in the following way: from geometry_msgs.msg import Point point_wrt_kinect = Point() point_wrt_kinect.x = -0.41 point_wrt_kinect.y = -0.13 point_wrt_kinect.z = 0.77 Any workaround, please?
type: AnsweredQuestion
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/47151099
favorite count: 0
type: Question
downvote count: 0
tagged with: ros
answer count: 1
accepted answer: http://stackoverflow.com/a/47151099

http://stackoverflow.com/comment/81284281
comment on: http://stackoverflow.com/a/47122732
score: 0
has text: Ok and what is the actual model location?
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47221292
downvote count: 0
favorite count: 0
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/47221780
has title: How do you get the indices of a Numpy slice with a step?
upvote count: 2
accepted answer: http://stackoverflow.com/a/47221371
tagged with: python
has answer: http://stackoverflow.com/a/47221371
score: 2
type: AnsweredQuestion
has body: Original Question (with stupid example): e.g my question is simple, how do you get the index positions of a slice with step, in Numpy. See example below where you can use np.nonzero on a slice but include a step and you don't. Is there another option import numpy as np d = np.hstack([np.arange(6), np.arange(6), np.arange(6)]) step = 6 np.nonzero(d[0:-1]) Out[45]: (array([ 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 15, 16]),) In [46]: np.nonzero(d[0:-1:step]) Out[46]: (array([], dtype=int64),) ` Question I should have asked. How do you get the indices of a slice with a step in Numpy. e.g import numpy as np d = np.hstack([np.arange(6), np.arange(6), np.arange(6)]) step = 6 #The indices of d[0:-1:step] would be: array([ 0, 6, 12])
has comment: http://stackoverflow.com/comment/81392162
answer count: 2
has answer: http://stackoverflow.com/a/47221780

http://stackoverflow.com/comment/81203029
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47126350
has text: It should but its bugging out and I want to know why
type: Comment

http://stackoverflow.com/comment/81509123
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47212210
type: AnswerComment
has text: You are setting a local variable Final_total to a list that contains the helper object. Which is not correct. --> Can you explain why this is not correct? Would be helpful and appreciated. I am obviously getting it wrong because I don't know what the correct answer is

http://stackoverflow.com/comment/81150259
comment on: http://stackoverflow.com/a/47096423
type: Comment
type: AnswerComment
score: 0
has text: @jezrael Now my other transformation function not working. `A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead`

http://stackoverflow.com/q/47096258
has comment: http://stackoverflow.com/comment/104763689
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/52283320
has body: I have following Visual Basic code that runs code from a frozen Python module: Sub CVpptx() RunFrozenPython ("C:\Users\admin\Desktop\drect\dist\drect\drect.exe") End Sub The Python code: import xlwings as xw from xlwings import Range from openpyxl import load_workbook from pptx import Presentation from pptx.shapes.autoshape import Shape from pptx.util import Inches, Pt from pptx.dml.color import ColorFormat, RGBColor from pptx.enum.shapes import MSO_SHAPE import matplotlib.pyplot as plt from math import pi from io import StringIO from shutil import copyfileobj import datetime import subprocess import sys, os import tkinter.filedialog as fdialog import tkinter.messagebox as msgbox import tkinter if getattr(sys, 'frozen', False): main_path = sys.executable else: main_path = __file__[0:__file__.rfind("\\")] asset_path = main_path + "\\assets\\" def add_text_box(slide,left, top, width, height): l = Inches(left) t = Inches(top) w = Inches (width) h = Inches (height) txBox = slide.shapes.add_textbox(l, t, w, h) return txBox def add_image(photo_path,slide,left, top, width, height): l = Inches(left) t = Inches(top) w = Inches (width) h = Inches (height) pic = slide.shapes.add_picture(photo_path, l, t, width=w, height=h) return pic def add_text(text,textbox): tf = textbox.text_frame tf.text = text def add_slide(prs,type=6, logo=True): slide_layout = prs.slide_layouts[type] new_slide = prs.slides.add_slide(slide_layout) if (logo): add_logo(new_slide) return new_slide def set_design(sp): fill = sp.fill fill.solid() fill.fore_color.rgb = RGBColor(0x01, 0x23, 0x45) fill.fore_color.theme_color = MSO_THEME_COLOR.ACCENT_1 fill.fore_color.brightness = 0.25 fill.transparency = 0.25 sp.fill = None fill.background() def add_shape(s,left, top, width, height): shapes = s.shapes l = Inches(left) t = Inches(top) w = Inches(width) h = Inches(height) shape = shapes.add_shape(MSO_SHAPE.ROUNDED_RECTANGLE, l, t, w, h) return shape def personal_slide(prs,photo_path): s = add_slide(prs) add_image…
type: UnansweredQuestion
tagged with: python
has title: Xlwings, run frozen Python
tagged with: xlwings
score: 0

http://stackoverflow.com/comment/81159927
type: AnswerComment
comment on: http://stackoverflow.com/a/47104519
has text: @NoahHuntington that's the part of the answer below the line
type: Comment
score: 0

http://stackoverflow.com/a/47103189
accepted answer of: http://stackoverflow.com/q/47102538
score: 0
has body: it is nearly the same. Most fortran intrinsics operate component-wise on arrays ( assuming you have at least fortran95 ) real a(2,4),b(4) a=reshape([.1,.2,.3,.4,.5,.6,.7,.8],shape(a)) b=sum(min(1-a,a)**2,1) write(*,'(4f5.2)')b end 0.05 0.25 0.41 0.13 note fortran's sum would by default sum the whole array.
answers question: http://stackoverflow.com/q/47102538
type: Answer
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81174571

http://stackoverflow.com/comment/81198758
type: Comment
score: 0
type: AnswerComment
has text: Sorry, my last comment wasn't clear. See my [answer to your question here](https://stackoverflow.com/a/47118758/4909087) on how to spruce this code, you can do this in a single line.
comment on: http://stackoverflow.com/a/47118698

http://stackoverflow.com/a/47170064
type: Answer
has comment: http://stackoverflow.com/comment/81289962
has comment: http://stackoverflow.com/comment/81289987
accepted answer of: http://stackoverflow.com/q/47169971
has comment: http://stackoverflow.com/comment/81290801
has body: As James already said, no you cannot continue an if statement outside of a function. Referring to your question if functions are useful in a larger program: yes they are. You can use data generated in functions in your main program or other functions by returning your results. For instance: def you (): gi=input("what up") return gi result = you() if result in ["Nothing much", "nothing much", "nothing"]: print("cool") elif result in ["stuff"]: print("sounds good")
has comment: http://stackoverflow.com/comment/81290701
answers question: http://stackoverflow.com/q/47169971
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81290829
has comment: http://stackoverflow.com/comment/81289929

kivy
tags question: http://stackoverflow.com/q/47086718
tags question: http://stackoverflow.com/q/47106357
tags question: http://stackoverflow.com/q/47107118
tags question: http://stackoverflow.com/q/47128196
type: Tag
tags question: http://stackoverflow.com/q/47188642
tags question: http://stackoverflow.com/q/47203069
tag name: kivy
tags question: http://stackoverflow.com/q/47163600
tags question: http://stackoverflow.com/q/47176777
tags question: http://stackoverflow.com/q/47083402
tags question: http://stackoverflow.com/q/47180782
tags question: http://stackoverflow.com/q/47111074
tags question: http://stackoverflow.com/q/47158882
tags question: http://stackoverflow.com/q/47109012
tags question: http://stackoverflow.com/q/47212144
tags question: http://stackoverflow.com/q/47085937
tags question: http://stackoverflow.com/q/47176947
tags question: http://stackoverflow.com/q/47138263
tags question: http://stackoverflow.com/q/47112878
tags question: http://stackoverflow.com/q/47205538
tags question: http://stackoverflow.com/q/47168094

http://stackoverflow.com/q/47117867
has comment: http://stackoverflow.com/comment/81185749
linked to: http://stackoverflow.com/q/36785417
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47117902
downvote count: 1
type: AnsweredQuestion
has body: I want to change the ADD python Magic Method (I mean, __add__) for add two numbers (Code 1). When I run the code, the output is equal to RecursionError: maximum recursion depth exceeded while calling a Python object in Pycharm IDE. But after changing the code (Code 2), then the new code worked properly. Why does the Code 1 not work? Code 1 (Wrong): class Number(int): def __add__(self, other): return self + other print(Number(5) + 3) Code 2 (Correct): class Number(int): def __add__(self, other): return self - (-other) print(Number(5) + 3)
score: 0
has title: Why __add__ magic method does not work?
accepted answer: http://stackoverflow.com/a/47117902
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/81185756
type: Question
duplicate of: http://stackoverflow.com/q/36785417

http://stackoverflow.com/q/47179297
has body: I have a number of projects that use the following configuration model: settings.py includes default configuration and config specifications, mainly used for development purposes. The default settings (including db settings) can be overridden by external configuration files, usually defined by admins for the various environments they manage. In order to ease the admins, I have written a management command and packaged separately, which adds the option to create example configuration files based on the default configuration in settings.py Trying to run the command without the possibility for successful db connection, however, raises django.db.utils.OperationalError. How can I make the command work without db connection, as it does not need one and normally when the command is needed, most probably the db connection is not configured properly. settings.DATABASES != {} as there are the default db settings. Django 1.10.6, Python 3.5.3
type: AnsweredQuestion
upvote count: 3
tagged with: django-management-command
downvote count: 0
has title: Django management command without working db connection
answer count: 1
favorite count: 0
type: Question
score: 3
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81307837
has answer: http://stackoverflow.com/a/47180454
has comment: http://stackoverflow.com/comment/81309024
accepted answer: http://stackoverflow.com/a/47180454

http://stackoverflow.com/q/47217479
tagged with: python
tagged with: visualization
has title: Creating Chart in Excel using python
tagged with: pandas
answer count: 0
score: 1
downvote count: 0
upvote count: 1
tagged with: excel
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I am doing some analysis using basic sorting and cumulative functions. I need to create a scatter plot in the excel using the data that I have created in sheet2. I am using the Worksheet , add_chart , add_series , insert_chart functions. But unable to create the chart in the same sheet. Code as below : # -*- coding: utf-8 -*- """ Created on Tue Nov 07 15:25:03 2017 @author: Harsh """ import numpy as np import pandas as pd import xlsxwriter from pandas import ExcelWriter from pandas import ExcelFile #Define variables for storing file names and sheet names input_file_path="C:\Users\paha7003\Documents\Adhoc Work\Training\python_work\OUT_Base_Sannap_1010.xls"; sheet_name = "Sheet1" output_file_path="C:\Users\paha7003\Documents\Adhoc Work\Training\python_work\Pareto_Sannap_1010.xlsx"; #Read data from file full_data = pd.read_excel(input_file_path, sheet_name) #Pareto will be run on category, hence change the variable name only_category = full_data.loc[full_data['PrdLevel_Name'] == 'CATEGORY_NAME'] #sort based on VAL catg_sorted = only_category.sort('VAL', ascending = [0]) #Cummilative sum , percenetage and ctg_rank binning catg_sorted['cum_sum'] = catg_sorted.SALVAL.cumsum() catg_sorted['cum_perc'] = 100*catg_sorted.cum_sum/catg_sorted.SALVAL.sum() bins = [0, 5, 10,15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100] labels = [5, 10,15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100] catg_sorted['ctg_rank'] = pd.cut(catg_sorted['cum_perc'], bins=bins, labels=labels) #Merge the CTG ranks calculated on the cateogry to other level in the out file final = pd.merge(full_data , catg_sorted, how = 'inner' , on='STORECODE' ) pivot = pd.pivot_table(final, values=['WDVAL_x' , 'PROJN_x'], index=['ctg_rank'], aggfunc=np.sum) pivot['cum_sum_wdval'] = pivot.WDVAL_x.cumsum() pivot['cum_sum_projn'] = pivot.PROJN_x.cumsum() pivot['cum_perc_wdval'] = 100*pivot.cum_sum_wdval/pivot.WDVAL_x.sum() pivot['cum_perc_projn'] = 100*pivot.cum_sum_projn/pivot…

http://stackoverflow.com/q/47092567
upvote count: 1
has body: I want to fill missing values of a specific column only if a condition is met. e.g. A B Nan 0 Nan 0 0 0 Nan 1 Nan 1 ..................... ..................... In the above case I want to fill Nan values in column A only when corresponding value in column B is 0. Rest values in A (with Nan) should not change.
has answer: http://stackoverflow.com/a/47092633
favorite count: 0
type: Question
score: -2
tagged with: missing-data
tagged with: python
possible better answer: http://stackoverflow.com/a/47094136
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47094136
answer count: 3
has title: Fill few missing values in python
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47092633
downvote count: 3
has answer: http://stackoverflow.com/a/47092715

http://stackoverflow.com/comment/81243874
comment on: http://stackoverflow.com/a/47146792
has text: The OP also has `qux` and `baz` as keys
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47111946
has body: I am facing a strange problem with graphene and Django. The documentation seems to lack a solution and I couldn't figure out what I'm doing wrong. I have the following models: Class Sentence(models.Model): ref = models.CharField(max_length=30, primary_key=True) body = models.TextField(default=None) Class Summary(models.Model): sentence = models.ForeignKey(Sentence, on_delete=models.CASCADE) text = models.TextField(default=None) (Each sentence can have multiple summaries) And the following schema: Class SentenceType(DjangoObjectType): class Meta: model = models.Sentence filter_fields = {"ref": ["exact"]} interfaces = (graphene.Node, ) Class SummaryType(DjangoObjectType): class Meta: model = models.Summary filter_field = {"text": ["icontains"]} interfaces = (graphene.Node, ) Class Query(graphene.ObjectType): all_sentences = DjangoFilterConnectionField(SentenceType) sentence = graphene.Field(SentenceType, ref=graphene.string(), body=graphene.string()) all_summary = all_provvedimenti = DjangoFilterConnectionField(SummaryType) summary = graphene.field(SummaryType, id=graphene.Int(), text=graphene.string()) def resolve_all_summaries(self, context, **kwargs): return models.Summary.objects.all() It can occur that there is one or more summaries in my database with no corresponding sentence. Now, when I query { allSummaries{ edges{ node{ text sentence{ ref } } } } } If the the sentence exists for the summary, no problem at all. But if there is no corresponding sentence I get: "errors": [ { "message": "Sentence matching query does not exist.", "locations": [ { "line": 6, "column": 9 } ] } ], ..., ..., "data":[ ..., { "node": null }, { "node":{ "text": "blah blah blah sentence summary" "sentence": { "ref": "sentence_reference" } } } { "node": null }, ..., ] Naturally, the output I would expect is that whenever a corresponding sentence does not exist for a summary node it would still give me back the text of the summary and "sentence": null or []. I had no luck in the documentat…
has comment: http://stackoverflow.com/comment/81198071
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has title: Graphene-django returns null node instead of just node field
has answer: http://stackoverflow.com/a/51776743
tagged with: graphene-python
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81184702
tagged with: django
tagged with: django-models
tagged with: python

http://stackoverflow.com/q/47083648
has answer: http://stackoverflow.com/a/47084579
score: 2
type: AnsweredQuestion
has body: I want to save a matplotlib figure as a png file with a width/height ratio of 1.25. I specified this ratio via the figsize argument. But when I save the figure using the option bbox_inches = "tight" then the output png has a size of 553 to 396 pixels which is a ratio of 1.39. I would like to keep the bbox_inches = "tight" option to prevent unnecessary white space in the figure borders. I tried different approaches suggested in similar posts on stackoverflow but couldn't figure out a solution. Here is example code: import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize = (3, 2.4), dpi = 150) ax = plt.subplot(111) for i in range(3): ax.plot(np.random.random(10), np.random.random(10), "o", label = i) ax.legend(bbox_to_anchor=(1, 0.6), title = "Title") plt.ylabel("Label") plt.xlabel("Label") plt.title("Title", loc = "left") plt.savefig("test.png", format = "png", dpi = 150, bbox_inches = "tight") This is the output png
tagged with: matplotlib
answer count: 1
has title: Save matplotlib plot with legend on the right in predefined width/height ratio
linked to: http://stackoverflow.com/q/42994338
favorite count: 0
type: Question
upvote count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/4700614
tagged with: python
accepted answer: http://stackoverflow.com/a/47084579

http://stackoverflow.com/comment/81105433
score: 3
comment on: http://stackoverflow.com/q/47077829
type: Comment
type: QuestionComment
has text: this command should install requests for you, just make sure the root folder is specified properly: `pip install requests -t PATH_TO_ROOT_FOLDER`

http://stackoverflow.com/comment/81304761
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47177256
has text: @priyanshagrawal what is output of `which python` ? is it also pointing to python2.7 ?
score: 0

http://stackoverflow.com/comment/81368357
score: 1
type: Comment
has text: @DanMašek absolutely correct. I tried keeping his code structure, but as I mentioned in my edit there is already an openCV function which does just that
type: AnswerComment
comment on: http://stackoverflow.com/a/47207589

http://stackoverflow.com/a/47285577
score: 0
has comment: http://stackoverflow.com/comment/81523037
has comment: http://stackoverflow.com/comment/81528297
has comment: http://stackoverflow.com/comment/81555792
answers question: http://stackoverflow.com/q/47217297
type: Answer
has body: Filter messages sent by request.user, order by receiver_id and -created_at then use distinct on receiver_id Message.objects.filter(sender=request.user).order_by('receiver_id','-created_at').distinct('receiver_id')

http://stackoverflow.com/q/47158220
possible better answer: http://stackoverflow.com/a/47166926
accepted answer: http://stackoverflow.com/a/47158770
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47166926
downvote count: 0
has comment: http://stackoverflow.com/comment/81266887
upvote count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81266889
has answer: http://stackoverflow.com/a/47158770
type: Question
answer count: 2
has body: I am trying to implement a system where outputs from an Arduino can be passed on to and printed in Python. I have the following Arduino code snippet below: void loop() { if (Serial.available()) { c = Serial.read(); if (c == '1') { digitalWrite(pinLED1, HIGH); digitalWrite(pinLED2, LOW); //Serial.print("1 ON, 2 OFF\n"); } My Python code snippet is as follow: import serial import time arduino = serial.Serial('COM3', 9600, timeout=1) msg = arduino.readline(arduino.inWaiting()) # read everything in the input buffer time.sleep(3) ASCIIdata = '121210' for i in range(len(ASCIIdata)): if ASCIIdata[i] == '1': strin = '1' arduino.write(strin.encode()) time.sleep(0.2) #print(ASCIIdata[i]) try: print ("Message from arduino: ") print arduino.readline() raise except Exception as e: print ("Fail to send!") In the above example, I am trying to send inputs to Arduino via ASCIIdata, and when it matches the if-statement in Arduino, commands in the if-statement will be executed. I have purposely not do a print in Arduino and attempt to read something from Python by doing: try: print ("Message from arduino: ") print arduino.readline() raise except: print ("Fail to send!") I observed that if I do not put raise in the try statement, the except statement will not be executed, but the program moves on after the specific timeout. Hence, I put raise in the try statement. May I ask if this is the correct approach to raising an exception? I read that I should be doing except Exception as e instead of doing except because I would be catching all kinds of exception while the program is running. May I ask if this thought process is correct?
has title: Handling Exceptions in Arduino-Python Communications
tagged with: arduino
tagged with: python
has comment: http://stackoverflow.com/comment/81266351

http://stackoverflow.com/a/47111912
accepted answer of: http://stackoverflow.com/q/47111779
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47111779
has body: In python, when testing multiple conditions in the same block, you use if for the first condition, elif for other conditional statements after that, and then else. The code block under else runs only if the other conditions were False. The problem with your code is that you use all if statements where you should use elif. The reason your first code goes to the else statement is because your last if statement runs no matter what the result of the first if statement was. if navigation_eingabe == 1: met1() elif navigation_eingabe == 2: pass put the rest of your elif statements, and end with the else statement, so it will print if none of the other conditions are true: else: print('Pls only give integer numbers.') However, this code does not do what you think it does. You are using the else statement for exception handling. This does not work. What you need is a try-except statement: try: navigation_eingabe = int(input()) if navigation_eingabe == 1: met1() elif navigation_eingabe == 2: pass elif navigation_eingabe == 3: pass elif navigation_eingabe == 4: pass elif navigation_eingabe == 5: pass elif navigation_eingabe == 6: pass else: print('not a number 1-6') except ValueError: #the type of error if you try to convert a non-integer string to an int. print('Pls only give integer numbers.') This will check each condition and catch the error if an invalid string is passed to the input.
type: AcceptedAnswer

http://stackoverflow.com/q/47216224
score: 0
answer count: 1
upvote count: 1
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/47216574
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47216574
has title: Selecting n_estimators based on dataset size for adaboostclassifier
tagged with: python
has body: I'm trying to train and a predict a model using the code below on a dataset with around 300 records and 100 features. I'm wondering if the choices of n_estimators that I'm searching below in the code are too high? Since I've only got 300 records would it make more sense to try something like [10, 20, 30] for n_estimators? Is n_estimators related to dataset size for training data? How about the learning rate? Code: from sklearn.grid_search import GridSearchCV from sklearn.metrics import accuracy_score, make_scorer from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier # TODO: Initialize the classifier clf = AdaBoostClassifier(random_state=0) # TODO: Create the parameters list you wish to tune parameters = {'n_estimators':[100,200,300],'learning_rate':[1.0,2.0,4.0]} # TODO: Make an fbeta_score scoring object scorer = make_scorer(accuracy_score) # TODO: Perform grid search on the classifier using 'scorer' as the scoring method grid_obj = GridSearchCV(clf,parameters,scoring=scorer) # TODO: Fit the grid search object to the training data and find the optimal parameters grid_fit = grid_obj.fit(X_train,y_train) # Get the estimator best_clf = grid_fit.best_estimator_ # Make predictions using the unoptimized and model predictions = (clf.fit(X_train, y_train)).predict(X_test) best_predictions = best_clf.predict(X_test)
type: Question

global
type: Tag
tags question: http://stackoverflow.com/q/47179133
tag name: global

http://stackoverflow.com/q/47186148
tagged with: python
tagged with: dictionary
answer count: 4
type: Question
has title: How to get keys and values from a dictionary within a list within a dictionary
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/47186332
has body: I would like to get the values from a list within a dictionary. I get the following json data structure when I make an Oanda REST-API request. When I use the get function I can access the dict and the keys and its values from "trades" and "lastTransactionID", but do not know how to get the list items which are in the "trades" key. I would really appreciate if you could help me to get this running Works print rv.get("trades") Does not work print rv.get("trades").get("financing") { "trades": [ { "financing": "0.0000", "openTime": "2017-11-08T17:21:49.533679739Z", "price": "1.15901", "unrealizedPL": "-0.0001", "realizedPL": "0.0000", "instrument": "EUR_USD", "state": "OPEN", "initialUnits": "1", "currentUnits": "1", "id": "2046" }, { "financing": "0.0000", "openTime": "2017-11-08T17:19:27.343697147Z", "price": "1.15905", "unrealizedPL": "-0.0001", "realizedPL": "0.0000", "instrument": "EUR_USD", "state": "OPEN", "initialUnits": "1", "currentUnits": "1", "id": "2044" } ], "lastTransactionID": "2046" } Thanks for your help and kind regards
favorite count: 0
has answer: http://stackoverflow.com/a/47186188
has answer: http://stackoverflow.com/a/47186233
tagged with: list
has answer: http://stackoverflow.com/a/47186235
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/81209787
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47127233
has text: Maybe I didn't under the question properly, I was thinking if you have a 4x4 box and letters are 6X5 the dimension would not allow at the text to show. So I am now assuming the @bibek wants the widget to follow the size of the text.
score: 0

http://stackoverflow.com/comment/81209632
score: 1
has text: you can not print each step of reversing when you are using slicing `input_string[::-1]` you need to make own function and add print statements on every desired step
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47129866

http://stackoverflow.com/q/47071771
upvote count: 1
tagged with: php
tagged with: python-requests
has comment: http://stackoverflow.com/comment/81092315
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81092063
has answer: http://stackoverflow.com/a/47088803
has comment: http://stackoverflow.com/comment/81092251
score: 1
has comment: http://stackoverflow.com/comment/81092363
has answer: http://stackoverflow.com/a/64469779
possible better answer: http://stackoverflow.com/a/64469779
tagged with: python
has body: I've been facing a few problems trying to convert the following PHP curl queries to Python requests. Given PHP Code $cfile = new CURLFile($filePath,$fileType,$filename); $request='{"signers":["abc@xyz.com"],"expire_in_days":10, "display_on_page":"all"}'; $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPHEADER, array('authorization: Basic Base64encode(client_id:client_secret)')); $post = array('file'=&gt;$cfile,'request' =&gt;$request); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_POST,1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); $res = curl_exec($ch) My version of Python code request_data = {} request_data['signers'] = ['abc@xyz.com'] request_data['expire_in_days'] = 10 request_data['display_on_page'] = 'all' temp_file_path = 'PdfTest.pdf' files = {'file': open(temp_file_path, 'rb')} headers = {} headers['content-type'] = "multipart/form-data" headers['authorization'] = 'Basic '+auth # auth contains b64 client:secret r = requests.post(url, files=files, data={'request': request_data}, headers=headers) Considering my request URLs are the same and so is the base 64 value for authorization. The PHP code returns the right response from the server but the Python one strangely says provides a response telling "code":"UNSUPPORTED_MEDIA_TYPE"
favorite count: 0
tagged with: curl
has title: Converting PHP Curl queries to Python requests
type: Question
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47088803

http://stackoverflow.com/comment/81154325
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47102104
type: QuestionComment
has text: I know that Kafka is message queue system. I have 2 source data - one is csv and another is api. I want to have Kafka as a messaging queue to get data from both these sources @DanielRoseman

http://stackoverflow.com/comment/81284388
type: AnswerComment
comment on: http://stackoverflow.com/a/47158826
score: 0
type: Comment
has text: Using this gives me: `C:\Users*Insert name here*\Downloads\Ross-1.1.0>Python\python.exe -m virtualenv venv FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\*Insert name here*\\Downloads\\Ross-1.1.0\\venv\\python36.zip\\site.py' `

http://stackoverflow.com/q/47184170
favorite count: 0
type: Question
has title: pandas dataframe: Changing from single index to multi-column index
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/11976503
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/47191721
accepted answer: http://stackoverflow.com/a/47184397
score: 1
possible better answer: http://stackoverflow.com/a/47185205
downvote count: 0
has answer: http://stackoverflow.com/a/47184397
upvote count: 1
has body: In python pandas I have a dataframe df_aaa: date data otherdata symbol 2015/1/1 11 12 aaa 2015/2/1 21 22 aaa 2015/3/1 31 31 aaa df_all: 2015/1/1 31 31 bbb Currently the index of both is by date . I want to append df_aaa to df_all, and have them with a composite index of both symbol and date. How do I do that? Basically the following are all one question: How do I set a multi-index and use it when appending. Can I do it with different column order? Do I need to refresh? Etc.: I'm not sure if a multi-index is an index that has multiple 'columns' (or rows), or is it the ability to have more than one index (and any of them could be for multiple columns or rows). Or are both correct? Must I first set the index of both dataframes to a multi-index, so the append will work? (otherwise I'll have duplicates for different symbols Do I have to "drop" the existing index before creating the new one? Is there such a thing as a dataframe with data but no index? Must a (single) index be of unique values? When do I use which of the following dataframe methods: set_index(), reindex(), reset_index(), set_level, reset_level? And what is the default when I give these methods an array. Python docs are daunting, and I can't find my hands or legs in them. Giving some good examples would help... Do I have to add anything (like axis=1) when setting the index? How do I set the index to be the data in a column. (And why does sometimes using ['symbol', 'date'] as a parameter, give me a new column with those two values, instead of setting the index on the existing values of the columns with those two names?) After I append and assuming the old index is correct do I need to 'update' the index (perhaps using reindex?) or since I told the dataframe that the index is in a certain column, is my data correctly indexed? And since my dataframes (will) have indices on the same column name, can I do an append of df_aaa on df_all even if df_all was defined to have the columns originally in a different order…
has answer: http://stackoverflow.com/a/47185205

http://stackoverflow.com/a/47147181
type: Answer
has comment: http://stackoverflow.com/comment/81244857
has body: You're missing the self as a parameter in getInputs. It should be def getInputs(self) and then you can call it with cball. Edit: the above suggestion would make cball.getInputs() work. But as mentioned in the comment, the other solution would be to move getInputs() out from the Projectile class, in which case you would not pass 'self' as parameter.
answers question: http://stackoverflow.com/q/47147133
has comment: http://stackoverflow.com/comment/81244683
score: 0
has comment: http://stackoverflow.com/comment/81244794
has comment: http://stackoverflow.com/comment/81244897

http://stackoverflow.com/q/47196133
tagged with: python
has answer: http://stackoverflow.com/a/47199983
has comment: http://stackoverflow.com/comment/81343768
type: Question
has comment: http://stackoverflow.com/comment/81348419
tagged with: numpy
has comment: http://stackoverflow.com/comment/81341035
answer count: 2
has comment: http://stackoverflow.com/comment/81341112
possible better answer: http://stackoverflow.com/a/47199556
has comment: http://stackoverflow.com/comment/81340886
has title: Find the closest value to another value in a NumPy array
has answer: http://stackoverflow.com/a/47199556
tagged with: arrays
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81341023
has comment: http://stackoverflow.com/comment/81341062
favorite count: 0
has comment: http://stackoverflow.com/comment/81340890
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81340992
has comment: http://stackoverflow.com/comment/81340979
has body: I want to find the element in yrs that is closest to 2013 (_tmp). yrs = [2000.0, 2001.0, 2002.0, 2003.0, 2004.0, 2005.0, 2006.0, 2007.0, 2008.0, 2009.0, 2010.0, 2011.0, 2012.0, 2014.0, 2015.0, 2016.0] _tmp = 2013 min(yrs, key=lambda x: abs(x - _tmp)) I've tried with a list comprehension but it throws a NameError. How else can I do this? Perhaps with numpy?
score: 1
accepted answer: http://stackoverflow.com/a/47199983

http://stackoverflow.com/q/47107228
downvote count: 0
upvote count: 1
tagged with: python
has body: I've array of string in python, I'm iterating over the loop each value and trying to append ('|') symbol using below code. But its not appending as expected result_list = [] new_value = 'iek,33833,,sdfd,lope' my_list = ['abc,1234,,ickd,sold', 'yeje,38393,,dkdi,eole', 'euei,38393,,idkd,dikd'] for val in my_list: result_list.append(val + '|') res = result_list.append(new_value) + '|') print res I'm trying to print the list of string including new string at last. But its giving me below error: TypeError: can only concatenate list (not "str") to list Sample output: abc,1234,,ickd,sold|yeje,38393,,dkdi,eole|euei,38393,,idkd,dikd|iek,33833,,sdfd,lope| Thanks a lot for your help!
has answer: http://stackoverflow.com/a/47107316
score: 1
has answer: http://stackoverflow.com/a/47107322
answer count: 4
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47107265
has title: How to append pipe delimiter in string array in python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47107271
tagged with: arrays

http://stackoverflow.com/comment/81086357
comment on: http://stackoverflow.com/q/47065193
has text: why dont you use requirements.txt?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47180036
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/47180101
answer count: 2
upvote count: 1
has title: Changing keys in dictionary
tagged with: key
has comment: http://stackoverflow.com/comment/81308879
favorite count: 0
has answer: http://stackoverflow.com/a/47180101
type: Question
has body: How can I change the keys of a dictionary of lists to display dates (outright) rather than datetime.date(2017, 1, 1) which is what they currently are formatted as? Example of section of list: {datetime.date(2017, 9, 7): [162.3, 163.24, 162.22, 163.18], datetime.date(2017, 7, 10): [160.44, 161.13, 160.44, 160.94], I am rather new to python so any help would be much appreciated. Thanks.
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/47180129
has answer: http://stackoverflow.com/a/47180129
tagged with: datetime
downvote count: 1

http://stackoverflow.com/q/47148553
has title: Operator overloading multiple operands to return class list
has answer: http://stackoverflow.com/a/47148779
type: Question
tagged with: operator-overloading
type: UnansweredQuestion
has body: How do I write code for a class in python that overloads add as follows: class A: def __init__(self,value): self.value = value def __add__(self,other): return [self.value, other.value] This works for two operands but how do I make it work for multiple operands, so: a1 = A(10) a2 = A(20) a3 = A(30) print a1 + a2 + a3 Should return [a1, a2, a3] That is the add function should return list of class A, with every '+' adding to the list
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/47148786
has answer: http://stackoverflow.com/a/47148856
score: 0
has answer: http://stackoverflow.com/a/47148657

http://stackoverflow.com/comment/81237338
comment on: http://stackoverflow.com/q/47142840
score: 0
has text: @ImportanceOfBeingErnest sure i will modify as quick as i can, the black area is he real name of the customers and the real values of CTR that i can't share. Morover it made a mistake adapting the question for stack from original code is not 'Customer Name" but "Client name"
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47192793
tagged with: numpy
tagged with: opencv
type: UnansweredQuestion
has body: I am trying to take in a image, checking pixel by pixel if there is any red in it. If there is it'll replace it with white. Once it runs through every pixel, it'll return a new image with white instead of red. The following are my attempts: import cv2 import numpy as np def take_out_red(): ''' Takes an image, and returns the same image with red replaced by white ------------------------------------------------------------ Postconditions: returns new_img (no red) ''' img = cv2.imread('red.png',1) #Reads the image# new_img = img #Makes a copy of the image for i in range(499): for y in range(499): if np.all(img[i,y]) == np.all([0,0,253]): #[0,0,253] is a red pixel #Supposed to check if the particular pixel is red new_img[i,y] == [255,255,255] #if it is red, it'll replace that pixel in the new_image #with a white pixel return cv2.imshow('image',new_img) #returns the new_image with no red Any help would be highly appreciated, thank you so much in advance.
tagged with: python
has title: Image manipulation, using openCV and numpy. Trying to return an image without the color red
has answer: http://stackoverflow.com/a/47194151
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81337154
tagged with: image-manipulation
has answer: http://stackoverflow.com/a/47192835
type: Question

http://stackoverflow.com/q/47166563
has comment: http://stackoverflow.com/comment/81326607
has answer: http://stackoverflow.com/a/47189555
has body: I am working on fetching the data from the database. I want to search for the next day format for the program_start_date, example: the program_start_date format show 20171107200000 so I want to search for the next day format which it is 20171108200000. Here is the code: channels_list = self.channel[self.channels_Index:min(len(self.channel), self.channels_Index + 7)] if len(self.programs_button) &gt; 0: #CONNECT TO THE DATABASE conn = database.connect(self.profilePath + 'source.db') cur = conn.cursor() for channels in channels_list: cur.execute('SELECT channel, title, start_date, stop_date FROM programs where channel=? LIMIT 1', [channels]) programs = cur.fetchall() for ind, row in enumerate(programs): program_start_date = str(row[2]) start_time = time.strptime(program_start_date, '%Y%m%d%H%M%S') start_time = datetime.datetime.fromtimestamp(time.mktime(start_time)) print program_start_date Here is the program_start_date data: 20171107200000 20171107210000 20171107220000 20171107223000 20171107224500 20171107232500 20171108000500 20171108001000 20171108060000 20171108091500 20171108100000 20171108110000 20171108114500 20171108121500 20171108130000 20171108133000 20171108134500 20171108141500 20171108150000 20171108154500 20171108163000 20171108171500 20171108180000 20171108183000 20171108190000 20171108200000 20171108210000 20171108220000 20171108223000 20171108224500 20171108231500 20171108234500 20171109004500 20171109005000 20171109060000 20171109091500 20171109100000 20171109110000 20171109114500 20171109121500 20171109130000 20171109133000 20171109134500 20171109141500 20171109150000 20171109154500 20171109163000 20171109171500 20171109180000 20171109183000 20171109190000 20171109193000 20171109200000 20171109210000 20171109220000 20171109223000 20171109224500 20171109234500 20171110004500 20171110005000 20171110060000 20171110091500 20171110100000 20171110110000 20171110114500 20171110121500 20171110130000 20171110133000 20171110134500 20171110141500 20171110150…
accepted answer: http://stackoverflow.com/a/47189555
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81286232
type: Question
has title: Search for the next day format in a database
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81328032
answer count: 1
has comment: http://stackoverflow.com/comment/81327865
favorite count: 0
has comment: http://stackoverflow.com/comment/81283436
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/comment/81367234
comment on: http://stackoverflow.com/q/47208928
has text: Why do you think you are doing something wrong?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/47082454
favorite count: 0
type: AnsweredQuestion
has title: Reshaping and averaging matrices of training data
answer count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81116195
has body: I am trying to "normalize" the shape of my training set so that I can feed them into a Vanilla Neural Net. The input always has the same number of "channels"/columns representing a feature but has a varying number of rows for a given "y" Is there a python or numpy or other utility that can take as input a matrix of dimension (m,n) of floats and stretch it to a given size of (m,o) where o > n by inserting rows throughtout the new shape with values averaged Example: I have an array of shape (4,4) but require my array to be (7,4) [ [1,1,1,1], [2,2,2,2], [1,1,1,1], [4,4,4,4] ] would become [ [1,1,1,1], [1.5,1.5,1.5,1.5], [2,2,2,2], [1.5,1.5,1.5,1.5], [1,1,1,1], [2.5,2.5,2.5,2.5], [4,4,4,4] ] Where the inserted rows have been averaged between the one before and the one after Any ideas ?
type: Question
tagged with: numpy
upvote count: 0
tagged with: arrays
accepted answer: http://stackoverflow.com/a/47083522
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/81115299
has comment: http://stackoverflow.com/comment/81114226
has answer: http://stackoverflow.com/a/47083522
downvote count: 1

http://stackoverflow.com/a/52538371
has body: You may place the button inside its own frame like this: buttonborder = Tkinter.Frame(root, highlightbackground="#37d3ff", highlightcolor="#37d3ff", highlightthickness=4, bd=0) photoshop = Tkinter.Button(buttonborder, text='Photoshop', fg='#37d3ff', bg='#001d26')
upvote count: 8
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47156055
score: 8

http://stackoverflow.com/comment/81346794
score: 0
type: AnswerComment
has text: Consider negative numbers in input: "-3, -2, -1, 0, 1, 2-5, 6".
comment on: http://stackoverflow.com/a/47199012
type: Comment

http://stackoverflow.com/q/47220616
has body: This question is similar to this one, but I couldn't find a way to adapt it in my case. I have a pretty big Nx3 matrix of integers. I need to find the list of rows matching a list of integers. The final goal is to filter the matrix to remove the rows containing one of these values. Right now, the best I could come out with involves a for loop on my list of integers and numpy.logical_and.reduce to find the rows. I believe there must be a more efficient way, without having to go to a lower level language. import numpy as np matrix = np.random.randint(0,100000,(50000, 3)) values_to_find = np.random.randint(0,100000,10000) matches = np.ones(len(matrix), bool) for value in values_to_find: matches = matches &amp; np.logical_and.reduce(matrix != value, axis=1) new_matrix = matrix[matches] What's the more efficient and elegant way?
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47220706
has answer: http://stackoverflow.com/a/47220737
accepted answer: http://stackoverflow.com/a/47220737
has comment: http://stackoverflow.com/comment/81390825
tagged with: python
linked to: http://stackoverflow.com/q/9566592
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47220706
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has title: Efficent way of finding rows matching a list of values

http://stackoverflow.com/q/47215352
has comment: http://stackoverflow.com/comment/81380288
has comment: http://stackoverflow.com/comment/81380152
answer count: 1
has comment: http://stackoverflow.com/comment/81380141
linked to: http://stackoverflow.com/q/43002323
has comment: http://stackoverflow.com/comment/81380245
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47216343
has comment: http://stackoverflow.com/comment/81380243
upvote count: 0
has comment: http://stackoverflow.com/comment/81380214
has comment: http://stackoverflow.com/comment/81380474
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81380341
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81380163
tagged with: flask
has title: How is this variable referenced before it is assigned?
has body: Error message: UnboundLocalError: local variable 'post_title' referenced before assignment I tried using global before the variable, which resulted in a syntax error. Relevant code: class PostForm(Form): title = StringField('Title', [validators.Length(min=1, max=200)]) body = TextAreaField('Body', [validators.Length(min=30)]) @is_logged_in @app.route('/add_post', methods=['GET','POST']) def add_post(): form = PostForm(request.form) if request.method == 'POST' and form.validate(): post_title = form.title.data body = form.body.data cur = mysql.connection.cursor() cur.execute('INSERT INTO posts(title, body, author) VALUES(%s, %s, %s)',(post_title, body, session['username'])) mysql.connection.commit() print(post_title) cur.close() flash('Post created', 'success') return redirect(url_for('dashboard')) return render_template('add_post.html', form=form)

http://stackoverflow.com/q/47142146
has comment: http://stackoverflow.com/comment/81234377
has comment: http://stackoverflow.com/comment/81234307
has comment: http://stackoverflow.com/comment/81234303
has body: I am trying to make range include end boundary, if distance == 1: end_boundary = int(d + distance + distance) else: end_boundary = int(d + distance + distance - 1) for y in range(int(d - distance), end_boundary): # some other code d contains int value, I am wondering if there is a better way to do this. Also I want to make this code work when d and distance contains float values.
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 0
has title: python how to make range include end boundary
tagged with: range
tagged with: python
score: 3

http://stackoverflow.com/q/47113979
upvote count: 11
has answer: http://stackoverflow.com/a/47121409
accepted answer: http://stackoverflow.com/a/47121409
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81177902
has body: I have an (x, y) signal with non-uniform sample rate in x. (The sample rate is roughly proportional to 1/x). I attempted to uniformly re-sample it using scipy.signal's resample function. From what I understand from the documentation, I could pass it the following arguments: scipy.resample(array_of_y_values, number_of_sample_points, array_of_x_values) and it would return the array of [[resampled_y_values],[new_sample_points]] I'd expect it to return an uniformly sampled data with a roughly identical form of the original, with the same minimal and maximalx value. But it doesn't: # nu_data = [[x1, x2, ..., xn], [y1, y2, ..., yn]] # with x values in ascending order length = len(nu_data[0]) resampled = sg.resample(nu_data[1], length, nu_data[0]) uniform_data = np.array([resampled[1], resampled[0]]) plt.plot(nu_data[0], nu_data[1], uniform_data[0], uniform_data[1]) plt.show() blue: nu_data, orange: uniform_data It doesn't look unaltered, and the x scale have been resized too. If I try to fix the range: construct the desired uniform x values myself and use them instead, the distortion remains: length = len(nu_data[0]) resampled = sg.resample(nu_data[1], length, nu_data[0]) delta = (nu_data[0,-1] - nu_data[0,0]) / length new_samplepoints = np.arange(nu_data[0,0], nu_data[0,-1], delta) uniform_data = np.array([new_samplepoints, resampled[0]]) plt.plot(nu_data[0], nu_data[1], uniform_data[0], uniform_data[1]) plt.show() What is the proper way to re-sample my data uniformly, if not this?
answer count: 1
downvote count: 0
tagged with: scipy
tagged with: signal-processing
has comment: http://stackoverflow.com/comment/81178224
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81178596
linked to: http://stackoverflow.com/q/20889501
has title: How to uniformly resample a non-uniform signal using SciPy?
tagged with: python
score: 11

http://stackoverflow.com/a/64696416
has body: In Windows I solved by adding this to PATH environment: C:\Program Files\PostgreSQL\12\bin then restart terminals and IDEs Path Environment PATH How to add a folder to Path environment variable in Windows
score: 7
type: Answer
downvote count: 0
upvote count: 7
answers question: http://stackoverflow.com/q/47124297

http://stackoverflow.com/comment/120043725
comment on: http://stackoverflow.com/a/48508289
type: AnswerComment
has text: I went to help->change memory settings in Pycharm, increased to 4000 and this stopped.: https://www.jetbrains.com/help/pycharm/increasing-memory-heap.html
type: Comment
score: 0

http://stackoverflow.com/a/47186961
score: 0
has comment: http://stackoverflow.com/comment/81323200
type: Answer
has comment: http://stackoverflow.com/comment/81323438
answers question: http://stackoverflow.com/q/47186604
has body: Compute all the differences, and use `np.argmin to lookup the closest. a,b=np.random.rand(2,10) all_differences=np.abs(np.subtract.outer(a,b)) ia=all_differences.argmin(axis=1) for i in range(10): print(i,a[i],ia[i], b[ia[i]]) 0 0.231603891949 8 0.21177584152 1 0.27810475456 7 0.302647382888 2 0.582133214953 2 0.548920922033 3 0.892858042793 1 0.872622982632 4 0.67293347218 6 0.677971552011 5 0.985227546492 1 0.872622982632 6 0.82431697833 5 0.83765895237 7 0.426992114791 4 0.451084369838 8 0.181147161752 8 0.21177584152 9 0.631139744522 3 0.653554586691 EDIT with dataframes and indexes: va,vb=np.random.rand(2,10) na,nb=np.random.randint(0,100,(2,10)) dfa=pd.DataFrame({'id':na,'odo':va}) dfb=pd.DataFrame({'id':nb,'odo':vb}) all_differences=np.abs(np.subtract.outer(dfa.odo,dfb.odo)) ia=all_differences.argmin(axis=1) dfc=dfa.merge(dfb.loc[ia].reset_index(drop=True),\ left_index=True,right_index=True) Input : In [337]: dfa Out[337]: id odo 0 72 0.426457 1 12 0.315997 2 96 0.623164 3 9 0.821498 4 72 0.071237 5 5 0.730634 6 45 0.963051 7 14 0.603289 8 5 0.401737 9 63 0.976644 In [338]: dfb Out[338]: id odo 0 95 0.333215 1 7 0.023957 2 61 0.021944 3 57 0.660894 4 22 0.666716 5 6 0.234920 6 83 0.642148 7 64 0.509589 8 98 0.660273 9 19 0.658639 Output : In [339]: dfc Out[339]: id_x odo_x id_y odo_y 0 72 0.426457 64 0.509589 1 12 0.315997 95 0.333215 2 96 0.623164 83 0.642148 3 9 0.821498 22 0.666716 4 72 0.071237 7 0.023957 5 5 0.730634 22 0.666716 6 45 0.963051 22 0.666716 7 14 0.603289 83 0.642148 8 5 0.401737 95 0.333215 9 63 0.976644 22 0.666716

http://stackoverflow.com/q/47120167
type: Question
tagged with: robotframework
type: UnansweredQuestion
has title: FakerLibrary: Adding a custom provider fails
tagged with: python
has body: When I run the following code, I'm facing some difficulty. Calling the Robot Framework FakerLibrary Add Provider keyword requires two arguments, instead of the expected 1: name of the module. This seems to me to be correct. As the Robot Framework Library is a Dynamic Hybrid library, the actual keywords come from the Faker Python module. In the Generator class the actual Add Provider method can be found. However, it only takes 2 arguments; one being self: def add_provider(self, provider). So, it should only require 1 argument when called from Robot. Using the normal Faker keywords works as expected and I'm not having any issues. I'm suspecting that the import through the Dynamic Library doesn't support the Faker module setup as I'm seeing a few Keywords in the Keyword Documentation that require self as an input argument. For now I've resorted in creating a wrapper around Faker for custom keywords but like the generic approach better. So that is why I would like to solve this issue. The Robot Script for this example. *** Settings *** Library FakerLibrary *** Test Cases *** Faker Custom Provider Generate Data ${fakerLib} Get Library Instance FakerLibrary Add Provider ${fakerLib} OceanProvider The custom provider Python code. When using it with regular Python programming this works as expected but not when adding it through Robot Keywords: from faker.providers import BaseProvider class OceanProvider(BaseProvider): __provider__ = "ocean" __lang__ = "en_US" oceans = [ u'Atlantic', u'Pacific', u'Indian', u'Arctic', u'Southern', ] @classmethod def ocean(cls): return cls.random_element(cls.oceans)
has comment: http://stackoverflow.com/comment/81194694
score: 2
upvote count: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/81191375
favorite count: 0

http://stackoverflow.com/q/47146105
tagged with: pymunk
tagged with: gravity
score: 0
has comment: http://stackoverflow.com/comment/81243357
has title: N gravity simulator using Pymunk
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/47146483
favorite count: 0
type: Question
has body: I am using Pymunk to make a gravity simulator. The problem I am facing is the units. For example, if I want to define the constant G for the vector Force, how do I do it? I need some sort of conversion table for this. I already tested 9.8 using the command "space.gravity(0, -9.8), and it falls very slowly, meaning pymunk is not set on meters and seconds. How can I use approximate values?
type: UnansweredQuestion
answer count: 1
tagged with: simulator
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/101749158
type: AnswerComment
type: Comment
has text: To get the layer name, e.g. on the 25th layer: `model.layers[25].name`
comment on: http://stackoverflow.com/a/47183890
score: 0

http://stackoverflow.com/a/47167716
upvote count: 2
type: Answer
has body: IIUC: In [47]: a = np.arange(10) In [48]: b = np.arange(16) In [49]: a[:,None] * b Out[49]: array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30], [ 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45], [ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60], [ 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75], [ 0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90], [ 0, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98, 105], [ 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120], [ 0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 99, 108, 117, 126, 135]])
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47167678

http://stackoverflow.com/q/47155256
tagged with: python-2.7
score: 0
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47155482
has title: Serial Communication: python
tagged with: serialization
has body: I am using Python Anaconda 2.7. I would like to toggle the port using serial communication, But I am getting error: AttributeError: 'module' object has no attribute 'Serial' My sample program is: import serial import time #remember to adjust “COM3” port = serial.Serial("COM3", 19200, timeout=0.5) #turn on port 2, sleep 2 seconds, turn off port 2 port.write(b"\nF2\r") time.sleep(2.0) port.write(b"\nF2\r") #turn on port 2 and 7, sleep 2 seconds, turn off port 2 and 7 port.write(b"\nF2\r\nF7\r") time.sleep(2) port.write(b"\nF2\r\nF7\r") #close the port port.close() I have tried many solutions: changing file name from 'serial.py' to 'any_other_name.py' and vise versa deleting related .pyc file Installing 'pip install pyserial' Doing From serial import serial When I run the same program from psychopy, it is working really fine. I don't know How to solve it. If some one can give me suggestions that It would be great help for me. Thanking you in advance. Ravi
tagged with: python
has answer: http://stackoverflow.com/a/47155482
type: AnsweredQuestion

http://stackoverflow.com/q/47185894
possible better answer: http://stackoverflow.com/a/47186441
tagged with: group-by
score: 7
accepted answer: http://stackoverflow.com/a/52557580
tagged with: python
has answer: http://stackoverflow.com/a/47186441
has answer: http://stackoverflow.com/a/52557580
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/81320948
downvote count: 0
upvote count: 7
has title: Iteration order with pandas groupby on a pre-sorted DataFrame
linked to: http://stackoverflow.com/q/26456125
has body: The Situation I'm classifying the rows in a DataFrame using a certain classifier based on the values in a particular column. My goal is to append the results to one new column or another depending on certain conditions. The code, as it stands looks something like this: df = pd.DataFrame({'A': [list with classifier ids], # Only 3 ids, One word strings 'B': [List of text to be classified], # Millions of unique rows, lines of text around 5-25 words long 'C': [List of the old classes]} # Hundreds of possible classes, four digit integers stored as strings df.sort_values('A', inplace=True) new_col1, new_col2 = [], [] for name, group in df.groupby('A', sort=False): classifier = classy_dict[name] vectors = vectorize(group.B.values) preds = classifier.predict(vectors) scores = classifier.decision_function(vectors) for tup in zip(preds, scores, group.C.values): if tup[2] == tup[0]: new_col1.append(np.nan) new_col2.append(tup[2]) else: new_col1.append(str(classifier.classes_[tup[1].argsort()[-5:]])) new_col2.append(np.nan) df['D'] = new_col1 df['E'] = new_col2 The Issue I am concerned that groupby will not iterate in a top-down, order-of-appearance manner as I expect. Iteration order when sort=False is not covered in the docs My Expectations All I'm looking for here is some affirmation that groupby('col', sort=False) does iterate in the top-down order-of-appearance way that I expect. If there is a better way to make all of this work, suggestions are appreciated. Here is the code I used to test my theory on sort=False iteration order: from numpy.random import randint import pandas as pd from string import ascii_lowercase as lowers df = pd.DataFrame({'A': [lowers[randint(3)] for _ in range(100)], 'B': randint(10, size=100)}) print(df.A.unique()) # unique values in order of appearance per the docs for name, group in df.groupby('A', sort=False): print(name) Edit: The above code makes it appear as though it acts in the manner that I expect, but I would like some more undeniable pro…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81321243
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/q/47161156
has comment: http://stackoverflow.com/comment/81271959
linked to: http://stackoverflow.com/q/39885359
has comment: http://stackoverflow.com/comment/81272272
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47162601
has title: How to discard certain tag and continue with the rest?
tagged with: web-scraping
possible better answer: http://stackoverflow.com/a/47161353
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/47161353
accepted answer: http://stackoverflow.com/a/47162601
type: Question
has comment: http://stackoverflow.com/comment/81272126
has body: I've written a script in python to scrape some text out of some html elements. When I execute my script, it gives me all the text available in it. I do not wish to get the text within p tag. Few days back when i went through BeautifulSoup documentation and I found a method .decompose(). Although i didn't understand what that does, i thought i might give this a try. However, upon execution, i get an error. This is the script: html_elem =''' pop singer intranet songs online instrumental hotline track one track two track three ''' from bs4 import BeautifulSoup soup = BeautifulSoup(html_elem, "lxml") item = soup.find_all(class_="track") # item.p.decompose() for elem in item: print(elem.text.strip()) I get this error when I uncomment the line containing .decompose() and run: Traceback (most recent call last): File "C:\Users\ar\AppData\Local\Programs\Python\Python35-32\Social.py", line 28, in <module> item.p.decompose() AttributeError: 'ResultSet' object has no attribute 'p' Btw, only using .find_all("a"), I could have got the desired data but i wish to know/learn even if i select the class track I will only get the text within a tag excluding the text within p tag.
tagged with: python
tagged with: python-3.x

http://stackoverflow.com/comment/81249826
comment on: http://stackoverflow.com/a/47114463
type: Comment
has text: Special thanks to you Erdem for considering my issue and for your great effort in explaining the answer
score: 0
type: AnswerComment

feature-selection
tags question: http://stackoverflow.com/q/47197989
tag name: feature-selection
type: Tag

http://stackoverflow.com/comment/81190520
type: QuestionComment
has text: You need to show how you are instantiating this form in the view, in particular what you are passing as the user parameter.
comment on: http://stackoverflow.com/q/47120069
score: 0
type: Comment

bayesian-networks
tag name: bayesian-networks
type: Tag
tags question: http://stackoverflow.com/q/47087068

http://stackoverflow.com/a/47174270
has comment: http://stackoverflow.com/comment/81297982
score: 2
has body: Some mistakes in your code: 1 - You need to use p &lt;= n instead of p &lt; n ( try n = 77 ) 2 - Use set instead of list to store your answer, that will speed up your solution. 3 - You don't need to call cumsum in the range [i, limit) you can accumulate until the sum gets greater than n. This will speed up your solution too. 4 - Try to be less "pythonic". Do not fill your code of long and ugly list comprehensions. (This is not a mistake exactly) This is your code after some changes: def is_palindrome(s): return s == s[::-1] def values(n): squares = [0] i = 1 while i * i &lt;= n: squares.append(squares[-1] + i * i) i += 1 pals = set() for i in range(1, len(squares)): j = i + 1 while j &lt; len(squares) and (squares[j] - squares[i - 1]) &lt;= n: s = squares[j] - squares[i - 1] if is_palindrome(str(s)): pals.add(s) j += 1 return len(pals)
has comment: http://stackoverflow.com/comment/81297943
type: AcceptedAnswer
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/47173576
type: Answer
accepted answer of: http://stackoverflow.com/q/47173576
has comment: http://stackoverflow.com/comment/81298289

python-2.6
type: Tag
tag name: python-2.6
tags question: http://stackoverflow.com/q/47189735

http://stackoverflow.com/q/47073072
has comment: http://stackoverflow.com/comment/81094379
tagged with: python
has body: I want to convert multiple text files into a single csv file.the text are named as(file1.txt,file2.txt....file1000.txt). A text file(file1.txt) format is as follows: Employee id: us51243 Employee name: Mark santosh department:engineering Age:25 I want the ouput as: Employee id,Employee name,department,Age us51243,Mark santosh,engineering,25//(file1.txt values) ...................................//(file2.txt values) But in the ouput I am getting the value of file1000.txt only as follows: Employee id,Employee name,department,Age us98621,Andy Gonzalez,Support &amp; services,25 Here is my code: import csv import os for x in range(1,1001): filepath=os.path.normpath('C:\\Text\\file{}.txt'.format(x)) with open(filepath) as f, open('emp.csv', 'w',newline='') as file: writer = csv.writer(file) val = zip(*[l.rstrip().split(': ') for l in f]) writer.writerows(val) Kindly note:Also I want to display the header(Employee id,Employee name,Department,Age) only once
has comment: http://stackoverflow.com/comment/81095809
type: Question
score: 2
has title: Converting 1000 text files into a single csv file
has comment: http://stackoverflow.com/comment/81095673
downvote count: 1
has comment: http://stackoverflow.com/comment/81094717
has comment: http://stackoverflow.com/comment/81094860
has answer: http://stackoverflow.com/a/47073520
favorite count: 0
accepted answer: http://stackoverflow.com/a/47073520
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/47073868
possible better answer: http://stackoverflow.com/a/47073395
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81094343
has answer: http://stackoverflow.com/a/47073395

http://stackoverflow.com/comment/81370511
score: 0
type: AnswerComment
has text: Writing out the same literal multiple times in the same code is a bad practice, isn't it? The question mentions reuse.
comment on: http://stackoverflow.com/a/47210551
type: Comment

http://stackoverflow.com/comment/81140212
type: Comment
score: 0
type: AnswerComment
has text: Thanks again. It passes the Hackerrank tests now.
comment on: http://stackoverflow.com/a/47094301

http://stackoverflow.com/a/47146421
accepted answer of: http://stackoverflow.com/q/47146358
type: Answer
score: 3
answers question: http://stackoverflow.com/q/47146358
has comment: http://stackoverflow.com/comment/81243525
upvote count: 3
has body: Let's try with assign using mean and std with parameter axis=1: df.assign(Mean=df.mean(1), Stddev=df.std(1)) Output: A1 A2 Mean Stddev 0 0.1 2.0 1.05 1.343503 1 0.5 4.5 2.50 2.828427 2 3.0 1.2 2.10 1.272792 3 9.0 9.0 9.00 0.000000 Edit for comment / add CpK: df.assign(mean=df.mean(1),stddev=df.std(1)).eval('Cpk = (mean + stddev) / A2') Output: A1 A2 mean stddev Cpk 0 0.1 2.0 1.05 1.343503 1.196751 1 0.5 4.5 2.50 2.828427 1.184095 2 3.0 1.2 2.10 1.272792 2.810660 3 9.0 9.0 9.00 0.000000 1.000000
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81243608

http://stackoverflow.com/q/47170100
tagged with: python
has answer: http://stackoverflow.com/a/47170712
score: 0
has title: Python pandas dataframe : selecting set of elements in array column
answer count: 1
tagged with: string
type: Question
type: AnsweredQuestion
has body: I have a dataframe which has some column like below which contains arrays of different sizes: array_column ["a","b","c","d"] ["d","e","f"] ["h","i","j","k","l"] ["m","n","o","p"] ["q","r","s"] I want to select set of array elements from each cell starting from index =1 till index = (whatever is the array length of that cell -1) and then convert the array into string in which array elements are joined using '/' So expected output column after selecting required elements will look like : array_column ["b","c"] ["e"] ["i","j","k"] ["n","o"] ["r"] final_ouput_column "b/c" "e" "i/j/k" "n/o" "r" If it's a simple array for eg which is not a dataframe i would do something like below: array = ["a","b","c","d","e","f"] new_array = array[1:len(array)-1] // I dont know what should be done //for len(array)-1 for dataframe print(new_array) . [output is "b","c","d","e"] print('/'.join(new_array)) "b/c/d/e"
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47170712
tagged with: dataframe

http://stackoverflow.com/comment/81312139
type: QuestionComment
score: 0
has text: @honeyboney I just noticed that I used the wrong text sample - I tried to match the list of numbers, not the html glob. So I guess it would need a little more work.
type: Comment
comment on: http://stackoverflow.com/q/47159417

http://stackoverflow.com/comment/81359960
type: QuestionComment
score: 0
has text: Probably you have to consider either: to scale the image before feeding it to the netowrk or to change the kernel size of the last average pooling layer before the fully connected layer (so it flattens the output) in the dense net model.
comment on: http://stackoverflow.com/q/47189734
type: Comment

http://stackoverflow.com/q/47070764
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47071017
has comment: http://stackoverflow.com/comment/81089954
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47071107
answer count: 4
tagged with: python-2.7
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/81090444
linked to: http://stackoverflow.com/q/28401904
has title: How can I combine values based on some key in python dict just like SQL GROUP BY
has answer: http://stackoverflow.com/a/47070992
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81089605
has answer: http://stackoverflow.com/a/47071083
has comment: http://stackoverflow.com/comment/81090033
has body: L = [{'id':1, 'quantity':1}, {'id':2, 'quantity':2}, {'id':1, 'quantity':3}] I want to add quantity base on id , So for the list above I would like the output to be: [{'id':1,'quantity':4},{'id':2,'quantity':2}] another example: L = [{'id':1, 'quantity':1}, {'id':2, 'quantity':2}, {'id':1, 'quantity':2}, {'id':1, 'quantity':3}] So for the list above I would like the output to be: [{'id':1, 'quantity':6}, {'id':2, 'quantity':2}]
has comment: http://stackoverflow.com/comment/81089922

http://stackoverflow.com/a/47066712
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47066711
type: AcceptedAnswer
has body: I found the answer mere moments before hitting "submit" on this question, so I figured I would put the answer here. I need to set the mime type of the response. I changed my testicon function to this: @app.route("/testicon") def testicon(): response = make_response(render_template("icons/test.svg", primary="ff0000")) response.mimetype = "image/svg+xml" return response Now it works perfectly.
accepted answer of: http://stackoverflow.com/q/47066711
type: Answer

http://stackoverflow.com/q/47087109
has title: Evaluate the output from scipy 2D interpolation along a curve
has answer: http://stackoverflow.com/a/56571651
downvote count: 0
has answer: http://stackoverflow.com/a/47233198
tagged with: scipy
has comment: http://stackoverflow.com/comment/81124971
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47087385
tagged with: numpy
has body: I have data z sampled from a 2D function f at grid points x, y, as in z = f(x, y). It is easy to interpolate f with scipy.interp2d via f = interp2d(x, y, z). However, evaluating f(x, y) returns an entire 2D grid as if I had done xx, yy = np.meshgrid(x, y) f(xx, yy) The behaviour I want is to simply return the values [f(x[i], y[i]) for i in range(len(x))], which I believe is the behaviour for pretty much any other method in numpy. The reason I want this behaviour is that I'm looking for the path traced out along the surface of f over "time" by the pair (t, u(t)). It is also surprising that np.diag(f(t, u(t))) differs from np.array([f(ti, u(ti)) for ti in t]), so It's not clear to me how to get at the path f(t, u(t)) from what is returned via interp2d. EDIT: About diag, I just thought it seemed we should have np.diag(f(t, u(t))) == np.array([f(ti, u(ti)) for ti in t]), but that isn't the case. Complete example: def f(t, u): return (t**2) * np.exp((u**2) / (1 + u**2)) x = np.linspace(0, 1, 250) xx, yy = np.meshgrid(x, x) z = f(xx, yy) f = scipy.interpolate.interp2d(x, y, z) print(f(x, y)) print(np.array([f(xi, yi)[0] for xi, yi in zip(x, y)])) I would like the output of both print statements to be the same.
type: UnansweredQuestion
score: 6
tagged with: python
linked to: http://stackoverflow.com/q/35360756
linked to: http://stackoverflow.com/q/46983476
upvote count: 6
has comment: http://stackoverflow.com/comment/81124516
answer count: 3

http://stackoverflow.com/comment/81332124
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47191225
has text: I like how this has an attempt to solve the problem, shows some level of understanding of `python` and requests for `the right path`
type: Comment

http://stackoverflow.com/comment/81386083
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47218275
has text: There's a network problem or a server of the Docker hub is down.

http://stackoverflow.com/comment/81107588
has text: @December Edited my answer. I misread your comment and thought there were multiple `range_start`s for each `resource_id`, but if there's only one, it's even easier and the code above should still apply, except you're only doing 1 iteration (since there's only 1 unique value of `range_start` for a given `resource_id`).
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47079132

http://stackoverflow.com/comment/81242917
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47137401
type: AnswerComment
has text: Here might be the modification in your code as i explained in the reply. https://ideone.com/veSoSC

http://stackoverflow.com/q/47090816
has title: Python thread parallelization escaping the GIL
accepted answer: http://stackoverflow.com/a/51682077
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81131956
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/14509662
tagged with: jython
tagged with: python
tagged with: gil
has answer: http://stackoverflow.com/a/51682077
tagged with: jyni
has comment: http://stackoverflow.com/comment/81136910
has body: I'm rephrasing my question because I think many thought it was the question "does python have threads". It does, but CPython also has the GIL, which will never schedule more than one thread at any given time. That makes CPython threads useless for cpu-intensive computations. I need to use threads; process parallelism won't work for me because of the IPC costs (I have large shared objects). I'm currently using Jython (no GIL) with JyNI so that I can use numpy. JyNI is alpha, but it does now support numpy. I got this to work. However, JyNI is alpha and buggy, and the whole process is slow. I've read a bunch of old threads. I wonder whether there has been a viable option since then? I'm forced to use python 2.7. Thanks.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81130755
score: 1

http://stackoverflow.com/comment/81375886
type: Comment
has text: Hello David, welcome to SO. This site isn't meant to provide coding services, it is generally expected that you show at least some basic research, some code you created on your own, and ask help with specific problems. See [here for some general directions on how to ask a good question](https://stackoverflow.com/help/mcve).
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47213130

python-3.x
tags question: http://stackoverflow.com/q/47106305
tags question: http://stackoverflow.com/q/47065460
tags question: http://stackoverflow.com/q/47091183
tags question: http://stackoverflow.com/q/47099027
tags question: http://stackoverflow.com/q/47116480
tags question: http://stackoverflow.com/q/47080174
tags question: http://stackoverflow.com/q/47191951
tags question: http://stackoverflow.com/q/47167538
tags question: http://stackoverflow.com/q/47117269
tags question: http://stackoverflow.com/q/47081521
tags question: http://stackoverflow.com/q/47153385
tags question: http://stackoverflow.com/q/47160153
tags question: http://stackoverflow.com/q/47207957
tags question: http://stackoverflow.com/q/47203685
tags question: http://stackoverflow.com/q/47139674
tags question: http://stackoverflow.com/q/47077304
tags question: http://stackoverflow.com/q/47121382
tags question: http://stackoverflow.com/q/47074617
tags question: http://stackoverflow.com/q/47198848
tags question: http://stackoverflow.com/q/47096887
tags question: http://stackoverflow.com/q/47166551
tags question: http://stackoverflow.com/q/47133993
tags question: http://stackoverflow.com/q/47084192
tags question: http://stackoverflow.com/q/47104172
tags question: http://stackoverflow.com/q/47185522
tags question: http://stackoverflow.com/q/47190911
tags question: http://stackoverflow.com/q/47213400
tags question: http://stackoverflow.com/q/47208911
tags question: http://stackoverflow.com/q/47111884
tags question: http://stackoverflow.com/q/47143368
tags question: http://stackoverflow.com/q/47068917
tags question: http://stackoverflow.com/q/47118721
tags question: http://stackoverflow.com/q/47094160
tags question: http://stackoverflow.com/q/47101750
tags question: http://stackoverflow.com/q/47156168
tags question: http://stackoverflow.com/q/47217718
tags question: http://stackoverflow.com/q/47129399
tags question: http://stackoverflow.com/q/47202581
tags question: http://stackoverflow.com/q/47172373
tags question: http://stackoverflow.com/q/47096794
tags question: http://stackoverflow.com/q/47197637
tags question: http://stackoverflow.com/q/47186213
tags question: http://stackoverflow.com/q/47114589
tags question: http://stackoverflow.com/q/47188227
tags question: http://stackoverflow.com/q/47212355
tags question: http://stackoverflow.com/q/47192150
tags question: http://stackoverflow.com/q/47094959
tags question: http://stackoverflow.com/q/47100481
tags question: http://stackoverflow.com/q/47096034
tags question: http://stackoverflow.com/q/47138753
tags question: http://stackoverflow.com/q/47171944
tags question: http://stackoverflow.com/q/47086683
tags question: http://stackoverflow.com/q/47108103
tags question: http://stackoverflow.com/q/47120159
tags question: http://stackoverflow.com/q/47209373
tags question: http://stackoverflow.com/q/47180651
tags question: http://stackoverflow.com/q/47205055
tags question: http://stackoverflow.com/q/47153325
tags question: http://stackoverflow.com/q/47104901
tags question: http://stackoverflow.com/q/47082599
tags question: http://stackoverflow.com/q/47147285
tags question: http://stackoverflow.com/q/47180633
tags question: http://stackoverflow.com/q/47191674
tags question: http://stackoverflow.com/q/47212821
tags question: http://stackoverflow.com/q/47188800
tags question: http://stackoverflow.com/q/47096930
tags question: http://stackoverflow.com/q/47154893
tags question: http://stackoverflow.com/q/47139180
tags question: http://stackoverflow.com/q/47087236
tags question: http://stackoverflow.com/q/47206742
tags question: http://stackoverflow.com/q/47125466
tags question: http://stackoverflow.com/q/47188590
tags question: http://stackoverflow.com/q/47116919
tags question: http://stackoverflow.com/q/47166428
tags question: http://stackoverflow.com/q/47116469
tags question: http://stackoverflow.com/q/47194629
tags question: http://stackoverflow.com/q/47182284
tags question: http://stackoverflow.com/q/47114619
tags question: http://stackoverflow.com/q/47209598
tags question: http://stackoverflow.com/q/47163986

http://stackoverflow.com/comment/81378152
score: 0
type: AnswerComment
has text: That added a ', ' before every capitalized Word, not I was thinking about doing key value to create two dictionaries that will log the specific lines for each character. Is that something you would advise?
comment on: http://stackoverflow.com/a/47214272
type: Comment

http://stackoverflow.com/comment/81337551
type: QuestionComment
comment on: http://stackoverflow.com/q/47194201
has text: Now when the code is easier to read, lets take a look at the `summarize` function. You define it to take an argument (`text`), but call it without passing any arguments. That's why you get the error. Which tells you exactly that.
score: 0
type: Comment

http://stackoverflow.com/q/47138691
tagged with: python-imaging-library
tagged with: python
has answer: http://stackoverflow.com/a/47138805
type: AnsweredQuestion
tagged with: tkinter
linked to: http://stackoverflow.com/q/4297949
has body: I have the following python code: from tkinter import * from PIL import ImageTk, Image import sys, os height = 5 width = 8 # window = Tk() class NSUI(Frame): def reload(self): os.execl(sys.executable, sys.executable, *sys.argv) def __init__(self, master=None): """ Initialise process application """ Frame.__init__(self, master) self.grid() self.master.title('PROGProject') # Configure columns for r in range(7): self.master.rowconfigure(r, weight=1) # Create columns for c in range(7): self.master.columnconfigure(c, weight=1) Button(master, text = "Actuele reistijden", bg = '#005ca0', fg = 'white', font = "Verdana 10", width = width, height = height, command = self.reload).grid(row = 5,column = 2,sticky = E+W) Button(master, text = 'Storingen', bg = '#005ca0', fg = 'white', font = "Verdana 10", width = width, height = height, command = self.reload).grid(row = 5,column = 4,sticky = E+W) Label(master, text = 'Welkom bij NS',font = "Verdana 50", bg = "#EFD10E", fg = "#005ca0").grid(row=0,column=1, columnspan=5) path = "test.jpg" img = ImageTk.PhotoImage(Image.open(path)) panel = Label(root, image=img).grid(column=2,row=2) root = Tk() root.configure(background="#EFD10E") root.tk.call('tk', 'scaling', 1.5) app = NSUI(master=root) app.mainloop() It should load an image, the image is in the right directory, I made sure of that. but for some reason it just loads a white square. Does anyone know how this is possible? The relevant bit of code that i have added : path = "test.jpg" img = ImageTk.PhotoImage(Image.open(path)) panel = Label(root, image=img).grid(column=2,row=2) Thanks in advance.
has title: Tkinter image is blank
accepted answer: http://stackoverflow.com/a/47138805
downvote count: 2
has comment: http://stackoverflow.com/comment/81226815
answer count: 1
score: 6
duplicate of: http://stackoverflow.com/q/4297949
favorite count: 0
type: Question
upvote count: 8

http://stackoverflow.com/a/47084292
has comment: http://stackoverflow.com/comment/81119564
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81118707
accepted answer of: http://stackoverflow.com/q/47084046
has comment: http://stackoverflow.com/comment/81142616
has comment: http://stackoverflow.com/comment/81117960
has comment: http://stackoverflow.com/comment/81119126
answers question: http://stackoverflow.com/q/47084046
has body: Use for-loop: @classmethod def __get_start_words(cls, iterable, n, start_words): buffer = Deque(maxlen=n) for idx, item in enumerate(iterable, 1): buffer.append(item) yield item if idx == n: start_words[buffer.prefix] += 1 if idx &gt;= n and buffer[0][-1] in cls.TERMINATORS: start_words[buffer.suffix] += 1 if len(buffer) &lt; n: raise ValueError('iterable was too short to satisfy n') Some thoughts on your second version: count is not necessary when using islice: for item in islice(iterator, n): buffer.append(item) yield item if len(buffer) &lt; n: raise ValueError('iterable was too short to satisfy n') Further refactoring leading to: @classmethod def __get_start_words(cls, iterable, n, start_words): iterable = iter(iterable) buffer = deque(islice(iterable, n-1)) yield from buffer if len(buffer) &lt; n - 1: raise ValueError('iterable was too short to satisfy n') start_words[tuple(buffer)] += 1 for item in iterable: buffer.append(item) yield item first = buffer.popleft() if first[-1] in cls.TERMINATORS: start_words[tuple(buffer)] += 1
has comment: http://stackoverflow.com/comment/81118077
has comment: http://stackoverflow.com/comment/81119774
has comment: http://stackoverflow.com/comment/81118256
score: 5
has comment: http://stackoverflow.com/comment/81119209
has comment: http://stackoverflow.com/comment/81119933
type: AcceptedAnswer
upvote count: 5

http://stackoverflow.com/q/47129971
has comment: http://stackoverflow.com/comment/81209919
has comment: http://stackoverflow.com/comment/81209821
upvote count: 1
has comment: http://stackoverflow.com/comment/81209884
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47130024
possible better answer: http://stackoverflow.com/a/47130108
tagged with: python
has answer: http://stackoverflow.com/a/47130024
has body: I don't understand array as index in Python Numpy. For example, I have a 2d array A in Numpy [[1,2,3] [4,5,6] [7,8,9] [10,11,12]] What does A[[1,3], [0,1]] mean?
has answer: http://stackoverflow.com/a/47130108
has comment: http://stackoverflow.com/comment/81209988
tagged with: numpy
type: AnsweredQuestion
score: 0
has title: Python Numpy syntax: what does array index as two arrays separated by comma mean?
answer count: 2
has comment: http://stackoverflow.com/comment/81209834

http://stackoverflow.com/q/47106792
tagged with: python
tagged with: security
answer count: 0
has comment: http://stackoverflow.com/comment/81164280
has title: Deploy service to customer's local network and how to guarantee code security
score: 1
has comment: http://stackoverflow.com/comment/81166173
downvote count: 0
upvote count: 1
tagged with: keras
tagged with: virtual-machine
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: encryption
has body: We have to deploy our service to customer's local network (offline), and guarantee our code's security. Our project's framework is python + keras, we conceive of the following ways: Depoly all the code to a local VM or Docker, but how can we avoid being cracked or hacked? Obfuscate python code and encrypt keras deep learning model (contains network structure, lots of params), but how can we encrypt our keras model? Thanks.

http://stackoverflow.com/comment/131558680
has text: Another approach to avoid having to add a `get_tags` property ``` return graphene.List( graphene.String, description=field.help_text, required=not field.null, resolver=lambda obj, info: obj.tags.all() ) ```
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/55525312
type: Comment

http://stackoverflow.com/comment/81370638
score: 0
comment on: http://stackoverflow.com/q/47210402
type: Comment
has text: possible duplicate of [Django form/database error: value too long for type character varying(4)](https://stackoverflow.com/questions/8484689/django-form-database-error-value-too-long-for-type-character-varying4)
type: QuestionComment

http://stackoverflow.com/a/73771721
has body: In the special case, that you have a hermitian or real symmetric matrix, you can use eigh from numpy. This returns the eigenvalues and eigenvectors in a sorted order, according to the current numpy reference manual! For the general case, you can now use take_along_axis to sort any array based on the index you obtained from numpy.argsort (see the argsort manual). This works directly for the eigenvalues. To sort the eigenvectors, you can use the same method, applied to each component of the eigenvectors separately. The following is an illustration. This approach is simple and not very fast, I guess, but I find it much easier to understand, compared to the previously sugested solutions. Maybe you can optimize it further. import numpy as np def eig_sorted(input_array): val, vec=np.linalg.eig(input_array) idx=val.argsort() val_sorted=np.take_along_axis(val, idx, -1) arr=[] for i in range(vec.shape[-2]): v=vec[...,i,:] #take one component arr.append(np.take_along_axis(v,idx,-1)) #sort it vec_sorted=np.stack(arr, -2) #stack everything together return val_sorted, vec_sorted
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47168312
type: Answer

http://stackoverflow.com/comment/81238440
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47143772
has text: Thanks for replying Wen. Yes, the problem was there were some additional NaN values at the first row which I do not want.

http://stackoverflow.com/comment/98462073
has text: Doing the above when having two user models (as the OP asks) leads to the exact error of the question.
type: AnswerComment
comment on: http://stackoverflow.com/a/47158323
score: 0
type: Comment

http://stackoverflow.com/comment/81185741
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47114998
score: 0
has text: Are you sure that your html doesn't work just fine even if you simply remove the `%pwd`? That should just display your working directory, not change it. http://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-pwd

http://stackoverflow.com/q/47149050
tagged with: python
has title: calculating windowed probability mass function on an image using numpy and scipy
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47152116
has body: I start with a 2D image array in numpy, for which I want to perform some windowed processing. I'm looking for a vectorized approach, that for each window, first calculates a probability mass function, and then replaces the center pixel with an operation on that mass function. Further, it needs to work with nonlinear operations, like log(x). For example: given the following 3x3 window: [[1, 1, 1], [2, 2, 2], [3, 4, 5]] The probability mass function would be something like: p(1) = 0.33, p(2) = 0.33, p(3) = p(4) = p(5) = 0.11. I started with this question yesterday, which led me to the following process, giving me probabilities for each value in a window ksize (3x3 in the example above), relative to the other values in that window. def process(a, ksize=3): # get the number of times a value occurs in each kernel window b = windowed_occurences(a, ksize) # convert to probabilities p = a / (ksize * ksize) def windowed_occurences(a, ksize): window_shape = (ksize, ksize) d = math.floor(ksize / 2) a = np.pad(a, (d, d), 'constant', constant_values=(0, 0)) # get the windowed array of shape (a.height, a.width, ksize, ksize) b = skimage.util.shape.view_as_windows(a, window_shape) # replace each element of ksize x ksize kernel with the number of occurances # of that element in the kernel # process from https://stackoverflow.com/questions/47130141/ @Divakar ar2D = b.reshape(-1, b.shape[-2] * b.shape[-1]) c = bincount2D_vectorized(ar2D) d = c[np.arange(ar2D.shape[0])[:, None], ar2D].reshape(b.shape) return d # bincount2D_vectorized from https://stackoverflow.com/a/46256361/ @Divakar def bincount2D_vectorized(a): N = a.max()+1 a_offs = a + np.arange(a.shape[0])[:,None]*N return np.bincount(a_offs.ravel(), minlength=a.shape[0]*N).reshape(-1,N) For the example window, this gives: [[0.33, 0.33, 0.33] [0.33, 0.33, 0.33] [0.11, 0.11, 0.11]] Now if I wanted the sum of the logarithms of those probabilities, I could do s = (np.log(p)).sum((-2, -1)) Gives me s = -13.18 (6*log(1/3)+3*log(1/9))…
has answer: http://stackoverflow.com/a/47152116
linked to: http://stackoverflow.com/q/46256279
tagged with: scipy
linked to: http://stackoverflow.com/q/47130141
type: Question
tagged with: numpy
answer count: 1

http://stackoverflow.com/q/47068125
score: 1
tagged with: iframe
answer count: 1
tagged with: web-scraping
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47069916
linked to: http://stackoverflow.com/q/46026399
accepted answer: http://stackoverflow.com/a/47069916
has body: Through some searching I was able to figure out that what I was trying to scrape was inside of an iframe. Which was the main reason I always recieved None back as my results. I was able to start pulling in some data like the headers but when it comes to the data within the table i can only get the first result which is the number 1. Here is the code: from bs4 import BeautifulSoup from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get('http://www.nhl.com/stats/player?aggregate=1&amp;reportType=game&amp;dateFrom=2017-10-20&amp;dateTo=2017-10-31&amp;filter=gamesPlayed,gte,1&amp;sort=shots') html = driver.page_source driver.quit() soup = BeautifulSoup(html,"html.parser") stat_cat = soup.find('div',attrs={'class':'rt-tr'}) header = stat_cat.text.strip() stats = soup.find('div',attrs={'class':'rt-td'}) player_stats = stats.text.strip() print(header,player_stats) What I am trying to figure out is how to get the Player and his stats scraped from the second soup.find but it only returns the first rt-td result. Once I have all of the data I would then like to not just print it but to save it to a csv. Thanks for taking a look!
tagged with: python
has title: Scraping iFrame with python
type: AnsweredQuestion
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81253254
type: QuestionComment
has text: Did you not get an error because of csrf token ?
comment on: http://stackoverflow.com/q/47148676
score: 0
type: Comment

http://stackoverflow.com/q/47079980
tagged with: excel
answer count: 2
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/81109058
downvote count: 0
has answer: http://stackoverflow.com/a/63957658
has comment: http://stackoverflow.com/comment/81109387
upvote count: 1
has body: I want to add an empty row to all of my excel files using python pandas. I leave you an example so you can understand. I have this: Excel example And I want to add this row before name and city: Example I need to do that, but not opening the excels files cause this is just a small example of what I really need. Thanks!
has title: Add empty row in excel using python pandas
favorite count: 0
has comment: http://stackoverflow.com/comment/95756909
has answer: http://stackoverflow.com/a/47080091
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81109866
has comment: http://stackoverflow.com/comment/81109670
tagged with: python

deep-learning
tags question: http://stackoverflow.com/q/47131497
tags question: http://stackoverflow.com/q/47186474
tags question: http://stackoverflow.com/q/47167533
tags question: http://stackoverflow.com/q/47192771
tags question: http://stackoverflow.com/q/47174098
tags question: http://stackoverflow.com/q/47172108
tags question: http://stackoverflow.com/q/47193488
tags question: http://stackoverflow.com/q/47166795
tags question: http://stackoverflow.com/q/47118678
tags question: http://stackoverflow.com/q/47197885
tags question: http://stackoverflow.com/q/47189734
tags question: http://stackoverflow.com/q/47203019
type: Tag
tags question: http://stackoverflow.com/q/47076707
tags question: http://stackoverflow.com/q/47103581
tags question: http://stackoverflow.com/q/47072859
tags question: http://stackoverflow.com/q/47107589
tags question: http://stackoverflow.com/q/47198593
tags question: http://stackoverflow.com/q/47192902
tags question: http://stackoverflow.com/q/47125723
tags question: http://stackoverflow.com/q/47084179
tags question: http://stackoverflow.com/q/47179307
tags question: http://stackoverflow.com/q/47197989
tags question: http://stackoverflow.com/q/47113465
tags question: http://stackoverflow.com/q/47206714
tags question: http://stackoverflow.com/q/47212464
tags question: http://stackoverflow.com/q/47143718
tags question: http://stackoverflow.com/q/47120637
tags question: http://stackoverflow.com/q/47151562
tag name: deep-learning
tags question: http://stackoverflow.com/q/47205248
tags question: http://stackoverflow.com/q/47160937
tags question: http://stackoverflow.com/q/47092626
tags question: http://stackoverflow.com/q/47111691
tags question: http://stackoverflow.com/q/47185461
tags question: http://stackoverflow.com/q/47086810
tags question: http://stackoverflow.com/q/47193088
tags question: http://stackoverflow.com/q/47183159

http://stackoverflow.com/a/47125047
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47124831
has body: '+' joins two lists and since int and bool is not iterable, it displays error. Use append to add items to the list. def afunc(alist): i = 0 new_list = [] for i in range(len(alist)): if type(alist[i]) == str: new_list.append(alist[i].upper()) elif type(alist[i]) == bool: new_list.append(not alist[i]) elif type(alist[i]) == list: new_list.append('List') else: new_list.append(1) return new_list
score: 2
accepted answer of: http://stackoverflow.com/q/47124831
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47219705
has comment: http://stackoverflow.com/comment/81389709
has comment: http://stackoverflow.com/comment/81389779
has comment: http://stackoverflow.com/comment/81388952
has comment: http://stackoverflow.com/comment/81419842
has comment: http://stackoverflow.com/comment/81389879
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81391967
has body: Edit: Since I just understood your idea now, here is some code to put you on the right track: import ctypes SetCursorPos = ctypes.windll.user32.SetCursorPos mouse_event = ctypes.windll.user32.mouse_event class Aimer: def __init__(self, clicks): self.clicks = clicks def handle_click(self, x, y): SetCursorPos(x, y) for i in range(self.clicks): mouse_event(2, 0, 0, 0, 0) mouse_event(4, 0, 0, 0, 0) thompsonAimer = Aimer(clicks=17) m1a1Aimer = Aimer(clicks=2) Your code is correct, but you do not explain your motivation to turn this into a class. A class is often used when the various functions need to share some state. For instance, let's say we want to fix the number of clicks for all function calls, and the functions do not receive such an argument. You set self.clicks = clicks in the constructor, and then in left_click... instead of clicks you use self.clicks. The way it is now, it is pointless to store self.x, self.y and self.clicks because they are not being used. If you are a beginner, I would not recommend focusing on classes, though it is good to have an idea of how they work.
type: Answer
has comment: http://stackoverflow.com/comment/81389345
has comment: http://stackoverflow.com/comment/81389065
has comment: http://stackoverflow.com/comment/81389231
accepted answer of: http://stackoverflow.com/q/47219588
has comment: http://stackoverflow.com/comment/81430666
answers question: http://stackoverflow.com/q/47219588
type: AcceptedAnswer

http://stackoverflow.com/q/47211732
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47212008
score: 3
duplicate of: http://stackoverflow.com/q/3191478
duplicate of: http://stackoverflow.com/q/38412887
tagged with: python
type: AnsweredQuestion
has title: How to send an object over network
upvote count: 4
answer count: 3
has answer: http://stackoverflow.com/a/47212008
accepted answer: http://stackoverflow.com/a/47211933
has comment: http://stackoverflow.com/comment/81372923
has answer: http://stackoverflow.com/a/47211933
has answer: http://stackoverflow.com/a/47211762
has body: I need to send an object from a client to a server, but sockets only let you send bytes. How do I convert a custom object to bytes in Python 3.5 so I can send it via the socket?
downvote count: 1

http://stackoverflow.com/q/47184345
tagged with: pandas
tagged with: python
has title: dynamically assign name to key python
type: Question
has body: I'm not sure if the title describes the problem correctly, so take a look: def get_outer_edges(df, col): # first drop all zeros df[df.number != 0] #REPLACE NUMBER WITH col FROM ARGUMENTS ABOVE. .... df.number is the name of the column that I'd like to filter on. What I'd like to do is be able to say df.col instead of df.number but col is a variable containing the string 'number' how do I do this? def get_outer_edges(df, col): # first drop all zeros df[df.col != 0] Also, what is this type of programming called? not 'dynamic programming' it has a name though right?
answer count: 1
accepted answer: http://stackoverflow.com/a/47184443
has answer: http://stackoverflow.com/a/47184443
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47112381
tagged with: python
favorite count: 0
type: Question
tagged with: numpy
upvote count: 2
type: UnansweredQuestion
has title: Order legend in same order that the (last value of) the plots are displayed
has answer: http://stackoverflow.com/a/47114841
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/4700614
has body: I am adding plots to a figure within a loop, so when I add a legend to the figure, it is ordered in the same order that the plots were added. Instead I would like to order the legend, intuitively, as the plots are displayed in the figure. Some of the plots overlap and cross over each other in some cases, so when I say "as the plots are displayed in the figure", a more definitive definition would be to order the legends based on the last y-value of each plot. Here is my code as of now: heights = [3, 4] algos = ["NegaMax w/o PV", "PVS w/o PV", "NegaMax w/ PV", "PVS w/ PV"] # (H, B, Algo, Approx) temp = np.swapaxes(results, 2, 3) for i in range(temp.shape[0]): for j in range(temp.shape[2]): plt.plot(temp[i][-1][j], label="{} (H = {})".format(algos[j], heights[i])) plt.title("Num of Evaluations for each Algorithm at each Height with Maximum Branching Factor") plt.xlabel("\'Aprox\' Value") plt.ylabel("Number of Evaluations") plt.xticks(np.arange(7), np.arange(0, 301, 50)) plt.legend() plt.show() which displays this figure: Here is myresults numpy array.
score: 2
tagged with: matplotlib

http://stackoverflow.com/a/47116024
has comment: http://stackoverflow.com/comment/81182770
answers question: http://stackoverflow.com/q/47115669
has comment: http://stackoverflow.com/comment/81182910
type: Answer
has comment: http://stackoverflow.com/comment/81182911
score: 0
type: AcceptedAnswer
has body: You just need to update the self.__amount property of your coin object by rebinding it to the sum of __amount and self.__amount in your coin's set_amount method. def set_amount (self, __amount): self.__amount = self.__amount + __amount or a little more succinctly, def set_amount (self, __amount): self.__amount += __amount
accepted answer of: http://stackoverflow.com/q/47115669

http://stackoverflow.com/comment/81353217
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47201783
type: QuestionComment
has text: Please show what output you _want_ to get instead. The output is showing exactly the exception message you use in your `raise` statements.

http://stackoverflow.com/a/47160023
has body: If I have understood the question correctly, you are trying to get the string "SIRET" from the &lt;td&gt; node which changes dynamically. To do that you can use the following line of code : print(driver.find_element_by_xpath("//td[@class='reportKeyword']").get_attribute("innerHTML"))
has comment: http://stackoverflow.com/comment/81285197
has comment: http://stackoverflow.com/comment/81269950
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/81273212
has comment: http://stackoverflow.com/comment/81275016
answers question: http://stackoverflow.com/q/47159302

http://stackoverflow.com/comment/81327983
has text: I didn't say that the client was the problem. I asked about the query since that is the issue.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47168595

http://stackoverflow.com/q/47071447
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: raspberry-pi
type: UnansweredQuestion
has title: python-pyaudio: OSError: [Errno Input overflowed] -9981
tagged with: python
has body: i am using raspberry pi to record audio:press button to start recording and press button again to stop recording. but get error: Traceback (most recent call last): File "/home/pi/november03 fullscreenwithoutdots.py", line 225, in &lt;module&gt; record_audio(is_recording, button_pressed) File "/home/pi/november03 fullscreenwithoutdots.py", line 154, in record_audio data = stream.read(CHUNK) File "/usr/lib/python3/dist-packages/pyaudio.py", line 605, in read return pa.read_stream(self._stream, num_frames) OSError: [Errno Input overflowed] -9981 I searched online solutions but they are all not effective in my case, i run the example from official documentation successfully. who can help me? thank you very much. following are my codes: recording_started = False CHUNK = 8192 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 RECORD_SECONDS=5 WAVE_OUTPUT_FILENAME = "output.wav" p = pyaudio.PyAudio() stream = p.open( format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK ) frames = [] def record_audio(is_recording, button_pressed): CHUNK = 8192 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 RECORD_SECONDS=5 WAVE_OUTPUT_FILENAME = "output.wav" if is_recording: print (" Recoding") while True: if joystick.get_button(0) != 0 and is_recording and not button_pressed: print('stop inside') button_pressed = True break else: if joystick.get_button(0)!= 0 and button_pressed: button_pressed = False data = stream.read(CHUNK) frames.append(data) print('recorded') #detect button press if joystick.get_numbuttons() &gt;= 1 and joystick.get_button( 0 ) == 0 and button_pressed: button_pressed = False is_recording = not is_recording #start recording if is_recording: dotting = dotting + 1 #change background background = pygame.image.load(background_image2).convert() #start timer stopFlag = Event() timer = MyTimer(stopFlag,time.clock()) #timer.start() text2 = font.render('.', True, BLACK) screen.blit(background, (0,0)) stopFlag.set() #record, remaining here record_…
tagged with: audio
tagged with: pyaudio
tagged with: recording
answer count: 0

http://stackoverflow.com/a/47199474
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47199225
has comment: http://stackoverflow.com/comment/81350230
has comment: http://stackoverflow.com/comment/81349964
has comment: http://stackoverflow.com/comment/81350418
type: Answer
has comment: http://stackoverflow.com/comment/81348820
accepted answer of: http://stackoverflow.com/q/47199225
has body: You need to export the function before you start the python program: export -f my_func python foo.py Well, the above example might not work if the system's default shell (/bin/sh) is not bash. To circumvent this, you may use subprocess call like this: $ function foo() { echo "bar" ; } $ export -f foo $ cat foo.py import subprocess subprocess.call(['bash', '-c', 'foo']) $ python foo.py bar Alternative: I would put the function into a lib file, let's say: # /usr/share/my_lib/my_lib.sh function my_func() { # do something } Then I would expose the function via a script in PATH: #!/bin/bash # /usr/local/bin/my_prog source /usr/lib/my_lib/my_lib.sh my_func "$1" "$2" In Python you would just: subprocess.call(['/usr/local/bin/my_prog', 'a', 'b']) Btw: If you don't need that function somewhere else, you can just put it directly into /usr/local/bin/my_prog.
downvote count: 0
has comment: http://stackoverflow.com/comment/81351483
score: 1

http://stackoverflow.com/q/47139839
answer count: 1
has body: What is the most elegant way in sympy to construct a matrix from a repeated vector. That is, given a row vector V = [ v00, v01, v02 ] the goal is to find an operation op such that M = op(V, N) delivers a matrix M consisting of N rows which are equal to V, i.e. / v00 v01 v02 \ | v00 v01 v02 | M = | ... | | | \ v00 v01 v02 / similar to what can be achieved by tile in numpy.
favorite count: 0
has title: sympy: Vector/Matrix repetition
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47148727
tagged with: matrix
score: 1
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/47148727
tagged with: sympy
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/81392052
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47220781
has text: I am dumping it right now. I don't to how to set and organize data as per sample.

http://stackoverflow.com/comment/81177490
has text: Also, clarify "setup.cfg is configured to invoke pytest" sentence, please. Why is it setup.cfg, not setup.py? Do you use pytest-runner or some other technique to run the tests on `python setup.py test`? How exactly is your project configured?
score: 0
comment on: http://stackoverflow.com/q/47095053
type: Comment
type: QuestionComment

module
tags question: http://stackoverflow.com/q/47119468
type: Tag
tags question: http://stackoverflow.com/q/47103890
tags question: http://stackoverflow.com/q/47171293
tags question: http://stackoverflow.com/q/47128135
tags question: http://stackoverflow.com/q/47193079
tag name: module
tags question: http://stackoverflow.com/q/47134336
tags question: http://stackoverflow.com/q/47211167
tags question: http://stackoverflow.com/q/47179466

http://stackoverflow.com/comment/81247039
type: Comment
type: QuestionComment
has text: Read up on this answer [link](https://stackoverflow.com/questions/17246260/python-readlines-usage-and-efficient-practice-for-reading)
comment on: http://stackoverflow.com/q/47148451
score: 1

http://stackoverflow.com/comment/87043584
comment on: http://stackoverflow.com/q/47081088
score: 1
type: Comment
type: QuestionComment
has text: Did you manage to do this? I also want to do something like this.

http://stackoverflow.com/q/47105363
answer count: 0
has comment: http://stackoverflow.com/comment/81161376
has comment: http://stackoverflow.com/comment/81162769
has comment: http://stackoverflow.com/comment/81161458
has comment: http://stackoverflow.com/comment/81162129
tagged with: fat
has comment: http://stackoverflow.com/comment/81161515
has comment: http://stackoverflow.com/comment/81161424
type: Question
type: UnansweredQuestion
has body: I am trying to find out, from a provided disc image things like, how many bytes does the boot block occupy, how many bytes are there in each sector, and how many sectors are there in each cluster(each allocation unit)? I need to write code in python that will tell me these things and I have been searching for a library of python commands that might help me, namely one being the import os If anyone has any suggestions to other libraries i'd greatly appreciate or any hints to start with, I am completely lost.
tagged with: python
has title: I am trying to read entries from the boot sector of a disc image that was partitioned with a FAT16 file system
has comment: http://stackoverflow.com/comment/81161654
tagged with: fat16
score: 0
has comment: http://stackoverflow.com/comment/81161341

http://stackoverflow.com/a/47135469
type: Answer
answers question: http://stackoverflow.com/q/47135132
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81221245
upvote count: 1
has body: Because you are adding a dimension when you put the boolean arrays in lists using square brackets: [a &lt;= 1] Note: In [10]: np.array([a &lt;= 1]) Out[10]: array([[[ True, True, True, True, True, True, True], [ True, True, True, True, True, True, True], [ True, True, True, True, True, True, True], [ True, True, True, True, True, True, True], [ True, True, True, True, True, True, True], [ True, True, True, True, True, True, True]]], dtype=bool) In [11]: np.array([a &lt;= 1]).shape Out[11]: (1, 6, 7) Just use: b = np.logical_and(a &lt;= 1, a &gt;= 0)
accepted answer of: http://stackoverflow.com/q/47135132

http://stackoverflow.com/comment/81353168
type: QuestionComment
score: 0
has text: Restarted spyder and it is functioning. should have done that first, I am pretty new to coding. sorry
comment on: http://stackoverflow.com/q/47201842
type: Comment

pyspark
tags question: http://stackoverflow.com/q/47202586
tags question: http://stackoverflow.com/q/47212841
tags question: http://stackoverflow.com/q/47105138
tags question: http://stackoverflow.com/q/47177669
tags question: http://stackoverflow.com/q/47100325
tags question: http://stackoverflow.com/q/47198678
tags question: http://stackoverflow.com/q/47213631
tags question: http://stackoverflow.com/q/47091529
tags question: http://stackoverflow.com/q/47081088
tags question: http://stackoverflow.com/q/47099332
tags question: http://stackoverflow.com/q/47176888
tags question: http://stackoverflow.com/q/47116294
tags question: http://stackoverflow.com/q/47146275
tags question: http://stackoverflow.com/q/47222505
tags question: http://stackoverflow.com/q/47209168
tags question: http://stackoverflow.com/q/47173286
tags question: http://stackoverflow.com/q/47177112
tags question: http://stackoverflow.com/q/47181025
tags question: http://stackoverflow.com/q/47150234
tags question: http://stackoverflow.com/q/47153151
tags question: http://stackoverflow.com/q/47102378
type: Tag
tags question: http://stackoverflow.com/q/47090432
tags question: http://stackoverflow.com/q/47211837
tags question: http://stackoverflow.com/q/47164588
tags question: http://stackoverflow.com/q/47198506
tags question: http://stackoverflow.com/q/47167891
tags question: http://stackoverflow.com/q/47221186
tags question: http://stackoverflow.com/q/47073414
tags question: http://stackoverflow.com/q/47174686
tag name: pyspark
tags question: http://stackoverflow.com/q/47111737
tags question: http://stackoverflow.com/q/47074909
tags question: http://stackoverflow.com/q/47083219
tags question: http://stackoverflow.com/q/47176607
tags question: http://stackoverflow.com/q/47177586

http://stackoverflow.com/comment/81183692
comment on: http://stackoverflow.com/q/47112895
has text: cant you just use `np.ones()` as cov?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81175587
type: AnswerComment
comment on: http://stackoverflow.com/a/47112782
score: 0
type: Comment
has text: @Eyshika If `a = np.ones((10, 1))` then you can either change the way it is defined, i.e., `a = np.ones(10)` to make it 1D or in my solution replace `a` with `[x[0] for x in a]`.

http://stackoverflow.com/q/47194806
answer count: 0
downvote count: 0
tagged with: pandas
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81370340
has title: pandas inconsistency in concat behavior
has comment: http://stackoverflow.com/comment/81339163
tagged with: valueerror
has body: The following works: df1 = pd.DataFrame([[1, 2, 3]], columns=['a', 'b', 'c']) df2 = pd.DataFrame(columns=['a', 'b', 'c']) pd.concat([df1, df2]) as of course it should. However, the following ought to be exactly the same, and yet it doesn't work: od3 = OrderedDict([('a', [1]), ('b', [2]), ('c', [3])]) od4 = OrderedDict([('a', []), ('b', []), ('c', [])]) df3 = pd.DataFrame(od3) df4 = pd.DataFrame(od4) pd.concat([df3, df4]) This block of code produces ValueError: Shape of passed values is (3, 1), indices imply (3, 0) Oddly, these all do work: pd.concat([df3.drop_duplicates(), df4.drop_duplicates()]) pd.concat([df3, df4.drop_duplicates()]) pd.concat([df3.drop_duplicates(), df4]) although these result in the dataframe having float64s instead of int64s. So what's going on? It seems that Pandas stores df3 differently from df1 even though they appear identical, and the .drop_duplicates() method converts df3 to a canonical form.(?) Any thoughts?
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/21287624
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81339142
has comment: http://stackoverflow.com/comment/81339194
tagged with: python
has comment: http://stackoverflow.com/comment/81338592
has comment: http://stackoverflow.com/comment/81339038

http://stackoverflow.com/comment/81463261
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47203620
has text: That's because the list that you've provided (or rather, the list that's in your file) _is_ the list that the csv file is writing out. Try testing `lines[0]` or `lines[3]` to see how the list looks after you read it.

opencv
tags question: http://stackoverflow.com/q/47114360
type: Tag
tags question: http://stackoverflow.com/q/47172219
tags question: http://stackoverflow.com/q/47169712
tags question: http://stackoverflow.com/q/47096480
tags question: http://stackoverflow.com/q/47113029
tags question: http://stackoverflow.com/q/47112642
tags question: http://stackoverflow.com/q/47078210
tags question: http://stackoverflow.com/q/47162334
tags question: http://stackoverflow.com/q/47172770
tags question: http://stackoverflow.com/q/47129926
tags question: http://stackoverflow.com/q/47074938
tags question: http://stackoverflow.com/q/47154989
tags question: http://stackoverflow.com/q/47126370
tags question: http://stackoverflow.com/q/47116309
tags question: http://stackoverflow.com/q/47115721
tags question: http://stackoverflow.com/q/47219727
tags question: http://stackoverflow.com/q/47072355
tags question: http://stackoverflow.com/q/47192793
tags question: http://stackoverflow.com/q/47090354
tags question: http://stackoverflow.com/q/47169685
tags question: http://stackoverflow.com/q/47085909
tags question: http://stackoverflow.com/q/47156091
tags question: http://stackoverflow.com/q/47161287
tags question: http://stackoverflow.com/q/47169543
tags question: http://stackoverflow.com/q/47221143
tags question: http://stackoverflow.com/q/47144719
tags question: http://stackoverflow.com/q/47206902
tags question: http://stackoverflow.com/q/47111379
tags question: http://stackoverflow.com/q/47206699
tags question: http://stackoverflow.com/q/47192709
tags question: http://stackoverflow.com/q/47165847
tags question: http://stackoverflow.com/q/47122837
tags question: http://stackoverflow.com/q/47180020
tags question: http://stackoverflow.com/q/47144382
tags question: http://stackoverflow.com/q/47097267
tags question: http://stackoverflow.com/q/47109980
tags question: http://stackoverflow.com/q/47129625
tags question: http://stackoverflow.com/q/47114707
tags question: http://stackoverflow.com/q/47129012
tags question: http://stackoverflow.com/q/47203243
tags question: http://stackoverflow.com/q/47178948
tags question: http://stackoverflow.com/q/47118488
tags question: http://stackoverflow.com/q/47099472
tags question: http://stackoverflow.com/q/47072498
tags question: http://stackoverflow.com/q/47198593
tags question: http://stackoverflow.com/q/47160523
tags question: http://stackoverflow.com/q/47094930
tags question: http://stackoverflow.com/q/47081309
tags question: http://stackoverflow.com/q/47087528
tags question: http://stackoverflow.com/q/47120507
tags question: http://stackoverflow.com/q/47189785
tags question: http://stackoverflow.com/q/47190372
tags question: http://stackoverflow.com/q/47153697
tag name: opencv
tags question: http://stackoverflow.com/q/47156711
tags question: http://stackoverflow.com/q/47132638
tags question: http://stackoverflow.com/q/47179464
tags question: http://stackoverflow.com/q/47120064
tags question: http://stackoverflow.com/q/47113341
tags question: http://stackoverflow.com/q/47117771
tags question: http://stackoverflow.com/q/47213110

http://stackoverflow.com/a/47129496
has body: You end up with range (0,4) which is four elements
score: 0
answers question: http://stackoverflow.com/q/47129403
type: Answer

http://stackoverflow.com/comment/81330929
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47190719
has text: I don't understand, what do you mean "Whenever 'run' is entered, the program reruns the function"??? You specifically call the function twice...

http://stackoverflow.com/comment/81300914
type: Comment
comment on: http://stackoverflow.com/a/47173143
type: AnswerComment
has text: OP accepted this answer for whatever reason despite my answer being faster... guess all OPs don't care about timings ;)
score: 1

http://stackoverflow.com/a/47106268
accepted answer of: http://stackoverflow.com/q/47106199
type: AcceptedAnswer
has body: You could use np.repeat to get an array with the right number of users: In [38]: [np.repeat(df.columns, row) for row in df.values] Out[38]: [Index(['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'C'], dtype='object'), Index(['A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C'], dtype='object'), Index(['B', 'B', 'C'], dtype='object')] And then permute them: In [39]: [np.random.permutation(np.repeat(df.columns, row)) for row in df.values] Out[39]: [array(['C', 'A', 'A', 'A', 'A', 'A', 'B', 'A', 'A', 'A', 'A'], dtype=object), array(['A', 'B', 'C', 'C', 'B', 'C', 'B', 'C', 'C', 'B', 'B', 'C', 'C', 'C', 'B', 'B'], dtype=object), array(['B', 'C', 'B'], dtype=object)] and then you could call pd.Series on each array if you wanted.
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47106199
score: 1
has comment: http://stackoverflow.com/comment/81173397

http://stackoverflow.com/a/47097105
has comment: http://stackoverflow.com/comment/81148055
type: AcceptedAnswer
score: 10
upvote count: 10
type: Answer
accepted answer of: http://stackoverflow.com/q/47096543
has body: You can sort your XML with ElementTree. In my example I sort it first by the tag-name and second by the value of the attribut 'name' and the child elements by tag-name and the value of the attribut 'desc' import xml.etree.ElementTree as ET tree = ET.ElementTree(ET.fromstring(xmlstr)) root = tree.getroot() # sort the first layer root[:] = sorted(root, key=lambda child: (child.tag,child.get('name'))) # sort the second layer for c in root: c[:] = sorted(c, key=lambda child: (child.tag,child.get('desc'))) xmlstr = ET.tostring(root, encoding="utf-8", method="xml") print(xmlstr.decode("utf-8")) this prints &lt;data&gt; &lt;e1 id="1" name="name1"&gt; &lt;e11 desc="desc4" num="num4" /&gt; &lt;e12 desc="desc12" num="num12" /&gt; &lt;/e1&gt; &lt;e2 id="2" name="name2"&gt; &lt;e11 desc="desc1" num="num1" /&gt; &lt;/e2&gt; &lt;e2 id="3" name="name3"&gt; &lt;e11 desc="desc1" num="num1" /&gt; &lt;e12 desc="desc11" num="num12" /&gt; &lt;e12 desc="desc12" num="num12" /&gt; &lt;/e2&gt; &lt;/data&gt;
answers question: http://stackoverflow.com/q/47096543
downvote count: 0

variables
tags question: http://stackoverflow.com/q/47110056
tag name: variables
tags question: http://stackoverflow.com/q/47129222
tags question: http://stackoverflow.com/q/47211782
tags question: http://stackoverflow.com/q/47180910
tags question: http://stackoverflow.com/q/47180633
tags question: http://stackoverflow.com/q/47113652
tags question: http://stackoverflow.com/q/47212687
tags question: http://stackoverflow.com/q/47119450
tags question: http://stackoverflow.com/q/47156698
tags question: http://stackoverflow.com/q/47180505
type: Tag
tags question: http://stackoverflow.com/q/47102397
tags question: http://stackoverflow.com/q/47190719
tags question: http://stackoverflow.com/q/47142567
tags question: http://stackoverflow.com/q/47158869

batch-normalization
tag name: batch-normalization
tags question: http://stackoverflow.com/q/47143521
type: Tag
tags question: http://stackoverflow.com/q/47197885

http://stackoverflow.com/a/47218297
score: 0
type: Answer
has body: a = ['This', 'containing', 'many'] string1 = "kappa pride pogchamp containing this string this many words" Break is better option but that solution is already there so i wanted to show you can do in with slice too: print("".join([item for item in string1.split() if item in a][:1])) Above list comprehension is same as: new=[] for item in string1.split(): if item in a: new.append(item) print("".join(new[:1]))
answers question: http://stackoverflow.com/q/47216834

http://stackoverflow.com/comment/81209328
comment on: http://stackoverflow.com/a/47125599
score: 0
has text: @MaheshKaria Can you help me to understand how you concluded `Airbnb has identified your scrapper`?
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81239130
has text: Hey @smassey your suggest code work fine but I want also 2017-10-28 04:39:25,54 these two fields with other fields.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47134052

http://stackoverflow.com/a/47100932
type: Answer
has body: I'm not sure about it, but I think that you would be able to use the find_elements_by_name('examResult.AnswerId') function which would return you a list of all the elements with the name 'examResult.AnswerId' in a list and then iterate over this list. Although it would be better if the elements had different id's, but I think this way will also do the job.
answers question: http://stackoverflow.com/q/47100760
score: 0

http://stackoverflow.com/a/47173318
has body: Just do print(dir(ListView)), or print dir(ListView) if you are using Python 2
type: Answer
accepted answer of: http://stackoverflow.com/q/47173220
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47173220
score: 0

http://stackoverflow.com/comment/81263806
score: 0
has text: I have included the lines mentioned in the code.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47072881

http://stackoverflow.com/comment/81210781
comment on: http://stackoverflow.com/a/47129800
score: 0
type: AnswerComment
type: Comment
has text: @Justin all the options are spelled out in that post.

http://stackoverflow.com/a/47141118
answers question: http://stackoverflow.com/q/47140570
has body: There is nothing to do with __missing__ here: &gt;&gt;&gt; Coordinate(x='6') {'x': '6'} &gt;&gt;&gt; dict(x='6') {'x': '6'} This is just calling the dict initializer, because you inherit dict and you don't override __init__. The effect of defining __missing__ is shown below: &gt;&gt;&gt; c = Coordinate(x='6') &gt;&gt;&gt; c['new_key'] 'new_key' # returns the key, instead of raising KeyError &gt;&gt;&gt; c # note: does not set it in the dict {'x': '6'}
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81232835
accepted answer of: http://stackoverflow.com/q/47140570
type: Answer

http://stackoverflow.com/comment/81154167
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47102036
score: 0
has text: `try`/`except` and on exception, `pass`.

http://stackoverflow.com/comment/81310390
score: 0
type: Comment
type: QuestionComment
has text: Use [global variable](https://www.python-course.eu/python3_global_vs_local_variables.php)?
comment on: http://stackoverflow.com/q/47180753

http://stackoverflow.com/q/47212737
type: Question
has title: Celery not processing tasks from RabbitMQ
has answer: http://stackoverflow.com/a/47229457
answer count: 2
has comment: http://stackoverflow.com/comment/81377723
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47235761
tagged with: python
has body: I have a Celery 4.1 worker configured to process tasks from a queue called "longjobs", using RabbitMQ as my messaging backend. My Celery configuration and workers are managed through a Django 1.11 project. Nothing throws any errors, but tasks launched from my Django application are never picked up by my worker. My celery.py file looks like: from __future__ import absolute_import import os import sys from celery import Celery from celery._state import _set_current_app import django app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') _set_current_app(app) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.settings') sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../myproject'))) django.setup() from django.conf import settings app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) My Django Celery settings are: CELERY_IGNORE_RESULT = False CELERY_TRACK_STARTED = True CELERY_IMPORTS = ( 'myproject.myapp.tasks', ) CELERY_RESULT_BACKEND = 'amqp' CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml'] CELERY_TASK_SERIALIZER = 'pickle' CELERY_RESULT_SERIALIZER = 'pickle' CELERY_RESULT_PERSISTENT = True CELERY_ALWAYS_EAGER = False CELERY_ROUTES = { 'mytask': {'queue': 'longjobs'}, } CELERY_WORKER_PREFETCH_MULTIPLIER = CELERYD_PREFETCH_MULTIPLIER = 1 CELERY_SEND_TASK_ERROR_EMAILS = True CELERY_ACKS_LATE = True CELERY_TASK_RESULT_EXPIRES = 360000 And I launch my worker with: celery worker -A myproject -l info -n longjobs@%h -Q longjobs and in its log file, I see: [2017-11-09 16:51:03,218: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672/myproject [2017-11-09 16:51:03,655: INFO/MainProcess] mingle: searching for neighbors [2017-11-09 16:51:05,441: INFO/MainProcess] mingle: all alone [2017-11-09 16:51:06,162: INFO/MainProcess] longjobs@localhost ready. indicating that the worker is successfully connecting to RabbitMQ with the correct virtual host and queue name. I'm using F…
tagged with: rabbitmq
tagged with: django
has comment: http://stackoverflow.com/comment/81375178
downvote count: 0
score: 1
upvote count: 1
tagged with: celery
favorite count: 0

pyopenssl
tags question: http://stackoverflow.com/q/47197083
tag name: pyopenssl
type: Tag

http://stackoverflow.com/a/47159721
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47159644
answers question: http://stackoverflow.com/q/47159644
type: Answer
has comment: http://stackoverflow.com/comment/81268971
downvote count: 0
has body: You need to pass the parameter c to the function display1. So your display1 function should be like as follows def display1(c): print(c) And while calling you need to give c to display1 function as a parameter as follows display.display1(c)

http://stackoverflow.com/a/50974917
answers question: http://stackoverflow.com/q/47112889
accepted answer of: http://stackoverflow.com/q/47112889
score: 0
type: Answer
has body: As per the Django documentation dispatch method should return a HTTP response. dispatch(request, *args, **kwargs) The view part of the view – the method that accepts a request argument plus arguments, and returns a HTTP response. Explanation based on your code. From the source code of Django View class, def dispatch(self, request, *args, **kwargs): # Try to dispatch to the right method; if a method doesn't exist, # defer to the error handler. Also defer to the error handler if the # request method isn't on the approved list. if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed return handler(request, *args, **kwargs) dispatch method is not only delegates the requested method to the corresponding handler it also returns back the handler response. i.e., In this line. return handler(request, *args, **kwargs) In your case you are invoking super(CourseModuleUpdateView, self).dispatch(request, *args, **kwargs) in your dispatch method, this will invoke the superclass's dispatch method(i.e., View class dispatch method). Since your requested http method is GET after executing the following line on the dispatch method handler = getattr(self, request.method.lower(), self.http_method_not_allowed) handler will be assigned to get. So in this case it is roughly equivalent to def dispatch(self, request, *args, **kwargs): return get(request, *args, **kwargs) This get will invoke the get method in your CourseModuleUpdateView class i.e., def get(self, request, *args, **kwargs): formset = self.get_formset() return self.render_to_response({'course': self.course, 'formset': formset}) Which returns a valid HTTP response. This response will reach the place where the get method is called. i.e., Inside Views dispatch method. And from there it will return the response from where it is invoked i.e., super(CourseModuleUpdateView, self).dispatch(request, *args, **kwargs). Si…
type: AcceptedAnswer

http://stackoverflow.com/comment/129518639
type: AnswerComment
comment on: http://stackoverflow.com/a/47177002
has text: if spark does the aggregation in the partitions first before shuffling, then why in skew cases many suggest to use salt in aggregation? example: df.groupBy('salt',the_keys).agg(target).groupBy(the_keys).agg(target)
score: 0
type: Comment

http://stackoverflow.com/a/47077249
has body: You could also get all the downloaded scripts via the window.performance API : scripts = driver.execute_script(""" return window.performance.getEntriesByType("resource") .filter(e =&gt; e.initiatorType === 'script') .map(e =&gt; e.name); """) print(scripts)
answers question: http://stackoverflow.com/q/47076246
type: Answer
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81104695
has comment: http://stackoverflow.com/comment/81104294
accepted answer of: http://stackoverflow.com/q/47076246

http://stackoverflow.com/a/47116384
upvote count: 4
has comment: http://stackoverflow.com/comment/81182861
has body: well, this isn't a great answer but it looks like I can modify the answer in https://stackoverflow.com/a/4828492/44330 --- essentially overriding __setattr__ and __delattr__ to meet my needs at least against accidental modification. (but not as nice as subclassing tuple) class Point(object): __slots__ = ('x','y','__weakref__') def __init__(self, x, y): object.__setattr__(self, "x", x) object.__setattr__(self, "y", y) def __setattr__(self, *args): raise TypeError def __delattr__(self, *args): raise TypeError def __eq__(self, other): return self.x == other.x and self.y == other.y def __hash__(self): return self.x.__hash__() * 31 + self.y.__hash__() Implementing @Elazar's idea: class Point(object): __slots__ = ('x','y','__weakref__') def __new__(cls, x, y): thing = object.__new__(cls) object.__setattr__(thing, "x", x) object.__setattr__(thing, "y", y) return thing def __setattr__(self, *args): raise TypeError def __delattr__(self, *args): raise TypeError def __eq__(self, other): return self.x == other.x and self.y == other.y def __hash__(self): return self.x.__hash__() * 31 + self.y.__hash__()
has comment: http://stackoverflow.com/comment/81182979
has comment: http://stackoverflow.com/comment/81276908
has comment: http://stackoverflow.com/comment/81183049
has comment: http://stackoverflow.com/comment/81182813
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47116225
has comment: http://stackoverflow.com/comment/81279197
type: Answer
has comment: http://stackoverflow.com/comment/81182751
accepted answer of: http://stackoverflow.com/q/47116225
has comment: http://stackoverflow.com/comment/81279149
score: 4

http://stackoverflow.com/q/47176450
type: AnsweredQuestion
tagged with: python-2.7
has title: Read osx notification in Python
possible better answer: http://stackoverflow.com/a/73134127
answer count: 2
tagged with: automation
has answer: http://stackoverflow.com/a/73134127
score: 0
type: Question
accepted answer: http://stackoverflow.com/a/47179744
has body: I need to launch an application on reading a Notification center notification on osx. Is there any python library for reading the notification center notifications?
has answer: http://stackoverflow.com/a/47179744
tagged with: python
tagged with: macos
linked to: http://stackoverflow.com/q/2940916

http://stackoverflow.com/a/47215358
upvote count: 4
has comment: http://stackoverflow.com/comment/81380550
has comment: http://stackoverflow.com/comment/81380334
has comment: http://stackoverflow.com/comment/81380198
downvote count: 0
score: 4
has body: def unroll(d): for k, v in d.items(): if isinstance(v, dict): for l in unroll(v): yield [k] + l else: yield [v] You'd call it like list(unroll(d)) For your input I got [[1, 3, 1, 32], [1, 3, 2, 12], [1, 4, 66], [2, 3, 1], [2, 5, 2]]
type: Answer
answers question: http://stackoverflow.com/q/47215270

http://stackoverflow.com/q/47123335
upvote count: 1
has body: I Have designed 2 ui with Qt Designer and I import both of them to a new .py file which I use as the Main program. One is the Main window and the other is a custom popup Dialog. I was able to run the MainWindow without any trouble. I'm also able to Run the Popup (QDialog, Modal) but once it´s displayed, the widgets does not respond Sorry for the question, but after looking online I just can´t get this to work and the big problem is that the compiler does not show me any error. The Code runs without a hassle, but the widgets won´t update/respond I'm sorry if the Code is a bit messy, I learned Python last Month and PyQT last week. Here is the code of the Program: import sys import _pickle as cPickle from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QWidget, QAction, QTabWidget,QVBoxLayout from PyQt5 import QtCore, QtGui, QtWidgets from PedidoUI import Ui_MainWindow from Emergente1 import Ui_Dialog #I define a PopUp Dialog class PopUp(Ui_Dialog): """docstring for PopUp""" def __init__(self,Dialog): Ui_Dialog.__init__(self) self.setupUi(Dialog) self.botonAceptar.clicked.connect(self.AgregarItems) #It should add the string "Prueba" as an Item to the list. def AgregarItems(self): self.listWidget.addItem("Prueba") #This is the Main Class class ProgramaPedido(Ui_MainWindow): def __init__(self, MainWindow): Ui_MainWindow.__init__(self) self.setupUi(MainWindow) self.Dialog = QtWidgets.QDialog() self.ui = PopUp(self.Dialog) self.ui.setupUi(self.Dialog) self.toolButton.clicked.connect(self.open_dialog) #I call the PopUp def open_dialog(self): self.Dialog.exec_() if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() prog = ProgramaPedido(MainWindow) MainWindow.show() sys.exit(app.exec_()) Here is the UI of MainWindow: from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(642, 912) MainWindow.setTabShape(QtWid…
has title: Widgets not responding on a PopUp Window
has comment: http://stackoverflow.com/comment/81196561
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81196531
has comment: http://stackoverflow.com/comment/81199763
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47123682
has comment: http://stackoverflow.com/comment/81196955
has comment: http://stackoverflow.com/comment/81196786
has answer: http://stackoverflow.com/a/47123682
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81196731
tagged with: pyqt
answer count: 1
downvote count: 0
tagged with: pyqt5

http://stackoverflow.com/q/47084540
score: 1
upvote count: 1
has body: According to the documentation, I can create a python environment by incorporating dependencies specified in a file named environment.yml conda env create -f environment.yml I can generate the yml by conda env export &gt; environment.yml In the file I see a spot for pip installs: - pip: - backports.shutil-get-terminal-size==1.0.0 - conda==4.3.30 - conda-build==3.0.22 - conda-verify==2.0.0 - et-xmlfile==1.0.1 - ipython-genutils==0.2.0 - jupyter-client==5.1.0 - jupyter-console==5.2.0 - jupyter-core==4.3.0 - jupyterlab-launcher==0.4.0 - nb-conda-kernels==2.1.0 - prompt-toolkit==1.0.15 - ruamel-yaml==0.11.14 - tables==3.4.2 However, I need to include a dependency on a library from a local gitlab server. How must I specify that in this yml file?
favorite count: 0
type: Question
tagged with: python
type: UnansweredQuestion
tagged with: conda
has title: Specify a dependency from a local gitlab server in an environment.yml file
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/81245916
type: Comment
has text: Yes, you don't close them ever.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47147768

http://stackoverflow.com/comment/81317859
type: QuestionComment
comment on: http://stackoverflow.com/q/47184192
score: 2
type: Comment
has text: Are you asking if there's another way you can get the instance's `name` out that doesn't use `@property`? I don't really understand your question.

django-rest-framework
tags question: http://stackoverflow.com/q/47203908
tags question: http://stackoverflow.com/q/47173486
tags question: http://stackoverflow.com/q/47170009
tags question: http://stackoverflow.com/q/47220070
tags question: http://stackoverflow.com/q/47222697
tags question: http://stackoverflow.com/q/47119879
tags question: http://stackoverflow.com/q/47072224
tags question: http://stackoverflow.com/q/47186526
tags question: http://stackoverflow.com/q/47153700
tags question: http://stackoverflow.com/q/47171763
tags question: http://stackoverflow.com/q/47220391
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/47102090
tags question: http://stackoverflow.com/q/47134307
tags question: http://stackoverflow.com/q/47170853
tags question: http://stackoverflow.com/q/47126641
tags question: http://stackoverflow.com/q/47153937
tags question: http://stackoverflow.com/q/47217438
tags question: http://stackoverflow.com/q/47199089
tags question: http://stackoverflow.com/q/47218977
tags question: http://stackoverflow.com/q/47088201
tags question: http://stackoverflow.com/q/47111898
tags question: http://stackoverflow.com/q/47065170
tags question: http://stackoverflow.com/q/47141998
tags question: http://stackoverflow.com/q/47134646
tags question: http://stackoverflow.com/q/47073515
tags question: http://stackoverflow.com/q/47196777
type: Tag
tags question: http://stackoverflow.com/q/47137382
tags question: http://stackoverflow.com/q/47205238
tags question: http://stackoverflow.com/q/47170878
tags question: http://stackoverflow.com/q/47184231
tags question: http://stackoverflow.com/q/47130739
tags question: http://stackoverflow.com/q/47073591
tags question: http://stackoverflow.com/q/47092023
tags question: http://stackoverflow.com/q/47139873
tags question: http://stackoverflow.com/q/47185334
tags question: http://stackoverflow.com/q/47136754
tags question: http://stackoverflow.com/q/47148894
tags question: http://stackoverflow.com/q/47173483
tags question: http://stackoverflow.com/q/47141225
tags question: http://stackoverflow.com/q/47208430
tags question: http://stackoverflow.com/q/47119569
tags question: http://stackoverflow.com/q/47186027
tags question: http://stackoverflow.com/q/47206601
tags question: http://stackoverflow.com/q/47094872
tags question: http://stackoverflow.com/q/47066083
tags question: http://stackoverflow.com/q/47154404
tags question: http://stackoverflow.com/q/47181946
tags question: http://stackoverflow.com/q/47199759
tags question: http://stackoverflow.com/q/47207996

http://stackoverflow.com/a/47145326
score: 14
answers question: http://stackoverflow.com/q/47144624
has body: You can try installing the C compiler and python development files by running apt-get install build-essential python3-dev and then try to install uwsgi link to relevant documentation
type: Answer
upvote count: 14
has comment: http://stackoverflow.com/comment/81251302
downvote count: 0

http://stackoverflow.com/comment/123762985
type: Comment
type: AnswerComment
has text: to quote effbot: "[...] Note that to pass the `from` option as a keyword argument, you need to add a trailing underscore (`from` is a reserved keyword in Python)." -- i.e. use `from_=100`
score: 1
comment on: http://stackoverflow.com/a/47097915

http://stackoverflow.com/comment/81228117
has text: Try manually doing `root.update()` right after you call `.configure()`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47127585
type: QuestionComment

http://stackoverflow.com/q/47192165
tagged with: python-3.x
has body: I am very new to coding and I am trying to code in Python 3 the following: How many students?: 4 How many units?: 3 What is the name of student 1?: John What did John get in unit 1?: 34 34 out of 100 is a Fail. What did John get in unit 2?: 67 67 out of 100 is a Credit. What did John get in unit 3?: 52 52 out of 100 is a Pass. On average, John is getting a Pass. Then after it does this for all 4 students, the program has to say: The top score is (Student Name) with an average score of (Student score). This is what I have so far. How can I get it to loop through the students information individually as above? Mine comes out one after another. numStudent = int (input('Please enter number of students: ')) numUnit = int(input('Please enter the number of units for your course: ')) for i in range(numStudent): studentName = input('Please enter students first name: ') for j in range(numUnit): unitmark = int(input('what did' + ' ' + studentName + ' ' + 'get for unit:')) def calculateGrade(unitmark): if unitmark &lt;= 49: Print(unitmark,"out of 100 You are failing") elif unitmark &lt;= 59: return(unitmark,"out of 100 is a Pass") elif unitmark &lt;=69: return(unitmark, "out of 100 is a Credit") elif unitmark &lt;= 79: return(unitmark, "out of 100 is a Distinction") elif unitmark &lt;=100: return(unitmark, "out of 100 is a High Distinction") print(calculateGrade(unitmark)) totalGrade = numUnit + unitmark averageGrade = totalGrade / 100 print(round (averageGrade, 7))
has comment: http://stackoverflow.com/comment/81333801
type: UnansweredQuestion
has title: Need help trying to code in Python 3
has comment: http://stackoverflow.com/comment/81416210
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81416489
has answer: http://stackoverflow.com/a/47233104
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/81416177
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81333712

http://stackoverflow.com/q/47166372
favorite count: 0
has title: Jupyter Pandas DataFrame - reading column values
has body: I have a snippet of python code that reads the values for SQL columns for a given row. The snippet below simply iterates thru columns within a DataFrame context and appends the numeric values to an array. If i print out the value of each column, the output looks correct. However, if I print out the final array, then i see weird formatting (metadata). values = [] for i in range(len(columns)): val = df[columns[i]]; values.append(val) #print(values) // this prints out the correct numeric value. #print(values) // but this prints out the array with the weird format. The weird/metadata output looks like the following: [0 0 Name: colname1, dtype: int64, 0 8 Name: colname2, dtype: int64, 0 0 Name: colname3, dtype: int64, 0 0 Name: colname4, dtype: int64, 0 0 Name: colname5, dtype: int64, 0 0 Name: colname6, dtype: int64, 0 0 Name: colname7, dtype: int64, 0 0 Name: colname8, dtype: int64, 0 0 Name: colname9, dtype: int64, 0 0 Name: colname10, dtype: int64, 0 1 Name: colname11, dtype: int64, 0 0 Name: colname12, dtype: int64] Why am i seeing all this metadata stuff when i clearly appended the numeric value? Note that the DataFrame was created via a pd.read_sql_query call.
has comment: http://stackoverflow.com/comment/81282582
type: Question
has comment: http://stackoverflow.com/comment/81282612
accepted answer: http://stackoverflow.com/a/47166438
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/47166438
has comment: http://stackoverflow.com/comment/81282742
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
tagged with: dataframe
upvote count: 1
score: 1

http://stackoverflow.com/a/47136936
upvote count: 2
has comment: http://stackoverflow.com/comment/81223270
type: Answer
has comment: http://stackoverflow.com/comment/81223324
score: 2
answers question: http://stackoverflow.com/q/47136680
downvote count: 0
has body: I made something like that, but to change mongodb connections. I created a GenericView that select the connection and use it on the get_queryset. I'm using django rest framework, so I made something like this: class SwitchDBMixinView(object): model = None fields = None def initial(self, request, *args, **kwargs): result = super().initial(request, *args, **kwargs) if request.user.is_authenticated(): request.user.database_connection.register() return result def get_object(self, *args, **kwargs): return super().get_object(*args, **kwargs).switch_db(self.get_db_alias()) def get_db_alias(self): if self.request is None or not self.request.user.is_authenticated(): return DEFAULT_CONNECTION_NAME return self.request.user.database_connection.name def get_queryset(self): return self.model.objects.using(self.get_db_alias()).all() def perform_destroy(self, instance): instance.switch_db(self.get_db_alias()).delete() The model: from mongoengine.connection import register_connection, get_connection AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL') class Connection(models.Model): class Meta: pass owner = models.OneToOneField( AUTH_USER_MODEL, related_name='database_connection', ) uri = models.TextField( default=DefaultMongoURI() ) def register(self): register_connection( self.name, host=self.uri, tz_aware=True, ) get_connection( self.name, reconnect=True ) def get_name(self): return 'client-%d' % self.owner.pk name = property(get_name) def __str__(self): return self.uri
has comment: http://stackoverflow.com/comment/81223260

http://stackoverflow.com/q/47130344
has answer: http://stackoverflow.com/a/47134136
has body: I have two DataFrames: df: Name Date_1 Date_2 0 Alan 2013-06-21 2013-06-26 1 Bob 2011-01-29 2011-02-01 2 Chris 2010-11-15 2010-11-17 3 Bob 2016-03-14 2016-03-16 4 Doug 2011-03-07 2011-03-10 5 Elijah 2011-02-24 2011-03-01 6 Bob 2011-01-03 2011-01-13 7 Bob 2011-02-07 2011-02-25 8 Frank 2014-07-21 2014-07-23 9 Chris 2011-02-18 2011-02-22 10 Doug 2010-09-13 2010-09-17 11 Chris 2011-01-15 2011-01-19 12 George 2010-06-29 2010-06-30 And df1: Date Name Period 12971 2015-08-18 Alan 2015-08-16 12972 2015-08-19 Alan 2015-08-17 12973 2015-08-20 Alan 2015-08-18 12974 2015-08-21 Alan 2015-08-19 12975 2015-08-22 Alan 2015-08-20 12976 2015-08-23 Alan 2015-08-21 12977 2015-08-24 Alan 2015-08-22 12978 2015-08-25 Alan 2015-08-23 12979 2015-08-26 Alan 2015-08-24 12980 2015-08-27 Alan 2015-08-25 12981 2015-08-28 Alan 2015-08-26 12982 2015-08-29 Alan 2015-08-27 Both dataframes are thousand of rows long, this is just a sample, what I want to do is to find the number of rows in df, where Date is less than Date_2, Date_1 is more than Period for a particular name in df. I have done the following, which achieves the result but is very slow: df1['Volume'] = df1.apply(lambda x: len(df[(df['Name'] == x['Name']) &amp; ( df['Date_1'] &lt; x['Period']) &amp; (df['Date_2'] &gt; x['Date'])]), axis=1) Please let me know if you have any suggestions
tagged with: pandas
score: 0
has comment: http://stackoverflow.com/comment/81210587
answer count: 1
has title: Finding the length of a dataframe for a moving time period for a particular category
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: date

http://stackoverflow.com/q/47075452
tagged with: fft
type: Question
has body: I think I have a slightly unusual question regarding combining two spectra that I cannot figure out! I want to calculate the fft of a time dependent function f(t), this function can be separated into two parts, f(t) = f_1(t) + f_2(t). f_1(t) is a slowly varying function (evolves on a nanosecond timescale), and f_2(t) is changes on a very fast (sub-picosecond) timescale. It seems computationally expensive/crazy to evaluate f(t) with sub-picosecond time steps, given that f_2(t) reaches a constant value very quickly. However, it is quite easy to take the fft of f_1 and f_2 independently, unfortunately I can't figure out how to add these functions at the end. Is there a smart way of combing f_1(w) + f_2(w), given f_1 and f_2 have different frequency ranges?
type: UnansweredQuestion
has title: Adding spectra over different frequency ranges
tagged with: python
answer count: 0
score: 1
downvote count: 0
upvote count: 1
tagged with: signal-processing
favorite count: 0

http://stackoverflow.com/q/47185334
has answer: http://stackoverflow.com/a/47186166
answer count: 2
tagged with: django-generic-views
type: UnansweredQuestion
tagged with: mixins
has body: I'm sorry if I may have wrong code but I havent really been doing django rest much. I want to detect permissions from django's built in User model. I added a permission to a user model but for some reason has_perm doesn't work. I instead use user_objects.all() and detect if the permission object is there. I want to return an error 400: Unauthorized if the user does not have permission. Heres my current solution(not working): class ProgramListCreateView(PermissionRequiredMixin,ListCreateAPIView): permission_required = Permission.objects.get(name="Can CRUD") permission_classes = (IsAuthenticated,) queryset = Program.objects.all() serializer_class = ProgramSerializer def check_user(self,request): if self.permission_required in request.user.user_permissions.all(): return True return Response(status=400) when I send a json with the user token without the permission, it still creates the object Heres my mixin: class PermissionRequiredMixin(object): user_check_failure_path = 'auth_login' permission_required = None def check_user(self, user): return user.has_perm(self.permission_required) note: has_perm always returns false for some reason even if I add it using user.user_permissions.add(permission_object)
downvote count: 0
has comment: http://stackoverflow.com/comment/81320517
tagged with: django
upvote count: 1
tagged with: python
tagged with: django-rest-framework
favorite count: 0
score: 1
has comment: http://stackoverflow.com/comment/81321180
has title: Mixins for Permissions Django REST ListCreateAPIView
type: Question
has answer: http://stackoverflow.com/a/47209523

http://stackoverflow.com/comment/81150352
score: 0
has text: Usually a host service provide you with a user and an admin panel where the settings are, like the ftp for uploading the files and the access to databases.
type: Comment
comment on: http://stackoverflow.com/q/47099826
type: QuestionComment

http://stackoverflow.com/comment/81216962
score: 0
comment on: http://stackoverflow.com/q/47133619
has text: I think that is more of a terminal question than a python question.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81266815
has text: I was referring to the syntax in the question, prior to the edit by coldspeed.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47158597

http://stackoverflow.com/a/47136476
type: Answer
score: 0
type: AcceptedAnswer
has body: You could use: import os os.path.dirname(original_image_path)
upvote count: 1
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47136376
answers question: http://stackoverflow.com/q/47136376

http://stackoverflow.com/a/47091971
has body: Well that basically does element-wise multiplication between the elements along the last axis for A for all pairs. Now, since that einsum expression isn't doing any sum-reduction and is simply doing the job of broacasting, we can avoid it by manually extending the input arrays to have one more dimension and let the broadcasting do its job. This would be more performant than using einsum and that's a good reason for look for an alternative to einsum for such a case. The implementation for a 2D and even a n-dim A (using the ellipsis notation) would be - A[...,None,:]*A[...,None] Sample run - In [71]: A = np.random.rand(3,4,5,6) In [72]: np.allclose(np.einsum('...i,...j-&gt;...ij',A,A), A[...,None,:]*A[...,None]) Out[72]: True The performance aspect discussed earlier makes more sense, when the axis of expansion is of decent length. So, with A of shape (200,2) i.e. 2 as the axis length for the last axis, the improvement with extension of dims and using broadcasting would be less/not-at-all noticeable, but only seen with decent lengths. Let's verify these aspects - In [76]: A = np.random.rand(20000,2) In [77]: %timeit np.einsum('...i,...j-&gt;...ij',A,A) 1000 loops, best of 3: 207 µs per loop In [78]: %timeit A[...,None,:]*A[...,None] 1000 loops, best of 3: 364 µs per loop In [79]: A = np.random.rand(200,200) In [80]: %timeit np.einsum('...i,...j-&gt;...ij',A,A) 100 loops, best of 3: 12.1 ms per loop In [81]: %timeit A[...,None,:]*A[...,None] 100 loops, best of 3: 9.74 ms per loop
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47091818
accepted answer of: http://stackoverflow.com/q/47091818
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/47200853
has title: Python - NaiveBayesClassifier - TypeError: 'float' object is not iterable
has comment: http://stackoverflow.com/comment/81350318
score: 0
has comment: http://stackoverflow.com/comment/81350275
tagged with: pandas
has comment: http://stackoverflow.com/comment/81350193
type: Question
has body: I am trying to train some data for a classification tool I am building. I have done some simple examples and it works fine. I am now trying to use some data from work (which is what it will be used on), and I am getting a TypeError: 'float' object is not iterable error, the traceback is here: Traceback (most recent call last): File "C:/Users/nicholas/Desktop/machineTraining/classLearning.py", line 13, in &lt;module&gt; cl = NaiveBayesClassifier(train) File "C:\Users\nicholas\AppData\Local\Programs\Python\Python36-32\lib\site-packages\textblob\classifiers.py", line 205, in __init__ super(NLTKClassifier, self).__init__(train_set, feature_extractor, format, **kwargs) File "C:\Users\nicholas\AppData\Local\Programs\Python\Python36-32\lib\site-packages\textblob\classifiers.py", line 139, in __init__ self._word_set = _get_words_from_dataset(self.train_set) #Keep a hidden set of unique words. File "C:\Users\nicholas\AppData\Local\Programs\Python\Python36-32\lib\site-packages\textblob\classifiers.py", line 63, in _get_words_from_dataset return set(all_words) This is my code: df = pd.read_csv("C:/Users/nicholas\Desktop/trainData.csv", encoding='latin-1') df['train'] = df'Summary', 'Primary Classification'.apply(tuple, axis=1) aTrain = df['train'].values.tolist() train = aTrain cl = NaiveBayesClassifier(train) Any ideas on what is going wrong?
answer count: 0
type: UnansweredQuestion
tagged with: naivebayes
has comment: http://stackoverflow.com/comment/81350115
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/81350400

http://stackoverflow.com/a/47094679
has comment: http://stackoverflow.com/comment/81285301
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81285225
accepted answer of: http://stackoverflow.com/q/47086715
has comment: http://stackoverflow.com/comment/81285578
answers question: http://stackoverflow.com/q/47086715
type: AcceptedAnswer
downvote count: 0
has body: A) Assumptions about a not delivered message are not correct. Why? The core logic ( actually the core, multiparty distributed-logic ) of the REQ/REP Scalable Formal Communication Pattern archetype is hard-wired so that if the REP-entity receives a REQ-message ( and never else , except with some recent API v4.+ delicate tweaking, to be utmost precise ), the REP-entity can ( and in your code will ) .send() a message to REQ-side. Symmetrically, after the REQ-entity has fired its first message to REP-side, it can never send another "next" message, unless it has prior to that, .recv()-ed the REP-side response. This symmetrical distributed-logic means, that if your server-side code reports positive acknowledgement of sending more than just one message, it on its own grounds itself represents a positive proof, that also the opposite side has been delivered each and every response from the server. ( For cases, where some messages got lost, you may kindly read my other posts on the risks of REQ/REP mutual dead-locks ). So this has been solved as indeed an incorrect assumption, Q.E.D. B) Assumptions about an ill-delivered message content are not correct. Why? ZeroMQ either delivers a completely correct message, or nothing at all. This means, that in case a message has been both sent and delivered ( for the core distributed-logic reasoning kindly ref. above ), the only possible alternative is, that the message payload is correct, as no other option exists in ZeroMQ framework internalities. Proof: change this: // Print the reply, memory address ... std::cout &lt;&lt; 'Mostrando reply' &lt;&lt; &amp;reply &lt;&lt; std::endl; into this: // Print the reply std::cout &lt;&lt; 'Mostrando reply was delivered' &lt;&lt; std::endl; and you will straight see, where the problem is -- it is not in the ZeroMQ tools, but the way, how your code tried to present the &amp;reply into a std::out output. C) Why I cannot see the reply from server? Because you do not try to show it. That simple. In …
upvote count: 1

http://stackoverflow.com/comment/81132544
has text: `date | time | id | name | count | +------------+----------+-----------+----------------------------+--------------+ | 2009-05-01 | 23:00:00 | 4 | Town Hall (West) | 1592 ` Datatype for Time given in MySQL is "Time". For this output, output in python is `datetime.timedelta(0, 82800)`
comment on: http://stackoverflow.com/q/47090958
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81110127
score: 0
has text: When "ownership" of an object is passed from one software component to another, the new owner becomes responsible for freeing the memory. Because *that's what "ownership" means.*
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47080411

http://stackoverflow.com/a/69896511
has body: For me I had to add astype() to make it work, otherwise it produced Nan values: oidx = s.index nidx = pd.date_range(oidx.min(), oidx.max(), freq='2min') res=s.reindex(oidx.union(nidx)).astype(float).interpolate('index').reindex(nidx)
answers question: http://stackoverflow.com/q/47148446
score: 0
type: Answer

cisco
type: Tag
tag name: cisco
tags question: http://stackoverflow.com/q/47087138

http://stackoverflow.com/a/47129186
accepted answer of: http://stackoverflow.com/q/47129107
has body: So, my code doesn't do anything, i need to somehow find if any of the strings have at least 2 words and print all of those words. Perhaps loop through the list and split each string. Then determine if the resulting sum is greater than 1: text_list = ['G', 'A', 'B', 'C D', 'E'] for i in range(len(text_list)): if len(text_list[i].split(' ')) &gt; 1: print(text_list[i]) Using list comprehension: x = [w for w in text_list if len(w.split(' ')) &gt; 1] print(x)
type: Answer
has comment: http://stackoverflow.com/comment/81208478
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47129107

http://stackoverflow.com/comment/81395590
has text: This is code that you would put in the app itself? Im not sure what I would do with this in my script.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47222769
type: Comment

http://stackoverflow.com/a/47337803
has comment: http://stackoverflow.com/comment/109112735
type: Answer
accepted answer of: http://stackoverflow.com/q/47134237
score: 15
upvote count: 15
has comment: http://stackoverflow.com/comment/89019404
has comment: http://stackoverflow.com/comment/87936598
answers question: http://stackoverflow.com/q/47134237
downvote count: 0
has comment: http://stackoverflow.com/comment/88997767
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88997226
has body: The RelationRecord reflects a subset of items, while ordered_statistics is a list of OrderedStatistics, which reflect the rules. Each OrderedStatistics' items_base is the antecedent and the items_add is the consequent. The support is stored in the RelationRecord, since it's the same for the contained rules. In your example: item1 -> item2 with 0.62 confidence and 2.2233410344037092x lift item2 -> item1 with 0.55 confidence and 2.2233410344037097x lift Both have support=0.15365410803449842. For what it's worth, I ended up switching to using PyFIM for relative feature richness and other bundled algorithms (e.g. fp-growth).
has comment: http://stackoverflow.com/comment/84623444

http://stackoverflow.com/comment/81326067
comment on: http://stackoverflow.com/a/47188208
type: AnswerComment
has text: @JohnAnderson huh? Why do you think that?
score: 0
type: Comment

http://stackoverflow.com/comment/81178042
type: Comment
score: 0
type: AnswerComment
has text: You're welcome. BTW, I recommend watching Ned Batchelder's presentation ["Loop like a native: while, for, iterators, generators"](https://www.youtube.com/watch?v=EnSu9hHGq5o).
comment on: http://stackoverflow.com/a/47113950

http://stackoverflow.com/a/47086418
has comment: http://stackoverflow.com/comment/81122744
score: 0
has comment: http://stackoverflow.com/comment/81123153
has comment: http://stackoverflow.com/comment/81123070
has comment: http://stackoverflow.com/comment/81122635
has comment: http://stackoverflow.com/comment/81122792
has comment: http://stackoverflow.com/comment/81122523
type: Answer
answers question: http://stackoverflow.com/q/47086376
has comment: http://stackoverflow.com/comment/81122823
has body: I may have interpreted this wrong but, shouldn't there be something like certain_value = '%s' otherwise it doesn't know what it is looking for.

http://stackoverflow.com/q/47162306
has body: Question I have a shared multiprocessing.Pool object in my application which is initialized with two queue objects (one for jobs and the other for results). How can I send an arbitrary queue object into the job queue and have the process send the result to this alternative queue? job_q.put_nowait((item, alt_q)) # Raises an exception. This approach works fine when doing multithreading but not when doing multiprocessing. Example The example code below demonstrates what I am trying to achieve. I initialize the pool with two multiprocessing.Queue objects job_q and res_q. Well, in fact, they are proxies created by multiprocessing.Manager. The run function is the run-loop of each process, it monitors the job queue for items and simply adds the items to the result queue. (A separate thread is monitoring the result queue and print to stdout). import multiprocessing as mp import queue import threading import time import os def run(job_queue, result_queue): """ Run-loop for each process. """ print("Starting process {}".format(os.getpid())) while True: job_q = job_queue res_q = result_queue try: # `item` is just a string # `opt_queue` is an optional result queue to use item, opt_queue = job_q.get(True, 0.05) if opt_queue is not None: res_q = opt_queue item = item + " Processed" res_q.put_nowait(item) except queue.Empty: continue def monitor_queue(mp_queue): """ The target of a monitoring thread. """ while True: try: item = mp_queue.get(True, 0.05) print("Got `{}`".format(item)) except queue.Empty: continue if __name__ == '__main__': m = mp.Manager() job_q = m.Queue() res_q = m.Queue() alt_q = m.Queue() # Monitor `res_q` for items threading.Thread(target=monitor_queue, args=(res_q,)).start() # Monitor `alt_q` for items threading.Thread(target=monitor_queue, args=(alt_q,)).start() # `run` is called by each process, share `job_q` and `res_q` with all processes pool = mp.Pool(2, run, (job_q, res_q)) time.sleep(1) # Add an item to `job_q` and `None` means send result to `res_q` pri…
score: 0
has title: Python passing queue objects to multiprocessing.Pool of processes
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47162453
tagged with: python
tagged with: python-multiprocessing
type: Question

http://stackoverflow.com/comment/81156038
type: Comment
has text: Sorry bro, I can not because I am new user, they are not allowing me for chatroom
comment on: http://stackoverflow.com/q/47094680
score: 0
type: QuestionComment

http://stackoverflow.com/a/57293842
answers question: http://stackoverflow.com/q/47113029
type: Answer
has comment: http://stackoverflow.com/comment/103165536
score: 2
upvote count: 4
downvote count: 2
has body: I was facing similar issue with openCV on the python:3.7-slim docker box. Following did the trick for me : apt-get install build-essential libglib2.0-0 libsm6 libxext6 libxrender-dev Please see if this helps !

http://stackoverflow.com/a/47129132
type: Answer
has body: You are initializing your sparse matrices incorrectly. Take a look a the documentation for lil_matrix. Given that m is your shape parameter you actually want to initialize the matrix as follows (note that the first argument is a tuple): matA = scipy.sparse.lil_matrix((m, m)) matA &lt;100000x100000 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 0 stored elements in LInked List format&gt; The way you are doing it you end up with a 1x1 matrix, which I assume is not your intent: matA = scipy.sparse.lil_matrix(m, m) matA &lt;1x1 sparse matrix of type '&lt;class 'numpy.int64'&gt;' with 1 stored elements in LInked List format&gt; The reason for this is that the first argument for lil_matrix is looking for an array, or array-like, another sparse matrix, or a tuple. When you enter lil_matrix(m,m) it essentially ignores the second argument, as the first is interpreted as an array-like, and just initializes a 1x1 array with the value set to m.
answers question: http://stackoverflow.com/q/47128535
score: 0

http://stackoverflow.com/a/47122878
has body: When you just iterate through all the pages you click ">" button on the top pagination (visible one), but when you do the same along with scraping you scroll page down to bottom pagination. In this case top pagination is no more visible, so your loop brakes on try: link = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "&gt;"))) link.click() as you cannot click ">" on the top. You need to handle bottom pagination. Just replace link = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "&gt;"))) with link = driver.find_elements_by_link_text("&gt;")[1]
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81196380
has comment: http://stackoverflow.com/comment/81197242
has comment: http://stackoverflow.com/comment/81197186
type: Answer
accepted answer of: http://stackoverflow.com/q/47122629
answers question: http://stackoverflow.com/q/47122629
score: 1

http://stackoverflow.com/a/47114513
has comment: http://stackoverflow.com/comment/81227186
has comment: http://stackoverflow.com/comment/81193358
type: Answer
has comment: http://stackoverflow.com/comment/81193239
has body: It sounds like you are trying to interact with Memcached via Boto3. This is not possible. Boto3 is for interacting with the AWS API. You can manage your ElastiCache servers via the AWS API, but you can't interact with the Memcached software running on those servers. You need to use a Memcached client library like python-memcached in your Python code to actually get and set keys in your Memcached cluster. Also, your Lambda function will need to reside in the same VPC as the ElastiCache node(s).
answers question: http://stackoverflow.com/q/47111787
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81193444
has comment: http://stackoverflow.com/comment/81226825
downvote count: 0

http://stackoverflow.com/a/47155769
answers question: http://stackoverflow.com/q/47155268
has body: Use a combination of groupby + itertools.combinations: from itertools import combinations g = df.groupby('State').apply(lambda x: pd.Series(list(combinations(x.City, 2)))) df = pd.DataFrame(g.apply(list).tolist(), columns=['City1', 'City2']) df['State'] = g.index.get_level_values(0) df City1 City2 State 0 LosA SanJ Cali 1 LosA SanF Cali 2 SanJ SanF Cali 3 Char Rale NC
upvote count: 3
downvote count: 0
type: AcceptedAnswer
score: 3
accepted answer of: http://stackoverflow.com/q/47155268
type: Answer

http://stackoverflow.com/q/47176420
tagged with: merge
upvote count: 6
tagged with: fillna
type: AnsweredQuestion
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47176467
possible better answer: http://stackoverflow.com/a/47176507
has body: I have a column with na values that I want to fill according to values from another data frame according to a key. I was wondering if there is any simple way to do so. Example: I have a data frame of objects and their colors like this: object color 0 chair black 1 ball yellow 2 door brown 3 ball **NaN** 4 chair white 5 chair **NaN** 6 ball grey I want to fill na values in the color column with default color from the following data frame: object default_color 0 chair brown 1 ball blue 2 door grey So the result will be this: object color 0 chair black 1 ball yellow 2 door brown 3 ball **blue** 4 chair white 5 chair **brown** 6 ball grey Is there any "easy" way to do this? Thanks :)
has answer: http://stackoverflow.com/a/47176467
downvote count: 0
has answer: http://stackoverflow.com/a/47176507
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47176619
has title: Filling na values with merge from another dataframe
has comment: http://stackoverflow.com/comment/81301978
score: 6
tagged with: dataframe
tagged with: python

http://stackoverflow.com/a/47083002
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/113012399
score: 7
type: AcceptedAnswer
has body: I think I came up with a solution. def get_line_number_of_function(func): return func.__code__.co_firstlineno def get_functions_from_module(app_module): list_of_functions = dict(inspect.getmembers(app_module, inspect.isfunction)) return sorted(list_of_functions.values(), key=lambda x: get_line_number_of_function(x))
accepted answer of: http://stackoverflow.com/q/47082391
type: Answer
answers question: http://stackoverflow.com/q/47082391

http://stackoverflow.com/comment/81108514
score: 0
type: Comment
type: AnswerComment
has text: Thanks, and thanks for the link. I'm sure I read that statement many years ago, but clearly it slipped my mind since them. What a drag it is... Anyway, I will give the approach a try. It seems pretty straightforward.
comment on: http://stackoverflow.com/a/47066898

http://stackoverflow.com/a/47134052
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47133498
downvote count: 0
has comment: http://stackoverflow.com/comment/81223163
answers question: http://stackoverflow.com/q/47133498
has body: I think this would be a nice use case for a filtering generator function: import re import csv def filter_lines(f): """this generator funtion uses a regular expression to include only lines that have a `$` and end with a `#`. """ filter_regex = r'.*\$.*\#$' for line in f: line = line.strip() m = re.match(filter_regex, line) if m: yield line with open(CSV_FILENAME) as f: filter_generator = filter_lines(f) csv_reader = csv.reader(filter_generator) for row in csv_reader: pass EDIT: I realize now that in your example a single "line" could contain multiple matches (as seen on line 6). This slightly modified version can handle that just as well: import re import csv def filter_lines(f): """this generator funtion uses a regular expression to include only lines that have a `$` and end with a `#`. """ filter_regex = r'(\$[^#]*\#)' for line in f: line = line.strip() matches = re.findall(filter_regex, line) for m in matches: yield m with open(CSV_FILENAME) as f: filter_generator = filter_lines(f) csv_reader = csv.reader(filter_generator) for row in csv_reader: print row Output generated from your example input: ['$SITE0011', '1654', '0000', '0000', '0000', '00000000', '000000^A^A^A^A^A^A^@^@#'] ['$SITE0011', '1654', '0000', '0000', '0000', '00000000', '000000^A^A^A^A^A^A^@^@#'] ['$SITE0011', '1654', '0000', '0000', '0000', '00000000', '000000^A^A^A^A^A^A^@^@#'] ['$SITE0011', '1654', '0000', '0000', '0000', '00000000', '000000^A^A^A^A^A^A^@^@#'] ['$SITE0011', '1654', '0000', '0000', '0000', '00000000', '000000^A^A^A^A^A^A^@^@#']
has comment: http://stackoverflow.com/comment/81239130
type: Answer
has comment: http://stackoverflow.com/comment/81226100
score: 2

http://stackoverflow.com/comment/81339056
comment on: http://stackoverflow.com/q/47194629
has text: I don't think what you're trying to do here is possible with `super`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81374962
score: 2
has text: the classic way is to use a set : `if choice.lower() in {'yes', 'y','yup'}` (`.lower()` just avoids to write all caps versions)
type: QuestionComment
comment on: http://stackoverflow.com/q/47212687
type: Comment

http://stackoverflow.com/a/47232117
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81499581
answers question: http://stackoverflow.com/q/47213852
has comment: http://stackoverflow.com/comment/81460749
accepted answer of: http://stackoverflow.com/q/47213852
type: Answer
has comment: http://stackoverflow.com/comment/81499098
has comment: http://stackoverflow.com/comment/81499283
has comment: http://stackoverflow.com/comment/81502973
has comment: http://stackoverflow.com/comment/81449779
score: 1
has body: Instead of trying to build based on the columns, you need to loop over the rows, and start building the items per row, I've used item loaders here so that you can avoid several .extract_first() or .strip(), please try this: # -*- coding: utf-8 -*- import scrapy # This should go to items.py from scrapy.loader import ItemLoader from scrapy.loader.processors import TakeFirst, MapCompose from operator import methodcaller class MatchStatItem(scrapy.Item): round = scrapy.Field() event1 = scrapy.Field() player_1 = scrapy.Field() player_2 = scrapy.Field() player_1_odds = scrapy.Field() player_2_odds = scrapy.Field() h_2_h = scrapy.Field() class MatchStatItemLoader(ItemLoader): default_item_class = MatchStatItem default_input_processor = MapCompose(methodcaller('strip')) default_output_processor = TakeFirst() class MatchStatSpider(scrapy.Spider): name = "matchstat" allowed_domains = ["matchstat.com"] start_urls = ['https://matchstat.com/tennis/all-upcoming-matches'] def parse(self, response): for row in response.css('tr.match'): il = MatchStatItemLoader(selector=row) il.add_css('round', '.round::text') il.add_css('event1', '.event-name a::text') il.add_css('player_1', '.player-name:nth-child(3) a::text') il.add_css('player_2', '.player-name:nth-child(4) a::text') il.add_css('player_1_odds', '.odds-td.odds-0 [payout]::text') il.add_css('player_2_odds', '.odds-td.odds-1 [payout]::text') il.add_css('h_2_h', 'a.h2h::text') yield il.load_item() The output should be something like: {'event1': u'ATP World Tour Finals', 'h_2_h': u'H2H 3-0', 'player_1': u'Roger Federer', 'player_1_odds': u'1.10', 'player_2': u'Jack Sock', 'player_2_odds': u'7.00', 'round': u'RR A'}

http://stackoverflow.com/comment/81174221
comment on: http://stackoverflow.com/a/47112184
type: AnswerComment
has text: good, now I want to do one more operation, I will edit the question
score: 0
type: Comment

http://stackoverflow.com/comment/81125722
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47081228
has text: Thank you for your answer. Can you check last part (EDIT PART) of my post please? Its the code which I use right now based on your code. `print form.errors` shows me in terminal error messages but in template I dont have them. Where I did mistake again?
type: AnswerComment

http://stackoverflow.com/a/47104584
type: AcceptedAnswer
has body: There is a cyclic import in your code. Please see Circular imports in Python with possible undesired behaviours. Anyway, it seems that your Stats module does not need LevelUp (does it?). I suggest rethinking your architecture.
accepted answer of: http://stackoverflow.com/q/47104440
has comment: http://stackoverflow.com/comment/81204025
type: Answer
answers question: http://stackoverflow.com/q/47104440
score: 0

http://stackoverflow.com/q/47091061
score: 1
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81131613
upvote count: 1
tagged with: virtualenv
has answer: http://stackoverflow.com/a/47093322
has comment: http://stackoverflow.com/comment/81134855
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81132068
has comment: http://stackoverflow.com/comment/81132073
has comment: http://stackoverflow.com/comment/81132848
has title: How to install and use python to work with python 2.7 in virtualenv?
has comment: http://stackoverflow.com/comment/81131410
type: UnansweredQuestion
has body: I seem to have multiple issues trying to install ipython in a virtual env, and work with python 2.7 in ipython. First of all, I created a virtualenv and pip-installed ipython: pip install ipython==1.2.1 So far, all looks good: $ which python ~/Projects/BGLibPy/venv/bin/python $ which ipython ~/Projects/BGLibPy/venv/bin/ipython $ which pip ~/Projects/BGLibPy/venv/bin/pip But the version of ipython does not match $ ipython -V 0.13.2 and when I start ipython I see: $ ipython WARNING: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv. Python 2.6.6 (r266:84292, Aug 9 2016, 06:11:56) And yes, I did install ipython in a virtualenv. And why is the version of python 2.6 (inside ipython) but outside its 2.7? $ python -V Python 2.7.13 I am confused. What is going on, and how to fix this?
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/81133513
has comment: http://stackoverflow.com/comment/81132096
has comment: http://stackoverflow.com/comment/81131368
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81131738
has comment: http://stackoverflow.com/comment/81131632

http://stackoverflow.com/comment/81284522
has text: The error is when it tries to read python36.zip. Inside of it, there isn't actually a site.py because it's an embeddable version of python.
type: Comment
comment on: http://stackoverflow.com/a/47158826
type: AnswerComment
score: 0

http://stackoverflow.com/q/47195051
has answer: http://stackoverflow.com/a/47195153
upvote count: 2
score: 0
downvote count: 2
answer count: 1
has title: I accidentally downloaded PyCharm with Python 3. How can I change it to Python 2?
has comment: http://stackoverflow.com/comment/81339015
has body: I accidentally downloaded PyCharm and chose Python 3 when I meant to choose Python 2.7. How can I change it to Python 2.7?
favorite count: 0
type: Question
tagged with: pycharm
has comment: http://stackoverflow.com/comment/81339266
type: UnansweredQuestion
tagged with: python

windows
tags question: http://stackoverflow.com/q/47158315
tags question: http://stackoverflow.com/q/47201677
tags question: http://stackoverflow.com/q/47128653
tags question: http://stackoverflow.com/q/47087635
tags question: http://stackoverflow.com/q/47121960
tags question: http://stackoverflow.com/q/47085279
tags question: http://stackoverflow.com/q/47142323
tags question: http://stackoverflow.com/q/47144580
tags question: http://stackoverflow.com/q/47203530
tags question: http://stackoverflow.com/q/47141263
tags question: http://stackoverflow.com/q/47096616
tags question: http://stackoverflow.com/q/47086510
tags question: http://stackoverflow.com/q/47196799
type: Tag
tags question: http://stackoverflow.com/q/47095129
tags question: http://stackoverflow.com/q/47071963
tags question: http://stackoverflow.com/q/47184124
tags question: http://stackoverflow.com/q/47114659
tags question: http://stackoverflow.com/q/47172110
tags question: http://stackoverflow.com/q/47172433
tags question: http://stackoverflow.com/q/47194189
tags question: http://stackoverflow.com/q/47181635
tags question: http://stackoverflow.com/q/47084078
tags question: http://stackoverflow.com/q/47180353
tags question: http://stackoverflow.com/q/47110606
tags question: http://stackoverflow.com/q/47122520
tags question: http://stackoverflow.com/q/47083929
tags question: http://stackoverflow.com/q/47085573
tags question: http://stackoverflow.com/q/47145750
tags question: http://stackoverflow.com/q/47120247
tag name: windows
tags question: http://stackoverflow.com/q/47075479
tags question: http://stackoverflow.com/q/47067506
tags question: http://stackoverflow.com/q/47211666
tags question: http://stackoverflow.com/q/47130163
tags question: http://stackoverflow.com/q/47077619
tags question: http://stackoverflow.com/q/47168026
tags question: http://stackoverflow.com/q/47156750
tags question: http://stackoverflow.com/q/47200741
tags question: http://stackoverflow.com/q/47165314
tags question: http://stackoverflow.com/q/47152301
tags question: http://stackoverflow.com/q/47127856
tags question: http://stackoverflow.com/q/47143773

http://stackoverflow.com/comment/81145769
comment on: http://stackoverflow.com/a/47097903
type: AnswerComment
score: 0
type: Comment
has text: I understand your use of the index, but how do I convert a dataset that its already given and index it? Because your code depends on me using a random nparray, while my problem is I'm trying to do it on a dataset

http://stackoverflow.com/a/47085758
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47085505
type: Answer
accepted answer of: http://stackoverflow.com/q/47085505
has body: The issue was the apache2 was not able to access the directory. Sadly, there's a very little comment in the question posted above, and the accepted answer isn't the right one. Adding the solution here if it helps someone: sudo chown -R www-data:www-data /home
type: AcceptedAnswer

http://stackoverflow.com/q/47105858
tagged with: selenium
tagged with: web-scraping
favorite count: 0
type: Question
has body: While trying out web scraping at https://store.obeygiant.com/collections/prints/products/obey-ripped-signed-offset-poster, made an attempt to click a button by id and even by name: browser.find_by_id('AddToCartText').click() browser.find_by_name('add').click() But got the following error for either attempt: selenium.common.exceptions.WebDriverException: Message: unknown error: Element is not clickable at point (657, 724) (Session info: chrome=61.0.3163.100) (Driver info: chromedriver=2.29.461585 (0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b),platform=Mac OS X 10.11.6 x86_64) Tested it out the same way and other sites actually worked. What could be the issue and what would be a good approach to it? Thank you in advance and will be sure to vote up and accept answer.
tagged with: splinter
linked to: http://stackoverflow.com/q/44912203
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/44912203
tagged with: python
has answer: http://stackoverflow.com/a/47107017
tagged with: selenium-webdriver
upvote count: 2
score: 2
downvote count: 0
answer count: 1
has title: Python/Splinter + Selenium error: Element is not clickable at point (657, 724)

http://stackoverflow.com/comment/81124104
has text: you are super fast @ShadowRanger :)
type: Comment
comment on: http://stackoverflow.com/a/47087117
score: 0
type: AnswerComment

http://stackoverflow.com/q/47104910
tagged with: machine-learning
upvote count: 1
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/47105093
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47105093
has title: Best tricks to handle my data in Machine learning(binary classification)?
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: -1
has body: I'm a newbie to machine learning please forgive me if I'm dumb. I have a traindata.csv file with 22 attributes and 30000 data points. I have to train my model(not specific algorithm) and predict on 20000 data points in testdata.csv file on which I have to make predictions with my trained model. In traindata.csv, the ratio of '0' and '1' class labels is 5:1. If I train my model with this whole train data, my model shows some bias towards predicting 0's than 1. I somehow know that the actual values in my test data are 0's and 1's in the ratio of 1:1. Can you suggest me some method(some sort of noise cancellation) to preprocess my train data such that there will be no bias towards 0's while predicting on my test data(as it has equal 0's and 1's)?
tagged with: validation
downvote count: 2
answer count: 1

http://stackoverflow.com/q/47089547
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
downvote count: 0
has body: i want to know how to remove a specific dict from this list if user status equals "offline" and order type equals "buy" (iterating over it with for loop and modifying the list while iterating produces an exception because of the list pointer) mylist = [ { "user": {"status": "offline"}, "order_type": "buy" }, { "user": {"status": "online"}, "order_type": "sell" } ]
possible better answer: http://stackoverflow.com/a/47089681
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47089681
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47089585
has title: python - remove a dictionary from a list if dictionary key equals a certain value
has answer: http://stackoverflow.com/a/47089585
score: 1

eigenvalue
tags question: http://stackoverflow.com/q/47168312
type: Tag
tag name: eigenvalue

http://stackoverflow.com/comment/81334869
has text: Sounds like a buffering issue; is your program doing something else that delays it from exiting? No matter how little output your program produces, the output should be flushed from the buffer at the end of its run.
comment on: http://stackoverflow.com/q/47192761
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/47066309
tagged with: ode
favorite count: 0
type: Question
tagged with: python-3.x
has body: I found the following code in my search to improve my codes for numerical analysis: from math import sqrt def RK4(f): return lambda t, y, dt: ( lambda dy1: ( lambda dy2: ( lambda dy3: ( lambda dy4: (dy1 + 2 * dy2 + 2 * dy3 + dy4) / 6 )(dt * f(t + dt, y + dy3)) )(dt * f(t + dt / 2, y + dy2 / 2)) )(dt * f(t + dt / 2, y + dy1 / 2)) )(dt * f(t, y)) def theory(t): return (t**2 + 4)**2 / 16 dy = RK4(lambda t, y: t * sqrt(y)) t, y, dt = 0., 1., .1 while t &lt;= 10: if abs(round(t) - t) &lt; 1e-5: print("y(%2.1f)\t= %4.6f \t error: %4.6g" % (t, y, abs(y - theory(t)))) t, y = t + dt, y + dy(t, y, dt) Now, the program works fine and can see the overall algorithm of the program. But i can't understand how does the lambda nesting works. If i understand correctly all the dyN in RK4 are functions that are defined inside as they are needed for this ODE-solving method. But i don't know how the inner lambdas use the outer lambdas in their definition. Perhaps I'm not understanding the lambda syntax correctly.
score: 1
accepted answer: http://stackoverflow.com/a/47069192
linked to: http://stackoverflow.com/q/32928543
tagged with: python
tagged with: nested-function
has title: How does the inner lambda use the outer lambda fuction in this RK4 ODE-solver? Python
tagged with: lambda
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81094799
downvote count: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47069192

http://stackoverflow.com/comment/81337187
type: QuestionComment
comment on: http://stackoverflow.com/q/47193892
has text: @AaryaHareendranath I added a screenshot of the error to the original question, and you can see that I'm using xpath given me by Chrome
score: 0
type: Comment

http://stackoverflow.com/comment/81206171
has text: Binary search only makes sense on a sorted list. You should probably call the `sort` method on your list before searching it. It's also a very bad idea to name your own variable `list`, since that shadows the name of the builtin `list` type.
comment on: http://stackoverflow.com/q/47128040
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47094551
possible better answer: http://stackoverflow.com/a/47094621
upvote count: 4
has title: Merge "one-to-one" dataframe in pandas
answer count: 2
has body: I have got two dataframes: df1 = pd.DataFrame(data = {'Invoice' : [1, 2, 3, 4, 5], 'Value' : [10, 25, 40, 10, 15]}) df2 = pd.DataFrame(data = {'Invoice' : [2, 3, 5, 2], 'Value' : [25, 11, 15,25], 'TestData':["A",'B','C','D']}) I've already merged them and get df3: df3=pd.merge(df1,df2, left_on=["Invoice","Value"], right_on=["Invoice","Value"]) Df3 output: Invoice Value TestData 0 2 25 A 1 2 25 D 2 5 15 C My question is how to get merged dataframe with "one-to-one" (I mean - when invoice number 2 occurs only once (or generally less) in one of two dataframes, then don't create another row with invoice number 2 in merged dataframe). I'd like to get something like this: Invoice Value TestData 0 2 25 A 1 5 15 C or this: Invoice Value TestData 0 2 25 D 1 5 15 C I tried only left and right merging, but this doesn't work - there are always two rows with invoice number 2. Thank you, Jarek
has answer: http://stackoverflow.com/a/47094621
tagged with: pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/47094610
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47094610
type: AnsweredQuestion
tagged with: dataframe
tagged with: python
tagged with: merge
score: 4

http://stackoverflow.com/comment/81105444
comment on: http://stackoverflow.com/q/47077619
score: 0
has text: Why not try using the `reticulate` package to avoid a system call?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81134237
comment on: http://stackoverflow.com/q/47092367
has text: There's also `str.startswith()`; and then you can use indexing of a string to remove the first 2 or 3 characters.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81143276
type: Comment
type: QuestionComment
has text: @offeltoffel, what do you mean it won't work? That's a syntactically valid string literal.
comment on: http://stackoverflow.com/q/47096806
score: 1

http://stackoverflow.com/q/47098049
has comment: http://stackoverflow.com/comment/81147591
tagged with: anaconda
tagged with: python
has answer: http://stackoverflow.com/a/47098268
score: -1
upvote count: 0
type: UnansweredQuestion
has title: RuntimeError when run my python code
answer count: 1
has body: I tried to run my code but I'm faced with this error: File "", line 1, in runfile('C:/Users/niloo/PycharmProjects/untitled/MADRL-master/runners/run_multiwalker.py', wdir='C:/Users/niloo/PycharmProjects/untitled/MADRL-master/runners') File "C:\Users\niloo\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "C:\Users\niloo\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/niloo/PycharmProjects/untitled/MADRL-master/runners/run_multiwalker.py", line 7, in from runners import RunnerParser File "", line 961, in _find_and_load File "", line 946, in _find_and_load_unlocked File "", line 881, in _find_spec File "", line 855, in _find_spec_legacy File "C:\Users\niloo\Anaconda3\lib\site-packages\pyximport\pyximport.py", line 253, in find_module fp, pathname, (ext,mode,ty) = imp.find_module(fullname,package_path) File "C:\Users\niloo\Anaconda3\lib\imp.py", line 269, in find_module raise RuntimeError("'path' must be None or a list, " RuntimeError: 'path' must be None or a list, not &lt;class '_frozen_importlib_external._NamespacePath'&gt; What should I do?
tagged with: django
downvote count: 1
has comment: http://stackoverflow.com/comment/81146413
favorite count: 0
type: Question

http://stackoverflow.com/comment/81166258
comment on: http://stackoverflow.com/q/47107754
type: Comment
type: QuestionComment
has text: Why is it happening?
score: 0

dlib
tags question: http://stackoverflow.com/q/47123545
tags question: http://stackoverflow.com/q/47205879
tag name: dlib
type: Tag

http://stackoverflow.com/comment/81326980
has text: I edited in a slapped-together solution, though I still have no idea what causes the problem in the first place beyond it apparently being OS-dependent. Thanks for taking a look!
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47184080
type: QuestionComment

http://stackoverflow.com/a/47165472
has body: df['text'] is a column of strings. Iterate over it and you iterate over each sentence. What did you expect? You'll need to split each word and iterate over that. You could use a list comprehension. You could also use apply: def f(x): return [w for w in x if w not in stop_words] df['text'] = df['text'].str.split().apply(f).str.join(' ')
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47165287
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47165287

http://stackoverflow.com/comment/81160419
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47104894
has text: What's the point of your inner loops anyways? All three of them create 5 values but only store the last. Each loop completes completely before the next one starts. Throw some print statements into the loops to understand what your code does.

http://stackoverflow.com/comment/81250002
has text: Short and sweet :)
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47150142

http://stackoverflow.com/a/47192993
type: Answer
score: 2
upvote count: 2
has body: Create a temporary column to indicate wins, then use .groupby with .cumsum on that: df['won'] = (df['Position'] == '1') * 1 df['Total 1st Position'] = df.groupby('Athlete').won.cumsum()
downvote count: 0
has comment: http://stackoverflow.com/comment/81370415
has comment: http://stackoverflow.com/comment/81378617
answers question: http://stackoverflow.com/q/47192133

http://stackoverflow.com/q/47085392
has comment: http://stackoverflow.com/comment/81121497
favorite count: 0
has comment: http://stackoverflow.com/comment/81120329
has comment: http://stackoverflow.com/comment/81120482
has comment: http://stackoverflow.com/comment/81120407
has comment: http://stackoverflow.com/comment/81120288
type: Question
tagged with: algorithm
has comment: http://stackoverflow.com/comment/81120543
tagged with: python
score: -2
has body: Write a function named q1() that accepts one (1) parameter, a String which you can assume will always contain a sequence of only digits and should evaluate the String as if it loops around infinitely end-to-end. The purpose of the q1() function is to verify that for every digit n in the String, there are never more than n other digits in between recurring values. (i.e., there are no more than two digits between each occurrence of 2, three digits between each 3, four digits between each 4, etc..) If this is the case, the function should return True, otherwise it should return False. For example, consider the String: '32423' The first digit is 3, and there are only three other values in between the occurrences of the digit 3. The second digit is 2, and are there are never more than two other values in between occurrences of the digit 2. The third digit is 4; it isn’t duplicated. However if you view the String as looping infinitely, you will find that only four other values are passed before looping back to the digit 4 again. For this example, the q1() function would return True def q1(nostring): for i in range(len(nostring)): count=0 for j in range(i+1,len(nostring)): if nostring[i]!=nostring[j]: count+=1 else: break if count &gt; eval(nostring[i]): return False else: return True This code gives fine output in every test case except '235234' It should return False It gives out True instead I came up with this so far and it doesn't work I have been having a really hard time figuring the out how to make it work
has answer: http://stackoverflow.com/a/47085561
tagged with: python-3.x
type: AnsweredQuestion
upvote count: 0
downvote count: 2
accepted answer: http://stackoverflow.com/a/47085561
has comment: http://stackoverflow.com/comment/81120341
answer count: 1
has title: Algorithm for this sequence in python function
has comment: http://stackoverflow.com/comment/81120887

http://stackoverflow.com/comment/81391804
type: Comment
score: 0
has text: What does "clicking on next process in application" mean?
type: QuestionComment
comment on: http://stackoverflow.com/q/47221024

http://stackoverflow.com/comment/81244472
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47144329
has text: Did you test with 1‘200 or 12‘000?
score: 0

http://stackoverflow.com/q/47161245
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/22783778
answer count: 1
has body: I have a dictionary that needs to create a key when the key first shows up and adds a value for it, later on, keeps updating the key with values by appending these values to the previous value(s), I am wondering how to do that. outter_dict = defaultdict(dict) num_index = 100 outter_dict['A'].update({num_index: 1}) outter_dict['A'].update({num_index: 2}) 2 will replace 1 as the value for key 100 of the inner dict of outter_dict, but ideally, it should look like, 'A': {100:[1,2]} UPDATE outter_dict = defaultdict(list) outter_dict['A'][1].append(2) but I got IndexError: list index out of range if I do dict['A'][1] = list() before assign any values to 1, I got IndexError: list assignment index out of range
type: Question
tagged with: python-3.x
has title: python dictionary updating/appending values for a key as a list
has answer: http://stackoverflow.com/a/47161282
accepted answer: http://stackoverflow.com/a/47161282
tagged with: python
tagged with: dictionary
duplicate of: http://stackoverflow.com/q/22783778

http://stackoverflow.com/comment/81136062
comment on: http://stackoverflow.com/a/47081589
has text: Main question is there bottleneck of your program? If it is in `popen` - yes, multiple ping in different threads will increase speed of execution. If bottleneck in inserting results into database, firstly do not execute `commit` after each query. Try to do commit after multiple insertion operation.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81118623
comment on: http://stackoverflow.com/q/47083667
score: 0
type: Comment
type: QuestionComment
has text: @DanielleM. Ok, just saw your answer. I'd say in cases where it's "infeasable" to provide an MCVE, it would be good to say so and say why. I don't get it, btw, "foo" and "bar" aren't floats. So was that output not the actual output? Were "foo" and "bar" really numbers? If so, then seeing that would've helped a lot.

http://stackoverflow.com/a/47107907
has body: self.senstive is an attribute of an object, which is a list of xmr(s). Now code writer want to create a dictionary with keys as xmr(s) and values of id(s) of the xmr(s). the way he is doing it is called the dictionary comprehension. End output dictionary looks like below {xmr_1 : xmr_id_1, xmr_2 : xmr_id_2,.....so on}
score: 0
answers question: http://stackoverflow.com/q/47107818
type: Answer

http://stackoverflow.com/q/47108103
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47112465
has body: I'm using a script: import sys sys.argv entry = 2 t = 0 SEC = 0 min = 0 hrs = 0 with open (sys.argv [1]) as fp: for in line fp: entry+=1 if entry% 8: continue t + = int (line) sec = t% 60 t // = 60 min = t% 60 hrs = t // 60 print ("Total time:% d hours% 02d minutes% 02d seconds"% (hrs, min, sec) Entrance: 315: 31: 54 0:00:32 1:11:24 8:18:18 111: 35: 56 112: 45: 26 0:21:33 of course much bigger;) And there is an error: invalid literal for int() with base 10: '112:45:26\n' I checked 10x. There are no white characters in the input txt file. So what is the cause?
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/47112465
tagged with: python
has title: Python sum time from file txt
has answer: http://stackoverflow.com/a/47108160
type: Question
score: 0
possible better answer: http://stackoverflow.com/a/47108160

machine-learning
tags question: http://stackoverflow.com/q/47120680
tags question: http://stackoverflow.com/q/47152610
tags question: http://stackoverflow.com/q/47065068
type: Tag
tags question: http://stackoverflow.com/q/47203019
tags question: http://stackoverflow.com/q/47137229
tags question: http://stackoverflow.com/q/47121762
tags question: http://stackoverflow.com/q/47106385
tags question: http://stackoverflow.com/q/47156906
tags question: http://stackoverflow.com/q/47213483
tags question: http://stackoverflow.com/q/47160399
tags question: http://stackoverflow.com/q/47149992
tags question: http://stackoverflow.com/q/47213469
tags question: http://stackoverflow.com/q/47066314
tags question: http://stackoverflow.com/q/47133719
tags question: http://stackoverflow.com/q/47205378
tags question: http://stackoverflow.com/q/47083947
tags question: http://stackoverflow.com/q/47192499
tags question: http://stackoverflow.com/q/47206168
tags question: http://stackoverflow.com/q/47149254
tags question: http://stackoverflow.com/q/47081149
tags question: http://stackoverflow.com/q/47094961
tags question: http://stackoverflow.com/q/47213847
tags question: http://stackoverflow.com/q/47084179
tags question: http://stackoverflow.com/q/47116894
tags question: http://stackoverflow.com/q/47222015
tags question: http://stackoverflow.com/q/47179307
tags question: http://stackoverflow.com/q/47156113
tags question: http://stackoverflow.com/q/47197989
tags question: http://stackoverflow.com/q/47206714
tags question: http://stackoverflow.com/q/47126121
tags question: http://stackoverflow.com/q/47220786
tags question: http://stackoverflow.com/q/47212464
tags question: http://stackoverflow.com/q/47156673
tags question: http://stackoverflow.com/q/47143521
tags question: http://stackoverflow.com/q/47143718
tags question: http://stackoverflow.com/q/47104910
tags question: http://stackoverflow.com/q/47169336
tags question: http://stackoverflow.com/q/47112610
tags question: http://stackoverflow.com/q/47197152
tags question: http://stackoverflow.com/q/47127554
tags question: http://stackoverflow.com/q/47210486
tags question: http://stackoverflow.com/q/47178371
tags question: http://stackoverflow.com/q/47082454
tags question: http://stackoverflow.com/q/47214731
tags question: http://stackoverflow.com/q/47207361
tags question: http://stackoverflow.com/q/47204919
tags question: http://stackoverflow.com/q/47153429
tags question: http://stackoverflow.com/q/47069744
tags question: http://stackoverflow.com/q/47172770
tags question: http://stackoverflow.com/q/47117136
tags question: http://stackoverflow.com/q/47208640
tags question: http://stackoverflow.com/q/47129383
tags question: http://stackoverflow.com/q/47136101
tags question: http://stackoverflow.com/q/47075719
tag name: machine-learning
tags question: http://stackoverflow.com/q/47178587
tags question: http://stackoverflow.com/q/47115946
tags question: http://stackoverflow.com/q/47115957
tags question: http://stackoverflow.com/q/47079266
tags question: http://stackoverflow.com/q/47107645
tags question: http://stackoverflow.com/q/47122052
tags question: http://stackoverflow.com/q/47165079
tags question: http://stackoverflow.com/q/47183159
tags question: http://stackoverflow.com/q/47193911
tags question: http://stackoverflow.com/q/47200853
tags question: http://stackoverflow.com/q/47192771
tags question: http://stackoverflow.com/q/47174098
tags question: http://stackoverflow.com/q/47093415
tags question: http://stackoverflow.com/q/47106830
tags question: http://stackoverflow.com/q/47215317
tags question: http://stackoverflow.com/q/47185586
tags question: http://stackoverflow.com/q/47186313
tags question: http://stackoverflow.com/q/47147454
tags question: http://stackoverflow.com/q/47127962
tags question: http://stackoverflow.com/q/47069303
tags question: http://stackoverflow.com/q/47172108
tags question: http://stackoverflow.com/q/47100481
tags question: http://stackoverflow.com/q/47106331

http://stackoverflow.com/comment/81247530
score: 0
type: Comment
has text: ...oh, of course. `--prefix` and `--exec-prefix` don't just affect `sys.prefix` and `sys.exec_prefix`; they actually configure where the relevant files are installed.
type: QuestionComment
comment on: http://stackoverflow.com/q/47145091

http://stackoverflow.com/comment/81322818
type: AnswerComment
score: 0
has text: Sorry, but it turns out it doesn't actually work. This sorts the vector array along the next-to-last axis, but it should be the last axis. I should have been more clear in the question. From the documentation: "The normalized (unit “length”) eigenvectors, such that the column v[:,i] is the eigenvector corresponding to the eigenvalue w[i]."
comment on: http://stackoverflow.com/a/47171243
type: Comment

http://stackoverflow.com/comment/81189161
comment on: http://stackoverflow.com/q/47119717
has text: it's in media. because each team has it's own logo.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47139258
has comment: http://stackoverflow.com/comment/81228146
answer count: 1
downvote count: 0
score: 1
favorite count: 0
type: Question
upvote count: 1
tagged with: python
tagged with: sorting
tagged with: quicksort
accepted answer: http://stackoverflow.com/a/47139346
has title: QuickSort which correctly orders an array, but doesn't return it ordered
tagged with: recursion
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47139346
has body: I'm implementing Quick Sort in Python and I have little problem with it. My function works perfectly recursively, but it doesn't return me the ordered array, and returns me just the original array. In my code I have two versions of Quick Sort. quickSort_2 works correctly and orders the list. Instead quickSort_1 works exactly equal to quicksort_1 , but gives me back the original array. Any idea on why this is happening? import random import list def partition(A,p): pivot=A[p] sup=0 inf=len(A)-1 while sup!=inf: while A[sup]&lt;pivot: sup+=1 while A[inf]&gt;pivot: inf-=1 list.swap(inf,sup,A) #swap print A return sup def quickSort_1(A): if len(A)&lt;=1: return A r=random.choice(range(0,len(A)-1)) print A m=partition(A,r) return quickSort_1(A[:m+1])+quickSort_2(A[m+1:]) def quickSort_2(A): if len(A)&lt;=1: return A r=random.choice(range(0,len(A)-1)) print A m=partition(A,r) quickSort_1(A[:m+1]) quickSort_2(A[m+1:]) return A

http://stackoverflow.com/q/47148342
type: UnansweredQuestion
has body: I would like to periodically create pdfs with stocks of interest to me and related graphs for each stock. For the moment, I have one dataframe for each technical indicator (price, moving average, exponential moving average, etc.) and would like to plot for each time series their relevant information from each dataframe. Until now, I have used bokeh and I am able to plot what I want but for each ticker individually... The code I have is this: # Import dataframes from import_data.py prices = pd.read_pickle('prices.pkl') date = prices.index # price 20, 50, 80 MA ma20 = pd.rolling_mean(prices, window=20) ma50 = pd.rolling_mean(prices, window=50) ma80 = pd.rolling_mean(prices, window=80) # price with 20EMA+Bollinger Bands - 20MA ema20 = pd.ewma(prices, span=20) bbandsup = pd.ewma(prices, span=20) + 2 * pd.ewmstd(prices, span=20) bbandslo = pd.ewma(prices, span=20) - 2 * pd.ewmstd(prices, span=20) plot = figure(title="Price Chart and Technical Indicators", x_axis_label='Date', y_axis_label='Price') plot.line(date, prices['SPY'], legend='Price', line_width=2) plot.line(date, ema20['SPY'], legend='EMA-20', line_width=2, line_color="red") plot.line(date, ma20['SPY'], legend='EA-20', line_width=2, line_color="green") plot.line(date, bbandsup['SPY'], legend='Bollinger', line_width=2, line_color="black", line_dash="4 4") plot.line(date, bbandslo['SPY'], legend='Bollinger', line_width=2, line_color="black", line_dash="4 4") show(plot) prices dataframe has a structure of date as index and the column headers are the ticker strings. For example, the first column header is SPY, the second is AAPL, etc... I would like to be able to print all of them into pdf before attacking the multiple plot beast. Thanks in advance!
tagged with: python
score: 0
tagged with: pandas
answer count: 1
tagged with: bokeh
has title: Multiple plots to pdf from multiple dataframes
type: Question
has answer: http://stackoverflow.com/a/47156770

http://stackoverflow.com/comment/81258262
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47154351
type: Comment
has text: Probably i can save alot of time by this rather than going to the whole refactor

subclass
tags question: http://stackoverflow.com/q/47184192
type: Tag
tags question: http://stackoverflow.com/q/47161113
tag name: subclass

http://stackoverflow.com/a/47190742
upvote count: 3
downvote count: 0
has body: Second to last line, you typed: `if reslut in ...` Try with result.
has comment: http://stackoverflow.com/comment/81330896
has comment: http://stackoverflow.com/comment/81330898
answers question: http://stackoverflow.com/q/47190719
type: Answer
score: 3

http://stackoverflow.com/comment/82080644
has text: Can someone help me?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47208466

http://stackoverflow.com/a/47220888
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/81394055
type: Answer
accepted answer of: http://stackoverflow.com/q/47220773
upvote count: 4
has body: Are you try to achieve groupby? df.groupby('A').median() B C D A XX 2.0 2.5 2.0 Y 4.0 4.0 4.0 YX 2.0 2.0 2.0
answers question: http://stackoverflow.com/q/47220773
has comment: http://stackoverflow.com/comment/81393922
type: AcceptedAnswer

http://stackoverflow.com/q/47188835
has answer: http://stackoverflow.com/a/47197242
type: UnansweredQuestion
tagged with: python
has body: I want to parse a .proto file that is part of a gRPC client/server definition. I just want a starting point for doing this. I have the gRPC code installed and can autogenerate python code from the proto files. I am wondering if there are any obvious python classes in the gRPC code (or open source libs out there) that read in proto files and, in some limited way, parses them into some kind of structured objects?
score: 0
answer count: 2
tagged with: parsing
type: Question
has answer: http://stackoverflow.com/a/47309243
has title: grpc proto file parser
tagged with: protocol-buffers

http://stackoverflow.com/comment/81119102
score: 0
type: AnswerComment
has text: The `trim.count(j)` part counts how many times the value appears in the list (and is entirely separate to the `count` variable I set, sorry lol), and if it appears twice then there's your prefix. I have however just realised it only supports a single result, so I'll fix it up shortly :)
comment on: http://stackoverflow.com/a/47082551
type: Comment

http://stackoverflow.com/q/47102613
has answer: http://stackoverflow.com/a/47102779
linked to: http://stackoverflow.com/q/3294889
has comment: http://stackoverflow.com/comment/81155455
has answer: http://stackoverflow.com/a/47102729
has comment: http://stackoverflow.com/comment/81155589
downvote count: 3
has comment: http://stackoverflow.com/comment/81155434
upvote count: 1
has comment: http://stackoverflow.com/comment/81155478
favorite count: 0
has comment: http://stackoverflow.com/comment/81155530
type: Question
has comment: http://stackoverflow.com/comment/81155363
linked to: http://stackoverflow.com/q/8589812
has answer: http://stackoverflow.com/a/47102751
tagged with: object
has comment: http://stackoverflow.com/comment/81155377
accepted answer: http://stackoverflow.com/a/47102729
answer count: 5
score: -2
possible better answer: http://stackoverflow.com/a/47102725
has comment: http://stackoverflow.com/comment/81155446
has comment: http://stackoverflow.com/comment/81155551
tagged with: python
has answer: http://stackoverflow.com/a/47102725
has comment: http://stackoverflow.com/comment/81155646
has answer: http://stackoverflow.com/a/47102823
has comment: http://stackoverflow.com/comment/81155579
has body: I have a dictionary of items, where the list is formatted to be {(x,y): z, (x,y):z...} where x and y are coordinates and z is a probability. I need to perform operations using the probability. How can I access those? I tried things like for item in lst: print item[1] However, that only returned the y coordinate. Attempting to print item[2] returned the error "Need more than 2 values to unpack"
type: AnsweredQuestion
has title: Can't access Second Item of Python object

http://stackoverflow.com/q/47085156
has title: Dynamic Programming: Rod cutting and remembering where cuts are made
has answer: http://stackoverflow.com/a/69646712
tagged with: algorithm
type: UnansweredQuestion
tagged with: python
has body: So I have this code in python and currently it only returns the maximum value for cutting a rod. How can I modify this to also give me where the cuts were made? It takes a list of prices whose indices+1 correspond to the value of the rod at each length, and n, for length of the rod. the problem:http://www.radford.edu/~nokie/classes/360/dp-rod-cutting.html def cutRod(price, n): val = [0 for x in range(n+1)] val[0] = 0 for i in range(1, n+1): max_val = 0 for j in range(i): max_val = max(max_val, price[j] + val[i-j-1]) val[i] = max_val return val[n]
has answer: http://stackoverflow.com/a/47085276
has comment: http://stackoverflow.com/comment/81119865
has comment: http://stackoverflow.com/comment/81120281
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81120124
has answer: http://stackoverflow.com/a/52694509
has comment: http://stackoverflow.com/comment/81120349
answer count: 3
tagged with: dynamic-programming
has comment: http://stackoverflow.com/comment/81120386
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/q/47122821
type: AnsweredQuestion
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81254814
tagged with: observers
has comment: http://stackoverflow.com/comment/81254601
type: Question
accepted answer: http://stackoverflow.com/a/47170753
tagged with: sikuli
tagged with: automation
has title: Sikuli 1.1 observe behaviour
has answer: http://stackoverflow.com/a/47170753
has body: I am new to create code. I try using Sikuli with observe function. When I use the script it does the thing one time and then never again. while(1): def Handler(event): stopObserver click(image) event.repeat(1) pass while(1): onAppear("image", Handler) observe(FOREVER) What is wrong with the script? Why does the script only click the image one time. If the image appears a second time nothing happens.
tagged with: python
has comment: http://stackoverflow.com/comment/81206413

http://stackoverflow.com/comment/81193032
comment on: http://stackoverflow.com/q/47121644
score: 0
has text: Use binary search or similar, generating a new wave file that is for example half of the original, or similar, then find out which part contains the word `shipping`... etc.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47123502
type: Answer
score: 0
type: AcceptedAnswer
has body: No, there is no method in tkinter that forces the window to be below all other windows on the desktop.
has comment: http://stackoverflow.com/comment/135400107
accepted answer of: http://stackoverflow.com/q/47122453
answers question: http://stackoverflow.com/q/47122453

http://stackoverflow.com/q/47146905
has answer: http://stackoverflow.com/a/47147228
upvote count: 9
has comment: http://stackoverflow.com/comment/81259291
has comment: http://stackoverflow.com/comment/81275145
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/21945732
has comment: http://stackoverflow.com/comment/81265841
has answer: http://stackoverflow.com/a/47147002
tagged with: python
has comment: http://stackoverflow.com/comment/81244989
has answer: http://stackoverflow.com/a/47158246
answer count: 4
has body: How would I turn a generator of pairs (tuples): tuple_gen = (i for i in [(1, "a"), (2, "b"), (3, "c")]) Into two generators which would yield [1, 2, 3] and ["a", "b", "c"]? I need to process separately the first and second elements of the tuples and the processing functions expect an iterable. The generator is very large (millions of items) so I'd like to avoid having all items in memory at the same time unless there is no other solution.
tagged with: generator
tagged with: tuples
has comment: http://stackoverflow.com/comment/81244209
has comment: http://stackoverflow.com/comment/81246253
has title: Turning a generator of pairs into a pair of generators
has comment: http://stackoverflow.com/comment/81281285
has comment: http://stackoverflow.com/comment/81283294
has comment: http://stackoverflow.com/comment/81281382
has comment: http://stackoverflow.com/comment/81244177
has comment: http://stackoverflow.com/comment/81244172
linked to: http://stackoverflow.com/q/47166701
has comment: http://stackoverflow.com/comment/81282407
has comment: http://stackoverflow.com/comment/81247775
has comment: http://stackoverflow.com/comment/81274243
downvote count: 1
has comment: http://stackoverflow.com/comment/81282285
score: 8
has comment: http://stackoverflow.com/comment/81244137
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47147107

http://stackoverflow.com/comment/81193605
has text: @eyllanesc also no difference :/
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47101062

http://stackoverflow.com/comment/81267104
type: QuestionComment
has text: The text literal should be in single-quotes: `cursor.execute("select custom_fn(col_1, 'xxx') as id from table;")`
comment on: http://stackoverflow.com/q/47143090
score: 0
type: Comment

http://stackoverflow.com/a/47107054
has comment: http://stackoverflow.com/comment/81165666
has comment: http://stackoverflow.com/comment/81416783
has comment: http://stackoverflow.com/comment/81416861
type: Answer
has body: I believe the reason why you can't scrap the nested elements is because the website you access is heavily rendered by Javascript. I've used selenium to verify if that was the case, and I was able to parse the nested elements normally with no problems. Code: from selenium import webdriver from bs4 import BeautifulSoup chromeOptions = Options() chromeOptions.add_argument("--headless") driver = webdriver.Chrome(chrome_options=chromeOptions) url = 'http://www.lcd-compare.com/televiseur-SAMUE49MU9005-SAMSUNG-UE49MU9005.htm' driver.get(url) soup = BeautifulSoup(driver.page_source, 'html.parser') tec_list = soup.findAll("div",{"class","product-tech-section-row"}) print(tec_list[0]) Output: Désignation : SAMSUNG UE49MU9005 (UE 49MU9005 TXXC) Plus d'informations sur les TV LED Samsung Voir les TV 4K (Ultra HD ou Quad HD)
has comment: http://stackoverflow.com/comment/81418629
score: 0
has comment: http://stackoverflow.com/comment/81376110
accepted answer of: http://stackoverflow.com/q/47106878
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81416828
has comment: http://stackoverflow.com/comment/81418500
answers question: http://stackoverflow.com/q/47106878

http://stackoverflow.com/a/47209075
has body: Create your dict with new lists: import string s = 'abcdabcd' n = len(s) cnt = dict(zip(string.ascii_lowercase, [[0 for _ in range(n + 1)] for __ in range(26)])) print('Before') print(cnt) for i in range(n): for char in string.ascii_lowercase: cnt[char][i + 1] = cnt[char][i] + (1 if char == s[i] else 0) print('After') print(cnt)
answers question: http://stackoverflow.com/q/47208911
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47208911
score: 0
type: Answer

http://stackoverflow.com/q/47203801
answer count: 2
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/65715120
favorite count: 0
type: Question
tagged with: google-analytics
tagged with: google-analytics-firebase
type: UnansweredQuestion
has body: Based on the example here: https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py I am trying to find search result information within a public library catalog. I can get results by filling in the proper metrics and dimensions, but I can't figure out how to integrate 'sort' into the def get_report(analytics): """Queries the Analytics Reporting API V4. Args: analytics: An authorized Analytics Reporting API V4 service object. Returns: The Analytics Reporting API V4 response. """ return analytics.reports().batchGet( body={ 'reportRequests': [ { 'viewId': VIEW_ID, 'dateRanges': [{'startDate': '1daysAgo', 'endDate': 'today'}], 'metrics': [{'expression': 'ga:avgSearchResultViews'}], 'dimensions': [{'name': 'ga:searchKeyword'}], }] } ).execute() Does anyone know how I can integrate a sort and possible a maxResults limiter in the block of code above? Google has info regarding sort here: https://developers.google.com/analytics/devguides/reporting/core/v3/reference#sort. I have tried adding the "-" to the metrics expression and even adding a whole new line for 'sort', but it hasn't been able to help me yet.
tagged with: python
tagged with: sorting
has answer: http://stackoverflow.com/a/55809238
has title: Google Analytics Reporting API v4 sort results
score: 2

http://stackoverflow.com/q/47126285
upvote count: 3
tagged with: dataframe
tagged with: python
tagged with: stock
has answer: http://stackoverflow.com/a/47126423
has comment: http://stackoverflow.com/comment/81202933
favorite count: 0
type: Question
tagged with: concatenation
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81202615
has comment: http://stackoverflow.com/comment/81202775
score: 3
has body: I am working on a simple trading also and need some help with concatenating to data frames together. Until my now my approach does't work. My code is the following: Connect to quantle API quandl.ApiConfig.api_key = 'xxxxxxxxxxxxxxx' Ticker symbols ticker = ['FSE/ZO1_X',"FSE/WAC_X"] Create a panel object with quotes from panda -> create a pandas DataFrame df = quandl.get(ticker, start_date='2017-01-01', end_date='2017-11-03') Slicing the close prices for each stock out of the panel data set close1 = df['FSE/ZO1_X - Close'] close2 = df['FSE/WAC_X - Close'] Concatenate the two data frames together - THIS STEP DOESN'T WORK close = pd.concat(close1,close2) The type of close1 and close 2 is pandas.core.series.Series. How can I put close1 and close2 together, so that the index is the date and I have two additional columns with the close prices of stock 1 (close1) and stock 2 (close2) - similar like an ordinary excel sheet.
has title: Concatenate two pandas data frames together (in python)
tagged with: pandas

http://stackoverflow.com/comment/81139295
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47094959
has text: Could you add that to the question? That way people will be able to see how you've formatted the code as well.

http://stackoverflow.com/a/47197558
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47197259
answers question: http://stackoverflow.com/q/47197259
type: Answer
has body: Assuming your data looks like this: emotion &lt;- c(0,1,2) pixels &lt;- c("23 54", "76 32", "86 23") df &lt;- data.frame(emotion,pixels,stringsAsFactors = FALSE) &gt; df emotion pixels 1 0 23 54 2 1 76 32 3 2 86 23 You can split the pixels column using this command df &lt;- cbind(emotion = df$emotion, data.frame(do.call( 'rbind', strsplit(as.character(df$pixels), ' ', fixed = TRUE) ), stringsAsFactors = FALSE)) which will give you this: &gt; df emotion X1 X2 1 0 23 54 2 1 76 32 3 2 86 23
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/108824270
comment on: http://stackoverflow.com/a/51547855
type: Comment
score: 1
has text: Just for fun if anyone likes pixelated images... https://www.bustle.com/articles/26226-italian-designer-marco-sodano-remakes-classic-art-with-legos-and-its-awesome
type: AnswerComment

http://stackoverflow.com/a/47096546
has body: You can use get function in dictionary print(john.get('age' , 0)) get take two parameter first the key then the default value to load if key not found
has comment: http://stackoverflow.com/comment/81142704
score: 0
answers question: http://stackoverflow.com/q/47096491
type: Answer

http://stackoverflow.com/q/47142936
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47143047
accepted answer: http://stackoverflow.com/a/47143047
type: Question
has body: I'm looking at https://github.com/ibininja/upload_file_python . I'm working in win 7 with pycharm 2017. The main code contains: @app.route("/upload", methods=["POST"]) def upload(): folder_name = request.form['superhero'] ''' # this is to verify that folder to upload to exists. if os.path.isdir(os.path.join(APP_ROOT, 'files/{}'.format(folder_name))): print("folder exist") ''' target = os.path.join(APP_ROOT, 'files/{}'.format(folder_name)) print(target) I'd like to debug this in pycharm. I can debug the '/' route as in the screenshot. How do I debug a specific flask route like "/upload" ?
score: 0
tagged with: pycharm
upvote count: 1
answer count: 1
has title: How to debug a flask route with pycharm
tagged with: python
tagged with: flask
downvote count: 1

http://stackoverflow.com/comment/81287127
score: 0
has text: I think you should use `[features_dict['coords']]` plus get rid of those dicts as I commented above
type: AnswerComment
comment on: http://stackoverflow.com/a/47137142
type: Comment

http://stackoverflow.com/q/47163914
has body: I'm currently testing disqus API, and faced a problem: after i've got code (after user authenticated) when trying to get an access token via given instructions POST https://disqus.com/api/oauth/2.0/access_token/ grant_type=authorization_code& client_id=PUBLIC_KEY& client_secret=SECRET_KEY& redirect_uri=http://www.example.com/oauth_redirect& code=CODE it returns me 405 when requesting as in instruction or 'parameter "grant_type" is required' if requesting as in my code. I use following code payload = {'grant_type':'authorization_code', 'client_id':data["client_id"], 'client_secret':data["client_secret"], 'redirect_uri':data["redirect_uri"], 'code':data["code"], } result = urlencode(payload, quote_via=quote_plus) r = requests.post("https://disqus.com/api/oauth/2.0/access_token/?"+result) I suspect, OAuth needs to be enabled for your API key. causes this issue. Any one knows what's wrong? If the problem is that my API key need to have OAuth enabled, then how can i do that (disqus documentation is a little bit inadequate)? Or the issue is in my code?
type: Question
tagged with: access-token
type: UnansweredQuestion
tagged with: python
score: 3
answer count: 0
upvote count: 3
downvote count: 0
tagged with: disqus
has title: Disqus API getting user access token via Python
favorite count: 0

http://stackoverflow.com/q/47173293
upvote count: 1
has answer: http://stackoverflow.com/a/47175207
linked to: http://stackoverflow.com/q/3701646
favorite count: 0
has title: How can I run python version 3.6.2 instead of 3.6.1
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47175207
tagged with: python
tagged with: python-3.6
has body: this is my first time here, and I'm fairly new to python, so please let me know if you need more information. Thanks in advance. I am running python 3 on Windows 7 I discovered my problem after I used pip install numpy. This works just fine. Then, when I try to use import numpy in the python shell I receive the ModuleNotFoundError: No module named 'numpy'. That's when I noticed that my default version of python was 3.6.1, despite having updated to 3.6.2 at some point. I still have both .exe setup files and when I run them it shows that I only have 3.6.2 installed. However, when I type python --version in the command line i get Python 3.6.1, even though Python36-32 is what i have in my path. I think my question is how can I make sure I'm running the newer version of python as my default, or if need be, how can I get rid of the older version?
type: AnsweredQuestion
score: 1
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/4750806

http://stackoverflow.com/q/47128070
tagged with: quicksort
type: AnsweredQuestion
score: 0
has title: QuickSort does not work well - Python 3
answer count: 1
has body: I have a problem with QuickSort. He's ordering me the list but taking some items from me. I don't know what the mistake is. I'd appreciate your help. Code: #QuickSort def quickSort(lista): if len(lista) &lt; 2: return lista menores, medio, mayores = _partition(lista) return quickSort(menores) + medio + quickSort(mayores) def _partition(lista): pivote = lista[0] menores = [] mayores = [] for x in range(1,len(lista)-1): if lista[x] &lt; pivote: menores.append(lista[x]) else: mayores.append(lista[x]) return menores, [pivote], mayores L = [6,7,-1,0,5,2,3,8] print(quickSort(L)) Result: [-1, 0, 5, 6, 7] [Finished in 0.2s]
has answer: http://stackoverflow.com/a/47128091
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/47128091

http://stackoverflow.com/comment/81379985
type: Comment
score: 0
has text: Oh I thought django requires title case to get the model object
comment on: http://stackoverflow.com/q/47214664
type: QuestionComment

http://stackoverflow.com/q/47184131
has body: Problem Description: You want to build a house on an empty land which reaches all buildings in the shortest amount of distance. You can only move up, down, left and right. You are given a 2D grid of values 0, 1 or 2, where: Each 0 marks an empty land which you can pass by freely. Each 1 marks a building which you cannot pass through. Each 2 marks an obstacle which you cannot pass through. For example, given three buildings at (0,0), (0,4), (2,2), and an obstacle at (0,2): 1 - 0 - 2 - 0 - 1 | | | | | 0 - 0 - 0 - 0 - 0 | | | | | 0 - 0 - 1 - 0 - 0 The point (1,2) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is minimal. So return 7. I solved this problem by BFS way. Then I want to solve it with DFS way but got stuck. Below is my code: class Solution(object): def shortestDistance(self, grid): """ :type grid: List[List[int]] :rtype: int """ rl, cl = len(grid), len(grid[0]) builds = sum([col for row in grid for col in row if col == 1]) dist, hit = [[0] * cl for _ in range(rl)], [[0] * cl for _ in range(rl)] def dfs(x, y, step): ''' Wrong answer, it seems result dist alway keep the longest distance? ''' if 0 &lt;= x &lt; rl and 0 &lt;= y &lt; cl and not visited[x][y]: visited[x][y] = True if grid[x][y] == 0: dist[x][y] += (step + 1) hit[x][y] += 1 dfs(x - 1, y, step + 1) dfs(x + 1, y, step + 1) dfs(x, y - 1, step + 1) dfs(x, y + 1, step + 1) def bfs(x, y): ''' works properly ''' visited = [[False] * cl for _ in range(rl)] queue =[(x, y, 0)] while queue: k, m, step = queue.pop(0) for i, j in ((k - 1, m), (k + 1, m), (k, m - 1), (k, m + 1)): if 0 &lt;= i &lt; rl and 0 &lt;= j &lt; cl and not visited[i][j]: visited[i][j] = True if grid[i][j] == 0: dist[i][j] += (step + 1) hit[i][j] += 1 queue.append((i, j, step + 1)) for i in range(rl): for j in range(cl): if grid[i][j] == 1: # bfs(i, j) # this works properly visited = [[False] * cl for _ in range(rl)] dfs(i - 1, j, 0) dfs(i + 1, j, 0) dfs(i, j - 1, 0) dfs(i, j + 1, 0) ret = float('inf') for…
tagged with: algorithm
has title: What's wrong with this DFS solution?
tagged with: python
type: Question
score: 0
has answer: http://stackoverflow.com/a/47185934
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/81248888
comment on: http://stackoverflow.com/a/47149069
has text: @Shta and what is that error? Please add that to the question.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/81391379
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47220781
score: 0
has text: My question is how do I write the data and save that data locally for every single employee individually.

http://stackoverflow.com/comment/81181422
type: Comment
type: QuestionComment
has text: Thanks for pointing in this direction. Then probably I need to change the type of distributions in the bimodal distribution function. I will look into it.
score: 0
comment on: http://stackoverflow.com/q/47110254

http://stackoverflow.com/comment/81252167
score: 2
comment on: http://stackoverflow.com/q/47151291
has text: `print("GOTO/" + line)`?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47067097
score: 1
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: I am working on a project which requires my current location's exact lat-long. I tried to run the code using Google Maps API as well as http://freegeoip.net/json on windows 7 machine, but nothing seems to take 'My current location' as an input and output the exact lat-long. Can someone please help? Thanks, Sanket.
has answer: http://stackoverflow.com/a/47067230
has comment: http://stackoverflow.com/comment/81082227
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81082222
has comment: http://stackoverflow.com/comment/81082241
has comment: http://stackoverflow.com/comment/81082578
tagged with: currentlocation
upvote count: 3
has title: Python 3.3.5 - Get my current location's lat and long
downvote count: 2
tagged with: google-maps

http://stackoverflow.com/q/47115684
has comment: http://stackoverflow.com/comment/81181318
tagged with: resize
tagged with: python
upvote count: 4
score: 4
tagged with: scrollbar
linked to: http://stackoverflow.com/q/21766890
linked to: http://stackoverflow.com/q/28631312
has answer: http://stackoverflow.com/a/75712699
possible better answer: http://stackoverflow.com/a/75712699
has answer: http://stackoverflow.com/a/47139120
type: AnsweredQuestion
tagged with: tkinter
answer count: 2
tagged with: canvas
downvote count: 0
has title: Python tkinter frame canvas resize
accepted answer: http://stackoverflow.com/a/47139120
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/29319445
has body: I'm attempting to resize a canvas so the canvas fills the entire window when the window is resized by the user employing a 'click and drag' on the window edge, but I am not successful. I have looked at the following other questions: Question #1 (previously posted, but not helping here) This one sent me in what I thought was the correct direction because I bind a Configure on canvas. However, I get an error that " 'canvas' is not defined in FrameWidth." Tkinter: How to get frame in canvas window to expand to the size of the canvas? If I modify the function call and the function, then I get the error that "TypeError: FrameWidth() missing 1 required positional argument: 'canvas' " The modification is canvas.bind('&lt;Configure&gt;', self.FrameWidth(canvas)) def FrameWidth(self, event, canvas): Question #2 (previously posted, but not helping here) I also looked at this question: Python Tkinter Scrollbar Shaky Scrolling But this question is addressing an erratically behaving scrollbar. Question #3 (previously posted, but not helping here) I have also looked at this questions and put in weight=1, but that is not helping: Python TKinter: frame and canvas will expand horizontally, but not vertically, when window is resized Any advice would be appreciated. Here's my MWE: #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 3 04:39:43 2017 @author: davidc """ import tkinter as tk class Selections(tk.Frame): def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) self.FifthLabelLeft = tk.Label(self, text="""Riding""", justify = tk.CENTER, width=20, padx = 10).grid(row=4, column = 0, pady=5) self.FifthLabelCenter = tk.Label(self, text="""Winning Candidate""", justify = tk.CENTER, width=20, padx = 10).grid(row=4, column = 1, pady=5) self.FifthLabelRight = tk.Label(self, text="""Percent of Vote""", justify = tk.CENTER, width=10, padx = 10).grid(row=4, column = 2, pady=5) mybox = tk.LabelFrame(self, padx=5, pady=4) mybox.grid(row=5, column=0,…
has comment: http://stackoverflow.com/comment/81181684

http://stackoverflow.com/q/47122317
tagged with: normal-distribution
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81196127
tagged with: java
has comment: http://stackoverflow.com/comment/81196201
has comment: http://stackoverflow.com/comment/81195155
has comment: http://stackoverflow.com/comment/81196153
tagged with: tensorflow
type: Question
type: UnansweredQuestion
has body: I need to implement the cumulative distribution function of the normal distribution in Java Tensorflow. There is a library function in the python library for Tensorflow Python. Is there a library function of the normal distribution in the Java Tensorflow library? If yes, how can I use it?
has comment: http://stackoverflow.com/comment/81194407
linked to: http://stackoverflow.com/q/442758
tagged with: python
has title: tensorflow java normal distribution

http://stackoverflow.com/comment/81241441
type: QuestionComment
comment on: http://stackoverflow.com/q/47144132
has text: Possible duplicate of https://stackoverflow.com/questions/29242000/how-can-i-write-a-recursive-function-to-reverse-a-linked-list
score: 0
type: Comment

http://stackoverflow.com/q/47098589
tagged with: python
has title: I want to setup a would you like to retry
type: AnsweredQuestion
score: -1
upvote count: 1
has comment: http://stackoverflow.com/comment/81147768
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47098751
answer count: 2
has body: I have created a guess the number game, at the end of it I want it to ask the user if they would like to retry. I got it to take invalid responses and if Yes then it will carry on, but when I say no it still carries on. import random from time import sleep #Introduction &amp; Instructions print ("Welcome to guess the number") print ("A random number from 0 - 1000 will be generated") print ("And you have to guess it ") print ("To help find it you can type in a number") print ("And it will say higher or lower") guesses = 0 number = random.randint(0, 1)#Deciding the number while True: guess = int (input("Your guess: "))#Taking the users guess #Finding if it is higher, lower or correct if guess &lt; number: print ("higher") guesses += 1 elif guess &gt; (number): print ("lower") guesses += 1 elif guess == (number): print ("Correct") print (" ") print ("It took you {0} tries".format(guesses)) #Asking if they want another go while True: answer = input('Run again? (y/n): ') if answer in ('y', 'n'): break print ('Invalid input.') if answer == 'y': continue if answer == 'n': exit()
has answer: http://stackoverflow.com/a/47098751
accepted answer: http://stackoverflow.com/a/47099182
downvote count: 2
has answer: http://stackoverflow.com/a/47099182

http://stackoverflow.com/q/47147964
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47148112
linked to: http://stackoverflow.com/q/849142
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47148029
score: 2
answer count: 2
upvote count: 2
downvote count: 0
has title: max_digits for IntegerField Django
has comment: http://stackoverflow.com/comment/81246183
favorite count: 0
type: Question
has body: I am looking for a way to specify an IntegerField so that it has a certain maximum of digits. What I'm looking for is similar to max_length of a CharField. I have searched the internet and even in this forum, but they are all answers related to adding minimum and maximum values such as min_length and max_length or adding validators. So that they do not get confused, what interests me is to establish an IntegerField with a maximum of digits and not a maximum value. Is there a function that can provide me so that in the model a parameter can be added to this IntegerField? E.g.: code = models.IntegerField('Code', primary_key=True, max_digits=8)
has comment: http://stackoverflow.com/comment/81253474

http://stackoverflow.com/q/47068017
has comment: http://stackoverflow.com/comment/81085682
has answer: http://stackoverflow.com/a/47089372
has comment: http://stackoverflow.com/comment/81085873
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81086156
tagged with: performance
answer count: 3
has answer: http://stackoverflow.com/a/47068264
upvote count: 5
has comment: http://stackoverflow.com/comment/81085354
accepted answer: http://stackoverflow.com/a/47068979
has title: alternative to numpy.argwhere to speed up for loop in python
has comment: http://stackoverflow.com/comment/81084692
has answer: http://stackoverflow.com/a/47068979
has body: I have two data-sets as following: ds1: a DEM (digital elevation model) file as 2d numpy array and, ds2: which is showing areas (pixels) with some excess water in them. I have a while loop that is responsible to spread (and change) excess volume in each pixel according to the elevation of its 8 neighbours and itself until the excess volume in each pixel is less than a certain value d = 0.05. Therefore in each iteration I need to find the index of pixels in ds2 where excess volume is greater than 0.05 and if there is no pixel left, exit the while loop: exit_code == "No" while exit_code == "No": index_of_pixels_with_excess_volume = numpy.argwhere(ds2&gt; 0.05) # find location of pixels where excess volume is greater than 0.05 if not index_of_pixels_with_excess_volume.size: exit_code = "Yes" else: for pixel in index_of_pixels_with_excess_volume: # spread those excess volumes to the neighbours and # change the values of ds2 the problem is that numpy.argwhere(ds2> 0.05) is very slow. I am looking for an alternative solution that is faster.
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/47068264
score: 5
has comment: http://stackoverflow.com/comment/81084452
has comment: http://stackoverflow.com/comment/81084411
downvote count: 0
tagged with: python
favorite count: 0

http://stackoverflow.com/q/47163874
score: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47164196
favorite count: 0
type: Question
has title: How can I add a list in a Tree`s node in Python?
tagged with: python
has body: I am trying to create a list inside this node of my AVL Tree, I also tried a function, someone has some library to import or some idea? #import random, math import re outputdebug = False def debug(msg): if outputdebug: print msg class Node(): def __init__(self, key): self.key = key self.left = None self.right = None self.list = [] #list at the node class AVLTree(): def __init__(self, *args): self.node = None self.height = -1 self.balance = 0; def ad_list(self, value): self.list.append(value) #function trying to add def print_list(self): print self.list
tagged with: avl-tree
has comment: http://stackoverflow.com/comment/81277461
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/81277466
upvote count: 2
accepted answer: http://stackoverflow.com/a/47164196

http://stackoverflow.com/q/47147801
upvote count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47150135
has comment: http://stackoverflow.com/comment/81288266
has comment: http://stackoverflow.com/comment/81254394
has title: After successfully login in facebook, i show this notification:
has body: enter image description here I tried to dismiss it by code#1: webdriver.Chrome('F:/chromedriver_win32 (3)/chromedriver.exe',chrome_options=options) options = Options() options.add_argument("--disable-notifications") This code doesn't work for me. I also tried with the code#2: alert=driver.switch_to_alert() alert.dismiss() Can anyone help me to solve this out ?
tagged with: selenium
has answer: http://stackoverflow.com/a/47149668
score: -1
type: Question
tagged with: selenium-chromedriver
answer count: 2

http://stackoverflow.com/q/47156332
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81262318
tagged with: xlsxwriter
downvote count: 0
has title: Appending multiple style on pandas excel worksheet
answer count: 1
has comment: http://stackoverflow.com/comment/81262293
favorite count: 0
tagged with: excel
has body: PandasWriter = pandas.ExcelWriter(self.sio, engine='xlsxwriter') workbook = PandasWriter.book worksheet = PandasWriter.sheets['Sheet1'] black_shade = workbook.add_format({'bg_color':'#f6f7f8'}) bold = workboot.add_format({'bold': True}) worksheet.set_columns('A:C',None, black_shade) worksheet.set_rows(20, None, bold) Need to have A20 cell to have black_shade and be bold. How do i append two formats. Format set on columns gets replaced by format on rows.
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47156561
tagged with: pandas

http://stackoverflow.com/comment/81380195
type: Comment
comment on: http://stackoverflow.com/a/47215202
score: 0
type: AnswerComment
has text: Cool, hope that gets you sorted. Remember to mark the right answer.

http://stackoverflow.com/comment/81436559
score: 1
type: Comment
type: AnswerComment
has text: Are you aware of [seaborn's palette system](http://seaborn.pydata.org/tutorial/color_palettes.html)? It may already go a lot into the direction of what you want, although it has no accessible categories/subcategories feature either.
comment on: http://stackoverflow.com/a/47232942

http://stackoverflow.com/comment/81283531
type: Comment
comment on: http://stackoverflow.com/a/47166423
score: 0
type: AnswerComment
has text: Thanks for the answer, it seems to work correctly and efficiently which is exactly what I was looking for. But could you maybe expand your commenting so explain what truncating is, map is, what splitlines is, what seek is ect. This is because firstly I can understand how it works fully instead of partially and secondly that I don't just copy code from the internet without knowing how it works (basically make me learn from the internet and not just copy and paste, you know what I mean :). ) Thanks in advance.

http://stackoverflow.com/q/47222655
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81395642
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
score: 0
linked to: http://stackoverflow.com/q/285061
has comment: http://stackoverflow.com/comment/81394996
has comment: http://stackoverflow.com/comment/81394993
duplicate of: http://stackoverflow.com/q/285061
has title: How I can add attribute to python object if its name is variable?
tagged with: python
has body: Hi I want add some attribut to python object. But its name I don't know and it is a varieble. In js it will be like this: obj[somename] = 'str'
answer count: 0

http://stackoverflow.com/a/47181140
score: 5
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/81311549
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47180910
has body: Thankfully Python doesn't allow you to do this, class is a keyword that can't be used as an identifier. One alternative also mentioned in PEP 8 is using a trailing underscore: class_ = ... but you really should avoid such names since they mostly serve to confuse. You should always strive for more descriptive ones. If class is the only option, the other (somewhat) viable approach would be to use a dictionary: &gt;&gt;&gt; names = {'class': 'something'} &gt;&gt;&gt; names['class'] 'something'
has comment: http://stackoverflow.com/comment/81311687
has comment: http://stackoverflow.com/comment/81311892
answers question: http://stackoverflow.com/q/47180910

http://stackoverflow.com/comment/127566510
type: Comment
comment on: http://stackoverflow.com/q/47180328
type: QuestionComment
has text: This thread answers the question very well: https://github.com/matplotlib/matplotlib/issues/17284
score: 0

http://stackoverflow.com/q/47208653
has comment: http://stackoverflow.com/comment/81493141
type: Question
has comment: http://stackoverflow.com/comment/81492209
has comment: http://stackoverflow.com/comment/81496142
has comment: http://stackoverflow.com/comment/81367352
has comment: http://stackoverflow.com/comment/81495954
has comment: http://stackoverflow.com/comment/81369617
has comment: http://stackoverflow.com/comment/81383141
type: UnansweredQuestion
has title: Django Changing css for base.html based on model instance field value
tagged with: python
has comment: http://stackoverflow.com/comment/81376650
has comment: http://stackoverflow.com/comment/81496018
tagged with: notifications
answer count: 0
has comment: http://stackoverflow.com/comment/81366703
has comment: http://stackoverflow.com/comment/81496108
score: 0
has comment: http://stackoverflow.com/comment/81496077
has body: I have just built this notification system and it works great. However, I don't want to expect that a user will check the notifications page themselves, and so in order to notify the user that they have a new notification I would like the notification link in the nabber to have different css properties depending on if that user has any notifications that have not been read. I am a little stuck on this because the html link that should be changed is in my base.html rather than the app. Also, being that it is a notifications system and new notifications are created all the time and being marked read all the time it needs to be able to go through a loop and look at every notification pertaining to the logged in user. Here is my code, any help would be much appreciated. Notify app Model: class UserNotification(models.Model): fromUser = models.ForeignKey(User,related_name='user',null=True) post = models.ForeignKey('feed.UserPost',related_name='post') toUser = models.CharField(max_length=100,default='user') timestamp = models.DateTimeField(auto_now_add=True) notify_type = models.CharField(max_length=10) read = models.BooleanField(default=False) def get_absolute_url(self): return reverse('notify:user_notifications') def __str__(self): return str(self.fromUser) Base.html navbar: Evverest Home {% if request.user.is_authenticated %} Notifications All Members Logout {% else %} Login Register {% endif %} There isn't really a view associated with this right now, let me know if you need to see anything else. Second Edit Just for clarification, I just want to be able to change the CSS of the notification button in the navbar. Here is picture to show what I am talking about:
has comment: http://stackoverflow.com/comment/81495856
has comment: http://stackoverflow.com/comment/81382284
has comment: http://stackoverflow.com/comment/81496155
tagged with: django

http://stackoverflow.com/q/47186746
score: 1
accepted answer: http://stackoverflow.com/a/47186965
linked to: http://stackoverflow.com/q/8968884
favorite count: 0
has answer: http://stackoverflow.com/a/47186965
has comment: http://stackoverflow.com/comment/81322646
has title: Export lists and variables in a txt file and import them in python
type: Question
linked to: http://stackoverflow.com/q/31915120
downvote count: 0
upvote count: 1
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/81322670
has comment: http://stackoverflow.com/comment/81322656
has body: I am new to python and would like to export some nested lists and some variables in a .txt file in python, and to be able to retrieve these data and to import them later in python. For instance, my_list1 = [[[-1, 1, 0, -1]], [[-1, 1, 0, -1]]] my_list2 = [[[2, 1, 1], [1, 1, 0, 2]], [[2, 1, 1, 0], [0, 2, 1, 1]]] my_var = 3 my_var2 = 7 I tried with open("file.txt", "w") as f: for ( my_list1 , my_list2) in zip(my_list1 , my_list2 ): f.write("{1},{2}\n".format(my_list1 , my_list2)) but I don't know how to also export my variables with it, and how to import and retrieve each data after. Thanks
type: AnsweredQuestion

http://stackoverflow.com/comment/81181211
type: AnswerComment
comment on: http://stackoverflow.com/a/47115578
type: Comment
score: 0
has text: `ctrl c - ctrl v` of @mgilson 's comment and adding a redundant `()` around the boolean statement...

http://stackoverflow.com/q/47099348
tagged with: pystache
has body: Say I want to write a function that format floats with 2 digits in pystache. I want both the float number and the function in the context (I believe this is the correct philosophy of Mustache). What should I do? In order to make the problem clear, I will show a pair of code snippets I have written. They do not work. Snippet (a): import pystache tpl = "{{#fmt}}{{q}}{{/fmt}}" ctx = { 'q' : 1234.5678, 'fmt' : lambda x: "%.2f" % float(x) } print pystache.render(tpl, ctx) This fails, with error "could not convert string to float: {{q}}". I can understand this error: {{fmt}} is evaluated before {{q}}. Snippet (b): import pystache tpl = "{{#q}}{{fmt}}{{/q}}" ctx = { 'q' : 1234.5678, 'fmt' : lambda x: "%.2f" % float(x) } print pystache.render(tpl, ctx) This fails with error: "lambda() takes exactly 1 argument (0 given)". I can't understand this error: shouldn't the context be passed as argument?
has comment: http://stackoverflow.com/comment/81149706
tagged with: mustache
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81150075
answer count: 3
upvote count: 3
has answer: http://stackoverflow.com/a/47125831
downvote count: 0
linked to: http://stackoverflow.com/q/10064975
favorite count: 0
has comment: http://stackoverflow.com/comment/81179186
type: Question
score: 3
has answer: http://stackoverflow.com/a/47132455
possible better answer: http://stackoverflow.com/a/47132455
has title: Understanding lambdas in pystache
has comment: http://stackoverflow.com/comment/81149995
has answer: http://stackoverflow.com/a/50490860
accepted answer: http://stackoverflow.com/a/47125831
tagged with: python
has comment: http://stackoverflow.com/comment/81148719
tagged with: lambda

http://stackoverflow.com/comment/81194465
comment on: http://stackoverflow.com/a/47122405
score: 0
type: Comment
has text: Oh no this simple. Again I thought too much maybe
type: AnswerComment

http://stackoverflow.com/comment/81442153
has text: the correct order that worked for me is tl -> tr -> bl -> br
type: AnswerComment
comment on: http://stackoverflow.com/a/47133639
score: 0
type: Comment

http://stackoverflow.com/a/47143789
answers question: http://stackoverflow.com/q/47142496
accepted answer of: http://stackoverflow.com/q/47142496
type: Answer
has comment: http://stackoverflow.com/comment/81247193
has body: If the distribution is one of those that is available in scipy.stats then you can evaluate its integral between the two bounds using the cdf for that distribution. Otherwise, you can define the pdf for rv_continuous and then use its cdf to get this integral. Now, you have, in effect, the pdf for the bounded version of the pdf you want because you have calculated the normalising constant for it, in that integral. You can proceed to use rv_continuous with the form that you have for the pdf plus the normalising constant and with the bounds. Here's what your code might be like. The variable scale is set according to the scipy documents. norm is the integral of the exponential pdf over [0,1]. Only about .49 of the probability mass is accounted for. Therefore, to make the exponential, when truncated to the [0,1] interval give a mass of one we must divide its pdf by this factor. Truncated_expon is defined as a subclass of rv_continuous as in the documentation. By supplying its pdf we make it possible (at least for such a simple integral!) for scipy to calculate this distribution's cdf and thereby to calculate random samples. I have calculated the cdf at one as a check. &gt;&gt;&gt; from scipy import stats &gt;&gt;&gt; lamda = 2/3 &gt;&gt;&gt; scale = 1/lamda &gt;&gt;&gt; norm = stats.expon.cdf(1, scale=scale) &gt;&gt;&gt; norm 0.48658288096740798 &gt;&gt;&gt; from math import exp &gt;&gt;&gt; class Truncated_expon(stats.rv_continuous): ... def _pdf(self, x, lamda): ... return lamda*exp(-lamda*x)/0.48658288096740798 ... &gt;&gt;&gt; e = Truncated_expon(a=0, b=1, shapes='lamda') &gt;&gt;&gt; e.cdf(1, lamda=lamda) 1.0 &gt;&gt;&gt; e.rvs(size=20, lamda=lamda) array([ 0.20064067, 0.67646465, 0.89118679, 0.86093035, 0.14334989, 0.10505598, 0.53488779, 0.11606106, 0.41296616, 0.33650899, 0.95126415, 0.57481087, 0.04495104, 0.00308469, 0.23585195, 0.00653972, 0.59400395, 0.34919065, 0.91762547, 0.40098409])
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81274064
type: AcceptedAnswer

http://stackoverflow.com/a/47076227
upvote count: 4
has body: As the KNIME FAQ states you can execute your workflow from the command line on a Linux machine: To run the workflow "Knime_project": knime -nosplash -application org.knime.product.KNIME_BATCH_APPLICATION -workflowDir="workspace/Knime_project" You can also change the configuration of the workflow: -workflow.variable=my_integer,5,int
answers question: http://stackoverflow.com/q/47074287
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47074287
downvote count: 0
type: Answer
score: 4

http://stackoverflow.com/comment/81164520
type: AnswerComment
has text: Sorry just one more question. Is there an easy way to dump this into the template? I'm guessing I just append them all into a list and then handle them that way. The only reason I ask is I find the list notation clunky compared to querysets
comment on: http://stackoverflow.com/a/47092756
score: 0
type: Comment

http://stackoverflow.com/q/47102979
has comment: http://stackoverflow.com/comment/81156276
tagged with: mathematical-optimization
has comment: http://stackoverflow.com/comment/81157739
score: 0
answer count: 0
has body: I have a set of pairs of edges (a, b) in E that are given. I want to define a 0-1 decision variable for all a in set A and b (b is different then a) in set A where A is a set of vertices of a graph. The decision variable should look like this : H[a,b] = 1 if (a,b) is in E 0 otherwise This decision variable will be used in some constraints within my mathematical model to test if a given pair of elements say (i,j) -for the sake of simplicity to put it different then the definition above- is in E or not to enforce some behaviour. I am not sure how to write it in Gurobi using Python API. One naive approach would be to go for: H = {} for i in SetA: for j in SetA: H[i, j] = [1 if (i, j) in E else 0] But this way, H is not a Gurobi variable.
has comment: http://stackoverflow.com/comment/81157138
has title: How to define this decision variable in Gurobi
type: Question
tagged with: gurobi
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81158098
has comment: http://stackoverflow.com/comment/81157000

http://stackoverflow.com/q/47162916
tagged with: regex
possible better answer: http://stackoverflow.com/a/72969483
accepted answer: http://stackoverflow.com/a/47176834
tagged with: parsing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47176834
answer count: 2
has body: I am trying to parse a document to build searchable data. The document has multiple key/value pairs that are determined by a colon :. Some lines have multiple key/value pairs on the same line. The tricky part is that aside from a colon, the strings for both the key name and the value are inconsistent. For example, there may be 1 space or 4 spaces between the colon and the value, each value can have spaces in it, and there can be an indeterminate number of spaces between the key/value pairs that are within the same line. Example document: Name: John Smith Address: 123 Main St, Some City, ST 12345 Country: US Date 1: 1/2/17 Date 2: 1/2/18 I need to extract: { "Name" : "John Smith", "Address" : "123 Main St, Some City, ST 12345", "Country" : "US", "Date 1" : "1/2/17", "Date 2" : "1/2/18" }
upvote count: 1
has title: Extract Multiple Key Value Pairs from a Line
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/72969483
score: -2
downvote count: 3
tagged with: python

http://stackoverflow.com/comment/81277318
has text: @CarlesMitjans, yes it will be always ordered and you can assume a step size of 1
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47163732
type: QuestionComment

http://stackoverflow.com/q/47151210
has title: How to filter by range of specific hours in Django Orm?
has answer: http://stackoverflow.com/a/47153728
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81257060
has body: I have a queryset below, that allows me to get objects that where created at last 14 days: qs_1 = Model.objects.filter(datetime_created__gte=datetime.now()-timedelta(days=14)) What I want is to create a new queryset that will allow me to get objects for last 14 days and filter them by range from 11 pm to 9am. How can I do that ?
accepted answer: http://stackoverflow.com/a/47153728
downvote count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81252135
tagged with: django-queryset
has comment: http://stackoverflow.com/comment/81252453
score: 1
answer count: 1

http://stackoverflow.com/q/47188244
answer count: 2
has body: According to the relevant portion of the requests library documentation, the primary method to pass a dictionary to the post method is as follows: r = requests.post(url, data = {"example": "request"}) Afterwards, the authors demonstrate an example of passing a JSON string directly to the Github API. Then the authors suggest that instead of encoding the dictionary as a JSON string and passing it via data, you can simply use the named parameter json to pass a dictionary in as follows. r= requests.post(url, json = {"example": "request"}) When would you use json instead of data? Is this redundancy idiosyncratic or intentional?
downvote count: 0
accepted answer: http://stackoverflow.com/a/47188297
tagged with: python-requests
has answer: http://stackoverflow.com/a/47188297
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81326097
score: 9
has title: What is the difference between the `data` and `json` named arguments with requests.post?
upvote count: 9
tagged with: python
possible better answer: http://stackoverflow.com/a/73095851
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/73095851

http://stackoverflow.com/comment/81386563
has text: @sataide Predicted values are not decoded. They will depend on what you sent to `fit()` method of estimator (not labelencoder). Did the above dataframe contained actual values ? If yes, then use `labelencoder_dict[actual_values_column_here].inverse_transform(b['Predicted_values'])`
comment on: http://stackoverflow.com/a/47217986
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47077891
has comment: http://stackoverflow.com/comment/81105119
linked to: http://stackoverflow.com/q/6893968
has body: I do some computationally expensive tasks in python and found the thread module for parallelization. I have a function which does the computation and returns a ndarray as result. Now I want to know how I can parallize my function and get back the calculated Arrays from each thread. The followed example is strongly simplified with light functions and calculations. import numpy as np def calculate_result(input): a=np.linspace(1.0, 1000.0, num=10000) # just an example result = input*a return(result) input =[1,2,3,4] for i in range(0,len(input(i))): t.Thread(target=calculate_result, args=(input)) t. start() #Here I want to receive the return value from the thread I am looking for a way to get the return value from the thread / function for each thread, because in my task each thread calculates different values. I found an other Question (how to get the return value from a thread in python?) where someone is looking for a similar problem (no ndarrays) and which is handled with ThreadPool and async... ------------------------------------------------------------------------------- Thanks for your answers ! Due to your help now I am looking for a way to solve my problem with the multiprocessing modul. To give you a better understanding what I do, see my following Explanation. Explanation: My 'input_data' is an ndarray with 282240 elements of type uint32 In the 'calculation_function()'I use a for loop to calculate from every 12 bit a result and put it into the 'output_data' Because this is very slow, I split my input_data into e.g. 4 or 8 parts and calculate each part in the calculation_function(). Now I am looking for a way, how to parallize the 4 or 8 function calls The order of the data is elementary, because the data is in image and each pixel have to be at the correct Position. So function call no. 1 calculates the first and the last function call the last pixel of the image. The calculations work fine and the image can be completly rebuilt from my algo but I need the p…
type: Question
has answer: http://stackoverflow.com/a/48014925
tagged with: return
has comment: http://stackoverflow.com/comment/81104397
linked to: http://stackoverflow.com/q/26432411
type: UnansweredQuestion
has title: How to get return value from thread in Python?
tagged with: python
has comment: http://stackoverflow.com/comment/81104698
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81104914
tagged with: multithreading
has answer: http://stackoverflow.com/a/47078021

http://stackoverflow.com/comment/81103771
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47072143
type: Comment
has text: In my work i call java from python , and after that i apply the last code and i use Mean Squared Error as objective function so when scipy change parameters it changes in java and after that apply objective function , but i tried to do somthing by ftol, gtol but i didn't success the values always like that parameteroutfile = 'paramout.lst' f = open(parameteroutfile, "a") f.write(str(x0)) f.write("\n") f.close() [ 59.37242798 0.19526749 6.67386831] [ 60.75445816 0.18820302 6.91529492] [ 57.36454047 0.25075446 6.44873114]

http://stackoverflow.com/comment/81207574
type: QuestionComment
comment on: http://stackoverflow.com/q/47117833
has text: Table z: id,date 1,10/7/2015 2,12/3/2012 2,12/3/2012 3,11/24/2014 4,2/10/2016 4,2/10/2016 4,2/10/2016 4,2/10/2016 5,12/1/2014
score: 0
type: Comment

range
tags question: http://stackoverflow.com/q/47219379
tags question: http://stackoverflow.com/q/47116080
tags question: http://stackoverflow.com/q/47071869
type: Tag
tags question: http://stackoverflow.com/q/47142146
tag name: range

http://stackoverflow.com/comment/81258584
comment on: http://stackoverflow.com/a/47144319
score: 0
type: AnswerComment
has text: If my answer didn't completely solve the issue and you came to the solution as described above, could you please expand your answer, so that it's helpful to other people too. You can then accept your own answer.
type: Comment

http://stackoverflow.com/comment/81171485
score: 1
has text: I can confirm 100% that the modal is being called. If I change the `data-target` from `#createbrand` to `#justastring`, then absolutely nothing happens when I click the button, but if it's set correctly to `#createbrand`, then the screen turns darker but the modal never actually shows up (even though its attributes show in source). I'm pretty much at loss on what to do now. [Here's my full page source after your code](https://pastebin.com/AgvrecH7).
type: Comment
comment on: http://stackoverflow.com/a/47107064
type: AnswerComment

http://stackoverflow.com/q/47155621
accepted answer: http://stackoverflow.com/a/47204663
has comment: http://stackoverflow.com/comment/81337337
has comment: http://stackoverflow.com/comment/81337357
type: AnsweredQuestion
downvote count: 0
tagged with: horizontal-line
tagged with: pandas
upvote count: 1
score: 1
answer count: 1
favorite count: 0
type: Question
has body: I have a pandas object with yearly averages data in this form: DatetimeIndex(['2005-12-31', '2006-12-31', '2007-12-31', '2008-12-31', '2009-12-31', '2010-12-31', '2011-12-31'], dtype='datetime64[ns]', freq='A-DEC') 2005-12-31 3.347463 2006-12-31 3.042220 2007-12-31 3.296574 2008-12-31 3.082333 2009-12-31 2.471380 2010-12-31 2.337974 2011-12-31 2.083004 I would like to draw horizontal lines from beginning of the year till the end of the year with the values currently associated to the last day of the year. Currently, when I plot this pandas object, I get linear interpolation between the points at the end of the year. I have tried adding indexes with: new_index= ['2005', '2006', '2007', '2008','2009', '2010', '2011'] df_year.reindex(new_index) which result in the same graph. Or adding the first day of each year (not good for automation though) with: z=datetime.strptime('01-01-2005', '%d-%m-%Y') indx.append(pd.Index([z])) df_year.set_value(z,2) which result in: DatetimeIndex(['2005-12-31', '2006-12-31', '2007-12-31', '2008-12-31', '2009-12-31', '2010-12-31', '2011-12-31', '2005-01-01'], dtype='datetime64[ns]', freq=None) 2005-12-31 3.347463 2006-12-31 3.042220 2007-12-31 3.296574 2008-12-31 3.082333 2009-12-31 2.471380 2010-12-31 2.337974 2011-12-31 2.083004 2005-01-01 2.000000 However, it seems like it cannot detect that that date is before 2005-12-31 so its just draw a horizontal line from 2005 till 2011. I would really appreciate if you can help me. Unfortunately, I am not able to upload the graphs, since I am working on a different server and I am not able to save images. Thank you. Edition: Here is the code I used: plt.figure() plt.plot(df_month.index, df_month, 'k') plt.plot(df_year.index, df_year, 'g') plt.show()
has title: Make horizontal lines with pandas yearly data?
has comment: http://stackoverflow.com/comment/81342340
tagged with: python
tagged with: date
has answer: http://stackoverflow.com/a/47204663

http://stackoverflow.com/comment/81203444
type: Comment
has text: @zindarod This almost worked, but the image turned out blue-ish. Did it drop a color channel? Do I have to specify the size of the array?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47126370

http://stackoverflow.com/q/47129619
tagged with: python
has comment: http://stackoverflow.com/comment/81242664
has title: sliced list encapsulated in "tuple", how to get list elems out and print?
tagged with: slice
tagged with: parameters
tagged with: list
score: 0
has comment: http://stackoverflow.com/comment/81209268
has comment: http://stackoverflow.com/comment/81211565
has comment: http://stackoverflow.com/comment/81209350
has comment: http://stackoverflow.com/comment/81211875
answer count: 1
type: Question
tagged with: tuples
has body: for example, I have a function print_members() that should print the 2 params passed in, the name of the given group and the names of the members of the group: def print_members(group_name, *member_names): print("Members of", group_name) for i in range(len(member_names)): print(member_names[i]) and in main() I create a list that needs to be printed with the function where the first element of the list is group_name and the rest are names of members of the group. To do this I run the following in main() def main(): group_mates = ["Book Club", "Allen", "Karla", "Matt", "Nadia"] print_members(group_mates[0], group_mates[1:]) however when this runs it (afaik) passes the second param as a tuple of one element, the sliced list, so when it goes through the for-loop, it only sees one element, the encapsulated sliced list. like this: (['Allen', 'Karla', 'Matt', 'Nadia']) so it prints: Members of Book Club ['Allen', 'Karla', 'Matt', 'Nadia'] even though it should be Members of Book Club Allen Karla Matt Nadia is there perhaps another way to call the function print_members() in main() so it doesn't encapsulate the sliced list in a tuple? or is there a better way of writing print_members() ? the function also needs to be able to take in an arbitrary number of group member names following the first param, hence the asterisk, and print it the same way as I want it to print the tuple of a single list, so I can't flatten the list after I get it as a param. doing so would (again afaik) flatten a list that is already a 1d list, making each character its own element in the list. I need each name as its own element. any and all help would be appreciated.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47129693
has comment: http://stackoverflow.com/comment/81211661

http://stackoverflow.com/q/47216437
has comment: http://stackoverflow.com/comment/81423259
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81432960
has comment: http://stackoverflow.com/comment/81423439
has comment: http://stackoverflow.com/comment/81424260
has title: Easygui module not found after compilation
answer count: 0
has comment: http://stackoverflow.com/comment/81423171
has comment: http://stackoverflow.com/comment/81424118
tagged with: python
has comment: http://stackoverflow.com/comment/81423136
has comment: http://stackoverflow.com/comment/81423673
has body: I am trying to compile python code with cython. The python code has easygui module: from easygui import * The commands used are: cython --embed myfile.py gcc -I/usr/include/python3.5m -lpython3.5m myfile.c -o myfile.x The process runs without any message or error but when I run myfile.x, I get following error message: $ ./myfile.x Traceback (most recent call last): File "myfile.py", line 6, in init myfile from easygui import * ImportError: No module named 'easygui' I am working on Debian Stable Linux. Where is the problem and how can it be solved? Thanks for your help.
has comment: http://stackoverflow.com/comment/81422946
score: 1
downvote count: 0
tagged with: cython
upvote count: 1
has comment: http://stackoverflow.com/comment/81411791
has comment: http://stackoverflow.com/comment/81432632
has comment: http://stackoverflow.com/comment/81423903
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81419474

http://stackoverflow.com/comment/81103331
type: QuestionComment
comment on: http://stackoverflow.com/q/47066192
has text: @be_good_do_good sorry, should have known better and added that. Additional info added via edit now. Thanks
type: Comment
score: 0

http://stackoverflow.com/q/47199248
has answer: http://stackoverflow.com/a/47255973
has comment: http://stackoverflow.com/comment/81347695
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81348835
has comment: http://stackoverflow.com/comment/81347039
answer count: 1
has comment: http://stackoverflow.com/comment/81349301
has comment: http://stackoverflow.com/comment/81349244
has title: UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 2247: character maps to <undefined>
has comment: http://stackoverflow.com/comment/81347110
has comment: http://stackoverflow.com/comment/81347587
accepted answer: http://stackoverflow.com/a/47255973
has comment: http://stackoverflow.com/comment/81350950
type: Question
linked to: http://stackoverflow.com/q/9233027
linked to: http://stackoverflow.com/q/16346914
has comment: http://stackoverflow.com/comment/81348106
has body: When I run my code (Python 3) I keep getting this error: Traceback (most recent call last): File "country.py", line 16, in &lt;module&gt; for row in csv_reader: File "C:\Users\benny\Anaconda3\lib\csv.py", line 112, in __next__ row = next(self.reader) File "C:\Users\benny\Anaconda3\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 2247: character maps to &lt;undefined&gt; I have tried these solutions but none work. The code only prints one line if I fix the encoding problem by adding encoding='UTF-8. If I leave the encoding problem in place it prints almost 700 rows before it throws an error. Either way, it still won't work. import csv import country_converter as coco with open('Interpol.csv', 'r') as csv_file, open('Interpol_Extra.csv', 'w', newline='') as new_file: csv_reader = csv.DictReader(csv_file) fieldnames = ['Case Happened - UN Region', 'Case Happened - Continent', 'Recovered - UN Region', 'Recovered - Continent'] + csv_reader.fieldnames csv_writer = csv.DictWriter(new_file, fieldnames) csv_writer.writeheader() for row in csv_reader: case_country_name = row['Case happened - Country'] recovered_country_name = row['Recovered - Country'] if case_country_name: row['Case Happened - UN Region'] = coco.convert(names=case_country_name, to='UNregion') row['Case Happened - Continent'] = coco.convert(names=case_country_name, to='Continent') if recovered_country_name: row['Recovered - UN Region'] = coco.convert(names=recovered_country_name, to='UNregion') row['Recovered - Continent'] = coco.convert(names=recovered_country_name, to='Continent') csv_writer.writerow(row)
has comment: http://stackoverflow.com/comment/81348352
has comment: http://stackoverflow.com/comment/81348416
has comment: http://stackoverflow.com/comment/81347930
has comment: http://stackoverflow.com/comment/81347365
tagged with: python

http://stackoverflow.com/a/47113879
downvote count: 0
type: Answer
upvote count: 1
score: 1
has body: There are many more numeric characters than decimal ones: &gt;&gt;&gt; "٣".isdecimal() True &gt;&gt;&gt; "¼".isdecimal() False &gt;&gt;&gt; "¼".isnumeric() True
answers question: http://stackoverflow.com/q/47113787

http://stackoverflow.com/q/47086776
has title: Server-side Polling using flask-socketIO
has comment: http://stackoverflow.com/comment/81123870
tagged with: client-server
answer count: 0
score: 0
tagged with: flask-socketio
has comment: http://stackoverflow.com/comment/81123620
tagged with: socket.io
has body: I have a client-server setup built around the flask-socketIO framework. One of the applications is that the server repeatedly polls a database, and lets the client know in case of updates. Here is a simple version of the code that I have: The client code: function poll(){ socket.emit('pollForUpdates'); } socket.on("update",function(msg){ alert("Recieved update"); }); The server side code: @socketio.on('pollForUpdates') def pollForUpdates(): event = threading.Event() k = ThreadJob(poll, event, 2) k.start() class ThreadJob(threading.Thread): def __init__(self,callback,event,interval): '''runs the callback function after interval seconds :param callback: callback function to invoke :param event: external event for controlling the update operation :param interval: time in seconds after which are required to fire the callback :type callback: function :type interval: int ''' self.callback = callback self.event = event self.interval = interval super(ThreadJob,self).__init__() def run(self): while not self.event.wait(self.interval): self.callback() def poll(): print "Polling at {}".format(datetime.now()) socketio.emit("update") gevent.sleep(0) The client fails to receive the updates that the server sends.
type: Question
has comment: http://stackoverflow.com/comment/81184956
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83211077
type: QuestionComment
comment on: http://stackoverflow.com/q/47149048
score: 0
type: Comment
has text: sorry for not specifying!!; www.codeforces.com is the website am solving problem on to enhance my programing ! :)

http://stackoverflow.com/a/47141792
score: 1
answers question: http://stackoverflow.com/q/47140761
downvote count: 0
type: Answer
upvote count: 1
has body: When a bound function is called, it passes an event object into it. What you think is your parameter text is in fact that event. Try this: def save_file(self, event): self.text2 = event.widget if (self.filename == ''): self.save_file_as() else: f = open(self.filename, 'w') f.write(self.text2.get('1.0', 'end')) # change every 'self' that refers to the Text, to self.text2 f.close() tkinter.messagebox.showinfo('FYI', 'File Saved.') root.title(self.filename) def save_file_as(self, event=None, whatever=None): self.filename = tkinter.filedialog.asksaveasfilename(defaultextension='.txt', filetypes=self._filetypes) f = open(self.filename, 'w') f.write(self.text2.get('1.0', 'end')) f.close() tkinter.messagebox.showinfo('FYI', 'File Saved')

http://stackoverflow.com/a/47118151
downvote count: 0
upvote count: 1
has body: As both sets of your data start the same place the following works for idx,i in enumerate(range(4,len(grades_list))): This should fulfill all requirements that Im aware of up to this point def class_avg(open_file): '''(file) -&gt; list of float Return a list of assignment averages for the entire class given the open class file. The returned list should contain assignment averages in the order listed in the given file. For example, if there are 3 assignments per student, the returned list should 3 floats representing the 3 averages. ''' marks = None avgs = [] for line in open_file: grades_list = line.strip().split(',') if marks is None: marks = [] for i in range(len(grades_list) -4): marks.append([]) for idx,i in enumerate(range(4,len(grades_list))): marks[idx].append(int(grades_list[i])) for mark in marks: avgs.append(float(sum(mark)/(len(mark)))) return avgs
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47118093
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47118093

http://stackoverflow.com/q/47146586
has comment: http://stackoverflow.com/comment/81413954
has body: After deploying my python application with Zappa and visiting the aws link, I can see the following error: When I checked the logs, I found the source of the error: I then decided to pip install -r requirements.txt to ensure that it's installed inside my virtual environment (which it is): Requirement already satisfied: Werkzeug==0.12 in ./flaskapi/lib/python3.6/site-packages (from -r requirements.txt (line 41)) Something is going wrong when it's uploaded to AWS. I'm not sure if this is the core issue, but I did notice the package name in the logs is different than the one inside requirements.txt file. The package name in the logs doesn't start with a capitalized 'W', while the package name in the requirements.txt does. Other than that, I'm not sure what I'm doing wrong. Any and all help is appreciated
has title: AWS Lambda with Zappa fails on "import module 'handler': No module named 'werkzeug' "
tagged with: python
tagged with: zappa
has answer: http://stackoverflow.com/a/56599610
type: UnansweredQuestion
score: 3
upvote count: 3
answer count: 1
downvote count: 0
tagged with: amazon-web-services
favorite count: 0
tagged with: aws-lambda
type: Question

http://stackoverflow.com/comment/81210465
score: 0
has text: into a dictionary
type: Comment
comment on: http://stackoverflow.com/q/47130325
type: QuestionComment

http://stackoverflow.com/comment/81336195
type: Comment
type: QuestionComment
has text: Can you change this 'output = Dense(labelLength, activation="linear", name="weightedAverage_output")(output)' to 'output = Dense(1, activation="linear", name="weightedAverage_output")(output) ' and let me know if this is working?
score: 0
comment on: http://stackoverflow.com/q/47192499

http://stackoverflow.com/comment/81414515
type: AnswerComment
comment on: http://stackoverflow.com/a/47207051
type: Comment
has text: Ah sorry I missed that his had been marked. No worries, glad to help!
score: 0

http://stackoverflow.com/a/48082100
upvote count: 4
has body: You use self.y() + self.rect().height() &gt; 0 to test if the item is still above the y-axis. However, self.y() refers to the old/current position. You should test on the new position with value.y() instead. So the method should be: def itemChange(self, change, value): if change == QGraphicsItem.ItemPositionChange: if value.y() + self.rect().height() &gt; 0: return QPointF(value.x(), -self.rect().height()) return super().itemChange(change, value) # Call super Note that I return value.x() if the test passes and call itemChange of the super class if the test fails (just like the C++ example in the itemChange Qt documentation)
accepted answer of: http://stackoverflow.com/q/47216468
type: AcceptedAnswer
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/47216468
has comment: http://stackoverflow.com/comment/83161744
type: Answer

http://stackoverflow.com/q/47074385
has comment: http://stackoverflow.com/comment/81109416
score: 2
tagged with: arm
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/81097573
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81097650
has comment: http://stackoverflow.com/comment/81108000
downvote count: 0
tagged with: raspberry-pi3
has title: Set Docker default architecture (armel/armhf/armv71) for Raspberry Pi
favorite count: 0
has comment: http://stackoverflow.com/comment/81166182
type: Question
tagged with: raspbian
tagged with: docker
linked to: http://stackoverflow.com/q/26490935
has body: I am trying to build and run cross-platform Docker spec for Python application. As suggested, my Dockerfile has "python" as an OS image: FROM python:2.7 which supposed to resolve to an appropriate image for a current platform. The issue is - on Raspberry it resolves to "armel" architecture which is lowest common denominator to all versions. I would like it to resolve to "armhf" or "armv71" for the sake of performance - especially having in mind that Docker providing official images for these platforms. (Update) Workaround - before building containers, pull armhf/python:2.7 image from Docker repository and tag it as python:2.7
tagged with: python

http://stackoverflow.com/comment/81326909
comment on: http://stackoverflow.com/q/47188143
score: 0
type: Comment
type: QuestionComment
has text: Make sure to see my edit. there was an edge case fail.

http://stackoverflow.com/q/47194095
favorite count: 0
tagged with: python
type: Question
has title: Error when trying example Autocad usage
score: 0
has comment: http://stackoverflow.com/comment/81359796
answer count: 0
has body: My autocad object has created well but getting error on acad.prompt(). Following is the error: acad.prompt("Hello") Hello Traceback (most recent call last): File "", line 1, in File "c:\users\snehal\appdata\local\temp\easy_install-lipjer\pyautocad-0.2.0-py2.7-win32.egg.tmp\pyautocad\api.py", line 162, in prompt File "c:\users\snehal\appdata\local\temp\easy_install-lipjer\pyautocad-0.2.0-py2.7-win32.egg.tmp\pyautocad\api.py", line 74, in doc File "c:\users\snehal\appdata\local\temp\easy_install-lipjer\pyautocad-0.2.0-py2.7-win32.egg.tmp\pyautocad\api.py", line 63, in app File "C:\Python27\lib\site-packages\comtypes-1.1.3-py2.7.egg\comtypes\client_init_.py", line 173, in GetActiveObject clsid = comtypes.GUID.from_progid(progid) File "C:\Python27\lib\site-packages\comtypes-1.1.3-py2.7.egg\comtypes\GUID.py", line 78, in from_progid _CLSIDFromProgID(unicode(progid), byref(inst)) File "_ctypes/callproc.c", line 950, in GetResult WindowsError: [Error -2147221005] Invalid class string
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/81337521
downvote count: 1

http://stackoverflow.com/q/47117769
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81691409
has body: I'm trying to print milliseconds from date in python, I used below code to get millisecond since I'm new to Python I would like to check with someone here if this is that right way of getting milliseconds: import datetime def findmili(date): return int(date.strftime("%s")) * 1000 x = datetime.datetime.strptime('01/27/2017', "%m/%d/%Y") print findmili(x) Can someone please help me to validate this, if this is not right way of getting can you tell what's the exact way of getting this in python. Looks like something wrong, I'm trying to get millisecond of Jan 12 2017 but my program returns this value: 1484179200000. If I convert those milliseconds to a date using this online utility, it shows Jan 11 2017 instead of Jan 12 2017. Note: I have to use Python 2.7 version only. :(
upvote count: 1
has comment: http://stackoverflow.com/comment/81185762
favorite count: 0
has comment: http://stackoverflow.com/comment/81185566
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47123079
has answer: http://stackoverflow.com/a/47118146
score: 1
has comment: http://stackoverflow.com/comment/81185618
tagged with: datetime
has comment: http://stackoverflow.com/comment/81185891
tagged with: python
has title: Getting milliseconds from the date, but showing one day less than actual
has comment: http://stackoverflow.com/comment/81185542
has comment: http://stackoverflow.com/comment/81185911
type: Question
answer count: 2

http://stackoverflow.com/comment/81244680
score: 0
type: AnswerComment
has text: `getInputs` is supposed to be a method of the projectile class.
comment on: http://stackoverflow.com/a/47147199
type: Comment

http://stackoverflow.com/comment/81348861
comment on: http://stackoverflow.com/q/47200131
has text: A while loop is perfect for your needs.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81136812
has text: Hi @ikolim! I've added the buildozer.spec as an update to the post above! yeah i added the path into the buildozer.spec with just '~' because the files are all in my home directory
score: 0
comment on: http://stackoverflow.com/q/47085937
type: QuestionComment
type: Comment

multithreading
tags question: http://stackoverflow.com/q/47167251
tags question: http://stackoverflow.com/q/47106876
tags question: http://stackoverflow.com/q/47164063
tags question: http://stackoverflow.com/q/47174001
tags question: http://stackoverflow.com/q/47168819
tags question: http://stackoverflow.com/q/47079559
type: Tag
tags question: http://stackoverflow.com/q/47158642
tags question: http://stackoverflow.com/q/47082636
tags question: http://stackoverflow.com/q/47147328
tags question: http://stackoverflow.com/q/47167207
tags question: http://stackoverflow.com/q/47089723
tags question: http://stackoverflow.com/q/47119723
tags question: http://stackoverflow.com/q/47081772
tags question: http://stackoverflow.com/q/47163438
tags question: http://stackoverflow.com/q/47182750
tags question: http://stackoverflow.com/q/47223157
tags question: http://stackoverflow.com/q/47139014
tags question: http://stackoverflow.com/q/47178187
tags question: http://stackoverflow.com/q/47182939
tags question: http://stackoverflow.com/q/47188370
tags question: http://stackoverflow.com/q/47080903
tags question: http://stackoverflow.com/q/47077891
tags question: http://stackoverflow.com/q/47131980
tags question: http://stackoverflow.com/q/47156183
tags question: http://stackoverflow.com/q/47110639
tags question: http://stackoverflow.com/q/47181150
tags question: http://stackoverflow.com/q/47190283
tag name: multithreading
tags question: http://stackoverflow.com/q/47078849
tags question: http://stackoverflow.com/q/47115274
tags question: http://stackoverflow.com/q/47183992
tags question: http://stackoverflow.com/q/47215161
tags question: http://stackoverflow.com/q/47077719
tags question: http://stackoverflow.com/q/47176083

http://stackoverflow.com/q/47071748
favorite count: 0
type: Question
tagged with: abstract-syntax-tree
answer count: 0
has comment: http://stackoverflow.com/comment/81163052
type: UnansweredQuestion
tagged with: python
tagged with: genetic-programming
downvote count: 1
score: 2
has body: Currently, We are working with ast representation of python program in Genetic Programming and we are not able to perform one point subtree crossover using python ast module. Here's the code node_to_be_replaced is a tuple 0th element contains the node which was selected from parent one randomly and 1st element contains the index of that node in that list. collector_two is a list of references from the second parent. def modify_node_using_parent(self, node_to_be_replaced, parent_two): size = len(self.collector_two.statements) if(self.get_the_node_type(node_to_be_replaced[0]) == "Assign") or (self.get_the_node_type(node_to_be_replaced[0]) == "AnnAssign") or (self.get_the_node_type(node_to_be_replaced[0]) == "AugAssign"): j = random.randint(0, size - 1) node_to_be_replaced_with = self.collector_two.statements[j] self.collector_one.all_changable_nodes[node_to_be_replaced[1]] = node_to_be_replaced_with self.collector_two.statements[j] = node_to_be_replaced[0] Collector class is a class which traverses the tree and makes the list of the references of the same type of nodes like statements and expression etc. Now I select a node from one parent and choose the same type of node from the other parent and finally, I swap those references from the list. But when I convert those ASTs back to the source code then unparser class raises the AttributetypeError. any help would be appreciated
upvote count: 3
has title: one point subtree crossover using python ast

http://stackoverflow.com/q/47096975
answer count: 1
tagged with: directory
type: Question
has title: How can I open a directory by its name?
has comment: http://stackoverflow.com/comment/81144530
has answer: http://stackoverflow.com/a/47097623
type: UnansweredQuestion
tagged with: python
score: 0
tagged with: filesystems
has body: I am writing a program that prompts for the name of the directory and then saves all the file names in a list. How can I get a path to a specific directory obly knowing its name? I tried os.path.dirname(os.path.realpath(__file__)) but it would only show me my current dir, where the file with the program is, not the searchable dir.

http://stackoverflow.com/a/47132021
has body: You don't need a negative lookbehind to match 2nd instance of 2017. You can use non-greedy quantifier: ^.*?2017.*?(2017) RegEx Demo Second instance is captured in group no. 1 Code: &gt;&gt;&gt; str = 'car price is $2017 and manufactured in 2017 and make is Honda' &gt;&gt;&gt; print re.findall(r'^.*?2017.*?(2017)', str) ['2017']
accepted answer of: http://stackoverflow.com/q/47131936
type: Answer
answers question: http://stackoverflow.com/q/47131936
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47126025
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81243725
has answer: http://stackoverflow.com/a/63863015
downvote count: 3
has body: Following error trace is observed when python code is executed. Potential cause ModuleNotFoundError: No module named 'restaurants' traceback (most recent call last): File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Archibald\Dev\trydjango1-11\lib\site-packages\django\apps\config.py", line 94, in create module = import_module(entry) File "C:\Users\Archibald\Dev\trydjango1-11\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 978, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 961, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'restaurants'
has comment: http://stackoverflow.com/comment/81202166
favorite count: 0
type: Question
has title: Python/Django ModuleNotFoundError: No module named 'restaurants'
upvote count: 2
type: UnansweredQuestion
answer count: 1
tagged with: django

http://stackoverflow.com/comment/81322315
type: AnswerComment
comment on: http://stackoverflow.com/a/47169253
score: 0
type: Comment
has text: @juanpa.arrivillaga This morning I changed my whole code to turn everything into numpy arrays, but they seem to be very memory consuming and my computer keeps freezing. Is this something normal given the size of the data? What kind of structure would be easier to run?

http://stackoverflow.com/a/47172348
accepted answer of: http://stackoverflow.com/q/47172219
score: 2
has comment: http://stackoverflow.com/comment/81304402
has comment: http://stackoverflow.com/comment/81297874
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47172219
has body: You can use plt.ion() to enable interactive plotting. import matplotlib.pyplot as plt import cv2 cap = cv2.VideoCapture(0) plt.ion() while (True): ret, frame = cap.read() if cv2.waitKey(1) &amp; 0xFF == ord('q'): break plt.subplot(1,2,1), plt.imshow(frame, interpolation='nearest') plt.pause(0.001) plt.show() In this solution you replot everything and even create a new subplot for each frame to be shown. This is highly inefficient and hence slow. Check out this answer Speed up live plotting of a footage (cv2).
has comment: http://stackoverflow.com/comment/81295669
has comment: http://stackoverflow.com/comment/81301104
type: Answer

http://stackoverflow.com/a/47147701
downvote count: 0
has body: I agree with @martineau's comment in general: If you do the graphical drawing correctly using only commands which are relative to the current position, you can put all of them in a function and just before calling it, position the turtle to the location you want them all to be relative to. But if your drawing is sufficiently simple, there's an alternative approach. You can make a turtle cursor that is your drawing, switch the turtle to that cursor and make your drawing do any move that the turtle cursor itself can do. I'm going to illustrate using this house drawing from this An Hour of Code == An Hour of Fun page: The following code invisibly draws the house and stashes it as a turtle cursor. It then sets the turtle shape to the house drawing and takes the house for a spin. Literally. After rotating the house in a circle, it shears it while moving it to the upper right of the drawing: from turtle import Turtle, Screen, Shape screen = Screen() screen.bgcolor('SkyBlue') shape = Shape('compound') turtle = Turtle(visible=False) turtle.speed('fastest') turtle.penup() turtle.goto(-100, 0) turtle.begin_poly() turtle.goto(-100, 50) turtle.goto(100, 50) turtle.goto(100, 0) turtle.goto(-100, 0) turtle.end_poly() shape.addcomponent(turtle.get_poly(), 'red') turtle.goto(-100, 50) turtle.begin_poly() turtle.goto(0, 100) turtle.goto(100, 50) turtle.goto(-100, 50) turtle.end_poly() shape.addcomponent(turtle.get_poly(), 'brown') turtle.goto(-40, 0) turtle.begin_poly() turtle.goto(-40, 30) turtle.goto(-20, 30) turtle.goto(-20, 0) turtle.goto(-40, 0) turtle.end_poly() shape.addcomponent(turtle.get_poly(), 'orange') turtle.goto(20, 20) turtle.begin_poly() turtle.goto(20, 40) turtle.goto(50, 40) turtle.goto(50, 20) turtle.goto(20, 20) turtle.end_poly() shape.addcomponent(turtle.get_poly(), 'white') screen.register_shape('house', shape) turtle.reset() turtle.penup() # Now we can move our house in any manner that we move a turtle: turtle.shape('house') for theta in range(0, 360, 10): tu…
answers question: http://stackoverflow.com/q/47144177
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/47144177
score: 5
type: AcceptedAnswer

http://stackoverflow.com/q/47169882
score: 0
has answer: http://stackoverflow.com/a/47169883
has body: When finishing off Section 2 I get the following error. "urllib.error.URLError: "
answer count: 1
has title: SSL issues when doing Lynda Course "Learning Python with PyCharm"
type: Question
tagged with: pycharm
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47191492
has title: How do I look specifically at the ends of a string in python?
has comment: http://stackoverflow.com/comment/81332390
favorite count: 0
has comment: http://stackoverflow.com/comment/81332404
upvote count: 1
answer count: 1
tagged with: loops
tagged with: string
has answer: http://stackoverflow.com/a/47191527
type: Question
accepted answer: http://stackoverflow.com/a/47191527
has body: I am trying to create a function that examines the ends of a string in python and returns an integer if it matches the conditions that I have defined, however i am having an issue with the numbers overlapping is there a way for me to get around this simply with just built in string functions and not using any import? so for example the string 'AAZZ' should return to me two but is returning four instead. The conditions are A matches with Z and it Y matches with C. the function will look for pairs to match until it runs into a pair that does not match where it will stop and return the value it has for count. Here is what i have so far: def matching(str): i = 0 j = -1 count = 0 while i &lt; len(str): if str[i] == 'A' and str[j] == 'Z': i += 1 j -= 1 count += 1 elif str[i] == 'Z' and str[j] == 'A': i += 1 j -= 1 count += 1 elif str[i] == 'Y' and str[j] == 'C': i += 1 j -= 1 count += 1 elif str[i] == 'C' and str[j] == 'Y': i += 1 j -= 1 count += 1 else: count = 0 return count
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81332494
downvote count: 1
tagged with: python

http://stackoverflow.com/comment/81368101
comment on: http://stackoverflow.com/q/47209287
type: Comment
type: QuestionComment
has text: You need to override `__add__` so that `z1 + z2` returns a `Zar` instance; at the moment, `Zar.__add__` is not defined, so `Decimal.__add__` is called to compute `z1 + z2`, and it returns a `Decimal` instance.
score: 0

http://stackoverflow.com/comment/81295817
type: AnswerComment
has text: with list comprehension method, I am getting error : TypeError: 'method' object is not iterable
comment on: http://stackoverflow.com/a/47173093
type: Comment
score: 0

http://stackoverflow.com/a/63898759
answers question: http://stackoverflow.com/q/47216204
upvote count: 3
downvote count: 0
has body: You should just send data object with your files named as you want: test_client.post('/api/upload', data={'title': 'upload sample', 'file1': (io.BytesIO(b'get something'), 'file1'), 'file2': (io.BytesIO(b'forthright'), 'file2')}, content_type='multipart/form-data')
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/131559620

http://stackoverflow.com/a/47119314
answers question: http://stackoverflow.com/q/47119303
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47119303
has body: Given: data = [{'createdTime': '2017-11-05T06:43:08.000Z', 'fields': {'Pair ID': 14}, 'id': 'rec5Y5ML3w2nlKCYx'}, {'createdTime': '2017-11-05T06:43:08.000Z', 'fields': {'Pair ID': 12}, 'id': 'recB8ioXO0c8f9AHc'}, {'createdTime': '2017-11-05T07:26:51.915Z', 'fields': {'Pair ID': 17}, 'id': 'recCxg3XzjbQ1z5zh'}] You can use a list comprehension: [d['id'] for d in data]
type: Answer

http://stackoverflow.com/comment/81263778
type: Comment
comment on: http://stackoverflow.com/a/47156863
score: 0
type: AnswerComment
has text: @coldSpeed this same approach work with Levenshtein Ratio ? If I am not wrong

http://stackoverflow.com/comment/81368236
comment on: http://stackoverflow.com/q/47206034
type: Comment
type: QuestionComment
score: 0
has text: X, Y, Z are relates attributes like coordinates of a point and each measurement i has up to 256 such points. a, b, c are other parameters of the measurement like e.g. a=temperature, b=voltage, c= number_of_points. Points between two measurements are somewhat related, but not strongly. The queries that I would lie to do are like:

http://stackoverflow.com/comment/81116483
has text: Note, this can get pretty complicated pretty fast if your `deepCopy` function will expect *any arbitrary object*.
type: QuestionComment
comment on: http://stackoverflow.com/q/47083204
score: 1
type: Comment

http://stackoverflow.com/comment/81162006
has text: Optimally, you'd not want to use globals as they aren't as efficient as local variables- why not simply return `parameter + 1` and set `parameter = function(parameter)` or something along those lines?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47105636
type: QuestionComment

http://stackoverflow.com/q/47108652
score: 0
answer count: 1
upvote count: 1
downvote count: 1
has body: I have a dataframe z, of which one of the columns are in datetime format: index time 0 2017-03-01 09:30:00.233 1 2017-03-01 09:30:00.243 2 2017-03-01 09:30:00.319 3 2017-03-01 09:30:00.981 4 2017-03-01 09:30:02.555 5 2017-03-01 09:30:02.959 6 2017-03-01 09:30:03.908 7 2017-03-01 09:30:12.659 8 2017-03-01 09:30:19.006 9 2017-03-01 09:30:22.990 10 2017-03-01 09:30:23.166 11 2017-03-01 09:30:27.879 12 2017-03-01 09:30:28.370 Basically, I want to delete the rows that is before a specific time in the data. For example, let's say in this case I want to delete all rows before 09:30:22.990 (row 9). What I have is: first_trade_AM = z['Time'][z['Time'].dt.day == date][z['EventType'] == 'trade'].head(1) for simplicity's sake, lets say this formula returns 9 2017-03-01 09:30:22.990 then I have z.drop(z['Time'][z['Time'].dt.day == date] &lt; first_trade_AM) but I get the error message: ValueError: Can only compare identically-labeled Series objects Any help will be greatly appreciated. Been stuck here for a while. Thanks! EDIT: The dataset I posted above is a subset of the entire month's worth of data. Every single day has a unique first_trade_AM, which I found using: for date in z['Time'].dt.day.unique(): first_trade_AM = z.loc[(z['Time'].dt.day == date) &amp; (z['EventType'] == 'trade'), 'Time'].head(1).item() My follow-up question being, how do I delete all the observations for unique days BEFORE the particular day's unique first_trade_AM, without affecting the data from other dates? EDIT: More general data: index time EventType 0 2017-03-01 09:30:00.233 other 1 2017-03-01 09:30:00.243 trade 2 2017-03-01 09:30:00.319 trade 3 2017-03-01 09:30:00.981 other 4 2017-03-01 09:30:02.555 other 5 2017-03-02 09:30:02.959 other 6 2017-03-02 09:30:03.908 other 7 2017-03-02 09:30:12.659 trade 8 2017-03-02 09:30:19.006 trade 9 2017-03-02 09:30:22.990 trade 10 2017-03-02 09:30:23.166 other 11 2017-03-02 09:30:27.879 other 12 2017-03-02 09:30:28.370 other
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81168606
has title: 'Can only compare identically-labeled Series objects' error when trying to compare column in dataframe with single data point
accepted answer: http://stackoverflow.com/a/47108675
tagged with: python
has answer: http://stackoverflow.com/a/47108675
has comment: http://stackoverflow.com/comment/81168156
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/q/47069508
answer count: 3
downvote count: 3
has answer: http://stackoverflow.com/a/47069555
upvote count: 1
has answer: http://stackoverflow.com/a/47069642
has title: compare date and time objects and get older date in python
has comment: http://stackoverflow.com/comment/81086919
favorite count: 0
has body: I have 3 dates (in hours and sec and mins) 2016-11-30T13:27:04-05:00 2016-11-30T13:27:41-05:00 2017-03-01T22:16:35-05:00 How can i get older date which is 2016-11-30T13:27:04-05:00 as output This python script is not giving correct results import time find_a = min(a) print find_a
type: Question
has comment: http://stackoverflow.com/comment/81087207
has answer: http://stackoverflow.com/a/47070218
tagged with: time
linked to: http://stackoverflow.com/q/12281975
has comment: http://stackoverflow.com/comment/81089391
type: UnansweredQuestion
score: -2
tagged with: python

http://stackoverflow.com/q/47173791
tagged with: qwebenginepage
answer count: 1
tagged with: pyqt5
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/47174104
linked to: http://stackoverflow.com/q/47067050
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47174104
has body: I am trying to learn Dynamic Web scraping on PyQt5. I was looking up the tutorials meant for PyQt4 so have some different libraries in Qt5. import sys from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QUrl from PyQt5.QtWebEngineWidgets import QWebEnginePage import bs4 as bs import urllib.request class Client(QWebEnginePage): def _init_(self, url): self.app=QApplication(sys.argv) QWebPage._init_(self) self.loadFinished.connect(self.on_page_load) self.mainFrame().load(QUrl(url)) self.app.exec_() def on_page_load(self): self.app.quit() url='https://pythonprogramming.net/parsememcparseface/' client_response=Client(url) source=client_response.mainFrame().toHtml() #sauce=urllib.request.urlopen('https://pythonprogramming.net/sitemap.xml').read() soup=bs.BeautifulSoup(sauce,'xml') js_test=soup.find('p',class_='jstest') print(js_test.text) The following error is being show: Traceback (most recent call last): File "jsp.py", line 19, in &lt;module&gt; client_response=Client(url) TypeError: arguments did not match any overloaded call: QWebEnginePage(parent: QObject = None): argument 1 has unexpected type 'str' QWebEnginePage(QWebEngineProfile, parent: QObject = None): argument 1 has unexpected Someone help me!
downvote count: 0
tagged with: python
has title: Cannot use QUrl
type: AnsweredQuestion
tagged with: pyqt

http://stackoverflow.com/comment/81206992
has text: Yes, someday there will be feature in 3 that I can't live without. When that day comes, I will go through and uglify my code to work in 3.
comment on: http://stackoverflow.com/a/47128383
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47131587
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81219557
has comment: http://stackoverflow.com/comment/81220360
has comment: http://stackoverflow.com/comment/81216090
has comment: http://stackoverflow.com/comment/81219819
upvote count: 2
answers question: http://stackoverflow.com/q/47131193
type: Answer
has body: Melt the dataframe 1 and convert it to dict. Then get the values of dict based on key obtained by pattern match in dataframe 2 i.e vals = df.melt() di = dict(zip(vals['value'],vals['variable'])) # {'or': 'Alpha', 1: 'Numeric', 2: 'Numeric', 'and': 'Alpha', 4: 'Numeric', '@': 'Special', '#': 'Special', '&amp;': 'Special', 'Special': 'new', 'Alpha': 'new', 'lol ok': 'Alpha'} #Create a regex pattern based on dict keys. pat = '|'.join(r"\s{}\s".format(x) for x in di.keys()) #Find the words that match the pattern df2['val'] = df2['Content'].str.lower().str.findall(pat).apply(lambda x : x[0].strip() if len(x)&gt;=1 else np.nan) # Map the values with di and fill nan with other. df2['new'] = df2['val'].map(di).fillna('other') Ouptut : Content new val 0 boy or girl Alpha or 1 school @ morn Special @ 2 pyc LoL ok student Alpha lol ok 3 Chandra other NaN
has comment: http://stackoverflow.com/comment/81219756
has comment: http://stackoverflow.com/comment/81725650

http://stackoverflow.com/comment/81310043
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47178793
has text: if you notice i use your method with littel changes because i have three elements for x0 but also this method guess negative values for parameters and if you notics all my bounds is positive
score: 0

http://stackoverflow.com/comment/81391351
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47201586
score: 0
has text: @tom I see. Thank you for explaining! Then I'm afraid I have to make due with the figure I've got.

http://stackoverflow.com/comment/81335923
has text: Yes, it should, my bad
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47193260
type: Comment

http://stackoverflow.com/comment/81319654
has text: I don't see how that makes a difference. Besides, OP conceded that it doesn't work as it is (a small change is needed, see my answer)
comment on: http://stackoverflow.com/a/47185205
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81236033
type: AnswerComment
has text: Ok, thanks. Setting the index helped. However, how can I set the colors? By default, I get the color legend on the right and it contains gradient. I want to have only two colors: one for `0` and another one for `1`.
type: Comment
comment on: http://stackoverflow.com/a/47142981
score: 0

http://stackoverflow.com/comment/81175539
has text: I modify to new_df.loc[new_df.index[-1], 'people'] = min(new_df.loc[new_df.index[-1], 'people'],5 - new_df.iloc[:-1].people.sum()) , this can work thanks again @FabienP
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47111961

http://stackoverflow.com/q/47065193
has answer: http://stackoverflow.com/a/47072356
type: AnsweredQuestion
has body: In Azure, using Python with the Flask and pandas modules to create a RESTful webservice. Azure doesn't appear able to find the requests_file module. Launching the web page keeps returning error: No module named requests_file I have installed "requests" and "requests_file" manually using the Kudu CLI https://"yoursitename".scm.azurewebsites.net/DebugConsole. They both appear to be there. What am I missing or is there a bug in Azure?
tagged with: pandas
tagged with: azure
has comment: http://stackoverflow.com/comment/81115344
has comment: http://stackoverflow.com/comment/81086357
favorite count: 0
type: Question
has title: Using Python and Flask in Azure cannot find the requests_file module
score: 0
linked to: http://stackoverflow.com/q/41473801
answer count: 1
has comment: http://stackoverflow.com/comment/81115159
accepted answer: http://stackoverflow.com/a/47072356
upvote count: 1
tagged with: python
tagged with: python-requests
downvote count: 1

http://stackoverflow.com/q/47179126
type: Question
tagged with: roc
has title: Calculate TPR and FPR of a binary classifier for roc curve in python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81337482
tagged with: python
has comment: http://stackoverflow.com/comment/81333053
score: 2
upvote count: 2
answer count: 1
downvote count: 0
has body: I was trying to calculate the True positive rate and false positive rate and then plot the roc curve by hand, since I wanted to check the roc curve I got from sklearn.metrics roc_curve function. But the roc curve of fpr(on x-axis) vs tpr(on y axis) I'm getting seems like the axes have been interchanged. I'm doing a gradient descent binary classifier with two labels positive and negative. The relevant portion of the tensorflow code for the tpr, fpr calculation is given below: prediction=tf.nn.softmax(tf.matmul(X,w)+b) pred_pos= prediction.eval(feed_dict={X: x_pos}) pred_neg= prediction.eval(feed_dict={X: x_neg}) tpr=[] fpr=[] for j in range(100): pos=0 neg=0 n=j/100. for i in range(0,len(pred_pos)): if(pred_pos[i,1]&gt;=n): pos+=1 if(pred_neg[i,1]&gt;=n): neg+=1 tpr.append(pos/len(x_pos)) fpr.append(neg/len(x_neg)) f= open('output.txt','wb') arr=np.array([fpr,tpr]) arr=arr.T np.savetxt(f,arr,fmt=['%e','%e']) f.close() I'm then plotting from the text file using gnuplot with fpr(x axis) and tpr(y axis), and I'm getting the plot attached. This is certainly not right. Why is this so? What am I doing wrong?
has answer: http://stackoverflow.com/a/47216779
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/81363104
has text: I'm not quite sure what you mean. Would it be possible to consider rephrasing? All it looks like is the splitting an array of length 9 into three arrays of length 3 while preserving the order. I.e `E_xy = [ E[i:i + 3] for i in [x*len(E)/3 for x in range(3)]]`
comment on: http://stackoverflow.com/q/47206914
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82489267
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47168168
has text: Because I just created the object, I know it doesn't have any children yet.
type: Comment

http://stackoverflow.com/q/47204447
has comment: http://stackoverflow.com/comment/81478374
type: UnansweredQuestion
has body: I am creating a game in python using turtle but I am unable to control the speed of the turtle in the loop as the speed of the turtle is 0. It is supposed to run like flash but it is running at normal speed import turtle c=turtle.Screen() a=turtle.Turtle() a.speed(0) b=True def ch( a , d): global b b = False while b: a.fd(1) c.onclick(ch) c.mainloop()
tagged with: python
has comment: http://stackoverflow.com/comment/81357519
has title: Python 3 turtle speed of drawing
answer count: 2
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81358047
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47217897
has comment: http://stackoverflow.com/comment/81358193
has answer: http://stackoverflow.com/a/47215664
type: Question
tagged with: turtle-graphics

http://stackoverflow.com/q/47126075
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/81202586
tagged with: gzip
tagged with: python
has answer: http://stackoverflow.com/a/47126097
has body: I'm trying to compress and encode my string using gGIP in python 2.7, I'm able to do that in Python 3 but I'm not getting same output in Python 2.7 version code: Python 3: import sys import redis import io import StringIO import gzip redisConn = redis.StrictRedis(host="127.0.0.1", port=6379, db=0) myValue = "This is test data" result = gzip.compress(myValue.encode()) redisConn.set("myKey", result) Python 2.7: import sys import redis import StringIO import gzip redisConn = redis.StrictRedis(host="127.0.0.1", port=6379, db=0) myValue = "This is test data" out = StringIO.StringIO() gzip_s = gzip.GzipFile(fileobj=out, mode="w") result = gzip_s.write(myValue.encode()) redisConn.set("myKey", result) But Python 2.7 version code is breaking I'm getting an error: 'int' object has no attribute 'encode' Can someone please help what's the equivalent code of Python 2.7 - my Python 3 version is working as expected. Thanks for your help in advance.
type: Question
has answer: http://stackoverflow.com/a/47126239
possible better answer: http://stackoverflow.com/a/47126239
answer count: 2
tagged with: encode
has comment: http://stackoverflow.com/comment/81203144
has title: How to compress the string using gzip and encode in python 2.7
upvote count: 1
has comment: http://stackoverflow.com/comment/81202161
accepted answer: http://stackoverflow.com/a/47126097

http://stackoverflow.com/comment/81120070
type: Comment
type: QuestionComment
has text: why not include, `Get_Y()`?
score: 0
comment on: http://stackoverflow.com/q/47072916

http://stackoverflow.com/comment/81194486
has text: see https://stackoverflow.com/a/13313828/333700 for how to use QR to find all collinear or linearly independent columns
type: QuestionComment
comment on: http://stackoverflow.com/q/47121953
score: 0
type: Comment

http://stackoverflow.com/comment/81149901
type: QuestionComment
has text: @cstaff91 it is http://www.shaditayari.pk/s&category=326&location=266&a=true&paged=1, http://www.shaditayari.pk/s&category=326&location=266&a=true&paged=2 and so on when paged=1 there are href like http://www.shaditayari.pk/businesses/best-western-hotel-2/http://www.shaditayari.pk/businesses/zaibis-marriage-garden/ etc and ,http://www.shaditayari.pk/businesses/zauk-banquet-hall/ actually pagination is there.
comment on: http://stackoverflow.com/q/47099741
score: 0
type: Comment

http://stackoverflow.com/q/47138394
tagged with: optimization
tagged with: numpy
has body: i am running pandas 0.20 and scipy 0.17.1. When I run the optimization: res = minimize(run_opt, x0, method='COBYLA', constraints=cons, tol=None, callback=None, options={'disp': True, 'catol': 0.0002, 'maxiter': 1000, 'rhobeg': 1.0}) and cons = ({'type':'ineq', 'fun':lambda t: t}) I get the following error on a pandas query that runs in the function as below: File "H:script_1.py", line 159, in Fun_3 Res_Table[i] = btst.query('Var_1=='+str(i+1)) File "C:\Program Files\Anaconda2\lib\site-packages\pandas\core\frame.py", line 2116, in query res = self.eval(expr, **kwargs) File "C:\Program Files\Anaconda2\lib\site-packages\pandas\core\frame.py", line 2186, in eval return _eval(expr, inplace=inplace, **kwargs) File "C:\Program Files\Anaconda2\lib\site-packages\pandas\core\computation\eval.py", line 262, in eval truediv=truediv) File "C:\Program Files\Anaconda2\lib\site-packages\pandas\core\computation\expr.py", line 727, in __init__ self.terms = self.parse() File "C:\Program Files\Anaconda2\lib\site-packages\pandas\core\computation\expr.py", line 744, in parse return self._visitor.visit(self.expr) File "C:\Program Files\Anaconda2\lib\site-packages\pandas\core\computation\expr.py", line 313, in visit return visitor(node, **kwargs) File "C:\Program Files\Anaconda2\lib\site-packages\pandas\core\computation\expr.py", line 319, in visit_Module return self.visit(expr, **kwargs) File "C:\Program Files\Anaconda2\lib\site-packages\pandas\core\computation\expr.py", line 313, in visit return visitor(node, **kwargs) File "C:\Program Files\Anaconda2\lib\site-packages\pandas\core\computation\expr.py", line 322, in visit_Expr return self.visit(node.value, **kwargs) File "C:\Program Files\Anaconda2\lib\site-packages\pandas\core\computation\expr.py", line 313, in visit return visitor(node, **kwargs) File "C:\Program Files\Anaconda2\lib\site-packages\pandas\core\computation\expr.py", line 644, in visit_Compare return self.visit(binop) File "C:\Program Files\Anaconda2\lib\site-packages\panda…
score: 0
has title: Scipy Optimisation Crashes with Pandas Error
answer count: 0
type: UnansweredQuestion
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/81232395
has comment: http://stackoverflow.com/comment/81231496
tagged with: python

tkinter
tags question: http://stackoverflow.com/q/47096930
tags question: http://stackoverflow.com/q/47109480
tags question: http://stackoverflow.com/q/47134833
tags question: http://stackoverflow.com/q/47098379
tags question: http://stackoverflow.com/q/47209402
tags question: http://stackoverflow.com/q/47080849
tags question: http://stackoverflow.com/q/47176470
tags question: http://stackoverflow.com/q/47107692
tags question: http://stackoverflow.com/q/47212078
tags question: http://stackoverflow.com/q/47117629
tags question: http://stackoverflow.com/q/47212747
tags question: http://stackoverflow.com/q/47122453
tags question: http://stackoverflow.com/q/47155654
tags question: http://stackoverflow.com/q/47090039
tags question: http://stackoverflow.com/q/47144454
tags question: http://stackoverflow.com/q/47145055
tags question: http://stackoverflow.com/q/47142567
tags question: http://stackoverflow.com/q/47110765
tags question: http://stackoverflow.com/q/47146805
tags question: http://stackoverflow.com/q/47158869
tags question: http://stackoverflow.com/q/47117060
tags question: http://stackoverflow.com/q/47132049
tags question: http://stackoverflow.com/q/47125800
tags question: http://stackoverflow.com/q/47116678
tags question: http://stackoverflow.com/q/47161279
tags question: http://stackoverflow.com/q/47066606
tags question: http://stackoverflow.com/q/47171562
tags question: http://stackoverflow.com/q/47170193
tags question: http://stackoverflow.com/q/47092784
tags question: http://stackoverflow.com/q/47151150
tags question: http://stackoverflow.com/q/47156119
tags question: http://stackoverflow.com/q/47168361
tags question: http://stackoverflow.com/q/47140761
tags question: http://stackoverflow.com/q/47152689
tags question: http://stackoverflow.com/q/47088350
tags question: http://stackoverflow.com/q/47137662
tags question: http://stackoverflow.com/q/47139645
tags question: http://stackoverflow.com/q/47156055
tags question: http://stackoverflow.com/q/47099027
tags question: http://stackoverflow.com/q/47214273
tag name: tkinter
tags question: http://stackoverflow.com/q/47122132
tags question: http://stackoverflow.com/q/47127233
tags question: http://stackoverflow.com/q/47081341
tags question: http://stackoverflow.com/q/47200625
tags question: http://stackoverflow.com/q/47192804
tags question: http://stackoverflow.com/q/47103714
tags question: http://stackoverflow.com/q/47169025
tags question: http://stackoverflow.com/q/47131795
tags question: http://stackoverflow.com/q/47177210
tags question: http://stackoverflow.com/q/47149230
tags question: http://stackoverflow.com/q/47085498
tags question: http://stackoverflow.com/q/47127875
tags question: http://stackoverflow.com/q/47174160
tags question: http://stackoverflow.com/q/47134017
tags question: http://stackoverflow.com/q/47133997
tags question: http://stackoverflow.com/q/47220783
tags question: http://stackoverflow.com/q/47116602
tags question: http://stackoverflow.com/q/47182049
tags question: http://stackoverflow.com/q/47213047
tags question: http://stackoverflow.com/q/47100670
tags question: http://stackoverflow.com/q/47125472
tags question: http://stackoverflow.com/q/47166447
tags question: http://stackoverflow.com/q/47117911
tags question: http://stackoverflow.com/q/47115684
tags question: http://stackoverflow.com/q/47110766
tags question: http://stackoverflow.com/q/47127585
tags question: http://stackoverflow.com/q/47215391
tags question: http://stackoverflow.com/q/47151336
tags question: http://stackoverflow.com/q/47167874
tags question: http://stackoverflow.com/q/47206449
tags question: http://stackoverflow.com/q/47191048
tags question: http://stackoverflow.com/q/47095278
tags question: http://stackoverflow.com/q/47212697
tags question: http://stackoverflow.com/q/47204680
tags question: http://stackoverflow.com/q/47074502
tags question: http://stackoverflow.com/q/47097593
tags question: http://stackoverflow.com/q/47107641
tags question: http://stackoverflow.com/q/47156700
tags question: http://stackoverflow.com/q/47095804

http://stackoverflow.com/q/47105893
tagged with: python
has comment: http://stackoverflow.com/comment/81162463
tagged with: decimal
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47105990
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47105990
tagged with: string
has comment: http://stackoverflow.com/comment/81162691
has body: I have a python function called read_memory that has one parameter that is called addr. I want to implement a way to convert the addr to HEX value. It sounds simple but the user can enter either a string/int in the parameter: read_memory(0x106940) read_memory('0x106940') read_memory(106940) #this is an int read_memory('106940') The result should all be 0x106940. I have the following code but it does not work as expected: def read_memory(addr): hex_addr = str(addr) if('0x' not in hex_addr): hex_addr = '0x' + hex_addr return hex_addr The results are: read_memory(0x106940) -&gt; 0x1075520 read_memory('0x106940') -&gt; 0x106940 read_memory(106940) -&gt; 0x106940 read_memory('106940') -&gt; 0x106940 Any help is appreciate.
tagged with: hex
type: Question
has comment: http://stackoverflow.com/comment/81162657
has title: Python - convert function parameter input to hex

http://stackoverflow.com/comment/81364950
score: 0
has text: In terminal `python -c "import cv2; print(cv2.getBuildInformation())" >> result.txt`. Post the file to pastebin.com, upload link here.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47206902

http://stackoverflow.com/a/50083732
type: Answer
answers question: http://stackoverflow.com/q/47069054
score: 0
has body: I realised I encounter so many errors because I did not had the requirement pyLint on my computer

http://stackoverflow.com/q/47178242
has body: I'm trying to use python-bioformats to open a .jp2 image. It throws the loci.formats.FormatException, as it is greater than the 2GB limit. The message suggests using the openBytes method found in the loci.formats.IFormatReader of the Java library. Where ( and if ) can I find the openBytes method within the python module?
tagged with: python
type: Question
upvote count: 2
has title: Python-Bioformats Image plane too large issue
answer count: 0
type: UnansweredQuestion
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81349841
score: 1
has comment: http://stackoverflow.com/comment/81305765
has comment: http://stackoverflow.com/comment/81357907

http://stackoverflow.com/comment/81327038
type: Comment
type: AnswerComment
score: 0
has text: @JasonLou - That expression controls the continuation of the `while` loop. It keeps reading, and throwing away data, until it finally reads a newline, i.e. until it finally reads the entire long line.
comment on: http://stackoverflow.com/a/47188562

http://stackoverflow.com/a/47199265
upvote count: 1
downvote count: 1
has body: your pip is default set for version $ python Python 2.7.5 SO if you want to install module for $ python2 Python 2.7.14 use python2 -m pip install module_name
type: Answer
answers question: http://stackoverflow.com/q/47199121
score: 0

http://stackoverflow.com/comment/81448237
has text: Do not try to install opencv by pip installing its .whl file: it will not work. Could you please provide details about the problems you are encountering with cmake?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47220372

http://stackoverflow.com/comment/81317629
type: Comment
has text: @CedricJulien Thanks for the answer, is it possible to make the text file executable within the python script? `subprocess.call(['chmod +x', ' absolute/path/to/commands.txt'], shell=True)` would work as well?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47184104

http://stackoverflow.com/q/47112388
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/47112478
has answer: http://stackoverflow.com/a/47112452
possible better answer: http://stackoverflow.com/a/47112452
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47112635
answer count: 3
tagged with: pandas
has title: Making many duplicates of columns and renaming them automatically
has answer: http://stackoverflow.com/a/47112478
type: Question
has body: I'm using pandas in Python. import pandas as pd Suppose I have a dataframe pd.DataFrame({"A": [1,2,3], "B": [3,2,1]}) I want to make three copies of each column and name the columns as A1 to A4, and B1 to B4. Example of desired output: pd.DataFrame({"A1": [1,2,3], "A2": [1,2,3], "A3": [1,2,3], "A4": [1,2,3], "B1": [3,2,1], "B2": [3,2,1], "B3": [3,2,1], "B4": [3,2,1]}) How can I do this?

http://stackoverflow.com/q/47196230
type: UnansweredQuestion
has title: Rum cmd from python subprocess module with admin privileges
has body: I would like to know if there is any way to run a cmd process using subprocess module in python(Using Popen) with admin privileges. I need to run some conmmand that must have admin privileges in order to run correctly. Thanks in advance!!
tagged with: python
has answer: http://stackoverflow.com/a/47216651
tagged with: subprocess
score: 1
linked to: http://stackoverflow.com/q/20505893
answer count: 1
downvote count: 0
tagged with: cmd
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81382749

http://stackoverflow.com/comment/81195435
score: 0
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ, i also understood it this way. First i wanted to use cartesian product as well, but then i realized that if we will use cartesian product of a sinlge list (`name_list`), then OP simply wants to check whether either `Source` or `Target` matches an element from the `name_list`. How do you think - does it make sense?
type: AnswerComment
comment on: http://stackoverflow.com/a/47122723

http://stackoverflow.com/q/47097474
accepted answer: http://stackoverflow.com/a/47097871
answer count: 1
has title: Find all quotes in json-like string and replace quotes inside using Python
has answer: http://stackoverflow.com/a/47097871
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
score: 0
tagged with: python
tagged with: regex
has body: I have a string which has similar structure to JSON like this: "data1":{ "data2":{ "x":"Some text" }, "source": "source: example.com" } "data3":{ "format": "f() { return this.data52 / 20 + "x"; }" } I want to remove quotes inside quotes like this: "data1":{ "data2":{ "x":"Some text" }, "source": "source: example.com" } "data3":{ "format": "f() { return this.data52 / 20 + \"x\"; }" } The string given in input is much longer, and I have many strings like this to format. As you can see some of the quotes are changed to \" already. I tried this: string = re.sub(r"\"(.*)\"", r"\1", string).re.replace("\"", "\\\"") but it replaces all quotes, I tried to use negative lookaround but it would work only if I have only one quote and another inside. Is there ANY way to do that with regex? I could always iterate over string and count the quotes but it is not the best solution I suppose. Thanks for help! @EDIT I founded where the algorithm provided by @L3viathan doesn't work: "data1":{ "data2":{ "x":"Some text" }, "source": "source: example.com" } "data3":{ "hereDoesntWork": { "format": "f() { return this.data52 / 20 + "x"; }" } } } The text in "hereDoesntWork` is just ommited. The thing is that I don't know how this strings can be nested.

http://stackoverflow.com/a/47215688
answers question: http://stackoverflow.com/q/47215520
has comment: http://stackoverflow.com/comment/81465029
has body: There are two cases in this situation. It might be permission issue or owner issue. Check permission of installed module. And provide it all permission. chmod -R 777 Second thing, it may be owner issue, might be you installed module using apt-get install module_name or pip install modual_name try to install modual using sudo sudo apt-get install module_name or sudo pip install modual_name If above thing not worked for you just try with sudo ln -s /usr/bin/python2.7 /usr/bin/python it will tell system to find the default system python.
has comment: http://stackoverflow.com/comment/81402745
type: Answer
score: 0

http://stackoverflow.com/q/47125697
accepted answer: http://stackoverflow.com/a/47126435
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81201571
has answer: http://stackoverflow.com/a/47126435
has comment: http://stackoverflow.com/comment/81201620
score: 8
favorite count: 0
type: Question
tagged with: numpy
upvote count: 8
has comment: http://stackoverflow.com/comment/81201651
has body: I have two matrices of interest, the first is a "bag of words" matrix, with two columns: the document ID and the term ID. For example: bow[0:10] Out[1]: array([[ 0, 10], [ 0, 12], [ 0, 19], [ 0, 20], [ 1, 9], [ 1, 24], [ 2, 33], [ 2, 34], [ 2, 35], [ 3, 2]]) In addition, I have an "index" matrix, where every row in the matrix contains the index of the first and last row for a given document ID in the bag of words matrix. Ex: row 0 is the first and last index for doc id 0. For example: index[0:4] Out[2]: array([[ 0, 4], [ 4, 6], [ 6, 9], [ 9, 10]]) What I'd like to do is take a random sample of document ID's and get all of the bag of word rows for those document ID's. The bag of words matrix is roughly 150M rows (~1.5Gb), so using numpy.in1d() is too slow. We need to return these rapidly for feeding into a downstream task. The naive solution I have come up with is as follows: def get_rows(ids): indices = np.concatenate([np.arange(x1, x2) for x1,x2 in index[ids]]) return bow[indices] get_rows([4,10,3,5]) Generic sample A generic sample to put forth the problem would be with something like this - indices = np.array([[ 4, 7], [10,16], [11,18]] The expected output would be - array([ 4, 5, 6, 10, 11, 12, 13, 14, 15, 11, 12, 13, 14, 15, 16, 17])
has comment: http://stackoverflow.com/comment/81201679
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/81201597
has comment: http://stackoverflow.com/comment/81202081
tagged with: vectorization
has comment: http://stackoverflow.com/comment/81202466
tagged with: optimization
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81201589
has title: Concatenate range arrays given start, stop numbers in a vectorized way - NumPy
has comment: http://stackoverflow.com/comment/81202227

http://stackoverflow.com/q/47188761
duplicate of: http://stackoverflow.com/q/379906
score: 0
tagged with: http://stackoverflow.com/tag/html
answer count: 1
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/379906
type: UnansweredQuestion
tagged with: flask
has title: How do I add n number of input fields depending on a passed value?
has body: I'm trying to create a dynamic number of HTML input text fields, where the number comes posted from another form. But Flask interprets the form number 10 as 1 0, i.e. 2 (string length). The first form: &lt;form action="/new_vocals" method="post"&gt; &lt;input type="text" name="count"&gt; &lt;input type="submit"&gt; The Flask app route: @app.route("/new_vocals", methods=['POST', 'GET']) def new_vocals(): voc_count = request.form['count'] return render_template("new_vocals.html", count=voc_count) Trying to use voc_count in a for loop, I get 2 input types with the value 10, 3 with 100 and so on. There has to be a way to get Flask to interpret 10 as a string?
has answer: http://stackoverflow.com/a/47188920

http://stackoverflow.com/a/47218839
has comment: http://stackoverflow.com/comment/81387356
answers question: http://stackoverflow.com/q/47218627
upvote count: 4
has body: Tensorflow describes the computation using a static graph. You first have to define the graph and then execute it. The graph execution start from the node you put into the sess.run([var1,var2, ..., vaN]) call: the order of the variables is meaningless. Tensorflow graph evaluation starts from a random node and follows each node from the leaf to the root. Since you want to force a certain order of execution, you have to use tf.control_dependencies to introduce an ordering constraint into the graph and thus for the execution of the operations in a certain order. Look at how I changed your code to make it work, it should be pretty clear. import tensorflow as tf # define the first 2 terms of the sequence a = tf.Variable(0) b = tf.Variable(1) # you have to force the order of assigments: # first execute newterm, then execute update1 and than update2 # define the next term. By definition it is the sum of the previous ones newterm = tf.add(a,b) # or newterm = a+b with tf.control_dependencies([newterm]): update1 = tf.assign(a, b) # thus, execute update2 after update1 and newterm # have been executed with tf.control_dependencies([update1]): update2 = tf.assign(b, newterm) # initialize variables init = tf.global_variables_initializer() # run with tf.Session() as sess: sess.run(init) fibonacci = [a.eval(), b.eval()] for i in range(10): next, up1, up2 = sess.run([newterm, update1, update2]) fibonacci.append(next) print(fibonacci)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81387287
score: 4
accepted answer of: http://stackoverflow.com/q/47218627
has comment: http://stackoverflow.com/comment/81387176
has comment: http://stackoverflow.com/comment/81387289
type: Answer

http://stackoverflow.com/comment/81170823
type: Comment
comment on: http://stackoverflow.com/q/47110093
score: 0
type: QuestionComment
has text: @ Alex Riley : I agree this is not the best example. I change the post with size attribute.

http://stackoverflow.com/comment/81109589
type: QuestionComment
comment on: http://stackoverflow.com/q/47079936
score: 0
has text: What confuses you about which of the two tasks you listed?
type: Comment

http://stackoverflow.com/comment/81326261
type: Comment
type: QuestionComment
has text: Continuing this idea, the next thing I'd be curious about would be having multiple values for the devices that are online - a dictionary that, say, stores the 5 most recent times the device has been seen online to see if it's dropping off for a while during attempted 'pings' or responding to each one. this would involve *not* overwriting the values of the online devices but rather appending to their current values. So it would look like `{'device1':'second_most_recent_time',most_recent_time';'device2':'';'device3:'second_most_recent_time',most_recent_time'}` etc. Thoughts?
comment on: http://stackoverflow.com/q/47187250
score: 0

http://stackoverflow.com/comment/81160719
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47105070
score: 0
has text: what about border colour of each bar?

http://stackoverflow.com/a/47177396
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/47177238
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81308338
has comment: http://stackoverflow.com/comment/81306628
downvote count: 0
has comment: http://stackoverflow.com/comment/81304881
has comment: http://stackoverflow.com/comment/81304791
has comment: http://stackoverflow.com/comment/81308417
has body: What you are doing the questions posted is adding timedelta to a list ['inc_cr_date'] + pd.DateOffset(1). Try it with row['inc_cr_date'] + pd.DateOffset(1) So instead of if, elseif, else we can use the power of np.select, and + pd.Timedelta i.e df['inc_cr_date2'] = np.select([(df['inc_cr_date_day'] == 'Saturday'), (df['inc_cr_date_day'] == 'Sunday')], [df['inc_cr_date']+pd.Timedelta('1 days'), df['inc_cr_date']+pd.Timedelta('2 days')], df['inc_cr_date']) inc_cr_date inc_cr_date_day inc_cr_date2 0 2017-10-26 21:59:28.075 Thursday 2017-10-26 21:59:28.075 1 2017-10-27 08:17:02.718 Friday 2017-10-27 08:17:02.718 2 2017-10-22 14:44:07.695 Sunday 2017-10-24 14:44:07.695 For specific time we can use normalize and add timedelta of hours you want ie. df['inc_cr_date2'] = np.select([(df['inc_cr_date_day'] == 'Saturday'), (df['inc_cr_date_day'] == 'Sunday')], [(df['inc_cr_date']+pd.Timedelta('1 days')).dt.normalize() + pd.Timedelta('9 Hours'), (df['inc_cr_date']+pd.Timedelta('2 days')).dt.normalize() + pd.Timedelta('9 Hours')], df['inc_cr_date']) inc_cr_date inc_cr_date_day inc_cr_date2 0 2017-10-26 21:59:28.075 Thursday 2017-10-26 21:59:28.075 1 2017-10-27 08:17:02.718 Friday 2017-10-27 08:17:02.718 2 2017-10-22 14:44:07.695 Sunday 2017-10-24 09:00:00.000
type: Answer
has comment: http://stackoverflow.com/comment/81307877
accepted answer of: http://stackoverflow.com/q/47177238
has comment: http://stackoverflow.com/comment/81306555

http://stackoverflow.com/comment/81354375
score: 0
comment on: http://stackoverflow.com/q/47201783
type: Comment
type: QuestionComment
has text: @tobias_k I have added, let me know if it make sense

http://stackoverflow.com/q/47100679
has comment: http://stackoverflow.com/comment/81151443
has body: I'm trying to use scipy.optimize to identify the optimal values for 3 parameters(variable). I am starting with a very simple optimization function that sums the analyzed parameters together with some predefined (past) values. The values are bound using some fixed values. I set the value of the sign parameter to -1 as I am dealing with a maximization problem. However, scipy returns [0, 0, 0] as optimal values (same as setting sign=1), while the correct solution is [2, 2, 2]. Am I setting something wrong? What am I missing? import scipy.optimize as optimize import numpy as np old = [1,1,1] def f(params,sign=-1.0): first, second, third = params return sum(old+[first, second, third]) initial_guess = [2,2,2] in1 = 1 in2 = 2 in3 = 1 bnds = ((0, in1+2), (0, in2+2), (0, in3+2)) result = optimize.minimize(f, initial_guess, bounds=bnds) print result.x
has comment: http://stackoverflow.com/comment/81151629
tagged with: function
type: UnansweredQuestion
tagged with: python
tagged with: optimization
has title: Wrong optimization with scipy (maximize)
score: 0
has comment: http://stackoverflow.com/comment/81152510
answer count: 1
has comment: http://stackoverflow.com/comment/81151800
tagged with: scipy
has comment: http://stackoverflow.com/comment/81151529
has answer: http://stackoverflow.com/a/47100961
type: Question
tagged with: numpy

literate-programming
type: Tag
tag name: literate-programming
tags question: http://stackoverflow.com/q/47111701

http://stackoverflow.com/comment/81205530
comment on: http://stackoverflow.com/a/47127257
type: AnswerComment
has text: ...for instance, if you want `runserver` to be the default command, you can't do that with an alias, but with a function, you could write `pm() { (( $# )) || set -- runserver; python manage.py "$@"; }`, such that `pm` will run `python manage.py runserver`, but `pm shell` will run `python manage.py shell`.
score: 1
type: Comment

http://stackoverflow.com/comment/81161654
comment on: http://stackoverflow.com/q/47105363
type: Comment
score: 0
type: QuestionComment
has text: Ah okay thank you for the help! I will try out the binascii library first and use a hex editor to see if i can make anything of it since i don't know much about the struct module. I will definitely look that up though thank you!

py2neo
tags question: http://stackoverflow.com/q/47116400
tag name: py2neo
type: Tag

http://stackoverflow.com/q/47105021
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/46814229
answer count: 2
has answer: http://stackoverflow.com/a/47105070
tagged with: matplotlib
has body: I am trying to learn python mainly for plotting. Here is my sample code: import numpy as np import matplotlib.pyplot as plt a=[[1,2,3,4],[2,3,4,5],[3,4,5,6]] x=np.arange(len(a[0])) width=0.2 fig, ax = plt.subplots(figsize=(8,6)) patterns=['/','\\','*'] for bar in a: ax.bar(x,bar,width,edgecolor='black',color='lightgray', hatch=patterns.pop(0)) x=x+width plt.show() Now the problem is that, I need black edge colour for all bars as well as given hatch patter. However, the formatting is applied to first set of bars only. Here is my output. (I am using python3). What's missing here or what's wrong? I have looked around but did not find any fix. Update: I have tried different options :python2, python3 and pdf/png. Here are results python2 png --fine python3 png -- shown above python2 pdf -- see python3 pdf -- see I have also tried 'backend' as matplotlib.use('Agg'). I have update my matplotlib version (2.1.0).
type: Question
accepted answer: http://stackoverflow.com/a/47105070
has title: formatting to group of bars using matplotlib
tagged with: python
tagged with: backend
has answer: http://stackoverflow.com/a/47109442
possible better answer: http://stackoverflow.com/a/47109442

http://stackoverflow.com/comment/81303924
comment on: http://stackoverflow.com/q/47160328
score: 0
type: Comment
type: QuestionComment
has text: @MarkTolonen, Yes I tried running Python script in a console and it worked. Thanks for your help !! But I am still interested to know if there is, anything exists, a possiblity to see the same output in python interpreter.

http://stackoverflow.com/q/47074632
score: 0
tagged with: django-generic-views
answer count: 1
tagged with: django
has answer: http://stackoverflow.com/a/47075026
accepted answer: http://stackoverflow.com/a/47075026
type: Question
has body: I have a PolymorphicModel class named Vehicle, and I derived two class from this: Car and Truck. I use UpdateView to update but it's getting vehicle_id from vehicle_list randomly. And I have to control which type of vehicle is this model. But I couldn't. My classes: class Vehicle(PolymorphicModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, verbose_name="ID") class Car(Vehicle): car_license = models.CharField(max_length=32) class Truck(Vehicle): truck_license = models.CharField(max_length=32) In view: class VehicleUpdate(UpdateView): car = object if car.car_license is not None: model = Car else: model = Truck fields = '__all__' def get_success_url(self, **kwargs): return reverse_lazy('person-list') But it's giving this error: AttributeError: type object 'object' has no attribute 'tr_id' By the way, I tried to use "isinstance()" but it didn't work. Maybe it's about being PolymorphicModel, I don't know. class VehicleUpdate(UpdateView): if isinstance(object, Car): model = Car else: model = Truck fields = '__all__' def get_success_url(self, **kwargs): return reverse_lazy('person-list')
tagged with: django-polymorphic
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/81098630
has title: Controlling PolymorphicModel classed object as model in Generic view
type: AnsweredQuestion

http://stackoverflow.com/q/47118721
tagged with: error-handling
upvote count: 1
accepted answer: http://stackoverflow.com/a/47118785
has answer: http://stackoverflow.com/a/47118785
type: AnsweredQuestion
has body: Is there a way to get more specific Error messages in Python? E.g The full error code or at least the line the error occurred on, the exact file that cannot be found rather than a generic "The system cannot find the file specified") for file in ['C:/AA/HA.csv', 'C:/AA1/HA1.csv']: try: os.remove(file) except OSError as e: pass print(getattr(e, 'message', repr(e))) #print(getattr(e, 'message', repr(e))) #print(e.message) #print('File Not Removed') The following prints twice: FileNotFoundError(2, 'The system cannot find the file specified') While this is great, is there a way to get more precise error messages for bug fixing? The following stops the job but gives out in console the exact line being 855 as well as the file directory ''C:/AC/HA.csv''. os.remove('C:/AA/HA.csv') Traceback (most recent call last): File "C:/ACA.py", line 855, in &lt;module&gt; os.remove('C:/AC/HA.csv') FileNotFoundError: [WinError 2] The system cannot find the file specified: ''C:/AC/HA.csv''
score: 1
answer count: 1
tagged with: python
has title: Printing precise error messages in Python
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: subprocess
downvote count: 0

feature-detection
type: Tag
tags question: http://stackoverflow.com/q/47140842
tag name: feature-detection

http://stackoverflow.com/a/47132228
downvote count: 0
answers question: http://stackoverflow.com/q/47132164
type: Answer
upvote count: 1
has body: You are almost there, you just need to nest one level deeper: [[sub[i] for i in [1, 5, 6]] for sub in Comps] Alternatively, you can use operator.itemgetter: &gt;&gt;&gt; list(map(operator.itemgetter(*[1, 5, 6]), Comps)) [(500, 350, 120), (501, 351, 121)] Or, more directly, &gt;&gt;&gt; list(map(operator.itemgetter(1, 5, 6), Comps)) [(500, 350, 120), (501, 351, 121)]
score: 1

http://stackoverflow.com/comment/81084692
comment on: http://stackoverflow.com/q/47068017
score: 0
type: Comment
type: QuestionComment
has text: I did a cProfile and conclude this based on the number of the cumulative seconds written besides `argwhere`.

elementtree
tags question: http://stackoverflow.com/q/47161961
type: Tag
tags question: http://stackoverflow.com/q/47151445
tags question: http://stackoverflow.com/q/47168397
tags question: http://stackoverflow.com/q/47080011
tags question: http://stackoverflow.com/q/47104413
tag name: elementtree
tags question: http://stackoverflow.com/q/47203492
tags question: http://stackoverflow.com/q/47208193

shell
tags question: http://stackoverflow.com/q/47166077
tags question: http://stackoverflow.com/q/47120873
tags question: http://stackoverflow.com/q/47128326
type: Tag
tags question: http://stackoverflow.com/q/47111279
tags question: http://stackoverflow.com/q/47203965
tags question: http://stackoverflow.com/q/47199225
tag name: shell
tags question: http://stackoverflow.com/q/47213685
tags question: http://stackoverflow.com/q/47139176
tags question: http://stackoverflow.com/q/47090982

http://stackoverflow.com/comment/81280241
type: Comment
type: QuestionComment
score: 0
has text: Yes sorry the float() was incorrect. Edited to what I had to get the error now. Thanks.
comment on: http://stackoverflow.com/q/47165189

http://stackoverflow.com/a/47192162
score: 0
has comment: http://stackoverflow.com/comment/81333666
has comment: http://stackoverflow.com/comment/81334517
has comment: http://stackoverflow.com/comment/81334551
has comment: http://stackoverflow.com/comment/81334610
type: Answer
has comment: http://stackoverflow.com/comment/81334839
has comment: http://stackoverflow.com/comment/81334803
has comment: http://stackoverflow.com/comment/81335047
has body: # With lambda expression def sorted_images(image_dict): result = sorted(image_dict.values(), key=lambda x: x[1].split('-')) return [image for (image, exif) in image_dict.items() for (_exif) in result if (exif == _exif)] # Without lambda expression def sort_by_date(x): return x[1].split('-') def sorted_images(image_dict): result = sorted(image_dict.values(), key=sort_by_date ) return [image for (image, exif) in image_dict.items() for (_exif) in result if (exif == _exif)] This is a function that does just that with the data you specified.
has comment: http://stackoverflow.com/comment/81335336
answers question: http://stackoverflow.com/q/47192123
has comment: http://stackoverflow.com/comment/81335169

ms-word
tag name: ms-word
tags question: http://stackoverflow.com/q/47157568
type: Tag
tags question: http://stackoverflow.com/q/47212459

http://stackoverflow.com/a/47193556
score: 0
has comment: http://stackoverflow.com/comment/81337970
has comment: http://stackoverflow.com/comment/81339778
type: Answer
has body: This will print out a list of value. l=fp_price.values.tolist() import functools functools.reduce(lambda x,y: x+y,l)
answers question: http://stackoverflow.com/q/47193493

http://stackoverflow.com/a/47214815
has comment: http://stackoverflow.com/comment/81380091
has comment: http://stackoverflow.com/comment/81379881
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47214594
has comment: http://stackoverflow.com/comment/81456572
has comment: http://stackoverflow.com/comment/81380029
upvote count: 2
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/81379950
has comment: http://stackoverflow.com/comment/81455546
has body: Well, your question is unclear but one thing for sure, at least one hit to the database will be required. Indeed, in your code sample your using: question_name = question.name But I don't see this working if question is not an instance of Question model beforehand. So, considering your initial hit on the DB from a query to create an instance, question_name can then be reused as often as you want without having to access the database. See, this as a static instance of a row of your database. EDIT Now for your edit, it is not the same behavior. To correctly understand what happens behind the scenes, you need to understand the concept of "Laziness". In fact, since querysets are lazy in Django, this line: questions = Question.objects.filter(test=some_test) won't result in any hit on the database. Querysets stands for sets of SQL queries. So, at this point, since you did not ask to fetch something from the database it is not actually evaluated yet. This is the wanted behavior because it makes sure the database is accessed only when it needs to. As the documentation says here are the cases where querysets are evaluated: Iteration A QuerySet is iterable, and it executes its database query the first time you iterate over it. Slicing Slicing an unevaluated QuerySet usually returns another unevaluated QuerySet, but Django will execute the database query if you use the “step” parameter of slice syntax, and will return a list. Slicing a QuerySet that has been evaluated also returns a list. Pickling/Caching repr(). A QuerySet is evaluated when you call repr() on it. This is for convenience in the Python interactive interpreter, so you can immediately see your results when using the API interactively. len(). A QuerySet is evaluated when you call len() on it. This, as you might expect, returns the length of the result list. list(). Force evaluation of a QuerySet by calling list() on it bool(). Testing a QuerySet in a boolean context, such as using bool(), or, and or an if statemen…
answers question: http://stackoverflow.com/q/47214594
score: 1

http://stackoverflow.com/q/47117884
has comment: http://stackoverflow.com/comment/89485800
type: AnsweredQuestion
has title: Whats the difference between PyPy and PyPI
has answer: http://stackoverflow.com/a/47117892
accepted answer: http://stackoverflow.com/a/47117892
answer count: 1
tagged with: pypi
tagged with: pypy
downvote count: 7
favorite count: 0
type: Question
upvote count: 26
tagged with: python
has body: This is probably a really stupid question but whats the difference between PyPy and PyPI? Are they the same thing?
has comment: http://stackoverflow.com/comment/89489388
score: 19

http://stackoverflow.com/a/47133267
has comment: http://stackoverflow.com/comment/81216978
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81216742
accepted answer of: http://stackoverflow.com/q/47133250
score: 3
answers question: http://stackoverflow.com/q/47133250
has body: Create dictionary of DataFrames and add new column with assign: rng = pd.date_range('2015-11-01 00:00:00', periods=100, freq='S') df = pd.DataFrame({'Date': rng, 'a': range(100)}) print (df.head(10)) Date a 0 2015-11-01 00:00:00 0 1 2015-11-01 00:00:01 1 2 2015-11-01 00:00:02 2 3 2015-11-01 00:00:03 3 4 2015-11-01 00:00:04 4 5 2015-11-01 00:00:05 5 6 2015-11-01 00:00:06 6 7 2015-11-01 00:00:07 7 8 2015-11-01 00:00:08 8 9 2015-11-01 00:00:09 9 g = df.groupby(pd.Grouper(key='Date', freq='5S')) dfs = {k.strftime('%Y-%m-%d %H:%M:%S'):v.assign(A=range(1,len(v)+1), B=len(v)) for k,v in g} print (dfs['2015-11-01 00:00:05']) Date a A B 5 2015-11-01 00:00:05 5 1 5 6 2015-11-01 00:00:06 6 2 5 7 2015-11-01 00:00:07 7 3 5 8 2015-11-01 00:00:08 8 4 5 9 2015-11-01 00:00:09 9 5 5 If need count rows first aggreagte size and for Interval is add 1 to index: df1 = df.groupby(pd.Grouper(key='Date', freq='5S')).size().reset_index(name='Count') df1['Interval'] = df1.index + 1 print (df1.head()) Date Count Interval 0 2015-11-01 00:00:00 5 1 1 2015-11-01 00:00:05 5 2 2 2015-11-01 00:00:10 5 3 3 2015-11-01 00:00:15 5 4 4 2015-11-01 00:00:20 5 5
type: Answer
has comment: http://stackoverflow.com/comment/81216575
has comment: http://stackoverflow.com/comment/81217010
has comment: http://stackoverflow.com/comment/81217920

http://stackoverflow.com/q/47066192
has title: SIGALRM not interrupting long running SVC fitting
has body: I'm trying to stop a fitting process for sklearn's SVC by using signal.alarm, along with an appropriate signal handler that throws an exception. Below is a MWE import numpy as np from sklearn.svm import SVC import signal n = int(1e5) np.random.seed(1) X = np.random.random((n, 100)) y = np.random.choice(['A', 'B'], size=n) def timeout_handler(s, f): raise Exception('Timed out') def not_interrupting(): signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(3) # this should take on the order of minutes SVC().fit(X, y) signal.alarm(0) def interrupting(): signal.alarm(3) SVC().fit(X, y) signal.alarm(0) # interrupts (but kills the current python process) interrupting() # doesn't interrupt as expected within 3 seconds not_interrupting() This doesn't seem to work. The exception raised doesn't interrupt execution. However if I don't register a signal handler, as done in interrupting, it does interrupt but kills the current python process. Any suggestions? Additional Info: scikit-learn 0.18.1 Python 3.6.1 OS X 10.11.16 I think I may have found my own answer. According to the signal docs: Although Python signal handlers are called asynchronously as far as the Python user is concerned, they can only occur between the “atomic” instructions of the Python interpreter. This means that signals arriving during long calculations implemented purely in C (such as regular expression matches on large bodies of text) may be delayed for an arbitrary amount of time. I believe SVC uses libsvm, so that is causing the delay of my signal handler being called.
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81080921
has comment: http://stackoverflow.com/comment/81103331
tagged with: scikit-learn
type: Question

http://stackoverflow.com/q/47096794
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: I have a file with strings that were pulled out of our HR system that are images of people that work for our company. I wrote the following code to convert these strings into .jpg files. d is the name of the new file and x is the image string. I have printed both of these variables and they seem to be working. The file is saving and it is 71KB but when I open it in paint it says that it "cannot read this file and This is not a valid bitmap file, or its format is not currently supported." I opened it with Photos and it just said it "can't open this file." Are you able to see any issue with the code? import csv import base64 import tkinter as tk from tkinter import filedialog root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename() with open(file_path, 'r') as csvfile: readCSV = csv.reader(csvfile,delimiter=',') next(readCSV) for line in readCSV: d = line[0] x = line[1] y = base64.encodebytes(x.encode()) with open("C:\\%s.jpg" %(d), "wb") as fh: fh.write(base64.decodebytes(y)) fh.close() break
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/jpeg
has title: Python Converting String to jpg file
answer count: 0

http://stackoverflow.com/comment/81189570
type: AnswerComment
has text: This is certainly the easiest way of doing it.
comment on: http://stackoverflow.com/a/47119745
score: 1
type: Comment

http://stackoverflow.com/a/47212870
upvote count: 1
has body: In python 3.6 urlopen is in urllib.request module. from urllib.request import urlopen url = "http://stackoverflow.com" f = urlopen(url) print (f.read())
type: Answer
answers question: http://stackoverflow.com/q/47212821
downvote count: 0
score: 1

http://stackoverflow.com/a/47188152
has body: The problem is that your regexp is buggy, and doesn't match the strings you want to extract. Specifically, you have two issues: { and } are regexp metacharacters, just like $, and also need to be escaped if you want to match them literally. \b matches a word boundary, i.e. a position between a "word character" (a letter, a number or an underscore) and a "non-word character" (anything else) or the beginning/end end of string. It does not match between, say, a space and $. To fix these issues, change your line: matches = re.findall(r'\b\${\S+}\b', line) to: matches = re.findall(r'\$\{\S+\}', line) and it should work. See the Python regular expressions documentation for more details.
type: Answer
accepted answer of: http://stackoverflow.com/q/47175817
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47175817

http://stackoverflow.com/q/47156055
has answer: http://stackoverflow.com/a/58352991
favorite count: 0
type: Question
answer count: 5
type: UnansweredQuestion
has body: Here's my Tkinter code: Photoshop = Tkinter.Button(root, text = 'Photoshop', fg = '#37d3ff', bg = '#001d26', bd = 10, highlightthickness=4, highlightcolor="#37d3ff", highlightbackground="#37d3ff", borderwidth=4) However, after I grid my Button, the color of border doesn't shows up. Instead, it used default grey.
has answer: http://stackoverflow.com/a/47156214
tagged with: python
has title: Tkinter's button can't change border color
has comment: http://stackoverflow.com/comment/81262137
has answer: http://stackoverflow.com/a/68651868
score: 2
upvote count: 3
has answer: http://stackoverflow.com/a/53579714
tagged with: tkinter
has answer: http://stackoverflow.com/a/52538371
has comment: http://stackoverflow.com/comment/81261428
tagged with: button
downvote count: 1

http://stackoverflow.com/comment/81355881
comment on: http://stackoverflow.com/a/47202252
score: 0
has text: @brunodesthuilliers Yeah, maybe he want to import something different, but the easiest way to do is import it explicitly and directly. I do think the questioner knows that.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/140025876
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47113530
has text: 2025 and also looking for this... :(

http://stackoverflow.com/q/47157613
tagged with: dataframe
tagged with: python
tagged with: flatten
has body: Having a DataFrame (or Series) consisting of lists, looking like this: df = pd.DataFrame([[[1,3], [2,3,4], [1,4,2,5]]], columns=['A', 'B', 'C']).T print(df) Output: 0 A [1, 3] B [2, 3, 4] C [1, 4, 2, 5] How can I transform it into 0 A 1 A 2 B 2 B 3 B 4 C 1 C 4 C 2 C 5 I've tried to use apply() but that didn't quite work. Can I implicitly convert that? I also tried to extract all number as tuples [('A', 1), ('A', 3), ..] for from_records() but I wasn't able to do that as well. I think I could do it like this: pd.DataFrame.from_records(df[0].map(lambda x: [(0, v) for v in x]).sum()) but I don't know how to access the index.. note (0, v) should actually be something like (x.index, v).
accepted answer: http://stackoverflow.com/a/47157646
type: AnsweredQuestion
tagged with: list
answer count: 2
possible better answer: http://stackoverflow.com/a/47157700
tagged with: pandas
has answer: http://stackoverflow.com/a/47157646
score: 1
has answer: http://stackoverflow.com/a/47157700
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: Convert DataFrame or Series of lists into one stacked DataFrame (or Series)

constraints
type: Tag
tag name: constraints
tags question: http://stackoverflow.com/q/47195005

http://stackoverflow.com/a/47199010
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81410352
accepted answer of: http://stackoverflow.com/q/47198876
has comment: http://stackoverflow.com/comment/81347382
answers question: http://stackoverflow.com/q/47198876
type: Answer
has comment: http://stackoverflow.com/comment/81347244
has comment: http://stackoverflow.com/comment/81347866
has body: I think this would output what you need, it's a bit long winded but demonstrates the process. string = '1,2,3-6,10' splt_a = string.split(",") o = [] for s in splt_a: if "-" in s: splt_b = s.split("-") for i in range(int(splt_b[0]), int(splt_b[1]) + 1): o.append(i) else: o.append(int(s)) print(o) # [1, 2, 3, 4, 5, 6, 10]
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47094064
answers question: http://stackoverflow.com/q/47093345
type: Answer
has comment: http://stackoverflow.com/comment/81143402
has body: The following indexer should do the trick on datetimes: threshold = pd.Timedelta('1 hour') indexer = pd.Series(df1.index, index=df1.index).apply( lambda x: min(abs(x - df2.index)) &lt; threshold ) df1.loc[indexer] Note: It doesn't scale well. It starts to take seconds if len(df1) * len(df2) ~ 106
score: 0

http://stackoverflow.com/comment/81152686
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47101239
has text: As already commented on the other question, I cannot reproduce this. I get the same output with both codes.
type: Comment

http://stackoverflow.com/comment/81185557
score: 4
has text: make a list of the files and pass them through a for loop
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47117780

http://stackoverflow.com/q/47191365
type: Question
type: UnansweredQuestion
has body: I have this segment of code to extract the shortest path in a graph from one node to another g = json_graph.node_link_graph(json.load(open("MPLS-topo.json"))) paths = nx.shortest_path(g, "H1", weight="weight") for dest in paths.keys(): # Nicely output all those paths if dest == "H2": print "Shortest Path from H1 to {} is:".format(dest) print "{}".format(paths[dest]) the output of it is Shortest Path from H1 to H2 is: ['H1', u'S1', u'S2', u'S3', u'S5', u'H2'] I want to remove u and convert the path to string like this H1-S1-S2-S3-S5-H2 I tried this path = [s.replace('u', '') for s in paths[dest]] print path y = "-".join(path) but it gives me the same output. How can I do this in python?
tagged with: python
has comment: http://stackoverflow.com/comment/81332293
has comment: http://stackoverflow.com/comment/81332329
tagged with: list
score: 0
answer count: 1
has title: extract strings from list
has answer: http://stackoverflow.com/a/47209670
tagged with: string

http://stackoverflow.com/q/47216204
accepted answer: http://stackoverflow.com/a/50018981
has answer: http://stackoverflow.com/a/63898759
has title: How do I upload multiple files using the Flask test_client?
has answer: http://stackoverflow.com/a/58397147
possible better answer: http://stackoverflow.com/a/63898759
has comment: http://stackoverflow.com/comment/81436099
tagged with: python-unittest
tagged with: python
has answer: http://stackoverflow.com/a/50018981
upvote count: 6
has body: How can I use the Flask test_client to upload multiple files to one API endpoint? I'm trying to use the Flask test_client to upload multiple files to a web service that accepts multiple files to combine them into one large file. My controller looks like this: @app.route("/combine/file", methods=["POST"]) @flask_login.login_required def combine_files(): user = flask_login.current_user combined_file_name = request.form.get("file_name") # Store file locally file_infos = [] for file_data in request.files.getlist('file[]'): # Get the content of the file file_temp_path="/tmp/{}-request.csv".format(file_id) file_data.save(file_temp_path) # Create a namedtuple with information about the file FileInfo = namedtuple("FileInfo", ["id", "name", "path"]) file_infos.append( FileInfo( id=file_id, name=file_data.filename, path=file_temp_path ) ) ... My test code looks like this: def test_combine_file(get_project_files): project = get_project_files["project"] r = web_client.post( "/combine/file", content_type='multipart/form-data', buffered=True, follow_redirects=True, data={ "project_id": project.project_id, "file_name": "API Test Combined File", "file": [ (open("data/CC-Th0-MolsPerCell.csv", "rb"), "CC-Th0-MolsPerCell.csv"), (open("data/CC-Th1-MolsPerCell.csv", "rb"), "CC-Th1-MolsPerCell.csv") ]}) response_data = json.loads(r.data) assert "status" in response_data assert response_data["status"] == "OK" However, I can't get the test_client to actually upload both files. With more than one file specified, the file_data is empty when the API code loops. I have tried my own ImmutableDict with two "file" entries, a list of file tuples, a tuple of file tuples, anything I could think of. What is the API to specify multiple files for upload in the Flask test_client? I can't find this anywhere on the web! :(
tagged with: multiple-file-upload
type: AnsweredQuestion
answer count: 3
downvote count: 0
tagged with: web-api-testing
tagged with: flask
score: 6
favorite count: 0
type: Question

http://stackoverflow.com/q/47128539
type: Question
has answer: http://stackoverflow.com/a/47128571
upvote count: 0
has body: I am looking to get the number of similar characters between two lists. The first list is: list1=['e', 'n', 'z', 'o', 'a'] The second list is going to be a word user inputted turned into a list: word=input("Enter word") word=list(word) I'll run this function below to get the number of similitudes in the two lists: def getSimilarItems(word,list1): counter = 0 for i in list2: for j in list1: if i in j: counter = counter + 1 return counter What I don't know how to do is how to get the number of similitudes for each item of the list(which is going to be either 0 or 1 as the word is going to be split into a list where an item is a character). Help would be VERY appreciated :) For example: If the word inputted by the user is afez: I'd like the run the function: wordcount= getSimilarItems(word,list1) And get this as an output: &gt;&gt;&gt;1 (because a from afez is in list ['e', 'n', 'z', 'o', 'a']) &gt;&gt;&gt;0 (because f from afez isn't in list ['e', 'n', 'z', 'o', 'a']) &gt;&gt;&gt;1 (because e from afez is in list ['e', 'n', 'z', 'o', 'a']) &gt;&gt;&gt;1 (because z from afez is in list ['e', 'n', 'z', 'o', 'a'])
downvote count: 2
answer count: 2
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/81207168
has comment: http://stackoverflow.com/comment/81207148
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/47128621
tagged with: list
has comment: http://stackoverflow.com/comment/81207041
has title: Python lists similitudes

http://stackoverflow.com/comment/81165721
type: QuestionComment
comment on: http://stackoverflow.com/q/47107717
score: 1
type: Comment
has text: What problem are you having? Python has `csv.writer` to write CSV to a file, so all you have to do is read the SQL results into a list.

http://stackoverflow.com/a/47129479
downvote count: 0
answers question: http://stackoverflow.com/q/47126157
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/89482682
score: 3
type: Answer
has body: The default behaviour of upload_from_filename is to read the whole file into memory in order to try uploading it all at once. To avoid this set blob.chunk_size before calling blob.upload_from_filename. A sensible value might be 1MiB (1024*1024). I suspect this may be an new issue introduced by this commit.
accepted answer of: http://stackoverflow.com/q/47126157
upvote count: 3

http://stackoverflow.com/comment/81341960
comment on: http://stackoverflow.com/q/47196591
score: 4
type: Comment
has text: `foo` does not inherit from `Foo`, `foo` is an instance of `Foo`, `Foo` inherits from `object`, therefore `foo` is (also) an `object`.
type: QuestionComment

http://stackoverflow.com/comment/81135802
score: 0
comment on: http://stackoverflow.com/q/47083947
type: Comment
has text: @RobertoTrani Do you mean `sigmoid(x)` function yes? Can you explain?
type: QuestionComment

http://stackoverflow.com/comment/81162921
type: QuestionComment
has text: Internally, a CPython `list` uses an array of pointers to store references to each item. Those pointers occupy 4 bytes = 32 bits on a 32 bit machine and 8 bytes on a 64 bit machine. The items themselves will occupy various amounts of RAM which is _not_ reported when you call `sys.getsizeof` on the `list`.
comment on: http://stackoverflow.com/q/47106101
score: 1
type: Comment

http://stackoverflow.com/q/47066727
has answer: http://stackoverflow.com/a/47088920
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81082079
has comment: http://stackoverflow.com/comment/81082126
type: AnsweredQuestion
has body: I've a python question, could be very simple but I have no idea how to do it. Basically I want to run: value = myUiClass().getValue() If I run the following, it will return None directly and not event wait for the user to interact with a UI (that I haven't defined here as the UI itself is not the point) class MyUi(QtWidgets.QWidget): def __init__(self, parent=None): super(MyUi, self).__init__(parent) self.finalValue = None # UI that will modify self.finalValue def getValue(self): return self.finalValue value = MyUi().getValue() I guess I'am missing something to pause the process until the user interacts with the UI ? Here is an example of what I want from PySide2 import QtWidgets col = QtWidgets.QColorDialog.getColor() print col Any idea ? Thx
has title: Python - how to return a value from a class AFTER user interaction
tagged with: pyside
answer count: 1
tagged with: user-interface
downvote count: 3
accepted answer: http://stackoverflow.com/a/47088920
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81081722
score: -2
tagged with: pyside2

http://stackoverflow.com/a/47149068
downvote count: 0
answers question: http://stackoverflow.com/q/47148683
upvote count: 3
score: 3
type: Answer
has body: ab = pd.DataFrame.from_dict(np.concatenate(df['items']).tolist()) lens = df['items'].str.len() rest = df.drop('items', 1).iloc[df.index.repeat(lens)].reset_index(drop=True) ab.join(rest) a b name 0 2 1 this 1 4 3 this 2 2 1 that 3 4 3 that

http://stackoverflow.com/q/47172068
has answer: http://stackoverflow.com/a/47172234
tagged with: buffer
possible better answer: http://stackoverflow.com/a/47172123
has title: How to flush the file write buffer in running python process with no file.close() statement?
tagged with: python
score: 4
upvote count: 4
answer count: 2
downvote count: 0
tagged with: file
has answer: http://stackoverflow.com/a/47172123
has body: I have a file that is being written to in a background Python 3.5 process. The file was opened in this process (which is basically a running Python script) but I forgot to include a file close statement to flush out the buffer occasionally in that script. The script is infinite unless it is ended manually and I (now) know that killing the python process will cause all the data in the buffer to be lost. Is there anyway to recover the data to be written in this already running process?
accepted answer: http://stackoverflow.com/a/47172234
favorite count: 0
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/81332458
comment on: http://stackoverflow.com/a/47185205
type: Comment
has text: Thank you tworec! Without your answer I wouldn't understand Coldspeed's which still states: Do I have to "drop" the existing index before creating the new one? No, just that the columns must align (column name and number of columns should be the same). The reset_index of course does exactly that. Neither of you replied to the question of re-indexing, nor to the question of index vs. column. I'll accept ColdSpeed's answer but put another answer of my own with the rest as far as I understand, for us programmers.
type: AnswerComment
score: 1

http://stackoverflow.com/comment/81368507
has text: Sorry, I don't have any other solution.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47208640
type: QuestionComment

http://stackoverflow.com/a/47098066
type: Answer
has body: I imagine the issue is what Daniel commented. Your URL to create a new object is expecting a PK, which doesn't exist so the Django URL dispatcher cannot find a match. You probably want something like this for your URLs: app_name = 'applicant' urlpatterns = [ url(r'view/(?P&lt;pk&gt;\d+)/$', views.ApplicantUpdate.as_view(), name='applicant-update'), url(r'view/new/$', views.ApplicationCreate.as_view(), name='application-new'), ] And something like this for your reverse URL: {% url 'applicant:application-new' %}
answers question: http://stackoverflow.com/q/47096820
score: 0

http://stackoverflow.com/a/47097808
accepted answer of: http://stackoverflow.com/q/47097363
has body: The difference between your script and your command prompt interaction is osmosis/bin/osmosis.bat vs. .\osmosis.bat. Since your call to Popen() already includes the cwd option, you don't need to specify the directory again. That means your call should be: proc = subprocess.Popen([ app, # &lt;== No app_path here "--read-pbf", pbf_file, "--bounding-box", "top=%d" % (tile_lat+1), "left=%d" % (tile_lng), "bottom=%d" % (tile_lat), "right=%d" % (tile_lng+1), "--write-pbf", "someotherfile.osm.pbf" ], cwd=app_path, shell=True) # &lt;== because of this cwd
upvote count: 2
has comment: http://stackoverflow.com/comment/81145312
answers question: http://stackoverflow.com/q/47097363
type: AcceptedAnswer
score: 2
downvote count: 0
type: Answer

http://stackoverflow.com/a/53823845
has body: f.drop_duplicates(subset='inc_id', keep="last").reset_index(drop=True)
upvote count: 0
type: Answer
score: -1
downvote count: 1
answers question: http://stackoverflow.com/q/47207237
has comment: http://stackoverflow.com/comment/94497081

http://stackoverflow.com/q/47097006
downvote count: 0
has answer: http://stackoverflow.com/a/47100572
favorite count: 0
has comment: http://stackoverflow.com/comment/81144385
possible better answer: http://stackoverflow.com/a/47099220
has title: Printing missing numbers from given input
has comment: http://stackoverflow.com/comment/81145573
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81143814
tagged with: python
type: Question
tagged with: python-3.x
score: 2
has comment: http://stackoverflow.com/comment/81143771
answer count: 2
has answer: http://stackoverflow.com/a/47099220
upvote count: 2
accepted answer: http://stackoverflow.com/a/47100572
has body: Numbers which are in sequence in ascending order are given as a input as string.The program should print the missing number ? EX: INPUT 567568600601602 OUTPUT 569 EXPLANATION 567,568,600,601,602 are the numbers in sequence and 569 is the missing number INPUT 1112131516 OUTPUT 14 EXPLANATION 11,12,13,15,16 are the numbers in sequence and 569 is the missing MY CODE a=input() a=a.rstrip() b=list(set(a)) l=[] p=[] c=0 for i in range(len(b)): if a.count(b[i])&gt;1: c+=1 j=0 while j&lt;=len(a): l.append(a[j:j+c+1]) j=j+c+1 del l[-1] k=int(l[0]) while k&lt;=int(l[-1]): p.append(k) k=k+1 for u in range(len(p)): if str(p[u]) not in l: print(p[u]) break My query: My program is unable to find the missing number in case of 2 or 4 digit numbers given as input in form of string . input 6768707172 output of my program 677 expected output 69 How to check the whether the string has 2 or 3 or 4 digit numbers and break them accordingly ?

http://stackoverflow.com/comment/81256828
comment on: http://stackoverflow.com/q/47131231
score: 0
type: Comment
type: QuestionComment
has text: I tried that, but it is not giving convincing results.

http://stackoverflow.com/q/47131980
has title: Group a few threading functions Python
has body: I have a few functions and I want them to be in different threading groups. That is, I want those different threading groups to run after another. My example codes are as below: import threading from threading import Thread def func_a(): # do something here def func_b(): # do something here def func_c(): # do something here def func_d(): # do something here thread_a = threading.Thread(target = func_a) thread_b = threading.Thread(target = func_b) thread_c = threading.Thread(target = func_c) thread_d = threading.Thread(target = func_d) thread_a.start() thread_b.start() thread_c.start() thread_d.start() thread_a.join() thread_b.join() thread_c.join() thread_d.join() What I want to do is very simple: put a func_a and func_b as threading_group_a, also put func_c and func_d as threading_group_b. Then execute threading_group_a first and then threading_group_b.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81214009
has comment: http://stackoverflow.com/comment/81213565
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47132254
tagged with: python
has answer: http://stackoverflow.com/a/47132562
has comment: http://stackoverflow.com/comment/81213995
score: 2
answer count: 2
has comment: http://stackoverflow.com/comment/81213903
upvote count: 2
tagged with: multithreading
tagged with: grouping
downvote count: 0

routes
type: Tag
tag name: routes
tags question: http://stackoverflow.com/q/47136884

http://stackoverflow.com/q/47102738
type: AnsweredQuestion
has title: delete all .csv file content in python
has comment: http://stackoverflow.com/comment/81156836
tagged with: http://stackoverflow.com/tag/csv
score: 1
accepted answer: http://stackoverflow.com/a/47103158
has comment: http://stackoverflow.com/comment/81156812
answer count: 1
has comment: http://stackoverflow.com/comment/81156922
tagged with: python
has comment: http://stackoverflow.com/comment/81156303
has comment: http://stackoverflow.com/comment/81155673
linked to: http://stackoverflow.com/q/9763675
has comment: http://stackoverflow.com/comment/81157152
favorite count: 0
type: Question
tagged with: python-3.x
has body: so, my program will replace the old data with new data which is the program will put in same .csv file. and after i run the program it is not replaced. below is my code. TEXTFILE = open("data.csv", "w") for i in book_list: TEXTFILE.write("{},{},{},{}".format(i[0],i[1],i[2],i[3])) TEXTFILE.close() book_list is the list that save new data to stored the result i got: k,k,45,c a,a,65,r d,s,65,r as,as,65,r df,df6,65,r as,as,6,r as,as,46,r as,as,45,r as,as,56,rk,k,45,r a,a,65,r d,s,65,r as,as,65,r df,df6,65,r as,as,6,r as,as,46,r as,as,45,r as,as,56,r it stored to csv with combining old and new content. well the origininal file is looks like this: k,k,45,r a,a,65,r d,s,65,r as,as,65,r df,df6,65,r as,as,6,r as,as,46,r as,as,45,r as,as,56,r idk how to explain. but I expect that the result will change one line with new data in the fourth row. for example, the previous line is k,k,45,r (line 1). and the program will change it become k,k,45,c that way hope you all can help me :)
has comment: http://stackoverflow.com/comment/81156456
has answer: http://stackoverflow.com/a/47103158
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47199085
has comment: http://stackoverflow.com/comment/81347687
score: 3
has comment: http://stackoverflow.com/comment/81347059
upvote count: 3
has comment: http://stackoverflow.com/comment/81346757
has comment: http://stackoverflow.com/comment/81347545
downvote count: 0
has body: one-liner which creates a range if - is detected (with boundary fixing) else just converts to integer: import itertools result = [x for y in '-1,1,2,3-6,10'.split(",") for x in (range(int(y.split("-")[0]),int(y.split("-")[1])+1) if y.find("-")&gt;0 else [int(y)]) ] result (as a list of integers): [-1, 1, 2, 3, 4, 5, 6, 10] note that it handles negative numbers as well (y.find("-")&gt;0 ensures that - is not at start when detecting range), but not negative ranges (would have to choose another separator for this like :)
has comment: http://stackoverflow.com/comment/81347623
has comment: http://stackoverflow.com/comment/81348235
has comment: http://stackoverflow.com/comment/81347799
type: Answer
answers question: http://stackoverflow.com/q/47198876
has comment: http://stackoverflow.com/comment/81351132

http://stackoverflow.com/comment/81202256
score: 0
type: AnswerComment
has text: @Aif change `myValue` by what?
type: Comment
comment on: http://stackoverflow.com/a/47126097

http://stackoverflow.com/comment/81288405
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47169221
score: 0
has text: http://127.0.0.1:5000 is no good if you want it for other computers, that will be only available on your computer.

http://stackoverflow.com/q/47083057
type: Question
has title: eyed3 add tag release date resolves in error "can't assign to operator"
has answer: http://stackoverflow.com/a/47083235
tagged with: python
tagged with: eyed3
type: AnsweredQuestion
score: 0
has body: I try to add the release-date tag to an mp3 file using eyed3 in python. It works fine for the tags "artist" and "date". It is not working for "release-date": `audiofile.tag.release-date = dateToTag` throws the error: SyntaxError: can't assign to operator This is my setup: `audiofile = eyed3.load(os.path.join("../mockDirectory", file)) audiofile.initTag() audiofile.tag.artist = u"Artist" audiofile.tag.year = year audiofile.tag.release-date = dateToTag` The value of dateToTag is 2017-10-27, formatted according to the documentation page 30: yyyy-mm-dd. Why is the date format throwing a syntax error?
accepted answer: http://stackoverflow.com/a/47083235
answer count: 1
tagged with: http://stackoverflow.com/tag/mp3

http://stackoverflow.com/q/47202740
has comment: http://stackoverflow.com/comment/81353947
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/81353845
has answer: http://stackoverflow.com/a/47202917
score: 1
has title: Python List to its exact string representation
downvote count: 1
accepted answer: http://stackoverflow.com/a/47202803
has comment: http://stackoverflow.com/comment/81355359
favorite count: 0
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/47202917
has comment: http://stackoverflow.com/comment/81353834
has body: I want to convert a python list to its exact string representation. Example: L = ['L','O','L',True] Desired string representation: "['L','O','L',true]" Reason: I need to embed that string inside a javascript snippet. Any ideas on how i can do this effectively ?
has answer: http://stackoverflow.com/a/47202803
tagged with: python
has comment: http://stackoverflow.com/comment/81353787

http://stackoverflow.com/q/47213485
tagged with: python
has comment: http://stackoverflow.com/comment/81376652
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81376577
accepted answer: http://stackoverflow.com/a/47215458
score: 1
has answer: http://stackoverflow.com/a/47215458
answer count: 1
tagged with: arrays
downvote count: 0
upvote count: 1
has title: Create numpy array with another array and an indexing array
tagged with: vectorization
has body: I have an array y that is of shape (m, n) and an array indices that is of shape (m, n, k). Suppose I want to do the following (in Python): x = np.ndarray(shape=(m,n,k)) for i in range(m): for j in range(n): for l in range(k): x[i,j,l] = y[indices[i,j,l],j] Is there a way to do this simply using NumPy that doesn't require using for loops?
type: AnsweredQuestion

http://stackoverflow.com/comment/81179147
score: 4
has text: this is json data, don't use regex to extract those. Use `json.loads()` and you'll get a python dictionary.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47114687

http://stackoverflow.com/comment/81151487
type: AnswerComment
has text: `@Mark Setchell`. Thanks Mark, that is a terrific resource. Unfortunately, I do not see a Python Skimage. I am also surprised that OpenCV 2.4 is not that fast. But perhaps OpenCV 3 is faster. Though one could use GPU with OpenCV.
comment on: http://stackoverflow.com/a/47088695
type: Comment
score: 0

http://stackoverflow.com/comment/81157426
type: AnswerComment
has text: Thank you so much! Sorry, I am really new to programming and I got really confused on what she was asking us to do. But thank you soo much! Is there anything you could recommend me to do to better understand this and be able to code without extra help all the time
type: Comment
comment on: http://stackoverflow.com/a/47103386
score: 0

http://stackoverflow.com/q/47107717
has answer: http://stackoverflow.com/a/47112458
has answer: http://stackoverflow.com/a/52448387
has comment: http://stackoverflow.com/comment/81165918
tagged with: api
has comment: http://stackoverflow.com/comment/81165759
type: UnansweredQuestion
has title: SQL query output to .csv
tagged with: python
has body: I am running SQL query from python API and want to collect data in Structured(column-wise data under their header).CSV format. This is the code so far I have. sql = "SELECT id,author From researches WHERE id &lt; 20 " cursor.execute(sql) data = cursor.fetchall() print (data) with open('metadata.csv', 'w', newline='') as f_handle: writer = csv.writer(f_handle) header = ['id', 'author'] writer.writerow(header) for row in data: writer.writerow(row) Now the data is being printed on the console but not getting in .CSV file this is what I am getting as output: What is that I am missing?
has comment: http://stackoverflow.com/comment/81165859
has comment: http://stackoverflow.com/comment/81165764
answer count: 4
has comment: http://stackoverflow.com/comment/81165876
has comment: http://stackoverflow.com/comment/81165721
score: 0
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/47537014
has answer: http://stackoverflow.com/a/72560927
has answer: http://stackoverflow.com/a/66592737
type: Question
tagged with: export-to-csv

http://stackoverflow.com/q/47126172
favorite count: 0
has comment: http://stackoverflow.com/comment/81202628
tagged with: matrix-multiplication
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81203215
accepted answer: http://stackoverflow.com/a/47126560
tagged with: strassen
upvote count: 1
has comment: http://stackoverflow.com/comment/81202671
has comment: http://stackoverflow.com/comment/81203742
tagged with: python
has comment: http://stackoverflow.com/comment/81203167
has comment: http://stackoverflow.com/comment/81203295
has body: I am attempting to implement Strassen's matrix multiplication algorithm as described in CLRS using Python 3 and numpy matrices. The issue is that the output matrix C is returned as a zero matrix instead of the correct product. I am not sure why my implementation is not working, but suspect that is has something to do with the creation of the C matrix with each recursive call. I would appreciate any explanation as to what I'm doing wrong and how I can fix it. Thank you! import numpy as np def strassen(A,B): n = A.shape[0] C = np.zeros((n*n), dtype=np.int).reshape(n,n) if n == 1: C[0][0] = A[0][0] * B[0][0] else: k = int(n/2) A11,A21,A12,A22 = A[:k,:k], A[k:, :k], A[:k, k:], A[k:, k:] B11,B21,B12,B22 = B[:k,:k], B[k:, :k], B[:k, k:], B[k:, k:] C11,C21,C12,C22 = C[:k,:k], C[k:, :k], C[:k, k:], C[k:, k:] S1 = B12 - B22 S2 = A11 + A12 S3 = A21 + A22 S4 = B21 - B11 S5 = A11 + A22 S6 = B11 + B22 S7 = A12 - A22 S8 = B21 + B22 S9 = A11 - A21 S10= B11 + B12 P1 = strassen(A11, S1) P2 = strassen(S2, B22) P3 = strassen(S3, B11) P4 = strassen(A22, S4) P5 = strassen(S5, S6) P6 = strassen(S7, S8) P7 = strassen(S9, S10) C11 = P5 + P4 - P2 + P6 C12 = P1 + P2 C21 = P3 + P4 C22 = P5 + P1 - P3 - P7 return C
tagged with: recursion
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81203408
has answer: http://stackoverflow.com/a/47126560
has comment: http://stackoverflow.com/comment/81208310
has title: Incorrect output matrix using Strassen's algorithm with numpy matrices
downvote count: 0
score: 1
answer count: 1

http://stackoverflow.com/a/47220918
score: 2
upvote count: 2
downvote count: 0
has body: A few pointers: You've declared a dict with {...}. Calling dict() over it is redundant. If your apply operation affects one column only, you should call apply on that series. invsf['Destn Branch'] = invsf['Destn Branch'].apply(covloc) This would allow you to get rid of the lambda. In your case, however, calling map would be more suitable. invsf['Destn Branch'] = invsf['Destn Branch'].map(maplist)
answers question: http://stackoverflow.com/q/47220777
type: Answer
has comment: http://stackoverflow.com/comment/81391723

http://stackoverflow.com/comment/113608103
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47088541
has text: Minor note, 40 is not DEBUG, 10 is. 40 is ERROR.

http://stackoverflow.com/comment/81159456
has text: Did you read the "XML vulnerabilities" link?
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47104413

http://stackoverflow.com/q/47097144
type: UnansweredQuestion
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: tesseract
has title: Calling exe from subprocess - xyv exe has stopped working
score: 1
tagged with: python
has body: I am periodically receiving the below error from Tesseract OCR, although I have received it from other executables as well. Is there a solution or way to better structure my popen calls to avoid this issue? I am imagining a subprocess.try_execute which may catch this type of third party issue? def run_tesseract(img_path,out_file='C:/temp/tesser_output'): image = Image.open(img_path) if len(image.split()) == 4: # In case we have 4 channels, lets discard the Alpha. # Kind of a hack, should fix in the future some time. r, g, b, a = image.split() image = Image.merge("RGB", (r, g, b)) image.save(img_path) command = '"C:/Program Files (x86)/Tesseract-OCR/tesseract.exe" '+img_path+' '+ out_file +' -l eng' # print command res = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) tmp = res.stdout.read() try: f = open(out_file + '.txt', 'rb') out = f.read().decode('utf-8').strip() except: traceback.print_exc() finally: f.close() return out
type: Question
tagged with: python-tesseract
answer count: 0

http://stackoverflow.com/a/47182399
has comment: http://stackoverflow.com/comment/81388113
has body: The community name does not exist in your context, the href link is therefore empty and you get redirects to the same page. You should probably be doing: Community Better to change the communities field to singular (i.e. community) since it's a foreign key field, so it's less confusing; one parishioner to one community (not multiple communities).
answers question: http://stackoverflow.com/q/47182268
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47182268
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47147250
has answer: http://stackoverflow.com/a/47148251
has comment: http://stackoverflow.com/comment/81246779
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81244847
tagged with: gmail-api
has comment: http://stackoverflow.com/comment/81248545
has body: so recently I have been trying to send emails using Python 3.6 through my college email account my_email@my_college.edu. This account is hosted on google, so I can use it with Gmail, Drive, etc. As such I thought it would be simple enough to write a simple program that would accomplish what I wanted, but nothing seems to be working. Here is the basic code that I found on practically every tutorial website: import smtplib TO = 'receiver_email' SUBJECT = 'TEST MAIL' TEXT = 'Here is a message from python.' # Gmail Sign In gmail_sender = 'my_email@my_college.edu' gmail_passwd = 'my_password' server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(gmail_sender, gmail_passwd) BODY = '\r\n'.join(['To: %s' % TO, 'From: %s' % gmail_sender, 'Subject: %s' % SUBJECT, '', TEXT]) try: server.sendmail(gmail_sender, [TO], BODY) print ('email sent') except: print ('error sending mail') server.quit() Whenever I run this, I get a "bad credentials" error. Specifically the error I get is this one: Traceback (most recent call last): File "D:\Coding Files\Projects in Progress\autoEmail.py", line 14, in &lt;module&gt; server.login(gmail_sender, gmail_passwd) File "C:\Users\Joe\AppData\Local\Programs\Python\Python36- 32\lib\smtplib.py", line 730, in login raise last_exception File "C:\Users\Joe\AppData\Local\Programs\Python\Python36- 32\lib\smtplib.py", line 721, in login initial_response_ok=initial_response_ok) File "C:\Users\Joe\AppData\Local\Programs\Python\Python36- 32\lib\smtplib.py", line 642, in auth raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/? p=BadCredentials g8sm9220621qtg.23 - gsmtp') I tried working with the Gmail API, and that was able to get me Gmail credentials and sign me in to a chrome page, but I couldn't seem to find a sufficient tutorial that I was able to understand using the Gmail API. Any help would be…
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/130692494
tagged with: python
score: -1
has title: Python 3, sending an email through a Gmail hosted college account
upvote count: 0
tagged with: email
downvote count: 1

http://stackoverflow.com/q/47147869
tagged with: aws-lambda
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/81249586
score: 0
has answer: http://stackoverflow.com/a/47152970
has body: I have been trying to POST bytes to an API Gateway endpoint, using Python, integrated with an AWS Lambda function. I receive a "Request too long" response message. It is a 3mb audio file. Could someone please point out what is the possible problem? import requests import json bytes = open('audio.mp3','rb').read() new_object = { 'audio' : bytes } response = requests.post(my_url,data=new_object) print(response.text) Thank you in advance.
answer count: 1
has title: Post mp3 bytes to API Gateway URL
tagged with: http

http://stackoverflow.com/q/47083799
has comment: http://stackoverflow.com/comment/81116912
has answer: http://stackoverflow.com/a/47083859
has answer: http://stackoverflow.com/a/47083932
has comment: http://stackoverflow.com/comment/81117071
favorite count: 0
type: Question
answer count: 8
has answer: http://stackoverflow.com/a/47083882
has answer: http://stackoverflow.com/a/47083943
has answer: http://stackoverflow.com/a/47083857
accepted answer: http://stackoverflow.com/a/47083857
has comment: http://stackoverflow.com/comment/81116900
has comment: http://stackoverflow.com/comment/81116902
has comment: http://stackoverflow.com/comment/81116977
has body: I have the following Python list: mylist = [a, b, c, d] where a,b,c,d are integers. I want to compare the 4 numbers and see if 3 of them are the same. I have tried converting the list to a set, but it didn't help me.
tagged with: python
has comment: http://stackoverflow.com/comment/81116891
has answer: http://stackoverflow.com/a/47083886
upvote count: 4
has comment: http://stackoverflow.com/comment/82293896
has comment: http://stackoverflow.com/comment/81116833
score: 2
type: AnsweredQuestion
tagged with: list
has title: Compare 4 numbers to find if 3 are the same
downvote count: 2
has answer: http://stackoverflow.com/a/47083924
has answer: http://stackoverflow.com/a/47083877
possible better answer: http://stackoverflow.com/a/47083877
has comment: http://stackoverflow.com/comment/81116946

http://stackoverflow.com/q/47121028
has body: I have a list and I want to understand slices of it. I take a slice [0:1] of it: &gt;&gt;&gt; l=[1,2,3,4] &gt;&gt;&gt; id(l[0]) 140079803522784 &gt;&gt;&gt; id(l[0:1][0]) 140079803522784 They are the same. But: &gt;&gt;&gt; l[0]=7 &gt;&gt;&gt; l [7, 2, 3, 4] &gt;&gt;&gt; l[0:1][0]=13 &gt;&gt;&gt; l [7, 2, 3, 4] So the slice's 0-element is the same as the list's 0-element, but when I change it in the slice, it is not changed in the list. Why not?
duplicate of: http://stackoverflow.com/q/19068707
score: 0
has comment: http://stackoverflow.com/comment/81191771
has comment: http://stackoverflow.com/comment/81191674
has comment: http://stackoverflow.com/comment/81191731
has title: Trying to understand slices of lists
tagged with: python
has comment: http://stackoverflow.com/comment/81191639
has comment: http://stackoverflow.com/comment/81191647
accepted answer: http://stackoverflow.com/a/47121071
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81194575
has answer: http://stackoverflow.com/a/47121071
linked to: http://stackoverflow.com/q/19068707
answer count: 1
type: Question

http://stackoverflow.com/a/47170894
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81291498
has body: Using this answer as a guide, the solution is to add default values to variables in the lambda callback function. In your case it would look something like this: def updateButton(row, column): buttons[row][column].config(text="1") for row in range(len(buttons)): for col in range(len(buttons[row])): buttons[row][col].config(command=lambda row=row, col=col: updateButton(row, col))
accepted answer of: http://stackoverflow.com/q/47170193
type: Answer
answers question: http://stackoverflow.com/q/47170193
downvote count: 0
score: 1

http://stackoverflow.com/q/47106830
tagged with: keras
downvote count: 1
has title: Why does get_weights return an empty list?
has comment: http://stackoverflow.com/comment/99877465
has answer: http://stackoverflow.com/a/65562153
tagged with: python
upvote count: 10
tagged with: tensorflow
favorite count: 0
type: Question
has body: I am teaching myself data science and something peculiar has caught my eyes. In a sample DNN tutorial I was working on, I found that the Keras layer.get_weights() function returned empty list for my variables. I've successfully cross validated and used model.fit() function to compute the recall scores. But as I'm trying to use the get_weights() function on my categorical variables, it returns empty weights for all. I'm not looking for a solution to code but I am just curious about what would possibly cause this. I've read through the Keras API but it did not provide me with the information I was hoping to see. What could cause the get_weights() function in Keras to return empty list except for of course the weights not being set?
answer count: 2
score: 9
has answer: http://stackoverflow.com/a/56950297
type: UnansweredQuestion
tagged with: machine-learning

http://stackoverflow.com/comment/81157464
score: 0
has text: @bphi: user2357112 is right, I learned that the hard way. :/
comment on: http://stackoverflow.com/q/47103306
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81102190
score: 0
has text: You probably won't find an exact solution for *your code*. However, lots of documentation exists for reading a CSV, making HTTP requests, and parsing HTML in python. Focus on that, not the specific ways your code works
type: QuestionComment
comment on: http://stackoverflow.com/q/47076883
type: Comment

http://stackoverflow.com/comment/81180462
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47115281
has text: actually it isn't an error, but it looks bad: [screenshot](https://imgur.com/a/7bzKw)
score: 0

http://stackoverflow.com/comment/81363995
has text: Yes, it can be done, but _why_ do you want the code in 2 lines? Readability is important. And why are you using Python 2?
comment on: http://stackoverflow.com/q/47207328
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47248858
accepted answer of: http://stackoverflow.com/q/47215072
has body: Perhaps a memory leak somewhere that slowly uses up systems memory, once full everything becomes very slow as swap is used for memory allocation and timeouts occur. However as Andrew says this can't be a problem with the python script or it would be fixed by restarting it. Monitor system memory and go from there.
answers question: http://stackoverflow.com/q/47215072
type: Answer
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/47101337
linked to: http://stackoverflow.com/q/19662906
score: 1
has comment: http://stackoverflow.com/comment/81154384
has comment: http://stackoverflow.com/comment/81184332
has title: Python: why would the recv() method of a Pipe block when it is called inside a nested function?
has comment: http://stackoverflow.com/comment/81154955
has comment: http://stackoverflow.com/comment/81207914
has body: I have a pair of functions defined, where the second is called inside the first, and the second has the associated pipe.recv() methods for each pipe.send() method in the first. However the first recv() method appears to be blocking despite information being in the pipe. Am I calling these in the wrong order? I don't quite understand what the problem is or why the recv() method would hang in this case. I know it's not a memory issue because the arrays involved are relatively small but I can't think of what the issue could be def plots(): #build axes and plots for i in range(num_sections): temp_arr = pipes_hist[1][0].recv() #the KeyboardInterrupt traceback message points here arr_section += temp_arr #in my actual code arr_section is predefined with the proper size #etc etc def main_function(section_number): #lots of code goes here pipes_hist[section_number][1].send(array_section) pipes_hist[section_number][1].close() #etc etc plots() #build list of pipes for each section pipes_hist_send = [[] for i in range(num_sections)] pipes_hist_recv = [[] for i in range(num_sections)] pipes_hist = list(zip(pipes_hist_recv,pipes_hist_send)) for i in range(num_sections): pipes_hist[i] = list(pipes_hist[i]) for i in range(num_sections): #these two loops can probably be combined pipes_hist[i][0],pipes_hist[i][1] = Pipe() #begin multiprocessing if __name__ == '__main__': pool = mp.Pool(num_sections) args = np.arange(num_sections) pool.map(main_function, args, chunksize=1) pool.close() pool.join() Edit: The hanging also happens when I change map to map_async and call the plots function after the subsequent pool.map_async instead of inside main_function
favorite count: 0
tagged with: multiprocessing
type: Question
linked to: http://stackoverflow.com/q/6457091
linked to: http://stackoverflow.com/q/10442870
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81159234
has comment: http://stackoverflow.com/comment/81154288
answer count: 0
has comment: http://stackoverflow.com/comment/81154119
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81318948
has comment: http://stackoverflow.com/comment/81154552
linked to: http://stackoverflow.com/q/18114285
has comment: http://stackoverflow.com/comment/81153772
has comment: http://stackoverflow.com/comment/81178788
has comment: http://stackoverflow.com/comment/81155297
has comment: http://stackoverflow.com/comment/81153597

http://stackoverflow.com/q/47200033
score: 53
has body: I can create beatiful scatter plot with seaborns regplot, obtain the right level of transparency through the scatter_kws as in sns.regplot(x='logAssets', y='logLTIFR', lowess=True, data=df, scatter_kws={'alpha':0.15}, line_kws={'color': 'red'}) and obtain this: Is there an option in a seaborn pairplot to tweak transparency?
type: AnsweredQuestion
answer count: 2
upvote count: 53
has answer: http://stackoverflow.com/a/58825873
downvote count: 0
accepted answer: http://stackoverflow.com/a/47200170
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47200170
possible better answer: http://stackoverflow.com/a/58825873
tagged with: seaborn
tagged with: matplotlib
linked to: http://stackoverflow.com/q/49930250
tagged with: python
has title: How to adjust transparency (alpha) in seaborn pairplot?

http://stackoverflow.com/comment/81326578
has text: @AdamSmith yes... it puts /n between.. you are right, I like more your way
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47188632
type: Comment

http://stackoverflow.com/a/47117406
type: Answer
has body: i found the dirty solution for my case but it not crossplatform(linux have difference behavior) # -*- coding: utf-8 -*- import tkinter from tkinter import ttk import sys,pickle,webbrowser def on_mousewheel(event): try: print("e ",event) shift = (event.state &amp; 0x1) != 0 canvas=event.widget scroll = -1 if event.delta &gt; 0 else 1 if shift: canvas.xview_scroll(scroll, "units") else: canvas.yview_scroll(scroll, "units") except:pass def cocoa_click(event): webbrowser.open("http://stts.pythonanywhere.com/") mainframe = tkinter.Tk() mainframe_width = (mainframe.winfo_screenwidth() / 2 - 200) mainframe_heigth = (mainframe.winfo_screenheight() / 2 - 250) mainframe.geometry("%dx%d+%d+%d" % (1000, 600, mainframe_width, mainframe_heigth)) mainframe.title('DAS progress 132') mainframe.resizable(False,True) n_book = ttk.Notebook(mainframe) n_book.pack(fill='both', expand='yes') n_book.pressed_index = None x_name=["tabnote1","tabnote2","tabnote3","tabnote4"] x_container=[]; x_canvas=[]; x_scroll=[]; x_frame=[] cvsw,cvsh=960,400; sreg=(0,0,1000,1320) for i in range(4): x_container.append(tkinter.Frame(n_book)) x_container[i].pack(fill=tkinter.BOTH, expand=True) n_book.add(x_container[i], text=x_name[i]) # add container to note book x_canvas.append(tkinter.Canvas(x_container[i], width=cvsw, height=cvsh)) # add canvas to container x_scroll.append(tkinter.Scrollbar(x_container[i], command=x_canvas[i].yview)) # add scroll to container x_canvas[i].config(yscrollcommand=x_scroll[i].set, scrollregion=sreg) x_canvas[i].pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=True) x_scroll[i].config(width=240) x_scroll[i].pack(side=tkinter.RIGHT, fill=tkinter.Y, expand=True) x_canvas[i].bind_all("&lt;MouseWheel&gt;", on_mousewheel) # index always 3 cocoa = ttk.Button(mainframe,text="(: cocoa") # add button to mainframe - worked cocoa.place(height=40,width=600,relx=0.4,rely=0) cocoa.bind("&lt;Button-1&gt;",cocoa_click) mainframe.mainloop()
score: 0
answers question: http://stackoverflow.com/q/47109480

http://stackoverflow.com/comment/81366110
has text: It ***does not*** modify the Python installation that came with macOS. What it does is it adds the system's `site-packages` folder to the list of searched directories by your homebrew's python installation. Your new python installation will point to the system's package directory.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47208280
score: 0

http://stackoverflow.com/a/47087214
score: 1
accepted answer of: http://stackoverflow.com/q/47087022
type: Answer
has comment: http://stackoverflow.com/comment/81124384
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81124523
has body: def PageUp(self): self.channels_Index = max(self.channels_Index -7), 0) channels_list = self.channel[self.channels_Index):min(len(self.channel), self.channels_Index + 7)]
answers question: http://stackoverflow.com/q/47087022

python-2.7
tags question: http://stackoverflow.com/q/47215370
tags question: http://stackoverflow.com/q/47089645
tags question: http://stackoverflow.com/q/47171562
tags question: http://stackoverflow.com/q/47070764
tags question: http://stackoverflow.com/q/47187642
tags question: http://stackoverflow.com/q/47208863
tags question: http://stackoverflow.com/q/47112745
tags question: http://stackoverflow.com/q/47158741
tags question: http://stackoverflow.com/q/47143182
tags question: http://stackoverflow.com/q/47160934
tags question: http://stackoverflow.com/q/47124100
tags question: http://stackoverflow.com/q/47137662
tags question: http://stackoverflow.com/q/47112878
tags question: http://stackoverflow.com/q/47116225
tags question: http://stackoverflow.com/q/47223184
tags question: http://stackoverflow.com/q/47100474
tags question: http://stackoverflow.com/q/47065332
tags question: http://stackoverflow.com/q/47107363
tags question: http://stackoverflow.com/q/47077349
tags question: http://stackoverflow.com/q/47222188
tags question: http://stackoverflow.com/q/47126567
tags question: http://stackoverflow.com/q/47128113
tags question: http://stackoverflow.com/q/47198848
tags question: http://stackoverflow.com/q/47221357
tags question: http://stackoverflow.com/q/47121163
tags question: http://stackoverflow.com/q/47137765
tags question: http://stackoverflow.com/q/47169858
tags question: http://stackoverflow.com/q/47103242
tags question: http://stackoverflow.com/q/47120465
tags question: http://stackoverflow.com/q/47192370
tags question: http://stackoverflow.com/q/47202751
tags question: http://stackoverflow.com/q/47221859
tags question: http://stackoverflow.com/q/47120360
tags question: http://stackoverflow.com/q/47068504
tags question: http://stackoverflow.com/q/47139180
tags question: http://stackoverflow.com/q/47075479
type: Tag
tags question: http://stackoverflow.com/q/47174806
tags question: http://stackoverflow.com/q/47172349
tags question: http://stackoverflow.com/q/47074214
tags question: http://stackoverflow.com/q/47200088
tags question: http://stackoverflow.com/q/47212518
tags question: http://stackoverflow.com/q/47105737
tags question: http://stackoverflow.com/q/47105208
tags question: http://stackoverflow.com/q/47199348
tags question: http://stackoverflow.com/q/47221651
tags question: http://stackoverflow.com/q/47120539
tags question: http://stackoverflow.com/q/47102397
tags question: http://stackoverflow.com/q/47087919
tags question: http://stackoverflow.com/q/47099307
tags question: http://stackoverflow.com/q/47218571
tags question: http://stackoverflow.com/q/47114950
tags question: http://stackoverflow.com/q/47212747
tags question: http://stackoverflow.com/q/47116602
tags question: http://stackoverflow.com/q/47082636
tags question: http://stackoverflow.com/q/47203069
tags question: http://stackoverflow.com/q/47145519
tags question: http://stackoverflow.com/q/47152742
tags question: http://stackoverflow.com/q/47085918
tags question: http://stackoverflow.com/q/47166447
tags question: http://stackoverflow.com/q/47112475
tags question: http://stackoverflow.com/q/47177660
tags question: http://stackoverflow.com/q/47163365
tags question: http://stackoverflow.com/q/47117769
tags question: http://stackoverflow.com/q/47212197
tags question: http://stackoverflow.com/q/47158071
tags question: http://stackoverflow.com/q/47076402
tags question: http://stackoverflow.com/q/47217105
tags question: http://stackoverflow.com/q/47136222
tags question: http://stackoverflow.com/q/47175020
tags question: http://stackoverflow.com/q/47202802
tags question: http://stackoverflow.com/q/47111684
tags question: http://stackoverflow.com/q/47106444
tags question: http://stackoverflow.com/q/47172110
tags question: http://stackoverflow.com/q/47216476
tags question: http://stackoverflow.com/q/47213631
tags question: http://stackoverflow.com/q/47144215
tags question: http://stackoverflow.com/q/47191477
tags question: http://stackoverflow.com/q/47117833
tags question: http://stackoverflow.com/q/47147087

http://stackoverflow.com/comment/81106416
score: 0
comment on: http://stackoverflow.com/q/47077719
type: Comment
type: QuestionComment
has text: @RomanPerekhrest: starting the thread is not the problem (via the provided code). What I do not understand is what exactly is the websocket object I can use in the threads (the `an_existing_websocket` passed to the thread)

http://stackoverflow.com/q/47203167
has answer: http://stackoverflow.com/a/47203191
has answer: http://stackoverflow.com/a/47203781
type: Question
answer count: 2
tagged with: nested-lists
upvote count: 3
accepted answer: http://stackoverflow.com/a/47203191
downvote count: 0
possible better answer: http://stackoverflow.com/a/47203781
favorite count: 0
type: AnsweredQuestion
score: 3
has body: I have a nested list and char variable: colors = [ ("r", [255,0,0]), ("g", [0,255,0]), ("b", [0,0,255]), ("y", [255,0,0]), ("p", [255,0,255]) ] char_to_check="b" How can I (in the most efficient way) check: 1. if char_to_check exists in nested list colors index (r, g, b, etc..) and 2. if exists (char_to_check) provide values for this char from colors (for example 255,0,0) else return error (any kind)
has title: Python - nested lists - efective checking
has comment: http://stackoverflow.com/comment/81354684
tagged with: python

http://stackoverflow.com/q/47167678
has answer: http://stackoverflow.com/a/47167731
type: UnansweredQuestion
has body: I have a two numpy 1-D arrays: a and b. a is of shape (10,) b is of shape (16,). I want to make a have the shape (10,1) and b to have the shape (16,1) to matrix multiply them as so: np.matmul(a, b.T). If successful, this should result in a (10,16) 2-D array. Does anyone know how to do this?
has comment: http://stackoverflow.com/comment/81285289
type: Question
score: 0
has answer: http://stackoverflow.com/a/47167716
tagged with: python
has title: Matrix multiply two 1-D numpy arrays
has answer: http://stackoverflow.com/a/47167838
tagged with: numpy
answer count: 3

http://stackoverflow.com/comment/81405445
type: Comment
has text: I try but I have to build the paths programmatically sometimes with drive letter and sometimes without. Thanks.
comment on: http://stackoverflow.com/a/47208591
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81166388
has text: python version is 3.6(Anaconda version is 4.3.1) and yes it is a windows 8 operating system.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47107009

http://stackoverflow.com/a/47092171
answers question: http://stackoverflow.com/q/47091810
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/81133906
has body: Try a different approach: In [9]: df['A'].apply(list) * 1 Out[9]: 0 [a] 1 [b] Name: A, dtype: object In [10]: df['A'].apply(list) * 2 Out[10]: 0 [a, a] 1 [b, b] Name: A, dtype: object In [11]: df['A'].apply(list) * 3 Out[11]: 0 [a, a, a] 1 [b, b, b] Name: A, dtype: object

http://stackoverflow.com/comment/81080751
type: QuestionComment
has text: actually, https://docs.python.org/3.6/reference/compound_stmts.html#with
comment on: http://stackoverflow.com/q/47066252
type: Comment
score: 1

http://stackoverflow.com/comment/133495109
type: AnswerComment
has text: This doesn't answer OP's question.
score: 0
comment on: http://stackoverflow.com/a/69052960
type: Comment

http://stackoverflow.com/comment/81188997
has text: @KaushikNP I mentioned in that case that OP should use a dict of lists, or some nested structure.
type: Comment
comment on: http://stackoverflow.com/a/47119649
score: 2
type: AnswerComment

http://stackoverflow.com/comment/81326149
score: 0
comment on: http://stackoverflow.com/q/47187410
type: Comment
type: QuestionComment
has text: Hey! How do you use that `memory_profiler` tool? I really liked it!

http://stackoverflow.com/comment/81149962
has text: @Jared Goguen Yes, that would be much cleaner. Thank you
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47097030
type: Comment

http://stackoverflow.com/a/47134303
has comment: http://stackoverflow.com/comment/81219039
answers question: http://stackoverflow.com/q/47134132
score: 0
has comment: http://stackoverflow.com/comment/81218487
has comment: http://stackoverflow.com/comment/81219376
has comment: http://stackoverflow.com/comment/81219101
type: Answer
has body: It seems to be a dictionary, this would be: new2[0]['value']

http://stackoverflow.com/q/47161850
linked to: http://stackoverflow.com/q/33491911
has answer: http://stackoverflow.com/a/59381921
tagged with: python
type: UnansweredQuestion
has body: I'm on Windows 10 running python 3.5.4 through Anaconda with pyopencl 2017.2 from conda-forge, installed through Anaconda. My system is an i5 4670K with an R9 290 running driver version 17.11.1 with OpenCL Version 23.20.788.0. When trying to import the pyopencl module I experience the following error &gt;&gt;&gt; import pyopencl as cl Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "[my home folder]\Anaconda3\lib\site-packages\pyopencl\__init__.py", line 37, in &lt;module&gt; import pyopencl.cffi_cl as _cl File "[my home folder]\Anaconda3\lib\site-packages\pyopencl\cffi_cl.py", line 39, in &lt;module&gt; from pyopencl._cffi import ffi as _ffi ImportError: DLL load failed: The specified module could not be found. The error appears to occur when loading _cffi.pyd. This error has similarities with problems shown in previous threads: Python pyopencl Import Error cffi load failure when trying to import PyOpenCL pyopencl import error cffi.so undefined symbol However, in spite of the installation completing (seemingly) without error, me installing the OCL SDK:s from both AMD and Intel the problem persists. I also updated my grahics card drivers. I tried using Dependency Walker to check dependencies of _cffi.pyd, as described in the following thread: Python pyopencl DLL load failed even with latest drivers This did turn up a lot of circular dependencies and missing dependencies under opencl.dll with names beginning in API-MS-WIN and EXT-MS-WIN. The dependency errors persisted when renaming the opencl.dll in /System32 and using the one in \Anaconda3\Library\bin instead. Doing a bit of searching I found this thread: Dependency Walker: missing dlls which basically says the missing dependencies are nothing to worry about.
linked to: http://stackoverflow.com/q/36240215
has answer: http://stackoverflow.com/a/76459343
score: 4
upvote count: 4
linked to: http://stackoverflow.com/q/41096313
has title: pyopencl Import Error
answer count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/43077427
tagged with: pyopencl
favorite count: 0
linked to: http://stackoverflow.com/q/45527726
type: Question
tagged with: dll
tagged with: opencl
has answer: http://stackoverflow.com/a/53821714

http://stackoverflow.com/a/47110609
answers question: http://stackoverflow.com/q/47110280
has comment: http://stackoverflow.com/comment/81185507
type: Answer
score: 0
has body: A couple of points : Keep the required imports only. Remove the unwanted imports to keep things simpler. Need to be careful with extra spaces as Python is sensitive to spaces and indents. To mention OS paths either use escaped back slashes (\\) or use single front slashes (/) along with the raw (r) switch. Here is your own working code with some minor tweaks: from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities import time cap = DesiredCapabilities().INTERNETEXPLORER cap['ignoreProtectedModeSettings'] = True browser = webdriver.Ie(capabilities=cap, executable_path="C:\\Utility\\BrowserDrivers\\IEDriverServer.exe") browser.get('https://www.naver.com/') browser.set_window_size(533,533) time.sleep(10) browser.quit() Update As you are seeing the error as WebDriverException: Message: Unexpected error launching Internet Explorer. Protected Mode set, follow the steps below and execute your tests : On IE 7 or higher on Windows Vista or Windows 7, you must set the Protected Mode settings for each zone to be the same value. The value can be on or off, as long as it is the same for every zone. To set the Protected Mode settings, choose "Internet Options..." from the Tools menu, and click on the Security tab. For each zone, there will be a check box at the bottom of the tab labeled "Enable Protected Mode". Additionally, "Enhanced Protected Mode" must be disabled for IE 10 and higher. This option is found in the Advanced tab of the Internet Options dialog. The browser zoom level must be set to 100% so that the native mouse events can be set to the correct coordinates. For Windows 10, you also need to set "Change the size of text, apps, and other items" to 100% in display settings.

http://stackoverflow.com/q/47198497
tagged with: google-maps
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47239376
has body: In my Django project, I let users to mark in which city they were recently. I use for this Google Places API - autocomplete with map. I have multiple use cases which I can't figure out to work with Google Places API T&amp;C and this is one of them: There is a filter of users. Each user have chosen their last visited place (so I can store place_id). When user filtered 100 users, they are showed one by one by their cards in results. The card should contain the user's last visited place. So I have to show 100 cards with 100 places (cities). How to do that if I have only place_id's? Should I send 100 detail requests to Google Places API to get name of each city? def user_filter(request): filtered_users = .... for user in filtered_users: api_result = request.get('https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&amp;key=MY_API_KEY') recent_city_name = parse_from_result(api_result) .... return render(request,....) Although this should teoretically work, it is a big overkill - time consuming and API requests consuming. Is there a better way to do that? I didn't find any bulk request option.
accepted answer: http://stackoverflow.com/a/47239376
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
has title: How to get multiple places names in Google Places API?
answer count: 1
favorite count: 0
type: Question
tagged with: google-places-api

http://stackoverflow.com/a/70940536
downvote count: 0
upvote count: 1
has body: My approach from datetime import datetime import calendar def get_week_numbers_in_month(year, month) -&gt; list: ending_day = calendar.monthrange(year, month)[1] # get the last day of month initial_week = datetime(year, month, 1).isocalendar()[1] ending_week = datetime(year, month, ending_day).isocalendar()[1] res = list(range(initial_week, ending_week + 1)) if not res: week_num = 52 if initial_week != 53 else 53 res = list(range(initial_week, week_num + 1)) + list(range(1, ending_week + 1)) return res Output &gt;&gt;&gt; print(get_week_numbers_in_month(2021, 1)) [52, 1, 2, 3, 4] &gt;&gt;&gt;
answers question: http://stackoverflow.com/q/47084509
type: Answer
score: 1

http://stackoverflow.com/a/47339150
score: 0
has body: You can use pytest package for unit testing. It is very simple and easy to use. @pytest.mark.parametrize() decorator can be used to achieve that functionality. An example for parametrized test cases is as follows: import pytest class SampleTesting(object): data_for_test = [ ('{inputdata1:value1}','output1'), ('{inputdata1:value2}','output2') ] @pytest.mark.parametrized('input_data, expected_output', data_for_test) def test_sample_function(self, input_data, expected_output): response = function_to_be_tested(input_data) assert response == expected_output You can read more about this decorator in the docs' You can also use the @pytest.fixture() decorator to setup the test function.
answers question: http://stackoverflow.com/q/47215825
type: Answer

http://stackoverflow.com/a/47080936
answers question: http://stackoverflow.com/q/47080315
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: Do you mean you want to filter rows where the value from a string column starts with some character? &gt;&gt;&gt; df foobar 0 0foo 1 1foo 2 2foo 3 3foo 4 4foo 5 5foo 6 0bar 7 1bar 8 2bar 9 3bar 10 4bar 11 5bar &gt;&gt;&gt; df.loc[(df.foobar.str.startswith('2'))] foobar 2 2foo 8 2bar Then it is: &gt;&gt;&gt; begining_with_2 = df.loc[(df.foobar.str.startswith('2'))] &gt;&gt;&gt; for i, row in begining_with_2.iterrows(): ... print(row.foobar) 2foo 2bar

http://stackoverflow.com/q/47165894
has title: PySNMP returns TypeError with Anaconda install even with example code
accepted answer: http://stackoverflow.com/a/47167620
has answer: http://stackoverflow.com/a/47167620
tagged with: python
tagged with: pysnmp
type: AnsweredQuestion
score: 0
answer count: 1
has body: I have installed Anaconda2.5 and it gives me Python 2.7. I have installed the latest PySNMP. Initially, I attempted to run the Python script from another server using Python 2.6 on this one and got a TypeError (see below). I thought it must be because of my Python version, maybe something changed with PySNMP, but when I ran their example code (see below), it returned the exact same error. I am baffled as to why their example code would return an error and can only suspect Anaconda installing PySNMP would be at fault? This is the example code: #!/root/anaconda2/python from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('IF-MIB', 'ifDescr')), ObjectType(ObjectIdentity('IF-MIB', 'ifType')), ObjectType(ObjectIdentity('IF-MIB', 'ifMtu')), ObjectType(ObjectIdentity('IF-MIB', 'ifSpeed')), ObjectType(ObjectIdentity('IF-MIB', 'ifPhysAddress')), ObjectType(ObjectIdentity('IF-MIB', 'ifType')), lexicographicMode=False): if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1][0] or '?')) break else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) This is my error: Traceback (most recent call last): File "get_aqx_intersite_bw.py", line 8, in varBinds) in nextCmd(SnmpEngine(), File "/root/anaconda2/lib/python2.7/site-packages/pysnmp/entity/engine.py", line 61, in __init__ self.msgAndPduDsp = MsgAndPduDispatcher() File "/root/anaconda2/lib/python2.7/site-packages/pysnmp/proto/rfc3412.py", line 29, in __init__ 'SNMP-TARGET-MIB', 'SNMP-USER-BASED-SM-MIB' File "/root/anaconda2/lib/python2.7/site-packages/pysnmp/smi/builder.py", line 337, in loadModules self.loadModule(modName, **userCtx) File "/root/anaconda2/lib/python2.7/site-packages/pysnmp/smi/builder.py", line 306, in loa…
type: Question

http://stackoverflow.com/a/47081911
type: Answer
has comment: http://stackoverflow.com/comment/81113411
answers question: http://stackoverflow.com/q/47081658
score: 0
has body: You need to create an array with dtype=object, so that numpy knows to treat each entry as a Python object rather than treating the entire nested list as a single array. For example: import numpy as np x = np.empty((5, 10)) y = np.empty((3, 10)) z = np.empty((6, 10)) test = np.array([x, y, z], dtype=object) test[0].shape # [5, 10]
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47081658

http://stackoverflow.com/q/47176083
tagged with: multiprocessing
tagged with: apache-kafka
tagged with: multithreading
has body: I am using Python (2.7) multiprocessing to push data to Kafka queue using kafka-python (1.3.5) KafkaProducer. from kafka import KafkaProducer import multiprocessing # other imports class TestClass(object): def __init__(self, producer): self.kafka_producer = producer def main(self, conf, nthreads): try: for i in range(nthreads): logger.info("Starting process number = %d " % (i + 1)) p = Process(target=self.do_some_task, args=(conf, 2)) p.start() processes.append(p) for p in processes: logger.info("Joining process") p.join() except Exception, ex: logger.error("Exception occurred : %s" % str(ex)) def do_some_task(conf, retry): # some task happening self.record(arg1, arg2) # pushing to kafka def record(self, arg1, arg2) message = json.dumps({"a": "arg1", "b": "arg2"}) self.kafka_producer.send(KAFKA_TOPIC, message) if __name__ == '__main__': kafka_producer = KafkaProducer( bootstrap_servers=KAFKA_BOOTSTRAP_SERVERS, request_timeout_ms=60000, retries=2) obj = TestClass(kafka_producer) try: parser = argparse.ArgumentParser(description='Description') parser.add_argument('-threads', type=int, default=1) # 20 threads parser.add_argument('-debug', type=int, default=0) args = parser.parse_args() me = SingleInstance(args.src) TestClass.main(CONF[args.src], args.threads) 20 threads are spawned inside which write to kafka. I saw the logs and found out that the process waits for the message to be written in kafka, but eventually it moves on without writing to Kafka. There are no exception raised. I tried running the same code without threads from python command line and everything worked as expected. What can be the issue.
tagged with: python
has title: Data doesn't get pushed to Kafka Queue using python multiprocessing
accepted answer: http://stackoverflow.com/a/47176924
has answer: http://stackoverflow.com/a/47176924
tagged with: kafka-python
type: AnsweredQuestion
score: 2
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/a/47081795
upvote count: 3
has body: This is propably the solution you are looking for: dict_1 = {'o': [Partner(state='Ohio', name='hi',logo='pic.png',link='http'), Partner(state='Ohio', name='ayo', logo='int.png',)], 'a':[Partner(state='alaska', name='hi', logo='pic.png', link='http'), Partner(state='arkansas', name='ayo', logo='int.png',)]} dict_2 = {'Ohio': [Partner(state='Ohio',name='shmo',logo='123.png',link=''), Partner(state='Ohio', name='joe', logo='png', link='')], 'Alaska': [Partner(state='Alaska', name='yo',logo='321.png', link='')], 'arkansas': [Partner(state='arkansas',name='yo',logo='321.png', link='')]} foo = {} for key_1,value_1 in dict_1.items(): for key_2,value_2 in dict_2.items(): if key_2.lower().startswith(key_1): if key_1 not in foo: foo[key_1] = [{key_2:value_2}] elif key_1 in foo: foo.get(key_1).append({key_2:value_2})
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47080956
score: 3
type: Answer
answers question: http://stackoverflow.com/q/47080956

http://stackoverflow.com/a/47117902
has comment: http://stackoverflow.com/comment/81185917
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/47117867
answers question: http://stackoverflow.com/q/47117867
has body: It doesn't work because self is a Number, so self + other calls self.__add__(other), which does self + other, which calls... The fix is to turn self into something that isn't a Number before adding. return int(self) + other
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/81185922
type: AcceptedAnswer

http://stackoverflow.com/comment/81108303
has text: I would recommend still doing a `pip install` on the cloned directory
type: Comment
comment on: http://stackoverflow.com/a/47079660
type: AnswerComment
score: 1

http://stackoverflow.com/comment/81123387
comment on: http://stackoverflow.com/q/47085527
has text: Is there any difference between the `U1A6RlJEQ1...` string from updated `selectedHits` and the version when you eliminate the `b`-prefix by hand? Try to `print(repr(...))` for both of these strings
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81184023
type: Comment
has text: Are you declaring it as global before using it? As in [this](http://www.geeksforgeeks.org/global-local-variables-python/) example (make sure to read the whole thing)?
type: AnswerComment
comment on: http://stackoverflow.com/a/47116874
score: 0

matrix
tags question: http://stackoverflow.com/q/47148119
tags question: http://stackoverflow.com/q/47121855
tag name: matrix
tags question: http://stackoverflow.com/q/47091732
tags question: http://stackoverflow.com/q/47196406
tags question: http://stackoverflow.com/q/47146800
tags question: http://stackoverflow.com/q/47117625
tags question: http://stackoverflow.com/q/47114208
tags question: http://stackoverflow.com/q/47213267
tags question: http://stackoverflow.com/q/47110284
tags question: http://stackoverflow.com/q/47153226
tags question: http://stackoverflow.com/q/47129329
tags question: http://stackoverflow.com/q/47214979
tags question: http://stackoverflow.com/q/47139839
tags question: http://stackoverflow.com/q/47100230
tags question: http://stackoverflow.com/q/47113299
tags question: http://stackoverflow.com/q/47202016
tags question: http://stackoverflow.com/q/47112826
tags question: http://stackoverflow.com/q/47124845
tags question: http://stackoverflow.com/q/47184099
tags question: http://stackoverflow.com/q/47117353
tags question: http://stackoverflow.com/q/47121953
tags question: http://stackoverflow.com/q/47207243
type: Tag
tags question: http://stackoverflow.com/q/47177795
tags question: http://stackoverflow.com/q/47089802

http://stackoverflow.com/a/47186132
accepted answer of: http://stackoverflow.com/q/47186040
score: 5
answers question: http://stackoverflow.com/q/47186040
upvote count: 5
type: Answer
has body: Using set_index and unstack, df.set_index(['start', 'end', 'id']).type.unstack().reset_index() id start end XXX YYY 0 2017-01-01 2017-01-31 car truck 1 2017-02-01 2017-03-03 car truck 2 2017-03-04 2017-04-03 car truck 3 2017-04-04 2017-05-04 car truck
has comment: http://stackoverflow.com/comment/81322358
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47131458
upvote count: 1
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/47131652
has answer: http://stackoverflow.com/a/47131652
type: Question
type: AnsweredQuestion
has body: I'm new to python. Can anyone help me to understand the call by reference in python. #include &lt;stdio.h&gt; #include &lt;conio.h&gt; #include &lt;malloc.h&gt; void rd(float *a, int *n) { int i; for (i=1;i&lt;= *n;i++) { printf("Enter element %d: ", i); scanf("%f", &amp;a[i]); } } float sum(float *a, int *n) { int i; float s=0; for (i=1 ; i &lt;= *n ; i++) s = s + a[i]; return s; } int main(void) { int size; float *x, g; printf("Give size of array: "); scanf("%d", &amp;size); x = (float *)malloc(size*sizeof(float)); // dynamic memory allocation printf("\n"); rd(x, &amp;size); // passing the addresses g = sum(x, &amp;size); // passing the addresses printf("\nSum of elements = %f\n", g); printf("\nDONE ! Hit any key ..."); getch(); return 0; } This is C example i trying to solve in python. Any help would be appreciated.
has title: Python : Call by Reference
score: -1
favorite count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/81212530
has comment: http://stackoverflow.com/comment/81212369

http://stackoverflow.com/q/47207389
has comment: http://stackoverflow.com/comment/81363834
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81364485
tagged with: plpython
tagged with: python
has answer: http://stackoverflow.com/a/47207866
has title: PostgreSQL: Set-returning function with single value in plpython3u
accepted answer: http://stackoverflow.com/a/47207866
type: AnsweredQuestion
tagged with: postgresql
has comment: http://stackoverflow.com/comment/81364327
has body: I want to write a plpython3u function in PostgreSQL that returns a set of texts. I've stumbled across a conundrum that looks strange to me. As per the manual, I can do the following: drop schema if exists X cascade; create schema X; create type X.greeting AS ( who text ); create function X.greet( how text ) returns setof X.greeting language plpython3u as $$ for who in [ 'World', 'PostgreSQL', 'PL/Python' ]: yield ( who, ) $$; This is a Python function that returns a set of rows with single texts; so much works, and I do get the expected output: select X.greet( 'helo' ); greet -------------- (World) (PostgreSQL) (PL/Python) (3 rows) select * from X.greet( 'helo' ); who ------------ World PostgreSQL PL/Python (3 rows) So far so good. However, I do not want to write a table definition for the purpose, I'd like to use setof record instead, like in this example (which happens to use integers, but still): create function X.pairs_of_integers_A( out integer, out integer ) returns setof record language plpython3u as $$ return [ ( 12, 24, ), ( 36, 48, ), ( 60, 72, ) ] $$; create function X.pairs_of_integers_B( out integer, out integer ) returns setof record language plpython3u as $$ for pair in [ ( 12, 24, ), ( 36, 48, ), ( 60, 72, ) ]: yield pair $$; select * from X.pairs_of_integers_A(); select * from X.pairs_of_integers_B(); column1 | column2 ---------+--------- 12 | 24 36 | 48 60 | 72 (3 rows) column1 | column2 ---------+--------- 12 | 24 36 | 48 60 | 72 (3 rows) Now we come to the interesting part. Generalizing from the above, one or more formulations of the below should be correct: to return a set of single values, either return a list of Python tuples, a list of Python numbers, or else iterate either over tuples with single values or over single values: create function X.single_integers_A( out integer ) returns setof record language plpython3u as $$ return [ ( 12, ), ( 36, ), ( 60, ), ] $$; create function X.single_integers_B( out integer ) returns setof record languag…
score: 1

http://stackoverflow.com/comment/113895210
comment on: http://stackoverflow.com/a/64410841
type: Comment
type: AnswerComment
has text: In the comments above OP said the size of the file is 1.2 MB. I find it hard to believe that's the issue
score: 0

http://stackoverflow.com/comment/81264805
has text: Hmmm, it is not possible this way :(
comment on: http://stackoverflow.com/a/47157646
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81350086
score: 0
comment on: http://stackoverflow.com/q/47200805
type: Comment
has text: Show us what you have tried so far!
type: QuestionComment

http://stackoverflow.com/comment/81196715
has text: Only in the middle. For example `He-llo` or `He-llo!#`. So that function read it like a char and returns `True`
score: 0
comment on: http://stackoverflow.com/a/47122781
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81311781
type: QuestionComment
has text: @VivekKumar As mentioned in the other link shared by you, I tried decision function as well. but could not understand the output. Here is the output.
score: 0
comment on: http://stackoverflow.com/q/47178587
type: Comment

http://stackoverflow.com/comment/81380341
comment on: http://stackoverflow.com/q/47215352
score: 0
has text: And you haven't fixed a typo without knowing it while writing this up as a question e.g. in `post_title = form.title.data`? I can see no other reason for the error.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47119114
has answer: http://stackoverflow.com/a/47119218
tagged with: python
type: AnsweredQuestion
has body: I'm kind of a Python noob at the moment as I've only been using it for a a few days and I was wondering how would you write a Python script that uses argparse to read the contents of a file containing numerous URLs and set the contents as a variable? For example: root@user:~# python myscript.py -f "URLs.txt" and the python shell would then print the variable URLs = The contents of the file print(URLs) resulting in: root@user:~# python myscript.py -f "URLs.txt" https://stackoverflow.com/ https://stackoverflow.com/ https://stackoverflow.com/ root@user:~# Any help would be greatly appreciated!
tagged with: bash
accepted answer: http://stackoverflow.com/a/47119218
answer count: 1
type: Question
score: 0
tagged with: linux
has title: How would I make a Python3 file with argparse that would read the contents of a file?
tagged with: argparse
has comment: http://stackoverflow.com/comment/81187945

http://stackoverflow.com/comment/81248308
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47148989
has text: @SethMMorton my mistake just fixed it thanks!
score: 0

http://stackoverflow.com/comment/81167207
has text: Paste here at least the first 3 or five timestamps and I can help you
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47108160
type: Comment

http://stackoverflow.com/comment/81306353
has text: Why are you accessing `model.predict_proba(input_series)[0]`, emphasis on the `[0]`?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47178587

http://stackoverflow.com/a/47087603
answers question: http://stackoverflow.com/q/47087380
score: 1
has comment: http://stackoverflow.com/comment/81125467
downvote count: 1
has comment: http://stackoverflow.com/comment/81125599
has comment: http://stackoverflow.com/comment/81125582
has comment: http://stackoverflow.com/comment/81125367
has comment: http://stackoverflow.com/comment/81125595
has comment: http://stackoverflow.com/comment/81125434
has comment: http://stackoverflow.com/comment/81125638
has comment: http://stackoverflow.com/comment/81125575
upvote count: 2
has comment: http://stackoverflow.com/comment/81125189
has comment: http://stackoverflow.com/comment/81125251
has comment: http://stackoverflow.com/comment/81125298
has comment: http://stackoverflow.com/comment/81125541
has comment: http://stackoverflow.com/comment/81125348
type: Answer
has comment: http://stackoverflow.com/comment/81125408
has body: def write_avg(L, out_file): '''(list, file) -&gt; NoneType Given a list of lists where each inner list consists of a string and a float,and an open file for writing, write the contents of each inner list as a line in the file. Each line of the file should be the string followed by the float separated by a comma. Close the file when done. ''' open_out_file = open(out_file, 'w') for y in L: # iterate over list result = y[0]+','+str(y[1]) + '\n' open_out_file.write(result) #format needed return result open_out_file.close() gradeL = [['S',34],['A',34],['N',34],['L',34]] write_avg(gradeL,'grades.csv') Output in file: S,34 A,34 N,34 L,34

http://stackoverflow.com/q/47222276
has answer: http://stackoverflow.com/a/47228403
downvote count: 0
has comment: http://stackoverflow.com/comment/81405215
favorite count: 0
has title: argparse not handling abbreviations in subparser properly
possible better answer: http://stackoverflow.com/a/47226396
type: Question
score: 5
tagged with: case-insensitive
upvote count: 5
tagged with: case-sensitive
has comment: http://stackoverflow.com/comment/81405420
tagged with: python
tagged with: subparsers
type: AnsweredQuestion
has body: (Run on python 3.6.0) TL;DR Usage: prog.py {caesar | vigenere} [key] parser = argparse.ArgumentParser() subp = parser.add_subparsers() caesar = subp.add_parser("caesar", aliases=["c"], allow_abbrev=True) args = parser.parse_args() $ python prog.py caes 123 prog.py: error: invalid choice: 'caes' (choose from 'caesar', 'c') Why is the subparser abbreviation invalid even with allow_abbrev=True? LONG VER Basically, having an issue getting argparse to accept abbreviated subparsers names/aliases. Here's the code: Usage: prog.py [caesar] [key] import sys, argparse def main(argv): parser = argparse.ArgumentParser (description="runs text through X cipher") subp = parser.add_subparsers\ (help="sub-command help") #&lt;ArgumentParser object&gt; caesar = subp.add_parser\ ("caesar", aliases=["c"], allow_abbrev=True) caesar.add_argument\ ("key", metavar = "key (any integer)",\ type = int, default = 0) args = parser.parse_args() print(caesar) if __name__ == "__main__": sys.argv = list(str(c).lower() for c in sys.argv[0:]) main(sys.argv) So from the code above, it should be expected that any of the following should be accepted: - "Caesar" or "caesar" - "C" or "c" - Any abbreviation in between "c" and "caesar" So here's the problem: This works: $ python prog.py c 123 O This gives an error: $ python prog.py caes 123 X prog.py: error: invalid choice: 'cae' (choose from 'caesar', 'c') Now here's the confusing part. According to the argparse doc: ArgumentParser supports the creation of such sub-commands with the add_subparsers() method. The add_subparsers() method is normally called with no arguments and returns a special action object. This object has a single method, add_parser(), which takes a command name and any ArgumentParser constructor arguments, and returns an ArgumentParser object that can be modified as usual. okay, so any object created with add_subparser() can create its own ArgumentParser objectwith object.add_parser() right? ...which means this newly created ArgumentParser…
answer count: 2
has answer: http://stackoverflow.com/a/47226396
accepted answer: http://stackoverflow.com/a/47228403
tagged with: argparse

http://stackoverflow.com/q/47223002
possible better answer: http://stackoverflow.com/a/47223101
has comment: http://stackoverflow.com/comment/81395980
accepted answer: http://stackoverflow.com/a/47223525
has comment: http://stackoverflow.com/comment/81401866
has answer: http://stackoverflow.com/a/47223525
tagged with: python
tagged with: lambda
has body: I'm using AWS Chalice to deploy my lamdbda function with. I want to include a file which is read by the function however, I cannot find this file when the lambda function runs. It should be in the same directory as the app.py however a simple check using if os.path.isfile('file.json'): does not find it. Am I missing something obvious about AWS Lambda and how it packages my code?
has comment: http://stackoverflow.com/comment/81395856
has comment: http://stackoverflow.com/comment/81412818
type: Question
tagged with: search
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47223101
tagged with: file
upvote count: 1
tagged with: amazon-web-services
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has title: Cannot find file in AWS Lambda function

http://stackoverflow.com/comment/81338854
score: 0
type: Comment
has text: I just want to implement, it's not a real life scenario. Take it as a example. I am just trying to implement multiple inheritance with super() function. If you have answer then post it @Blurp
type: QuestionComment
comment on: http://stackoverflow.com/q/47194629

http://stackoverflow.com/q/47124512
tagged with: recursion
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/47124708
has answer: http://stackoverflow.com/a/47124708
type: AnsweredQuestion
has title: merge sort/recursion in python
score: 0
tagged with: mergesort
has comment: http://stackoverflow.com/comment/81199304
answer count: 1
has body: I understand how merge sort work but however when I try to implement in python, I think I am still a little confused about how things are really working out on stack. I have a function called merge_sorted_list which is used for merging two sorted list and a function called merge_sort1 and merge_sort2, which are accounted for the recursion process. "merge_sort1" and "merge_sort2" are very similar but only merge_sort2 gave the correct answer. It looks like merge_sort1 was not taking the returned value at each level of the stack. Could anyone tell me what is the difference in the evaluation between merge_sort1 and merge_sort2 please? def merge_sorted_list(list1,list2): if(len(list1) == 0 or len(list2) == 0): print('input error') return; i = 0 j = 0 k = 0 list_merge = [0]*(len(list1) + len(list2)) while(i &lt; len(list1) and j &lt; len(list2)): if (list1[i] &lt; list2[j]): list_merge[k] = list1[i] i += 1 else: list_merge[k] = list2[j] j += 1 k += 1 while(i &lt; len(list1)): list_merge[k] = list1[i] i += 1 k += 1 while (j &lt; len(list2)): list_merge[k] = list2[j] j += 1 k += 1 return(list_merge) def merge_sort1(mylist): print("splitting ",mylist) if (len(mylist) &gt; 1): mid = len(mylist)//2 merge_sort1(mylist[:mid]) merge_sort1(mylist[mid:]) # lefthalf = mylist[:mid] # righthalf = mylist[mid:] # merge_sort1(lefthalf) # merge_sort1(righthalf) mylist[:] = merge_sorted_list(mylist[:mid],mylist[mid:]) print("merging result ",mylist) return mylist def merge_sort2(mylist): print("splitting ",mylist) if (len(mylist) &gt; 1): mid = len(mylist)//2 # merge_sort2(mylist[:mid]) # merge_sort2(mylist[mid:]) lefthalf = mylist[:mid] righthalf = mylist[mid:] merge_sort2(lefthalf) merge_sort2(righthalf) mylist[:] = merge_sorted_list(lefthalf,righthalf) print("merging result ",mylist) return mylist if we try merge_sort1([4,67,3,3,2,6]), the output will be ('splitting ', [4, 67, 3, 3, 2, 6]) ('splitting ', [4, 67, 3]) ('splitting ', [4]) ('splitting ', [67, 3]) ('splitting ', [67]) ('spli…
has comment: http://stackoverflow.com/comment/81199546

http://stackoverflow.com/comment/81145735
score: 0
type: AnswerComment
has text: You can get info about the request with the `request` object, eg `res.request.headers['Content-Length']`
comment on: http://stackoverflow.com/a/47097428
type: Comment

http://stackoverflow.com/comment/81190082
type: QuestionComment
comment on: http://stackoverflow.com/q/47119748
score: 0
has text: @ashokeapen, can you post a small sample data set and your desired data set? This would help us to understand what are you trying to achieve...
type: Comment

http://stackoverflow.com/comment/81348764
score: 0
has text: Thats what i meant with my last two sentences. The problem here is that normally you want to sum to the next non-zero value, but if you last value is zero then there is no next non zero value. You will have to add some extra code to cover that.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47199620

http://stackoverflow.com/q/47204277
has title: Edit csv column using python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47204586
tagged with: python
has answer: http://stackoverflow.com/a/47204533
tagged with: regex
linked to: http://stackoverflow.com/q/8265648
has comment: http://stackoverflow.com/comment/81357549
tagged with: python-2.7
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/81357447
tagged with: http://stackoverflow.com/tag/csv
has body: I would like to make column 2 in the csv file to be all lowercase and removing all the punctuation and save the file. How can i do that? import re import csv with open('Cold.csv', 'rb') as f_input1: with open('outing.csv', 'wb') as f_output: reader = csv.reader(f_input1) writer = csv.writer(f_output) for row in reader: row[1] = re.sub('[^a-z0-9]+', ' ', str(row[1].lower())) writer.writerow(row) f_input1.close() How do i add : re.sub('[^A-Za-z0-9]+', ' ', str(row)) filewriter.writerow([new_row.lower()]) or .lower in this code?
has comment: http://stackoverflow.com/comment/81357555
type: Question
has comment: http://stackoverflow.com/comment/81358643
has answer: http://stackoverflow.com/a/47204536

http://stackoverflow.com/a/47096352
has comment: http://stackoverflow.com/comment/81142235
has comment: http://stackoverflow.com/comment/81152148
has comment: http://stackoverflow.com/comment/85500706
type: Answer
has body: I would suggest to introduce a tolerance that defines how close you can come to zero and perhaps iterate on the tolerance value I.e. Rewrite 3 * x1 + 2 * x2 + 4 * x3 &gt; 0 x1 + 4 * x2 + 7 * x3 &gt; 0 as 3 * x1 + 2 * x2 + 4 * x3 &gt;= t x1 + 4 * x2 + 7 * x3 &gt;= t Now, you can use spicy.linprog to solve this. where t &gt; 0. Perhaps t &gt;= 0.01 is acceptable as a starting point. Then iterate on t in [0.01, 0.001, 0.0001, ... ] At some point, your solution might start changing by less than your precision requirement. Hope this helps.
score: 0
answers question: http://stackoverflow.com/q/47096132

http://stackoverflow.com/q/47143182
has comment: http://stackoverflow.com/comment/81236853
tagged with: python-2.7
score: 0
linked to: http://stackoverflow.com/q/30458354
has comment: http://stackoverflow.com/comment/81236823
has comment: http://stackoverflow.com/comment/81236524
has comment: http://stackoverflow.com/comment/81236441
has title: Sending an Array from Python to JS
has comment: http://stackoverflow.com/comment/81236931
type: Question
has body: I am new to python and JS. I am trying to call a python method from a js code. The python code is supposed to do some calculation and returns me the results which is array of arrays (e.g., [[1,3],[3, 5]]). I have looked at few answers such as this. However, I was not able to solve my problem. Below is what I have so far: JS code : This sends string "start" to my python code. var a = $.post("/mlModel", { Ml_list: JSON.stringify("start"), contentType: "application/json", dataType: "json" }); console.log(JSON.parse(a)); Python Code: Python code gets the string "start", does some process, and return the results in the form of array of arrays [[2,4],[2,6]] enter code here @app.route('/mlModel', methods = ['POST']) def get_post_MlModel(): jsdata = request.form['Ml_list'] jsdata = json.loads(jsdata) jsdata = ast.literal_eval(json.dumps(jsdata)) // I send "start" to calculate method and it returns data = [[2,3],[1,3]] data = calculate(jsdata) return json.dumps(data) When I run this code, this returns me "Unexpected token o in JSON at position 1" Any idea?
answer count: 2
has answer: http://stackoverflow.com/a/47143928
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47143578
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/81236764

http://stackoverflow.com/q/47151452
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81252701
upvote count: 1
has answer: http://stackoverflow.com/a/47152108
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81252485
has title: Not able execute netsh interface command in python
score: 1
accepted answer: http://stackoverflow.com/a/47152108
has body: I am not able execute "netsh interface tcp set global nonsackrttresiliency=enabled" command even as admin in python.could any body please help
tagged with: netsh
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/47135539
has body: I have a dataframe object column which looks like 104.5 and always has a suffix like K, B or M standing for Kilo, Billions or Millions. For instance 104.5B. What I would like to do is to check for the suffix and multiple the value by 10^3, 10^6 or 10^9 'inplace'. I found some explanations for labeling a new column, but nothing like a multiplication in place. How am I doing it smart?
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47135665
has comment: http://stackoverflow.com/comment/81220541
score: 2
type: AnsweredQuestion
tagged with: if-statement
tagged with: pandas
has title: If/Elseif Condition on a Dataframe combined with multiple actions
answer count: 1
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47135665
upvote count: 2

http://stackoverflow.com/comment/81153126
score: 0
type: Comment
type: QuestionComment
has text: Please post your spec file
comment on: http://stackoverflow.com/q/47090316

http://stackoverflow.com/comment/81266188
type: Comment
type: QuestionComment
has text: @mhawke My file is much bigger. I updated my question. Please, have a look.
score: 0
comment on: http://stackoverflow.com/q/47158071

http://stackoverflow.com/comment/81153737
comment on: http://stackoverflow.com/a/47101843
type: Comment
type: AnswerComment
score: 1
has text: @P.Prunesquallor Just have time check the question queue , and pick the questioner which I know firstly .. :-), it is obviously , I know you :-)

http://stackoverflow.com/q/47086652
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: forms
has title: Django Model choices based off another model
has body: Sorry if this is confusing, I'm still a bit green with Django. So basically I have two models and I want a selection from one to have all the choices from another model. So basically: class Show(models.Model): venue = models.CharField(max_length=100, choices = VENUE NAME) class Venues(models.Model): Name = models.CharField(max_length=100) Essentially I want the venue to have a list of the venue names that were input into that model. Is this possible?
answer count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81123059
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/67580720
has answer: http://stackoverflow.com/a/47091169
favorite count: 0
type: Question
tagged with: model
has comment: http://stackoverflow.com/comment/81123115
score: 1

reverse
tags question: http://stackoverflow.com/q/47131096
tags question: http://stackoverflow.com/q/47170219
tag name: reverse
type: Tag
tags question: http://stackoverflow.com/q/47129866

http://stackoverflow.com/q/47137592
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/47140427
answer count: 1
downvote count: 0
favorite count: 0
tagged with: celery
type: Question
has title: Celery : launch chord callback after its associated body
has body: When I launch a list of chord() containing a group of tasks and a callback, the callbacks are called only after all the group of tasks have been done, even the tasks which are not in the current chord. Here is the code for a better explanation : import time from celery import Celery, group, chord app = Celery('tasks') app.config_from_object('celeryconfig') @app.task(name='SHORT_TASK') def short_task(t): time.sleep(t) return t @app.task(name='FINISH_GROUP') def finish_group(res, nb): print("Pipe #{} finished".format(nb)) return True @app.task def main(total): tasks = [] for nb in range(1, total+1): short_tasks = [short_task.si(i) for i in [0.5, 0.75, 1]] chord( group(short_tasks), finish_group.s(nb) ).apply_async() I launch it with 5 items for example : In [5]: main.delay(5) Out[5]: &lt;AsyncResult: db1f97f0-ff7a-4651-b2f9-11e27a001480&gt; And the results : [2017-11-06 13:50:38,374: INFO/MainProcess] Received task: tasks.main[6da738b5-4eae-4de4-9ac5-1dc67d210f1d] [2017-11-06 13:50:38,409: INFO/MainProcess] Received task: SHORT_TASK[9581f9e0-1128-4b87-ae6b-16f238b2337e] [2017-11-06 13:50:38,411: INFO/MainProcess] Received task: SHORT_TASK[579dc498-3770-4385-a25a-06173fbe639c] [2017-11-06 13:50:38,412: INFO/MainProcess] Received task: SHORT_TASK[bfafb943-46d8-42e3-941f-b48a9c8e0186] [2017-11-06 13:50:38,414: INFO/MainProcess] Received task: SHORT_TASK[a1208f06-250f-48ac-b3df-45c4525fe8eb] [2017-11-06 13:50:38,416: INFO/MainProcess] Received task: SHORT_TASK[86ee7408-9d61-4909-bce8-c42cf691e9c2] [2017-11-06 13:50:38,416: INFO/MainProcess] Received task: SHORT_TASK[e2bb22c0-1d20-4da7-91d9-45b7ed8bfc6f] [2017-11-06 13:50:38,419: INFO/MainProcess] Received task: SHORT_TASK[7551199b-4690-45dd-a434-3911861f0093] [2017-11-06 13:50:38,420: INFO/MainProcess] Received task: SHORT_TASK[362d18f4-2252-4a31-ad21-4a2d192fd22e] [2017-11-06 13:50:38,421: INFO/MainProcess] Received task: SHORT_TASK[7561c33b-7020-4feb-b054-3919e4ae31c2] [2017-11-06 13:50:38,423: INFO/MainProcess] Receive…
accepted answer: http://stackoverflow.com/a/47140427
tagged with: python
linked to: http://stackoverflow.com/q/51076827
type: AnsweredQuestion

http://stackoverflow.com/q/47187332
has title: Calculating standard deviation on list ignoring zeros using numpy
has body: I am having a list pct_change. I need to calculate std deviation on the list ignoring the zeros. I tried below code, but it is not working as expected. import numpy as np m = np.ma.masked_equal(pct_change, 0) value = m.mask.std() Input value: pct_change 0 0.00 1 0.00 2 0.00 3 18523.94 4 15501.94 5 14437.03 6 13402.43 7 18986.14 Code has to ignore 3 zero values and then calculate standard deviation.
has answer: http://stackoverflow.com/a/47187391
type: AnsweredQuestion
score: 3
tagged with: standard-deviation
downvote count: 1
has answer: http://stackoverflow.com/a/47187439
favorite count: 0
type: Question
upvote count: 4
tagged with: numpy
answer count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/47187439
accepted answer: http://stackoverflow.com/a/47187391

http://stackoverflow.com/a/47082483
type: Answer
answers question: http://stackoverflow.com/q/47066680
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/81161294
has body: Workers regularly exiting from the signal ttou (means decrement # of processes by one) every so often is intentional. This is airflow periodically "refreshing" workers. Based on what I read in AIRFLOW-276, which added this feature, refreshing workers is to ensure they pickup on new or updated DAGs. This behavior can be modified in your airflow config under worker_refresh_interval and worker_refresh_batch_size. From looking at the source, it spins new workers up before spinning down old workers, so I don't think this would cause a delay for your requests. However, you can try disabling it with worker_refresh_batch_size = 0.
downvote count: 0

http://stackoverflow.com/comment/81324170
type: AnswerComment
comment on: http://stackoverflow.com/a/47187277
score: 0
type: Comment
has text: Your suggestion never fails sir. I visualized that the script is successfully clicking each links but i wonder why doesn't any box with information pop up with each click? Any further activity i should perform at this point?

http://stackoverflow.com/a/47204411
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81358472
has body: Lets say that you have an array cycle with these elements: cycle = [1,2,3,4,5,6,1,2,3,1,2,3,4] This will give you desired output: ID = [] i = 0 for n in cycle: if n == 1: i += 1 ID.append(i) #[1,1,1,1,1,1,2,2,2,3,3,3,3] And given that this is exact same solution as the other answer, here's a fun one: i = 0 def makeID(): global i i += 1 return i ID = [makeID() if n == 1 else i for n in cycle]
has comment: http://stackoverflow.com/comment/131240438
has comment: http://stackoverflow.com/comment/131248264
accepted answer of: http://stackoverflow.com/q/47204256
has comment: http://stackoverflow.com/comment/81357776
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/81358024
answers question: http://stackoverflow.com/q/47204256
has comment: http://stackoverflow.com/comment/81358046

http://stackoverflow.com/a/47208406
accepted answer of: http://stackoverflow.com/q/47208095
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47208095
score: 1
has body: There are a couple of different ways of doing this, but the easiest is to use a dictionary instead. group_dict = {group: [] for group in group_list} This will leave you with a dictionary { 'dev': [], 'test': [], 'prod': [] } which gives you access to all the handy pythonic tools when dealing with it. (Iteration, etc.)
has comment: http://stackoverflow.com/comment/81366073
type: AcceptedAnswer

http://stackoverflow.com/q/47212687
upvote count: 1
has title: How to multiple variable inputs for a single output | Python
has comment: http://stackoverflow.com/comment/81375087
tagged with: python
tagged with: variables
has answer: http://stackoverflow.com/a/47212958
favorite count: 0
has body: fairly new to python, and coding in general. I am following an online guide for a simple Python function, but I want to edit it so I can learn more it. I want to know how my function can look for a variety of inputs via the user that will activate the same output. For example, I want 'Yes' and 'yes' to output the same text. choice = raw_input('Do you like YouTube videos? ') if choice == 'yes' : print 'I like YouTube videos too!' elif choice == 'no' : print 'Damn, you suck' else : print '*invalid answer*'
type: AnsweredQuestion
tagged with: python-2.7
answer count: 3
has comment: http://stackoverflow.com/comment/81374962
score: 1
has answer: http://stackoverflow.com/a/47212770
accepted answer: http://stackoverflow.com/a/47212770
linked to: http://stackoverflow.com/q/15112125
has answer: http://stackoverflow.com/a/47212793
type: Question
possible better answer: http://stackoverflow.com/a/47212793
downvote count: 0

http://stackoverflow.com/comment/81486417
has text: Please edit your question to include a sample of your CSV data, this would make it much easier for us to help you.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47210345

http://stackoverflow.com/a/47140802
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81232148
accepted answer of: http://stackoverflow.com/q/47140580
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47140580
has comment: http://stackoverflow.com/comment/81231552
has body: If the installation is ok. You can use python, opening the command prompt window and navigating to your Python installation directory (default is C:\Python27). Type python from this location to launch the Python interpreter. Microsoft Windows [Version 6.2.9200] (c) 2012 Microsoft Corporation. All rights reserved. C:\Users\Username> cd C:\Python27 C:\Python27> python Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> Another way you can follow an Installation tutorial. You can run Python from any location without having to constantly reference the full installation pathname. This can be done by adding the Python installation path to Windows' PATH ENVIRONMENT VARIABLE *In Windows 7 and Windows 8, simply searching for "environment variables" will present the option to Edit the system environment variables. This will open the System Properties / Advanced tab *In Windows XP, right-click on My Computer->Properties to open System Properties and click on the Advanced tab. On the System Properties / Advanced tab, click Environment Variables to open User Variables and System Variables Create a new System Variable named Variable name: PYTHON_HOME and Variable value: c:\Python27 (or whatever your installation path was) Find the system variable called Path and click Edit Add the following text to the end of the Variable value: ;%PYTHON_HOME%\;%PYTHON_HOME%\Scripts\ Verify a successful environment variable update by opening a new command prompt window (important!) and typing python from any location.
has comment: http://stackoverflow.com/comment/81231624
type: AcceptedAnswer

http://stackoverflow.com/comment/81271449
type: Comment
type: QuestionComment
has text: Thanks for the comments - could someone modify the code for me - so that I know where to change it - if possible. Thank you
comment on: http://stackoverflow.com/q/47159821
score: 0

http://stackoverflow.com/q/47213631
upvote count: 3
score: 3
has title: env: ‘jupyter’: No such file or directory
tagged with: python
has answer: http://stackoverflow.com/a/47218979
tagged with: jupyter-notebook
possible better answer: http://stackoverflow.com/a/47218979
answer count: 4
has answer: http://stackoverflow.com/a/53290227
type: Question
accepted answer: http://stackoverflow.com/a/47214369
tagged with: pyspark
downvote count: 0
has answer: http://stackoverflow.com/a/47214369
has body: I'm trying to apply this tuto in my ubuntu, and this is what i did: 1-install spark 2.2.... (pyspark)+ java(1.8) + anaconda (Python2.7) 2-edit the .bachrc (adding 2 lines): export PYSPARK_DRIVER_PYTHON=jupyter export PYSPARK_DRIVER_PYTHON_OPTS="notebook" 3-lanch Pyspark: $sudo Pyspark it works fine 4-lanch jupyter: $sudo jupyther notebook it works fine when i run PYSPARK_DRIVER_PYTHON="jupyter" PYSPARK_DRIVER_PYTHON_OPTS="notebook" spark-2.2.0-bin-hadoop2.7/bin/pyspark the command to launch Pyspark with Jupyter notebook i get this: env: ‘jupyter’: No such file or directory what should i do ??
has answer: http://stackoverflow.com/a/56977057
tagged with: python-2.7
tagged with: apache-spark
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/81175155
type: Comment
has text: Column names need to be A1 B1 ... na?
type: AnswerComment
comment on: http://stackoverflow.com/a/47112635
score: 0

http://stackoverflow.com/comment/81259101
comment on: http://stackoverflow.com/q/47154694
has text: The real question is why do you want mixed dtypes in the first place? By doing this you lose the advantage of fast value comparison, arithmetic operations etc..
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81152510
has text: For some reasons I thought that it was directly used by optimize.minimize. It does make sense to multiply the return value! (facepalm)
comment on: http://stackoverflow.com/q/47100679
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81318760
type: Comment
comment on: http://stackoverflow.com/q/47150155
has text: Usually `import` is followed by a **module name**. So when you are using `import Block` it will search for a module named `Block` in it's `sys.path`. But in your case Block is not a module. It is a part of a module. So either you can just import Block as i mentioned above or you import everything as `from block_library import *` or you could just import the module itself `import block_library`. I suggest you to read the documentation about importing because it's very confusing and highly valuable when dealing with larger codebases
score: 0
type: QuestionComment

email
tags question: http://stackoverflow.com/q/47085943
tags question: http://stackoverflow.com/q/47089450
tags question: http://stackoverflow.com/q/47126108
tags question: http://stackoverflow.com/q/47119868
tags question: http://stackoverflow.com/q/47115583
tags question: http://stackoverflow.com/q/47122680
tags question: http://stackoverflow.com/q/47147250
tags question: http://stackoverflow.com/q/47153105
type: Tag
tag name: email

http://stackoverflow.com/comment/99877465
type: Comment
comment on: http://stackoverflow.com/q/47106830
type: QuestionComment
has text: With no source code or the specs you are using to run your tutorials we can't get down to the reason this happened.
score: 0

http://stackoverflow.com/a/47144579
type: Answer
has comment: http://stackoverflow.com/comment/81239882
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/81239200
has comment: http://stackoverflow.com/comment/81239557
has comment: http://stackoverflow.com/comment/81239221
has comment: http://stackoverflow.com/comment/81239262
downvote count: 0
has comment: http://stackoverflow.com/comment/81239351
answers question: http://stackoverflow.com/q/47144509
has comment: http://stackoverflow.com/comment/81240201
has body: \xeb encodes ë in ISO 8859-1. To convert from bytes to a Unicode string, use the .decode() method. string.decode('iso-8859-1') That being said: where is this data coming from? Do you know it's always ISO 8859-1, or may it be encoded differently? Why is it in bytes instead of a Unicode string already? Answers to these questions may allow for better solutions.

http://stackoverflow.com/comment/81194531
type: QuestionComment
comment on: http://stackoverflow.com/q/47120069
score: 0
has text: Updated with the view. Please let me know if anything else is required.
type: Comment

http://stackoverflow.com/q/47128414
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47128489
tagged with: indexoutofrangeexception
has comment: http://stackoverflow.com/comment/81206863
tagged with: python
score: -1
has body: I'm writing a python version of the board Game Onitama, and I'm currently trying to write a function to shuffle the cards: temp_deck = onitama_deck.deck print(temp_deck) print(len(onitama_deck.deck)) print(len(temp_deck)) for i in range(len(temp_deck)): next_card = temp_deck[random.randrange(0, len(temp_deck))] deck.deck[i] = next_card temp_deck.remove(next_card) print(onitama_deck.deck) Both onitama_deck.deck and temp_deck are lists, but when I run the program with a deck containing the values from 1-10, i get the following output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 10 10 Traceback (most recent call last): File "onitama.py", line 33, in &lt;module&gt; deck.shuffle() File "onitama.py", line 25, in shuffle onitama_deck.deck[i] = next_card IndexError: list assignment index out of range At first I was wondering why i was too big, so I tried printing both lists. For some reason, each iteration the lowest odd number is removed from temp_deck, and then onitama_deck.deck is set equal to temp_deck, like this: iteration: 1 temp_deck: [2, 3, 4, 5, 6, 7, 8, 9, 10] deck: [2, 3, 4, 5, 6, 7, 8, 9, 10] iteration: 2 temp_deck: [2, 4, 5, 6, 7, 8, 9, 10] deck: [2, 4, 5, 6, 7, 8, 9, 10] iteration: 3 temp_deck: [2, 4, 6, 7, 8, 9, 10] deck: [2, 4, 6, 7, 8, 9, 10] iteration: 4 temp_deck: [2, 4, 6, 8, 9, 10] deck: [2, 4, 6, 8, 9, 10] iteration: 5 temp_deck: [2, 4, 6, 8, 10] deck: [2, 4, 6, 8, 10] And then I get the index out of range error. Can anyway explain the flaw in my logic? Thanks for the help.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47128489
downvote count: 2
has title: Index out of range error in deck shuffling algorithm
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81207128

http://stackoverflow.com/q/47200538
has body: I can create regression plot with seaborns regplot, where I can change the order of the linear regression model with the order option, or choose a lowess model with the lowess=True option as in: sns.regplot(x='logAssets', y='logLTIFR', lowess=True, data=df, scatter_kws={'alpha':0.15}, line_kws={'color': 'red'}) and obtain this: Is it possible to change the order of the linear regression in a pairplot? Or even better, to use a lowess model in seaborn pairplot?
type: AnsweredQuestion
score: 2
tagged with: matplotlib
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: How to change regression model in seaborn pairplot
upvote count: 2
tagged with: seaborn
tagged with: python
has answer: http://stackoverflow.com/a/47200647
accepted answer: http://stackoverflow.com/a/47200647

http://stackoverflow.com/q/47211128
has answer: http://stackoverflow.com/a/47211707
downvote count: 0
has title: How do I store mutidimensional arrays contained in a dictionary in a python xarray?
tagged with: python
tagged with: python-xarray
type: AnsweredQuestion
tagged with: multidimensional-array
tagged with: pandas
answer count: 1
has body: I have a dictionary containing numpy arrarys of varying sizes. All arrays have a common axis length (time) that I would like to store the data along. For example: arr1 = np.random.rand(239, 1) arr2 = np.random.rand(239, 6) arr3 = np.random.rand(239, 3, 7) time = np.random.rand(239, 1) d = {'A': arr1, 'B': arr2, 'C': arr3, 'time': time} I need to be able to index and manipulate the data easily so my first inclination was to use a pandas.Panel to store the data, however, with the inconsistency in dimensions I have been unsuccessful. Is a xarray.Dataset the right approach to take here to store my data, if so, how would that be best implemented?
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47211707
favorite count: 0
upvote count: 2
score: 2

http://stackoverflow.com/comment/81325110
type: QuestionComment
has text: So if i say "if range(1,n+1)%n==0" the problem would be the n? if i can't use range and int what would i use otherwise for this. Sorry i am kinda new to python/programming and still do alot of mistakes....
comment on: http://stackoverflow.com/q/47187607
score: 0
type: Comment

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/47092627
tags question: http://stackoverflow.com/q/47151375
tags question: http://stackoverflow.com/q/47193509
tags question: http://stackoverflow.com/q/47084230
tags question: http://stackoverflow.com/q/47131440
type: Tag
tags question: http://stackoverflow.com/q/47212868
tags question: http://stackoverflow.com/q/47084040
tags question: http://stackoverflow.com/q/47153575
tags question: http://stackoverflow.com/q/47212741
tags question: http://stackoverflow.com/q/47118121
tags question: http://stackoverflow.com/q/47183314
tags question: http://stackoverflow.com/q/47073072
tags question: http://stackoverflow.com/q/47190916
tags question: http://stackoverflow.com/q/47182821
tags question: http://stackoverflow.com/q/47097615
tags question: http://stackoverflow.com/q/47078886
tags question: http://stackoverflow.com/q/47082785
tags question: http://stackoverflow.com/q/47168749
tags question: http://stackoverflow.com/q/47127940
tags question: http://stackoverflow.com/q/47140578
tags question: http://stackoverflow.com/q/47134833
tags question: http://stackoverflow.com/q/47117780
tags question: http://stackoverflow.com/q/47107692
tags question: http://stackoverflow.com/q/47121762
tags question: http://stackoverflow.com/q/47147591
tags question: http://stackoverflow.com/q/47163127
tags question: http://stackoverflow.com/q/47203620
tags question: http://stackoverflow.com/q/47146759
tags question: http://stackoverflow.com/q/47210345
tag name: csv
tags question: http://stackoverflow.com/q/47118937
tags question: http://stackoverflow.com/q/47121767
tags question: http://stackoverflow.com/q/47160127
tags question: http://stackoverflow.com/q/47220094
tags question: http://stackoverflow.com/q/47124791
tags question: http://stackoverflow.com/q/47074778
tags question: http://stackoverflow.com/q/47117295
tags question: http://stackoverflow.com/q/47181844
tags question: http://stackoverflow.com/q/47073459
tags question: http://stackoverflow.com/q/47193139
tags question: http://stackoverflow.com/q/47108773
tags question: http://stackoverflow.com/q/47107717
tags question: http://stackoverflow.com/q/47133498
tags question: http://stackoverflow.com/q/47209273
tags question: http://stackoverflow.com/q/47188061
tags question: http://stackoverflow.com/q/47159735
tags question: http://stackoverflow.com/q/47115979
tags question: http://stackoverflow.com/q/47207293
tags question: http://stackoverflow.com/q/47108215
tags question: http://stackoverflow.com/q/47121397
tags question: http://stackoverflow.com/q/47213852
tags question: http://stackoverflow.com/q/47099741
tags question: http://stackoverflow.com/q/47145858
tags question: http://stackoverflow.com/q/47196339
tags question: http://stackoverflow.com/q/47172373
tags question: http://stackoverflow.com/q/47138162
tags question: http://stackoverflow.com/q/47104910
tags question: http://stackoverflow.com/q/47096034
tags question: http://stackoverflow.com/q/47221348
tags question: http://stackoverflow.com/q/47115041
tags question: http://stackoverflow.com/q/47124817
tags question: http://stackoverflow.com/q/47128265
tags question: http://stackoverflow.com/q/47163599
tags question: http://stackoverflow.com/q/47102738
tags question: http://stackoverflow.com/q/47112401
tags question: http://stackoverflow.com/q/47135922
tags question: http://stackoverflow.com/q/47167613
tags question: http://stackoverflow.com/q/47170773
tags question: http://stackoverflow.com/q/47066476
tags question: http://stackoverflow.com/q/47080272
tags question: http://stackoverflow.com/q/47212518
tags question: http://stackoverflow.com/q/47192096
tags question: http://stackoverflow.com/q/47153134
tags question: http://stackoverflow.com/q/47072285
tags question: http://stackoverflow.com/q/47104617
tags question: http://stackoverflow.com/q/47212994
tags question: http://stackoverflow.com/q/47187792
tags question: http://stackoverflow.com/q/47076992
tags question: http://stackoverflow.com/q/47211664

http://stackoverflow.com/comment/81365483
comment on: http://stackoverflow.com/q/47208095
type: QuestionComment
has text: The fact that our three different answers answer three different questions suggests that your question isn't clear enough. Could you provide some sample output?
score: 1
type: Comment

http://stackoverflow.com/q/47177905
has comment: http://stackoverflow.com/comment/81347234
has comment: http://stackoverflow.com/comment/81314013
has answer: http://stackoverflow.com/a/47178211
has comment: http://stackoverflow.com/comment/81313450
has title: PyQt - How can I re-initialise the whole code without restarting it?
has comment: http://stackoverflow.com/comment/81304876
type: Question
has comment: http://stackoverflow.com/comment/81309800
has body: I wrote a python GUI program consisting of two separate files; One is for logic code and the other for GUI using PyQt4. The behaviour of some objects (buttons, text fields ...) changes throughout the code and I need to reset everything to its original status by clicking on a QAction class menu item. How can I do that? EDIT: the function that supposed to reset the GUI to the original status: def newSession(self): self.ui.setupUi(self) self.filename = "" self.paramsSplitted = [] self.timestep = None self.index = None self.selectedParam = None self.selectedMethod = None --Snip--
has comment: http://stackoverflow.com/comment/81305042
type: UnansweredQuestion
tagged with: python
tagged with: qaction
answer count: 2
has comment: http://stackoverflow.com/comment/81422161
linked to: http://stackoverflow.com/q/4528347
has answer: http://stackoverflow.com/a/47284003
tagged with: pyqt
score: 0

http://stackoverflow.com/comment/81099322
score: 0
has text: Did you create a module yourself called "socketserver.py"?
comment on: http://stackoverflow.com/q/47074315
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47147126
answers question: http://stackoverflow.com/q/47147106
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81244694
has comment: http://stackoverflow.com/comment/81244783
has body: Preferred Approach Use pd.DataFrame.filter Your choice for regex pattern can be as explicit as you'd like. In this case, I specified that the column must start with 'A' and have 1 or more digits afterwards. d = df.filter(regex='^A\d+') df.assign(Average=d.mean(1), Stddev=d.std(1)) A1 A2 Random data Random data2 Average Stddev 0 0.1 2.0 300 3000 1.05 1.343503 1 0.5 4.5 4500 450 2.50 2.828427 2 3.0 1.2 800 80 2.10 1.272792 3 9.0 9.0 900 90 9.00 0.000000 Alt 1 This is trying too hard. rnm = dict(mean='Average', std='Stddev') df.join(df.T[df.columns.str.startswith('A')].agg(['mean', 'std']).T.rename(columns=rnm)) A1 A2 Random data Random data2 Average Stddev 0 0.1 2.0 300 3000 1.05 1.343503 1 0.5 4.5 4500 450 2.50 2.828427 2 3.0 1.2 800 80 2.10 1.272792 3 9.0 9.0 900 90 9.00 0.000000
type: Answer
accepted answer of: http://stackoverflow.com/q/47147106
score: 2

http://stackoverflow.com/a/47150979
has comment: http://stackoverflow.com/comment/81251603
upvote count: 1
has comment: http://stackoverflow.com/comment/81251662
has body: This will only work if the files are in the same order, and the words in file 1 are are purely a subset of words in file 2: def gen_overlap(file1, file2): for word in file1: line = file2.read() while word not in line: line = file2.read() yield line If they fail to meet either of those conditions, the best method is to create a set of all of the words: gen_overlap(file1, file2): word_set = set(line.split() for line in file1) for line in file2: if line.split()[0] in word_set: yield line
accepted answer of: http://stackoverflow.com/q/47150875
type: Answer
answers question: http://stackoverflow.com/q/47150875
score: 1
type: AcceptedAnswer
downvote count: 0

teradata
type: Tag
tag name: teradata
tags question: http://stackoverflow.com/q/47210308

http://stackoverflow.com/q/47147805
has title: How to remove duplicate line items from a file?
has comment: http://stackoverflow.com/comment/81246021
has answer: http://stackoverflow.com/a/47147995
score: 0
answer count: 3
upvote count: 1
has body: I want to remove duplicate line items from my file, need to check duplicate based of few fields. myfile.txt productItem1 ProductName11,ProdutctPrice27,ProductModelHP11,10/06/2016,ProductDescription-abc1,,,,,,01/11/2017 productItem2 ProductName12,ProdutctPrice99,ProductModelHP12,10/06/2016,ProductDescription-abc2,,,,,,09/02/2017 productItem3 ProductName13,ProdutctPrice87,ProductModelHP13,10/06/2016,ProductDescription-abc3,,,,,,09/02/2017 productItem1 ProductName11,ProdutctPrice27,ProductModelHP11,10/06/2016,ProductDescription-abc1,,,,,,01/12/2017 productItem1 ProductName11,ProdutctPrice27,ProductModelHP11,10/06/2016,ProductDescription-abc1,,,,,,01/11/2017 productItem2 ProductName13,ProdutctPrice991,ProductModelHP123,10/06/2016,ProductDescription-abc3,,,,,,09/02/2017 As per above example, I want to eliminate duplicate records - in this case productItem1 has duplicate. I want to remove duplicated based on these field (ProductName11,ProdutctPrice27,10/06/206 which is index 0, index 1 and index 3). I would like to keep the record which is having recent date. In this example 01/12/2017 is greater date for productItem1 . I've scenario where key can have same value for example: productItem2 but the field which I've mentioned index 0, index 1 and index 3 are different so it should not consider as duplicate. How can we eliminate in Python Output should be: newFile.txt productItem2 ProductName12,ProdutctPrice99,ProductModelHP12,10/06/2016,ProductDescription-abc2,,,,,,09/02/2017 productItem3 ProductName13,ProdutctPrice87,ProductModelHP13,10/06/2016,ProductDescription-abc3,,,,,,09/02/2017 productItem1 ProductName11,ProdutctPrice27,ProductModelHP11,10/06/2016,ProductDescription-abc1,,,,,,01/12/2017 productItem2 ProductName13,ProdutctPrice991,ProductModelHP123,10/06/2016,ProductDescription-abc3,,,,,,09/02/2017 What's the elegant way of eliminating duplicate record? I tried in shell script but that's not giving me the expected output. It would be really appreciated if someone can h…
linked to: http://stackoverflow.com/q/44575562
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47147841
type: Question
duplicate of: http://stackoverflow.com/q/44575562
has answer: http://stackoverflow.com/a/47147909
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/47101607
downvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/47101937
has comment: http://stackoverflow.com/comment/81153409
has comment: http://stackoverflow.com/comment/81153696
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47101937
tagged with: list
has answer: http://stackoverflow.com/a/47101953
has comment: http://stackoverflow.com/comment/81153483
has comment: http://stackoverflow.com/comment/81154712
has comment: http://stackoverflow.com/comment/81153325
has comment: http://stackoverflow.com/comment/81153583
has comment: http://stackoverflow.com/comment/81153309
has answer: http://stackoverflow.com/a/47102252
has title: python Split list based on delimiting list value
answer count: 4
possible better answer: http://stackoverflow.com/a/47101953
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81153660
has answer: http://stackoverflow.com/a/47102022
upvote count: 2
has body: I've dug through countless other questions but none of them seem to work for me. I've also tried a ton of different things but I don't understand what I need to do. I don't know what else to do. list: split_me = ['this', 'is', 'my', 'list', '--', 'and', 'thats', 'what', 'it', 'is!', '--', 'Please', 'split', 'me', 'up.'] I need to: Split this into a new list everytime it finds a "--" name the list the first value after the "--" not include the "--" in the new lists. So it becomes this: this=['this', 'is', 'my', 'list'] and=['and', 'thats', 'what', 'it', 'is!'] please=['Please', 'split', 'me', 'up.'] current attempt (Work in progress): for value in split_me: if firstrun: newlist=list(value) firstrun=False continue if value == "--": #restart? set firstrun to false? firstrun=False continue else: newlist.append(value) print(newlist)

http://stackoverflow.com/a/47170753
has comment: http://stackoverflow.com/comment/81596172
type: Answer
has body: Observer in Sikuli can be a bit confusing at times. Generally, you register one or more events to be observed with a Region using onXXXXX (observe-events or just events). Then you start the observation in a Region by starting its observer and later stopping it again as needed. However, if you do not need the observer run in the background while you continue interacting with other areas of your screen, in most cases it would be easier to use timed wait. You can do it like this: wait(pattern, waitTime) Here the wait will only last for waitTime before the script flow continues.
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47122821
answers question: http://stackoverflow.com/q/47122821
has comment: http://stackoverflow.com/comment/81386310

http://stackoverflow.com/q/47197989
has answer: http://stackoverflow.com/a/47201360
accepted answer: http://stackoverflow.com/a/47347095
tagged with: python
has comment: http://stackoverflow.com/comment/81344734
linked to: http://stackoverflow.com/q/47068709
has answer: http://stackoverflow.com/a/47347095
upvote count: 6
type: AnsweredQuestion
has title: Items of feature_columns must be a _FeatureColumn
possible better answer: http://stackoverflow.com/a/47201360
score: 5
tagged with: deep-learning
has answer: http://stackoverflow.com/a/51617939
has body: I am getting this error: ValueError: Items of feature_columns must be a _FeatureColumn. Given (type ): Index(['CreditScore', 'Age', 'Tenure', 'Balance', 'NumOfProducts', 'HasCrCard', 'IsActiveMember', 'EstimatedSalary', 'Exited'], dtype='object'). I am using tensorFlow lib. I want to get prediction results but I can not run m.train(input_fn=get_input_fn ,steps=5000) code. I always got the same error whatever I did. I used these input functions in the following but nothing changed. def input_fn_train(): x=tf.constant(df_train.astype(np.float64)), y=tf.constant(df_train[LABEL].astype(np.float64)) return x, y and def get_input_fn(data_set, num_epochs=None, shuffle=False): return tf.estimator.inputs.pandas_input_fn( x=pd.DataFrame({k: data_set[k].values for k in data_set.columns}), y=pd.Series(data_set[LABEL].values), num_epochs=num_epochs, shuffle=shuffle) I can not understand what should I do. What the error is about? I've been googling but never found useful thing. How can I handle this error. The code is below. Thanks! import pandas as pd import tensorflow as tf import numpy as np import tempfile COLS= ["RowNumber","CustomerId","Surname","CreditScore","Geography", "Gender","Age","Tenure","Balance","NumOfProducts","HasCrCard", "IsActiveMember","EstimatedSalary","Exited"] FEATURES = ["CreditScore","Age","Tenure","Balance","NumOfProducts", "HasCrCard","IsActiveMember", "EstimatedSalary"] LABEL="Exited" df_train = pd.read_csv("Churn_Modelling.csv", skipinitialspace=True, header=0) df_test = pd.read_csv("Churn_Modelling.csv", skipinitialspace=True, header=0) test_label = df_test[LABEL].astype(float) df_test.drop("Surname", axis = 1, inplace=True) df_test.drop("RowNumber", axis = 1, inplace=True) df_test.drop("CustomerId", axis = 1, inplace=True) df_train.drop("CustomerId", axis = 1, inplace=True) df_train.drop("Surname", axis = 1, inplace=True) df_train.drop("RowNumber", axis = 1, inplace=True) df_train.drop("Geography", axis = 1, inplace=True) df_train.drop("Gender", ax…
tagged with: machine-learning
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: feature-selection
answer count: 3

http://stackoverflow.com/comment/81301366
has text: You want to repeat the same thing that 2 other answers have said?
comment on: http://stackoverflow.com/a/47176019
score: 2
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47077036
has comment: http://stackoverflow.com/comment/81102915
upvote count: 2
has comment: http://stackoverflow.com/comment/81103188
accepted answer of: http://stackoverflow.com/q/47076874
type: Answer
has comment: http://stackoverflow.com/comment/81102736
has comment: http://stackoverflow.com/comment/81102952
has comment: http://stackoverflow.com/comment/81102980
has comment: http://stackoverflow.com/comment/81103097
score: 2
type: AcceptedAnswer
downvote count: 0
has body: Use combine_first, after setting Key to the index with set_index. df1 identifier A B C D E F Key 1 Foo 1 1 1 NaN NaN NaN 2 Foo 2 2 2 NaN NaN NaN 3 Bar 3 3 3 NaN NaN NaN df2 identifier A B C D E F Key 1 NaN 10 10 10 5 6 7 2 NaN 12 12 12 8 9 10 3 NaN 13 13 13 11 12 13 df2[df1.eval('identifier == "Foo"')].combine_first(df1) identifier A B C D E F Key 1 Foo 10.0 10.0 10.0 5.0 6.0 7.0 2 Foo 12.0 12.0 12.0 8.0 9.0 10.0 3 Bar 3.0 3.0 3.0 NaN NaN NaN
answers question: http://stackoverflow.com/q/47076874
has comment: http://stackoverflow.com/comment/81102762
has comment: http://stackoverflow.com/comment/81103081
has comment: http://stackoverflow.com/comment/81102943

http://stackoverflow.com/comment/81284613
has text: I'm currently on windows, and with the embeddable version you don't install it. You download + extract the zip file, and you're good to go.
type: AnswerComment
comment on: http://stackoverflow.com/a/47158826
type: Comment
score: 0

http://stackoverflow.com/comment/81342469
score: 0
type: Comment
type: AnswerComment
has text: thanks man, >just click on the frame> select inspect> loacate the code > right click on it > select "copy as Xpath".... and about your code above what do you mean "CLICKABLE_ELEMENT_XPATH"?
comment on: http://stackoverflow.com/a/47196083

http://stackoverflow.com/q/47108912
has body: So I am trying to make a game on pygame which would display a vocabulary as a question and three answer choices. And if the user presses the correct answer, their score will go up by one, and the game will move on to the next vocabulary question. I store my questions in an 2D array called questions[], in each element of the array it holds the questions and answers for each question as [question, correct answer choice, answer choice, answer choice]. So the correct answer is always at index position [i][1]. I do randomize the order in which the answer choices are shown later. Now my problem is that my game goes through the questions without waiting for user input. The point was that it would wait for the user to click. When the user clicks, then it checks where the user click. The position of the user's mouse will determine which "answer box" the user pressed. Let's pretend the user pressed the first box. The game then compares whether the text stored in that box is correct (i.e the text is the same as questions[i][1]). It displays each question for a split second, and then moves on to the next question and the next question. But it does not wait for the user to click first. Not even, it doesn't even display the questions long enough for the user to read the question. Is there a way I can perhaps structure the loop or add certain conditions so that the program would display each question until the user chooses an answer, and then add the score and move on to the next question? Here is the code: import pygame from random import randint from pygame import * pygame.init() pygame.font.match_font('Courier New.ttf') BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) GREEN = (71, 212, 15) BLUE = (42, 250, 246) PINK = (255,102, 196) YELLOW = (255, 255, 0) i = 0 size = (700, 500) screen = pygame.display.set_mode(size) pygame.display.set_caption("Spanish Space Quiz") done = False questions = [["Hola", "Hello", "Goodbye", "Cow"],["Amigo", "Friend", "…
has title: Making pygame wait for user click/input before proceeding (python quiz game)
tagged with: python
tagged with: pygame
score: 2
upvote count: 2
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47112546
has answer: http://stackoverflow.com/a/47108972
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81236661
type: UnansweredQuestion

http://stackoverflow.com/comment/81386342
has text: Could you please fix the code you show to be the same you actually use? There is no `messagesplit` but probably `message.split`. Also the indentation is wrong.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47217273

http://stackoverflow.com/a/47129317
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47129229
has body: You can use Pandas to do this. import pandas as pd a = [[1234,'1/8/2014'],[4123,'1/3/2014'],[5754,'1/12/2014'],[8548,'11/8/2014'],[9469,'11/9/2013'],[3564,'1/8/2013']] df = pd.DataFrame(a) df[1] = pd.to_datetime(df[1]) df = df.set_index(1) df.groupby(df.index.year.astype(str)).mean()\ .reset_index().values.tolist() Output: [['2013', 6516.5], ['2014', 4914.75]]
score: 2
upvote count: 2

http://stackoverflow.com/a/47065923
type: AcceptedAnswer
has body: The explanations in the dupe target explain what's going on pretty well, but I'll address what happens in swap_then_append. def swap_then_append(l1, l2): print l1,l2 # [3],[4] l1, l2 = l2, l1 print l1,l2 # [4] [3] l1.append(1) l2.append(2) l1 = [3] l2 = [4] print l1, l2 # [3] [4] swap_then_append(l1, l2) print l1, l2 # [3,2] [4,1] The 'swapping' changes the names of the variables used to refer to the lists, but only within the function. While mutation of the underlying object is permanent, the assignment of variables depends on the scope. The new l1 and l2 in the function might as well be called something else, as they are now just shadowing the original variables l1 and l2 defined in the function signature, which, in turn, shadow the l1 and l2 defined in the main script. The mutations then apply to the original lists.
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/47065693
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47065693

http://stackoverflow.com/q/47216089
type: Question
has comment: http://stackoverflow.com/comment/81384079
answer count: 0
has comment: http://stackoverflow.com/comment/81381733
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Error in django 1.8.7 version with python 2.7.12
tagged with: ubuntu
tagged with: python-2.7
score: 0
has body: I am getting the following trackback error message when I run command(python3 manage.py runserver) on ubuntu OS: Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 303, in execute settings.INSTALLED_APPS I am using the following version of django and python: Django 1.8.7 python: 2.7.12 Can someone please help me to resolve this issue? Because I tried it 10 times from google suggestion but didn't get the right answer.
tagged with: django-models

http://stackoverflow.com/q/47088637
answer count: 0
has comment: http://stackoverflow.com/comment/81127306
tagged with: flask-sqlalchemy
type: Question
tagged with: flask-wtforms
type: UnansweredQuestion
has title: Flask-WTForms not passing data when submitted. AttributeError: 'NoneType' object has no attribute 'id'
tagged with: python
score: 0
has body: I'm new to Python and the Flask framework and I can't figure out how to pass data to a form. I keep getting AttributeError: 'NoneType' object has no attribute 'id' when I submit the form. I'm able to pass the object (invoice1) from the view to the template and display the object properties. (invoice.id) but I can't pass the object to the Form. @app.route('/invoice/add', methods=['GET', 'POST']) @login_required def addItem(): invoice2 = request.args.get('invoice_id', type=int) invoice1 = Invoice.query.filter_by(id=invoice2).first() form = ItemForm(obj=invoice1) if form.validate_on_submit(): newItem = Item( invoice = invoice1, quantity = form.quantity.data, category = form.category.data, brand = form.brand.data, model = form.model.data, serialNumber = form.serialNumber.data, condition = form.condition.data, notes = form.notes.data, cost = form.cost.data ) db.session.add(newItem) db.session.commit() return redirect(url_for('invoice')) return render_template('invoice/addItems.html', form=form, invoice1=invoice1) form.py from flask_wtf import Form from wtforms import validators, IntegerField, StringField, TextAreaField, HiddenField from wtforms.ext.sqlalchemy.fields import QuerySelectField from item.models import Category, Brand class BrandForm(Form): name = StringField('Enter Brand', [validators.Required(), validators.Length(max=80)]) class CategoryForm(Form): name = StringField('Enter Category', [validators.Required(), validators.Length(max=80)]) def categories(): return Category.query.order_by(Category.name).all() def brands(): return Brand.query.order_by(Brand.name).all() class ItemForm(Form): #invoice = IntegerField('Invoice Number') quantity = IntegerField('Quantity', [validators.Required()]) category = QuerySelectField('Category', [validators.Required()], query_factory=categories, allow_blank=True, blank_text=u'-- please choose --') brand = QuerySelectField('Brand', [validators.Required()], query_factory=brands, allow_blank=True, blank_text=u'-- please choose --')…
has comment: http://stackoverflow.com/comment/81150631

http://stackoverflow.com/q/47163048
tagged with: python
linked to: http://stackoverflow.com/q/40181344
has body: Since python 3.6 (or 3.4 ? I don't remember) we can annotate a function. Ex: def getVersion() -&gt; str: Now what happens when a function returns a tuple ? We can do that: def func() -&gt; tuple: But if we know the tuple is a tuple of two integers ? I read here: How to annotate types of multiple return values? that we can do that: def func() -&gt; Tuple[int, int] But it requires to import the typing module. Also I tried that: def func() -&gt; (int, int): And it doesn't crash. What is the right way ?
tagged with: python-typing
type: AnsweredQuestion
answer count: 1
downvote count: 0
has title: Python annotations: difference between Tuple and ()
accepted answer: http://stackoverflow.com/a/47190640
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47190640
score: 9
upvote count: 9

http://stackoverflow.com/comment/81374310
score: 1
has text: Why not use just `r'\W+'`?
type: Comment
comment on: http://stackoverflow.com/q/47212409
type: QuestionComment

http://stackoverflow.com/comment/81336034
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47193228
has text: This code works for me, maybe it is a problem within your computer?

http://stackoverflow.com/q/47067202
answer count: 1
has body: I created an app that allows registered users to create products using a form. Each registered user has a profile page displaying their products that only they can see when logged in. I want to create a view that will allow an unregistered user to view products by any user by clicking on a username. How do I do that? Here's the product form: class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'description', 'url', 'product_type', 'price', 'image', 'image_url'] labels = { 'name': 'Product Name', 'url': 'Product URL', 'product_type': 'Product Type', 'description': 'Product Description', 'image': 'Product Image', 'image_url': 'Product Image URL', 'price': 'Product Price' } widgets = { 'description': Textarea(attrs={'rows': 5}), } The product views are simple: def products(request): products = Product.objects.all() form = ProductForm() return render(request, 'products.html', {'products': products, 'form':form}) def post_product(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = ProductForm(data = request.POST, files = request.FILES) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required product = form.save(commit = False) product.user = request.user product.likes = 0 product.save() # redirect to a new URL: return HttpResponseRedirect('/products') Let me know if I need to show anything else.
favorite count: 0
type: Question
has title: Django view to display objects by user to visitor
tagged with: django
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: view
downvote count: 0
has answer: http://stackoverflow.com/a/47067297
accepted answer: http://stackoverflow.com/a/47067297

http://stackoverflow.com/comment/81139589
has text: @DanielRoseman: Yes, I agree. Django1.4 is no longer alive. But to support old Clients, I am using Django1.4, Client not want upgrade Django.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47094868
type: Comment

http://stackoverflow.com/q/47189191
upvote count: 0
has comment: http://stackoverflow.com/comment/81327866
downvote count: 3
has comment: http://stackoverflow.com/comment/81327925
answer count: 1
has body: I dont understand why i get always a invalid syntax error. Can you please help? def steigung(a,b,c,d,x): Ausgabe= 3*a*x**2+2*b*x+c Ausgabe2= 6*a*x+2*b if Ausgabe &gt;= 1: print("Die Funktion Steigt") elif Ausgabe &lt;= -1: print("Die Funktion Fällt") elif Ausgabe=0 and Ausgabe2 &gt; 0: print("Die Funktion hat ein lokales Minimum") elif Ausgabe=0 and Ausgabe2 &lt; 0: print("Die Funktion hat ein lokales Maximum") elif Ausgabe=0 and Ausgabe2 = 0: print("die Funktion einen kritischen Punkt unbekannten Typs") return print
has answer: http://stackoverflow.com/a/47189282
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81327745
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81327806
score: -3
tagged with: python
has title: Python always getting invalid syntax error
has comment: http://stackoverflow.com/comment/81328098

http://stackoverflow.com/comment/81228399
type: AnswerComment
has text: Thanks a lot for this anyway! Good day!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47118728

http://stackoverflow.com/comment/81162404
type: AnswerComment
comment on: http://stackoverflow.com/a/47105336
score: 0
type: Comment
has text: @Elisha512 you can do somthing like `missing = df1.columns.difference(df2.columns)` and pass that.

http://stackoverflow.com/comment/81203948
type: Comment
type: QuestionComment
has text: That part runs now. I am skill getting another error, although it's from a different part of the code.
score: 0
comment on: http://stackoverflow.com/q/47124427

http://stackoverflow.com/comment/81217076
type: AnswerComment
comment on: http://stackoverflow.com/a/47132562
has text: I've udnerstood you correctly, take a look now where I have 3 different groups, the first uses two different functions (`func_a` and `func_b`) with no arguments, the second one uses the same func (`func_c`) with different arguments, and the third combines both, different functions and arguments.
score: 0
type: Comment

http://stackoverflow.com/q/47147328
has answer: http://stackoverflow.com/a/76979553
downvote count: 0
score: 16
favorite count: 0
tagged with: python-3.x
has body: My program appears to run in a deadlock sometimes when I hit Ctrl+C. I'm trying to catch the keyboard interrupt and gracefully stop all running threads, but I'm not quite there yet. I'm using a concurrent.futures.ThreadPoolExecutor. To find the location of the deadlock, I'm using the this receipe from ActiveState. Now, here's the full stacktrace: # ThreadID: 4856 File: "c:\users\niklas\appdata\local\programs\python\python36\lib\threading.py", line 884, in _bootstrap self._bootstrap_inner() File: "c:\users\niklas\appdata\local\programs\python\python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File: "C:\Users\niklas\repos\nodepy\craftr\lib\utils\tracer.py", line 66, in run self.stacktraces() File: "C:\Users\niklas\repos\nodepy\craftr\lib\utils\tracer.py", line 80, in stacktraces fout.write(stacktraces()) File: "C:\Users\niklas\repos\nodepy\craftr\lib\utils\tracer.py", line 28, in stacktraces for filename, lineno, name, line in traceback.extract_stack(stack): # ThreadID: 6068 File: "c:\users\niklas\appdata\local\programs\python\python36\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File: "c:\users\niklas\appdata\local\programs\python\python36\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File: "C:\Users\niklas\repos\nodepy\craftr\.nodepy_modules\.bin\craftr.exe\__main__.py", line 9, in &lt;module&gt; sys.exit(nodepy.main.main()) File: "c:\users\niklas\repos\nodepy\nodepy\nodepy\main.py", line 103, in main ctx.load_module(ctx.main_module, do_init=False) File: "c:\users\niklas\repos\nodepy\nodepy\nodepy\context.py", line 253, in load_module module.load() File: "c:\users\niklas\repos\nodepy\nodepy\nodepy\loader.py", line 43, in load exec(code, vars(self.namespace)) File: "C:\Users\niklas\repos\nodepy\craftr\lib\main.py", line 110, in &lt;module&gt; sys.exit(main()) File: "C:\Users\niklas\repos\nodepy\craftr\lib\main.py", line 106, in main return backend.build_main(backend_args, session, module) File: "C:\Users\nikla…
type: Question
has title: Thread._wait_for_tstate_lock() never returns
answer count: 2
tagged with: python
type: UnansweredQuestion
upvote count: 16
has answer: http://stackoverflow.com/a/55643196
tagged with: deadlock
tagged with: multithreading

http://stackoverflow.com/q/47220094
type: AnsweredQuestion
answer count: 1
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47220332
has body: Hoping for someone to help me out with something to help with personal finance. I use an online budget tool but my bank statements are formatted annoyingly. Trying to script a CSV modification that reads a file, and replaces part of a string in the second column (12 characters removed from start if "Visa Purchase" exists in string, then dumps it out as a renamed CSV. Any help would be much appreciated. so far I have the below (to read file and give options for displaying); csvfile = input("CSV File Name?: ") choice = input("all or some?: ") import csv with open(csvfile + '.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') if choice == "all": for row in readCSV: print(row) elif choice == "some": for row in readCSV: print(row[0], row[1]) else: print("Error") Thanks!
type: Question
tagged with: python-3.x
has title: (Basic) Python CSV Import, Replace, Export
upvote count: 1
accepted answer: http://stackoverflow.com/a/47220332
favorite count: 0
score: 0
tagged with: http://stackoverflow.com/tag/csv

compression
tags question: http://stackoverflow.com/q/47123915
tags question: http://stackoverflow.com/q/47088399
tag name: compression
tags question: http://stackoverflow.com/q/47183503
type: Tag

http://stackoverflow.com/comment/81260492
has text: thanks for reply.Can you give me one more favour? when i click on fourth then submenu show under fourth menu.how to show in front of fourth
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47121049

http://stackoverflow.com/q/47144665
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81239461
tagged with: python-requests
downvote count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81239553
has answer: http://stackoverflow.com/a/47144808
tagged with: python
score: -1
has body: def reporta(): with open("userinfo.txt","r") as f: text = [line.strip() for line in f] ulist = [x.split(",") for x in text] for n in range(len(ulist)): uname = input("Which username do you want to see?\n") if uname == ulist[n][0]: print("The username is",ulist[n][0],"\nThe user's password is",ulist[n][1],"\nThe user's name is", ulist[n][2],"\nThe user's age is",ulist[n][3],"\nThe user's year group is",ulist[n][4]) for i in range (5,11): if i == 5: if ulist[n][i] == "-1": print("Maths easy has not been taken by",ulist[n][0]) else: print(ulist[n][0],"got",ulist[n][i]) elif i == 6: if ulist[n][i] == "-1": print("Maths medium has not been taken by",ulist[n][0]) else: print(ulist[n][0],"got",ulist[n][i]) elif i == 7: if ulist[n][i] == "-1": print("Maths hard has not been taken by",ulist[n][0]) else: print(ulist[n][0],"got",ulist[n][i]) elif i == 8: if ulist[n][i] == "-1": print("History easy has not been taken by",ulist[n][0]) else: print(ulist[n][0],"got",ulist[n][i]) elif i == 9: if ulist[n][i] == "-1": print("History medium has not been taken by",ulist[n][0]) else: print(ulist[n][0],"got",ulist[n][i]) else: if ulist[n][i] == "-1": print("History hard has not been taken by",ulist[n][0]) else: print(ulist[n][0],"got",ulist[n][i]) break In this piece of code, i am attempting to print things from a file according to which username is inputted, however, if i try to input a username on the second or third row of the list, i have to input the username two or three times before it recognises it. What am i not including/doing wrong? Example: file contains: aad15,arbiter,aadam,15,11,-1,-1,-1,-1,-1,-1 jam11,jammy,james,11,15,-1,-1,-1,-1,-1,-1 ton15,tonehh,tony,15,11,-1,-1,-1,-1,-1,-1 mas15,radicallx,mash,15,11,-1,-1,-1,-1,-1,-1 If i input aad15 as a username, it runs the program as it is supposed to. If i input jam11, i have to input it twice before it does what its supposed to do. If i put ton15 in i have to input it three times before it does what its supposed to do and so on.
type: Question
has comment: http://stackoverflow.com/comment/81239528
has comment: http://stackoverflow.com/comment/81239616
has title: for-loops (how can i get it to ignore some parts if need be)
upvote count: 0

http://stackoverflow.com/q/47136680
has comment: http://stackoverflow.com/comment/81223227
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81224645
answer count: 2
downvote count: 0
tagged with: django
has body: For example assume that I have 100 clients who uses WordPress and I have to write a service in Django which should return list of posts from WordPress's MySQL DB. The problem is 100 clients are having different database connection settings. I know that I can use DatabaseRouter to switch databases which are already loaded in settings. But I don't know how to make a singe model class to use different database settings. I have tried mutating settings. I also tried mutating model's app_label. But I later understood that mutating anyting in Django is meaning less. My Requirements I want to create a model and dynamically change database connection. List of connection can be in a managed database table. But I don't want to unnecessarily load all the connection settings or create multiple models.
favorite count: 0
has answer: http://stackoverflow.com/a/47136936
type: Question
has comment: http://stackoverflow.com/comment/81224045
has comment: http://stackoverflow.com/comment/81223109
has comment: http://stackoverflow.com/comment/81223335
has comment: http://stackoverflow.com/comment/81223184
has answer: http://stackoverflow.com/a/47140225
has comment: http://stackoverflow.com/comment/81224496
tagged with: python
has title: Single model dynamic database settings in Django
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81223312
has comment: http://stackoverflow.com/comment/81224321
has comment: http://stackoverflow.com/comment/81224898

http://stackoverflow.com/a/47141422
upvote count: 7
type: Answer
answers question: http://stackoverflow.com/q/47141264
has body: be careful with tabs and spaces, they are not the same, so: (_ are withe spaces) def func(): ____x = 1 ____ ____print(x) ____return It will work just fine is not the same as (+ are tabs, _ white spaces) def func(): ++x = 1 __ ++print(x) ++return Won't work
score: 7
has comment: http://stackoverflow.com/comment/81233688
downvote count: 0

http://stackoverflow.com/a/49508723
upvote count: 6
has body: Change your file name from git.py to othername .py, since your file is referring to itself it is throwing error
answers question: http://stackoverflow.com/q/47177533
downvote count: 0
type: Answer
score: 6

http://stackoverflow.com/q/47212518
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47212592
favorite count: 0
type: Question
has title: Python - Write a list of tuples to a CSV file ignoring the commas within parentheses
has answer: http://stackoverflow.com/a/47212573
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: python-2.7
answer count: 2
score: 1
has body: So I have the following list: L2 = [(1,2), (1,3), (1,4), (1,5)] I want to write it to a csv file in one column and four rows: (1,2) (1,3) (1,4) (1,5) However my wonderful attempt here with open('myfile.csv', "w") as outfile: for entries in L2: outfile.write(str(entries)) outfile.write("\n") Leads me to two columns and four rows: (1 2) (1 3) (1 4) (1 5)

http://stackoverflow.com/comment/81134772
type: QuestionComment
score: 0
type: Comment
has text: Any problem decrypting **make sure the development packages of libxml2 and libxslt are installed**?
comment on: http://stackoverflow.com/q/47087635

http://stackoverflow.com/comment/81332963
comment on: http://stackoverflow.com/a/47174384
score: 0
type: Comment
has text: Nice, thanks for taking the time to post the answer. I had actually attempted something similar with takewhile but could not make it work.
type: AnswerComment

http://stackoverflow.com/comment/81307695
type: Comment
has text: @mkurnikov, actually yes. The fields will have fixed values (depending on the pricing plan). Even if we move to another plan, we can reset the values to the new default.
score: 0
comment on: http://stackoverflow.com/q/47179188
type: QuestionComment

http://stackoverflow.com/a/47113901
score: 0
has body: This is how I did it using beautifulsoup. id = tweet.find_element_by_class_name("js-tweet-text-container").find_element_by_tag_name("p").text soup = BeautifulSoup(id) text = soup.get_text() print(text)
type: Answer
answers question: http://stackoverflow.com/q/47112972

http://stackoverflow.com/q/47066452
accepted answer: http://stackoverflow.com/a/47066475
tagged with: jinja2
has answer: http://stackoverflow.com/a/47066475
type: Question
has title: Global variable in python flask claims it is being referenced before usage in 1 of 5 functions using it
score: 0
answer count: 1
tagged with: python
tagged with: flask
has body: I get the following error when viewing my page on the browser. File "/home/jsnyder10/Documents/45/flask/lib/python2.7/site-packages/flask/app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "/home/jsnyder10/Documents/45/flask/lib/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "/home/jsnyder10/Documents/45/flask/lib/python2.7/site-packages/flask/app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "/home/jsnyder10/Documents/45/flask/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/home/jsnyder10/Documents/45/flask/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/jsnyder10/Documents/45/flask/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/jsnyder10/Documents/45/flask/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/home/jsnyder10/Documents/45/flask/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/jsnyder10/Documents/45/flask/lib/python2.7/site-packages/flask_login/utils.py", line 228, in decorated_view return func(*args, **kwargs) File "/home/jsnyder10/Documents/jMessage/app/views.py", line 66, in admin_edit_groups if not g.user.admin: UnboundLocalError: local variable 'g' referenced before assignment Here is my python code using Flask for routing. The first function is the code I used in every single admin route that works perfectly, but for some reason the admin_edit_groups route throws this error.What am I missing? from flask import render_template, flash, redirect, session, url_for, request, \ g, jsonify, send_from_directory @app.route('/admin', methods=['GET', 'POST']) @login_requi…
type: AnsweredQuestion
tagged with: python-2.7
tagged with: flash-message

http://stackoverflow.com/q/47145604
has comment: http://stackoverflow.com/comment/81243875
tagged with: python
tagged with: keyboard
has answer: http://stackoverflow.com/a/47145998
has title: How to determine the laptops FN keyboard button HEX code?
has comment: http://stackoverflow.com/comment/81241491
answer count: 3
has comment: http://stackoverflow.com/comment/81278315
tagged with: autohotkey
has comment: http://stackoverflow.com/comment/81279310
has body: I have a python script which presses FN + RightArrow and so on to control the special brightness/volume functions. I do not know the HEX code for the FN button. I tried 255 but it does not seem to be ok. I've tried to determine it with KeyView.exe. It provides the HEX code for the pressed keys. For RightArrow it has a small value and for FN + RightArrow it has a bigger one. I substract them and find FN value (174 or something like that). But it does not work this way neither. I've looked on a bunch of websites and installed several additional tools, but I can't figure it out. Could I maybe lower my brightness automatically in some other ways? The laptop is a Lenovo Y50-70 and I run Windows 10. Any ideas, guys? Thank you!
score: 1
tagged with: keyboard-shortcuts
has answer: http://stackoverflow.com/a/47145686
downvote count: 1
has comment: http://stackoverflow.com/comment/81241528
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/7713539
has answer: http://stackoverflow.com/a/47158190
linked to: http://stackoverflow.com/q/514781
upvote count: 2
type: UnansweredQuestion
tagged with: scancodes

http://stackoverflow.com/a/47122497
has comment: http://stackoverflow.com/comment/81196953
has body: You've told the form to expect the user as the first positional parameter, so you need to pass it there. form2 = class_model(request.user, data=request.POST)
type: Answer
has comment: http://stackoverflow.com/comment/81254436
has comment: http://stackoverflow.com/comment/81250883
score: 0
answers question: http://stackoverflow.com/q/47120069

http://stackoverflow.com/a/54763039
downvote count: 0
has comment: http://stackoverflow.com/comment/111012046
answers question: http://stackoverflow.com/q/47086702
upvote count: 3
score: 3
type: Answer
has body: The accepted answer did not work in my case (on an elder Raspbian), but providing the download URL with the command helped me as described in this post: sudo pip install paho-mqtt -i https://pypi.python.org/simple

http://stackoverflow.com/a/47192610
accepted answer of: http://stackoverflow.com/q/47181141
score: 0
answers question: http://stackoverflow.com/q/47181141
type: AcceptedAnswer
type: Answer
has body: I have found a partial solution, but not in rsgislib. Using GDAL, I can open a subdataset: from osgeo import gdal # get the projection and geotransform from the original input image ids = gdal.Open(inputImg, gdal.GA_ReadOnly) gt = ids.GetGeoTransform() wkt = ids.GetProjectionRef() print gt del ids # now set the projection and geotransform for the specific subdatsert infile = 'HDF5:"'+outputMeanImg+'"://BAND1/DATA' ods = gdal.Open(infile, gdal.GA_ReadOnly) ods.SetProjection(wkt) ods.SetGeoTransform(gt) del ods The above code sets the projection and geotransform for the subdataset I am interested in, but please note that I am opening the output as ReadOnly. If I set it to update, it fails, and it actually updates the selected dataset even though it is opened in read only mode. I consider that a bug, but it appears to work by creating a new .aux.xml file. There may be an easer/better way to do this, but this works for now.

http://stackoverflow.com/a/47095959
downvote count: 0
answers question: http://stackoverflow.com/q/47094872
has body: Instead of trying to figure out what you're capturing in the URL itself, try capturing whatever kwarg is passed to the URL then figure out what to do with it in your view. Your URL pattern could look like this: url(r'^runs_list/(?P&lt;search_term&gt;\d+)/$', RunsDetailAPIView.as_view(), name='runs_list_detail'), Then parse search_term in your view: def get_object(self): search_term = self.kwargs['search_term'] ... For instance, you could use your search_term to make some Q statements: https://docs.djangoproject.com/en/1.11/topics/db/queries/#complex-lookups-with-q-objects Runs.objects.filter( Q(chamber = search_term) | Q(start_time = search_term) ) Depending on your use case, search fields, and environment, you might also consider making SearchVectors: https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/search/#searchvector Or you could even simply filter your queryset with try/except blocks. The main point is to get the kwarg from your URL and work with it in your get_object function rather than trying to figure it all out within the URL itself. All of the above works with base Django; no DRF required. Since you are working with Django Rest Framework, you might also be interested in the django-filters package: http://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend
type: Answer
has comment: http://stackoverflow.com/comment/81219402
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47094872
type: AcceptedAnswer

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/47182641
tags question: http://stackoverflow.com/q/47106385
tags question: http://stackoverflow.com/q/47213483
tags question: http://stackoverflow.com/q/47077310
tags question: http://stackoverflow.com/q/47105227
tag name: decision-tree

http://stackoverflow.com/comment/81350115
comment on: http://stackoverflow.com/q/47200853
score: 2
has text: It seems some `NaN`s, so `df = df.dropna(subset=['train'])` should be help.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47081144
has comment: http://stackoverflow.com/comment/81111514
favorite count: 0
type: Question
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/24571005
has title: Find the highest value in a dataframe
tagged with: dataframe
tagged with: python
has body: I'm struggling to go through ever value in my dataframe to find the highest value. What would be the most efficient way of doing this? I've tried creating a for-loop to go through each item, but I'm not having much luck. Any suggestions?
accepted answer: http://stackoverflow.com/a/47081331
has answer: http://stackoverflow.com/a/47081331
tagged with: pandas
score: 1
answer count: 1
linked to: http://stackoverflow.com/q/24571005
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47173143
has body: Use str[0] for select first values in list and then check ID by contains: m = df['column'].str[0].str.contains('ID', case=False) print (m) 0 True 1 True 2 False 3 True 4 True Name: column, dtype: bool And then remove it by mask with str[1:]: df['column'] = df['column'].mask(m, df['column'].str[1:]) print (df) column 0 [b, c, d] 1 [e, f] 2 [h, i, j, k, l] 3 [n, o, p] 4 [r, s]
type: AcceptedAnswer
score: 4
accepted answer of: http://stackoverflow.com/q/47173057
has comment: http://stackoverflow.com/comment/81295852
has comment: http://stackoverflow.com/comment/81296250
answers question: http://stackoverflow.com/q/47173057
type: Answer
has comment: http://stackoverflow.com/comment/81296224
upvote count: 4
has comment: http://stackoverflow.com/comment/81300914
downvote count: 0

win32gui
type: Tag
tags question: http://stackoverflow.com/q/47222524
tag name: win32gui

http://stackoverflow.com/a/47212594
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47211752
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47211752
downvote count: 1
has body: What's wrong ....scrapy.exe -scrapy crawl quotes What it should be ....scrapy.exe crawl quotes Why This is scrapy's all available commands, there is no -scrapy option: Suggestions Scrapy Official Tutorial PDF Version

http://stackoverflow.com/a/47149786
accepted answer of: http://stackoverflow.com/q/47149756
upvote count: 5
has body: You can use re.sub with a positive lookahead: In [165]: re.sub('\W(?=\s|$)', '', s) Out[165]: 'Hello this episode is thirty-five minutes long 35.26 mins to be precise' Details \W # any character that is not a letter or digit (?= # positive lookahead \s # whitespace | # regex OR $ # EOL )
type: Answer
answers question: http://stackoverflow.com/q/47149756
type: AcceptedAnswer
downvote count: 0
score: 5

http://stackoverflow.com/q/47145404
answer count: 1
has comment: http://stackoverflow.com/comment/81241149
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/81241147
tagged with: python
upvote count: 0
downvote count: 2
has title: What is wrong with this program? Syntax error in print() function python
has body: Why do I get syntax error in line 18? There is something wrong with the print() function, IDE says, but I can't figure out what exactly. I'm porting this program from C to Python as I'm learning the latter. #caesar encipher import sys import cs50 if len(sys.argv)!= 2: print("Nope") k = int(sys.argv[1]) if k&lt;0: print("Nope") else: code = cs50.get_string() #add k letters to each character in the string. For example is code[0]='a' and k=3, program will return 'd'. for i in code: if code[i].islower(): new_code = chr((((ord(code[i]+k)- 97)% 26)+ 97) print(f"{new_code}") elif code[i].isupper(): new_code = chr((((ord(code[i]+k)- 65)% 26)+ 65) print(f"{new_code}") else: print(code[i]) print()
has answer: http://stackoverflow.com/a/47145830
has comment: http://stackoverflow.com/comment/81241033

http://stackoverflow.com/q/47107818
score: 1
has comment: http://stackoverflow.com/comment/81166171
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47107852
has comment: http://stackoverflow.com/comment/81166090
has comment: http://stackoverflow.com/comment/81165989
has answer: http://stackoverflow.com/a/47107852
answer count: 5
downvote count: 0
has answer: http://stackoverflow.com/a/47107960
upvote count: 1
tagged with: python
has title: Meaning of this Python statement with colon and for at the end of the line
has comment: http://stackoverflow.com/comment/81166155
accepted answer: http://stackoverflow.com/a/47107916
has answer: http://stackoverflow.com/a/47107907
type: AnsweredQuestion
has body: I am new to Python. I'm trying to understand this syntax, but I'm not even able to find the correct reference since I don't know what the various semantic elements mean: self._sensitive_ids = {xmr : self.parser.get_id(xmr) for xmr in self.sensitive} Now this doesn't work in my python installation (V2.4). It says "SyntaxError: invalid syntax" Could someone explain what is being assigned to the LHS, and the correct way to rewrite the statement for Python 2.4? What is the "for" loop looping over here when it's mentioned at the end of the line? Btw, the original code is from here: vcd_parse
has answer: http://stackoverflow.com/a/47107916
has comment: http://stackoverflow.com/comment/81165978
has answer: http://stackoverflow.com/a/47107836

http://stackoverflow.com/comment/81280298
comment on: http://stackoverflow.com/q/47165314
has text: Do you have permissions to do so. I do not think you have permissions. What error do you get?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81349563
type: Comment
type: QuestionComment
has text: Thanks @Divakar. That solved the problem
comment on: http://stackoverflow.com/q/47200447
score: 0

http://stackoverflow.com/comment/81358970
score: 0
type: AnswerComment
has text: That condition is never going to come to pass if the line is actually empty. You're currently printing strings of length 1 or more that contain a quotation mark, i.e. ' " ' (spaces added for legibility).
comment on: http://stackoverflow.com/a/47204089
type: Comment

http://stackoverflow.com/comment/81759411
score: 0
type: Comment
type: QuestionComment
has text: Strangely, I am maintaining an old app that uses PyGTK2 and `self.player.set_xwindow(self.window.xid)` works :\
comment on: http://stackoverflow.com/q/47209918

http://stackoverflow.com/comment/81322772
type: AnswerComment
has text: That document leads to [this SO question](https://stackoverflow.com/q/26456125/2000793), which specifically states order within the groups, not order between groups.
comment on: http://stackoverflow.com/a/47186441
type: Comment
score: 0

http://stackoverflow.com/comment/81184031
type: Comment
type: QuestionComment
has text: I suggest that you turn off your computer and get a piece of paper and pencil. Describe **in words** what steps you need to take to solve this problem. Don't worry about python syntax. Just get a clear idea of what the solution should be. **After** you do that, turn your computer back on and attempt to translate your steps into Python code.
score: 1
comment on: http://stackoverflow.com/q/47111762

http://stackoverflow.com/comment/81247843
comment on: http://stackoverflow.com/q/47148509
type: Comment
type: QuestionComment
has text: Derek I have been researching. I dont know how to separate the date, name, and the stats into year, name, stats. So that i can pass it to PlayersYear
score: 0

http://stackoverflow.com/comment/81411664
has text: @RyanFrancisCashMiller notice mine is a list of rows (a list of lists), it needs to make a DataFrame so as it's a list of rows. If it's a single list, do you need to split it into chunks somehow (how do you know when a new row starts)?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47213857
score: 0

http://stackoverflow.com/comment/81170604
type: Comment
has text: @sitilge yes. Exactly that. :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47110106

http://stackoverflow.com/a/47185859
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81324822
has comment: http://stackoverflow.com/comment/81321891
answers question: http://stackoverflow.com/q/47184919
type: AcceptedAnswer
downvote count: 0
has body: Reference: http://lxml.de/tutorial.html#namespaces You mustn't specify the namespace as a :-qualified string. Instead you may use {http://url.url/url}tag form, or QName form. Here is your program, using namespaces: from lxml import etree as ET NS_DC = "http://purl.org/dc/elements/1.1/" NS_OPF = "http://www.idpf.org/2007/opf" nsmap = { "dc": NS_DC, None: NS_OPF, } PACKAGE = ET.QName(NS_OPF, 'package') METADATA = ET.QName(NS_OPF, 'metadata') TITLE = ET.QName(NS_DC, 'title') et = ET.Element(PACKAGE, attrib={'version': "2.0", 'unique-identifier': "BookId"}, nsmap=nsmap) md = ET.SubElement(et, METADATA) au = ET.SubElement(md, TITLE) au.text = "A Tale of Two Cities" s = ET.tostring(et, pretty_print=True) print(s.decode('utf-8')) You might choose to use lxml.builder.ElementMaker. Here is a program that creates a portion of your example. Notes: Note the use of dicts to represent attribute names that are not valid Python names. Note the use of QName to represent namespace-qualified names. Note the use of validator to validate the resulting tree. &nbsp; from lxml import etree as ET from lxml.builder import ElementMaker NS_DC = "http://purl.org/dc/elements/1.1/" NS_OPF = "http://www.idpf.org/2007/opf" SCHEME = ET.QName(NS_OPF, 'scheme') FILE_AS = ET.QName(NS_OPF, "file-as") ROLE = ET.QName(NS_OPF, "role") opf = ElementMaker(namespace=NS_OPF, nsmap={"opf": NS_OPF, "dc": NS_DC}) dc = ElementMaker(namespace=NS_DC) validator = ET.RelaxNG(ET.parse("opf-schema.xml")) tree = ( opf.package( {"unique-identifier": "uuid_id", "version": "2.0"}, opf.metadata( dc.identifier( {SCHEME: "uuid", "id": "uuid_id"}, "d06a2234-67b4-40db-8f4a-136e52057101"), dc.creator({FILE_AS: "Homes, A. M.", ROLE: "aut"}, "A. M. Homes"), dc.title("My Book"), dc.language("en"), ), opf.manifest( opf.item({"id": "foo", "href": "foo.pdf", "media-type": "foo"}) ), opf.spine( {"toc": "uuid_id"}, opf.itemref({"idref": "uuid_id"}), ), opf.guide( opf.reference( {"href": "cover.jpg", "title": "Cover", "type": "cover"}) ),…
type: Answer
has comment: http://stackoverflow.com/comment/81322714
accepted answer of: http://stackoverflow.com/q/47184919

http://stackoverflow.com/q/47218675
answer count: 4
score: 2
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/81387292
has comment: http://stackoverflow.com/comment/81386757
has body: I am learning to work with lists and I've had the thought of how do I delete a list that has any foreign number or letter? Let's suppose I have a list: [['c', 'b', 'a', 'd', 'a'], ['c', 'd', 'a', 'a', 'b'], ['d', 'a', 'a', 'c', 'b'], ['d', 'a', 'c', 'a', 'b'], ['a', 'c', 'a', 'b', 'd'], ['d', 'c', 'b', 'a', 'a'], ['d', 'c', 'b', 'a', 'a'], ['a', 'a', 't', 'j', 'a']] and I want to delete the list with "t" and "j" (the last list). I want to say "if there are values other than "0", "1", "2" or "3", then delete the list" but I am not sure how to do that. I know that there are operators like "any" and "all" but is there an equivalent to "other"? so far I've tried for item in listt: if any(('a','b','c','d')) not in item: data.remove(item) But this removes lists that ONLY contain foreign items I need it to remove all foreign characters (128 ascii characters or more) apart form a b c and d
has answer: http://stackoverflow.com/a/47218807
has answer: http://stackoverflow.com/a/47218915
has answer: http://stackoverflow.com/a/47218805
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47218801
upvote count: 2
accepted answer: http://stackoverflow.com/a/47218805
has comment: http://stackoverflow.com/comment/81386851
downvote count: 0
has title: Deleting lists with foreign number of letter
has answer: http://stackoverflow.com/a/47218801
tagged with: python

http://stackoverflow.com/comment/81202687
has text: `__L = []` and `self.__L = []` ouch same variable name but one is class-variable the other is instance variable...
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47126257
type: Comment

http://stackoverflow.com/a/47069916
has comment: http://stackoverflow.com/comment/81117529
has comment: http://stackoverflow.com/comment/81117410
has comment: http://stackoverflow.com/comment/81116760
has comment: http://stackoverflow.com/comment/81179077
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81114914
type: Answer
answers question: http://stackoverflow.com/q/47068125
has comment: http://stackoverflow.com/comment/81114854
has comment: http://stackoverflow.com/comment/81120864
has comment: http://stackoverflow.com/comment/81117575
has comment: http://stackoverflow.com/comment/81119821
accepted answer of: http://stackoverflow.com/q/47068125
has body: Give it a try. If you wanna get all the data from that table, you can have it running the script. import csv import requests outfile = open("table_data.csv","a",newline='') writer = csv.writer(outfile) writer.writerow(["n","m","y","u"]) req = requests.get('http://www.nhl.com/stats/rest/skaters?isAggregate=true&amp;reportType=basic&amp;isGame=true&amp;reportName=skatersummary&amp;sort=[{%22property%22:%22shots%22,%22direction%22:%22DESC%22}]&amp;cayenneExp=gameDate%3E=%222017-10-20%22%20and%20gameDate%3C=%222017-10-31%22%20and%20gameTypeId=2') data = req.json()['data'] for item in data: Player = item['playerName'] Pos = item['playerPositionCode'] GP = item['gamesPlayed'] G = item['goals'] A = item['assists'] P = item['points'] Plus_Minus = item['plusMinus'] PIM = item['penaltyMinutes'] PPG = item['ppGoals'] PPP = item['ppPoints'] SHG = item['shGoals'] SHP = item['shPoints'] GWG = item['gameWinningGoals'] OTG = item['otGoals'] S_down = item['shots'] S_per = item['shootingPctg'] TOI = item['timeOnIcePerGame'] Shifts = item['shiftsPerGame'] FOW = item['faceoffWinPctg'] print(Player,Pos,GP,G,A,P,Plus_Minus,PIM,PPG,PPP,SHG,SHP,GWG,OTG,S_down,S_per,TOI,Shifts,FOW) writer.writerow([Player,Pos,GP,G,A,P,Plus_Minus,PIM,PPG,PPP,SHG,SHP,GWG,OTG,S_down,S_per,TOI,Shifts,FOW]) outfile.close() Partial results: Brent Burns D 6 0 5 5 -3 4 0 3 0 0 0 0 31 0.0 1458.8333 29.0 0.0 Max Pacioretty L 5 3 0 3 0 4 0 0 1 1 0 0 29 0.1034 1240.8 26.2 0.0 Phil Kessel R 6 2 4 6 -1 4 0 4 0 0 2 2 27 0.074 1044.3333 21.5 0.3333 Jakub Voracek R 5 2 4 6 2 8 0 0 0 0 0 0 26 0.0769 1191.2 25.4 1.0 John Carlson D 5 0 3 3 -3 2 0 1 0 0 0 0 25 0.0 1686.2 29.4 0.0 Evgeny Kuznetsov C 5 3 1 4 -1 6 0 1 0 0 1 0 24 0.125 1138.4 20.2 0.3703
downvote count: 0
has comment: http://stackoverflow.com/comment/81178660
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81117626
has comment: http://stackoverflow.com/comment/81119516
has comment: http://stackoverflow.com/comment/81180547

http://stackoverflow.com/comment/81286948
type: QuestionComment
has text: I mean, the other option is to use a bash loop to run it `while true; do python file.py; sleep 5; done`, though it also means that trying to clean exit will also restart the bot, so you'd have to interrupt the loop to kill the bot...
comment on: http://stackoverflow.com/q/47167062
type: Comment
score: 1

http://stackoverflow.com/q/47091987
has answer: http://stackoverflow.com/a/47092090
has answer: http://stackoverflow.com/a/47092382
tagged with: python
has body: I'm doing some practice in Hackerrank for Python 3 learning. In the task Most Common you are given a string which contains only lowercase English characters and you need to find the top three most common characters in that string. I met some questions. My solution for this problem is below: #!/bin/python3 import sys if __name__ == "__main__": s = input().strip() ch_dict = {} for ch in s: if ch in ch_dict : ch_dict[ch] +=1 else: ch_dict[ch] = 1 result = sorted(ch_dict.items(),key=lambda d:d[1],reverse=True) for i in result: if i[1] != 1: print(" ".join(map(str,i))) When I test this code in local environment, it works! But in online test, it may fail! For this input: aabbbccde I submit a lot of times, sometimes get right answer like this: b 3 a 2 c 2 and can also get this: b 3 c 2 a 2 It seems like the sort can be unstable ? OR what's matter whit my code ? OR is something wrong in Hackerrank environment ? How can i guarantee my output?
tagged with: sorting
linked to: http://stackoverflow.com/q/15479928
answer count: 6
tagged with: dictionary
downvote count: 1
has comment: http://stackoverflow.com/comment/81133819
has answer: http://stackoverflow.com/a/47092201
possible better answer: http://stackoverflow.com/a/47092080
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1915376
score: 3
has comment: http://stackoverflow.com/comment/82618683
has comment: http://stackoverflow.com/comment/81134018
favorite count: 0
has title: Python Sorting Dictionary by values can be unstable? (in Hackerrank)
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/47094301
has answer: http://stackoverflow.com/a/47092080
has comment: http://stackoverflow.com/comment/81133724
has comment: http://stackoverflow.com/comment/81135332
accepted answer: http://stackoverflow.com/a/47092382
has answer: http://stackoverflow.com/a/47092129

http://stackoverflow.com/q/47116259
downvote count: 0
tagged with: keras
accepted answer: http://stackoverflow.com/a/47116281
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47116281
score: 3
tagged with: python
type: Question
has title: Does keras save_weights() function overwrite previous weights?
upvote count: 3
answer count: 1
has body: I just want to confirm if the save_weights() function in keras defaults to overwriting a previous weights file if the weight file already exists? For example, if I train my neural net for 10 epochs, save the weights to 'myweights.h5' via save_weights, and then I load those weights and train it for another 10 epochs and then save the weights to 'myweights.h5' again, will the first 10 epoch's weights get erased and now I'll have new weights from after 20 epochs? I looked at the documentation at https://keras.io/getting-started/faq/#savingloading-only-a-models-weights but it didn't specify whether it overwrites the old file or not. Some searching on google seems to say that it doesn't default to overwriting the older weights, but those are older threads and probably for older versions of keras.

scipy
tags question: http://stackoverflow.com/q/47187841
tags question: http://stackoverflow.com/q/47130957
tags question: http://stackoverflow.com/q/47110254
tags question: http://stackoverflow.com/q/47089749
tags question: http://stackoverflow.com/q/47094382
tags question: http://stackoverflow.com/q/47151464
tags question: http://stackoverflow.com/q/47136369
tags question: http://stackoverflow.com/q/47217357
tags question: http://stackoverflow.com/q/47107328
tags question: http://stackoverflow.com/q/47101515
tags question: http://stackoverflow.com/q/47178793
tags question: http://stackoverflow.com/q/47142496
tags question: http://stackoverflow.com/q/47188932
tags question: http://stackoverflow.com/q/47172758
tags question: http://stackoverflow.com/q/47136595
tags question: http://stackoverflow.com/q/47100559
tags question: http://stackoverflow.com/q/47072143
tags question: http://stackoverflow.com/q/47069303
tags question: http://stackoverflow.com/q/47140842
tags question: http://stackoverflow.com/q/47104869
tags question: http://stackoverflow.com/q/47071345
tags question: http://stackoverflow.com/q/47122461
tags question: http://stackoverflow.com/q/47139515
tags question: http://stackoverflow.com/q/47220535
type: Tag
tags question: http://stackoverflow.com/q/47110284
tags question: http://stackoverflow.com/q/47094705
tags question: http://stackoverflow.com/q/47109031
tags question: http://stackoverflow.com/q/47213443
tags question: http://stackoverflow.com/q/47080928
tags question: http://stackoverflow.com/q/47115996
tag name: scipy
tags question: http://stackoverflow.com/q/47184148
tags question: http://stackoverflow.com/q/47100679
tags question: http://stackoverflow.com/q/47084045
tags question: http://stackoverflow.com/q/47085975
tags question: http://stackoverflow.com/q/47197748
tags question: http://stackoverflow.com/q/47126055
tags question: http://stackoverflow.com/q/47130141
tags question: http://stackoverflow.com/q/47159199
tags question: http://stackoverflow.com/q/47202182
tags question: http://stackoverflow.com/q/47128535
tags question: http://stackoverflow.com/q/47087109
tags question: http://stackoverflow.com/q/47113979
tags question: http://stackoverflow.com/q/47108803
tags question: http://stackoverflow.com/q/47067443
tags question: http://stackoverflow.com/q/47149050
tags question: http://stackoverflow.com/q/47208838
tags question: http://stackoverflow.com/q/47116977
tags question: http://stackoverflow.com/q/47138394
tags question: http://stackoverflow.com/q/47148803
tags question: http://stackoverflow.com/q/47207311
tags question: http://stackoverflow.com/q/47129329

http://stackoverflow.com/comment/81230751
has text: I have not put an underscore in `AUTOINCREMENT`, have you added that in when you copied it over?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47140412

http://stackoverflow.com/a/47822768
has body: I don't know if this is an option for your case, but I would suggest that, instead of obfuscating the existing ID field, you could add another unique field to the model: a UUIDField. This way, you could pass the 'uuid' to the serializer instead of the 'id', and then use the 'uuid' for the lookup (because it's guaranteed to also be unique). This way, you are not revealing the volume of your data, while still being able to perform your queries. You should be careful about adding a unique field to an existing model though. Fortunately, there's an example about precisely adding a UUIDField to an existing model in the django docs. Hope this helps!
type: Answer
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47181946
answers question: http://stackoverflow.com/q/47181946

http://stackoverflow.com/q/47187841
downvote count: 0
score: 1
upvote count: 1
tagged with: lambda
has title: Python optimization indexed sum using sympy lambdify and scipy
favorite count: 0
accepted answer: http://stackoverflow.com/a/47208090
type: Question
linked to: http://stackoverflow.com/q/34115233
type: AnsweredQuestion
tagged with: python
tagged with: scipy
has answer: http://stackoverflow.com/a/47208090
tagged with: sympy
has body: I am kind of looking for a mixed solution of the proposed answer of this thread. The first code snippet is using a more symbolic way, which I am after with the property of the second code snippet where the number of variables change. So something close to this where number of variables n can change. from sympy import * from scipy.optimize import minimize from sympy.utilities.lambdify import lambdify x, i, n = symbols("x i n") n = 10 func = Sum((Indexed('x',i)-3)/(1+0.2)**i,(i,1,n)) my_func = lambdify((x, i, n), func) def my_func_v(x): return my_func(*tuple(x)) results = minimize(my_func_v, np.zeros(n)) Any ideas?
answer count: 1

http://stackoverflow.com/a/47173779
has comment: http://stackoverflow.com/comment/81298211
has body: I think you need unstack + reset_index for reshape data: #create `MultiIndex` DataFrame df = pd.read_excel('HowItIs.xlsx', header=[0,1], index_col=[0]) #print (df) #get names for new columns values a, b = df.columns.names d = {'level_2':'Category', 'Section Subheading':'Mesurement_Period_Week', 'SECTION TITLE':'Mesurement_Period'} fin_order = ['Section_Title','Section_Subheading','Category','Mesurement_Period', 'Mesurement_Period_Week','Value'] df = (df.unstack() .reset_index(name='Value') .rename(columns=d) .sort_values(['Category','Mesurement_Period','Mesurement_Period_Week']) .assign(Section_Title = a, Section_Subheading=b) .reset_index(drop=True) [fin_order] ) print (df.head()) Section_Title Section_Subheading Category Mesurement_Period \ 0 SECTION TITLE Section Subheading Apples FY15 P03 Dec Count 1 SECTION TITLE Section Subheading Apples FY15 P03 Dec Count 2 SECTION TITLE Section Subheading Apples FY15 P03 Dec Count 3 SECTION TITLE Section Subheading Apples FY15 P03 Dec Count 4 SECTION TITLE Section Subheading Apples FY15 P03 Dec Weight Mesurement_Period_Week Value 0 W1 53 1 W2 53 2 W3 53 3 W4 53 4 W1 2120 Last if need increment each value in Value column per groups: df['Value'] += df.groupby(['Category','Mesurement_Period']).cumcount() print (df.head()) Section_Title Section_Subheading Category Mesurement_Period \ 0 SECTION TITLE Section Subheading Apples FY15 P03 Dec Count 1 SECTION TITLE Section Subheading Apples FY15 P03 Dec Count 2 SECTION TITLE Section Subheading Apples FY15 P03 Dec Count 3 SECTION TITLE Section Subheading Apples FY15 P03 Dec Count 4 SECTION TITLE Section Subheading Apples FY15 P03 Dec Weight Mesurement_Period_Week Value 0 W1 53 1 W2 54 2 W3 55 3 W4 56 4 W1 2120
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81297785
has comment: http://stackoverflow.com/comment/81298597
has comment: http://stackoverflow.com/comment/81321687
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81297998
answers question: http://stackoverflow.com/q/47173631
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81298195
accepted answer of: http://stackoverflow.com/q/47173631

http://stackoverflow.com/comment/81241491
has text: Which laptop is this?
score: 0
comment on: http://stackoverflow.com/q/47145604
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81297684
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47165892
has text: Interesting, I will give it a try and report back :)
type: Comment

message-queue
type: Tag
tags question: http://stackoverflow.com/q/47185422
tag name: message-queue

http://stackoverflow.com/a/47191303
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47191224
has comment: http://stackoverflow.com/comment/81332072
type: Answer
has body: Indentation matters in Python: import os import sys print('Current working directory (CWD) is:', os.getcwd()) confcwd = input('Confirm intended CWD by enerting: ') if confcwd == os.getcwd(): print ("CWD confirmed.") else: print ("ERROR! Unable to verify CWD.") exit()
downvote count: 0

http://stackoverflow.com/comment/81199833
comment on: http://stackoverflow.com/a/47122261
type: Comment
has text: @DeepSpace how can I add up those trues/falses in the list? The way you suggested just gives me my original data frame? Why does it do that?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81189780
score: 0
comment on: http://stackoverflow.com/q/47119868
type: Comment
has text: Can you run the commands interactively and check the output? Both login and sendmail give fairly descriptive output.
type: QuestionComment

http://stackoverflow.com/q/47147780
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47147821
tagged with: python
tagged with: boto3
tagged with: amazon-web-services
has title: "start_instances() only accepts keyword arguments" error in AWS EC2 Boto3
type: AnsweredQuestion
score: 2
upvote count: 3
tagged with: amazon-ec2
has answer: http://stackoverflow.com/a/47147821
has body: I'm trying to start an EC2 instance using boto3. When I execute the below code it works fine import boto3 ec2client = boto3.client('ec2') class StartInstances: def start_ec_instances(self): response = ec2client.start_instances(InstanceIds=['i-XXXXXXXXXX']) return StartInstances().start_ec_instances() But when I run the code below I get import boto3 ec2client = boto3.client('ec2') class StartInstances: def start_ec_instances(self, instanceid): response = ec2client.start_instances(instanceid) return StartInstances().start_ec_instances('InstanceIds=[\'i-XXXXXXXXXX\']') Traceback (most recent call last): File "/Users/xxx/PycharmProjects/ctm-scripting-utils/ec2/start_instances.py", line 25, in StartInstances().start_ec_instances("InstanceIds=[\'i-XXXXXXXXXX\']") File "/Users/xxx/PycharmProjects/ctm-scripting-utils/ec2/start_instances.py", line 11, in start_ec_instances response = ec2client.start_instances(instanceids) File "/Users/xxx/Library/Python/3.6/lib/python/site-packages/botocore/client.py", line 310, in _api_call "%s() only accepts keyword arguments." % py_operation_name) TypeError: start_instances() only accepts keyword arguments.
answer count: 1
downvote count: 1

http://stackoverflow.com/q/47098198
tagged with: python
has answer: http://stackoverflow.com/a/47098690
has title: My Django dont show anything
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81146152
linked to: http://stackoverflow.com/q/47095388
type: Question
type: UnansweredQuestion
has body: Thank you very much guys! that issue has solved!(Here is my old post Django name 'admin' is not defined ) but it show nothing. I want to show the content in header.html & home.html here is the code personal/views from django.shortcuts import render def index(request): return render(request,'personal/templates/personal/home.html') And here are the code of home and header {% extends "personal/header.html" %} {% block content %} Hey welcome to my very first project by Django :D {% include "personal/includes/"htmlsnippet.html %} {% endblock %} header: Harry-Phuc Coi {% block content %} {% endblock %} And here is my path my path
tagged with: django

http://stackoverflow.com/q/47078768
tagged with: pandas
has answer: http://stackoverflow.com/a/47079056
has title: Elegant way to add an array on each column dataframe pandas
downvote count: 1
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47078805
tagged with: python
score: -1
has body: I would like to add a 1D array on each column of a pandas dataframe. Exemple : import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(0,100,size=(4, 4)), columns=list('ABCD')) s = np.random.randint(0,100,size=(4, 1)) Is there a way more elegant way than : for col in df.columns: df[col] = df[col] + s Obviously, summ = df + s doesn't work
has comment: http://stackoverflow.com/comment/81107348
answer count: 2

http://stackoverflow.com/q/47175020
answer count: 4
has comment: http://stackoverflow.com/comment/81299540
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47175406
has comment: http://stackoverflow.com/comment/81299252
has answer: http://stackoverflow.com/a/47181645
possible better answer: http://stackoverflow.com/a/47175126
downvote count: 3
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/44478164
score: -2
accepted answer: http://stackoverflow.com/a/47175108
has title: How can I write a python method to compute all combinations of a dict of lists?
duplicate of: http://stackoverflow.com/q/15211568
tagged with: python
linked to: http://stackoverflow.com/q/12935194
tagged with: dictionary
has answer: http://stackoverflow.com/a/47175126
has answer: http://stackoverflow.com/a/47175108
has body: I have an arbitrary python dictionary x such that the values of each key is itself a list. Here is an example: x = {"first_name": ["Mahmoud", "Pei-chi"], "second_name": ["Abadi", "Yao"]} Given x I would like write a method that computes a list of dictionaries such that each dictionary has the same keys as x but the values are each combination of individual list element. So in this case, the result should be: [{"first_name": "Mahmoud", "second_name": "Abadi"}, {"first_name": "Mahmoud", "second_name": "Yao"}, {"first_name": "Pei-chi", "second_name": "Abadi"}, {"first_name": "Pei-chi", "second_name": "Yao"}] How can I do it? The dictionary x may have any arbitrary number of keys with arbitrary names.

http://stackoverflow.com/q/47072014
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81099278
tagged with: python
tagged with: plot
has title: 3D plots in python using cubic Interpolation and given data on three axes in List format
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81100967
tagged with: matplotlib
linked to: http://stackoverflow.com/q/46844655
type: Question
duplicate of: http://stackoverflow.com/q/46844655
linked to: http://stackoverflow.com/q/44355270
has body: I am using following code to plot a surface from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator import numpy as np fig = plt.figure() ax = fig.gca(projection='3d') # Make data. X = np.arange(-5, 5, 0.25) xlen = len(X) Y = np.arange(-5, 5, 0.25) ylen = len(Y) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) # Create an empty array of strings with the same shape as the meshgrid, and # populate it with two colors in a checkerboard pattern. colortuple = ('y', 'b') colors = np.empty(X.shape, dtype=str) for y in range(ylen): for x in range(xlen): colors[x, y] = colortuple[(x + y) % len(colortuple)] # Plot the surface with face colors taken from the array we made. surf = ax.plot_surface(X, Y, Z, facecolors=colors, linewidth=0) # Customize the z axis. ax.set_zlim(-1, 1) ax.w_zaxis.set_major_locator(LinearLocator(6)) plt.show() Now I have three variables in List Form. X = [-0.105625455, -0.174359608, -0.105873346, -0.20576805399999998, -0.120525806, -0.28215594, -0.093060075, -0.14982578900000001, -0.119486435, -0.151960108, -0.10104339999999999, -0.23913942, -0.106686264, -0.16127649300000002] Y = [0.177165099, -0.029949987, 0.145072897, -0.038238821, 0.157384682, -0.035901472000000004, 0.138161626, -0.037059772000000005, 0.151773712, -0.04529447, 0.14621367300000002, -0.036671638, 0.16619656800000002, -0.032974679] Z = [0.166806127, 0.20898661899999998, 0.187877354, 0.226367115, 0.18765406699999998, 0.22494885899999997, 0.19316028699999999, 0.212110438, 0.204398195, 0.22953668100000002, 0.205943133, 0.231321515, 0.194322528, 0.246532118] I want to plot these on some beautiful 3D surface. In MATLAB I just used 3 lines to plot and it all plotted beautifully. Can someone guide me how to plot this beautifully on a 3D surface with cubic Interpolation I tried to replace my variables with this and converted all Variables to ndarray and then took a mesh grid but still did not w…

http://stackoverflow.com/a/47085426
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47085373
has body: This works: import numpy as np x = np.arange(12).reshape(3,4) y = np.array( [[1,1,1,1], [2,2,2,2]] ) z = x[y[:, np.newaxis], np.arange(4)[np.newaxis, :]] print(z) Result: [[[ 4 5 6 7]] [[ 8 9 10 11]]]
type: Answer
has comment: http://stackoverflow.com/comment/81120293
has comment: http://stackoverflow.com/comment/81120308
accepted answer of: http://stackoverflow.com/q/47085373
score: 0

http://stackoverflow.com/a/58343259
has comment: http://stackoverflow.com/comment/103041894
has body: fruits = ['apple', 'banana', 'kiwi', 'peach', 'watermelon','dog','cat'] def in_bisect(t, word): # cheks if the word is in the list if word not in t: return False if len(t)==0: return False low=0 high=len(fruits) #loop will when the value is found while True: mid=(low + high)//2 if t[mid]==word: return mid,t[mid] if word in t[:mid] : high=mid else: low=mid def test(): print(in_bisect(fruits, 'apple')) print(in_bisect(fruits, 'banana')) print(in_bisect(fruits, 'kiwi')) print(in_bisect(fruits, 'dog')) print(in_bisect(fruits, 'ewf') ) print(in_bisect(fruits, 'banana')) return 'Test completed sucssfuly' print (test())
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47196917

http://stackoverflow.com/comment/81356035
score: 2
comment on: http://stackoverflow.com/a/47203627
type: Comment
has text: This is not equivalent because here you create sets from the items in `good` and `bad` instead of the ids, as in `g.ticket.id`. That's why the list comprehension is needed, as can be seen in the already existing answer. Also you are not casting to set, you are creating new sets using the `set()` function.
type: AnswerComment

http://stackoverflow.com/q/47199121
tagged with: python-2.7
tagged with: linux
tagged with: importerror
accepted answer: http://stackoverflow.com/a/47199467
has comment: http://stackoverflow.com/comment/81347139
answer count: 3
has answer: http://stackoverflow.com/a/47199467
score: 0
possible better answer: http://stackoverflow.com/a/47199265
has answer: http://stackoverflow.com/a/47199265
downvote count: 1
favorite count: 0
has body: I downloaded the source code of python 2.7.14 and built it and installed it on linux ( Red Hat 4.8.5-16 ). I have earlier installed python-magic and requests libraries. Now when I try to import modules installed using pip, I get this: $ python2 Python 2.7.14 (default, Nov 9 2017, 09:05:45) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import magic Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named magic &gt;&gt;&gt; import requests Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named requests while similar thing works perfectly fine in python 2.7.5 (default with the RHEL system) $ python Python 2.7.5 (default, May 3 2017, 07:55:04) [GCC 4.8.5 20150623 (Red Hat 4.8.5-14)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import magic &gt;&gt;&gt; import requests &gt;&gt;&gt; Am I missing any configuration step here?
type: Question
tagged with: python-import
has answer: http://stackoverflow.com/a/47199229
has title: Cannot import any modules (installed used pip) in python 2.7.14
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/81308582
comment on: http://stackoverflow.com/a/47175245
score: 0
type: AnswerComment
type: Comment
has text: The main reason I'm asking this question is to get answer for this question: https://stackoverflow.com/questions/47154689/setup-python-app-module-missing-on-cpanel-vps

http://stackoverflow.com/comment/81522520
comment on: http://stackoverflow.com/a/47280363
type: Comment
type: AnswerComment
has text: What the hell. I get the same error, but I have a x86_64 architecture. I'll see if I can find a solution, but at the moment I'm pretty much clueless on why it won't work^^
score: 0

http://stackoverflow.com/q/47087919
tagged with: ajax
type: Question
has title: How to protect Django's views functions from directly calling through browser url
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5100539
has body: I want to protect my functions from directly calling through browser url. May be it is possible through CSRF. But I am not able to do it. In front end side I am using ajax to call this function. So, the call should only be possible through ajax but not directly from browser url. My javascript code is function getData(table,id){ data = [] $.ajax({ type: "POST", url: "getData", dataType:'json', data:{'tableName':table}, success: function(result) { for(var i=0;i&lt;result.length;i++){ for (var key in result[i]){ val = result[i][key] if (data.indexOf(val)==-1){ data.push(val) } } } $( "#"+id ).autocomplete({ source: data }); } }); } so I am calling this function in javascript. In urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^getData', views.getData, name='getData'), ] In Views.py def getData(request): tableName = request.POST.get('tableName') tableName = 'colleges' cursor = connection.cursor() query = "select * from "+tableName cursor.execute(query) columnDesc = cursor.description result=[dict(zip([col[0] for col in columnDesc], row)) for row in cursor.fetchall()] return HttpResponse(json.dumps(result), content_type="application/json") So, when i am calling through web browser url directly like... http://localhost/shikshapp/getData I am getting response from my views and i am able to see the data.. So, how can i protect this kind of call.. when the token is not there... But this call should be accessible through ajax
has comment: http://stackoverflow.com/comment/81126771
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81129447
has answer: http://stackoverflow.com/a/47092222
score: 0
tagged with: django
answer count: 1
tagged with: django-csrf

http://stackoverflow.com/q/47100959
has body: I've been recently working with or-tools and now I'm playing around with break intervals for CVRP using python. What I want to achieve is creating N number of breaks for a vehicle and place on top a XOR constraint, so one and only one of the breaks is performed. I've create the breaks and a list of the performed values of each break interval as follow: for i in xrange(len(self.breaks)): name_break = "break_{}".format(i) start_min, start_max, duration_break = breaks[i] optional_break = True break_intervals.append(solver.FixedDurationIntervalVar(start_min, start_max, duration_break, optional_break, name_break)) performed_values.add(break_intervals[i].PerformedExpr()) Then I use the syntactic sugar of solver to add a constraint using the SumEquality method and add the break intervals to the vehicle: solver.Add(solver.SumEquality(performed_values, 1)) routing.GetDimensionOrDie("Time").SetBreakIntervalsOfVehicle(break_intervals, 0) The constraint works perfectly when there is only one break in breaks (which is the same as change the value of 'optional_break' to False). Problem is when I add a new break in breaks, there is no solution. Assignment is empty. The solution is feasible, with the first break I get an assignment and adding one optional break shouldn't return a null assignment. I've followed pretty much this cpp tutorial, except for the break interval constraints and minimize time variables statements. Perhaps I'm missing something. Do you have any insight about the issue?
tagged with: or-tools
tagged with: constraint-programming
tagged with: python
has title: Implement XOR statement for break_intervals on or-tools using Python
answer count: 0
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/58798988
type: Answer
score: -1
upvote count: 0
has body: i encounter this problem before and the solution can be by adding manually something in the file and delete it .
downvote count: 1
answers question: http://stackoverflow.com/q/47199300

http://stackoverflow.com/comment/81156363
has text: it's a NameError
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47102764

http://stackoverflow.com/q/47176947
tagged with: buildozer
upvote count: 9
tagged with: android
tagged with: kivy
has answer: http://stackoverflow.com/a/66264619
has body: im very noob still in python and kivy. Anyways, I'm making a simple android app, which just showing a single label. Now I'm trying to package that python file to an apk via buildozer. The buildozer init works, but then the buildozer -v android debug doesnt and give an error Unknown command/target android_old. Anyone can help me resolve this? Thanks
favorite count: 0
score: 9
type: Question
has title: Buildozer Unknown command/target android_old
answer count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/75695006

http://stackoverflow.com/q/47139958
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81233183
score: 6
tagged with: python
tagged with: qtableview
has answer: http://stackoverflow.com/a/47142279
upvote count: 6
accepted answer: http://stackoverflow.com/a/47142279
has body: There is a table: tab=QTableView() sti=QStandardItemModel(parent=None) sti.appendRow([QStandardItem(str(1)),QStandardItem(str(2)),QStandardItem(str(3)),QStandardItem(str(4))]) tab.setModel(sti) tab.setEditTriggers(QAbstractItemView.NoEditTriggers) There is a button: btn=QPushButton('Press', self) btn.clicked.connect(self.on_clicked) btn.resize(btn.sizeHint()) Task: How can I insert button btn in the table cell insert of QStandardItem(str(4))? There is a method .setCellWidget() of class QTableWidget for it, but I inherited from QTableView. If I'll use QTableWidget I'll can't use private method .setModel()
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81233038
tagged with: qwidget
tagged with: pyqt
has title: PyQt. How to insert a widget in a QTableView
answer count: 1
downvote count: 0
tagged with: pyqt5

http://stackoverflow.com/comment/81288551
score: 1
comment on: http://stackoverflow.com/a/47169253
type: Comment
has text: @python_newbie as in, that replaces your whole `scenarios = [[]]*1000; for i in range(10000): ...` loop
type: AnswerComment

http://stackoverflow.com/comment/81166849
type: Comment
has text: Do you want to calculate after a user fill the `first_year_estimate and second_year_estimate ` ?
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47108278

http://stackoverflow.com/q/47215520
tagged with: python-import
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47215688
has title: Python modules are installed but can't be imported
type: Question
tagged with: python
tagged with: import
has body: I'm a novice Python user and slowly going crazy over following problem: I installed a number of modules for Python 2.7 (win34) using pip. I confirmed that the modules are indeed installed. Then I import the modules in a .py script (using Atom editor): import numpy as np import pandas as pd import fiona import geopandas as gpd import shapely There is no problem with importing the first two modules, but fiona, geopandas and shapely trigger errors: ImportError: No module named geopandas I suspect the issue may be related to the different directories where the modules are stored, but not sure how to address this. I saw several similar questions, but no answers..Grateful for any tips!
tagged with: python-2.7
score: 0

http://stackoverflow.com/q/47106773
has comment: http://stackoverflow.com/comment/81164474
type: UnansweredQuestion
has title: tqdm makes map async
tagged with: python
has comment: http://stackoverflow.com/comment/81164186
tagged with: tqdm
has comment: http://stackoverflow.com/comment/81164910
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81164507
has body: I wanted to add a progress bar to my map functions. But after adding tqdm to them, they seem to be asynchronous. The coding: print("---&gt; First…") res = map(func1, tqdm(res)) print("---&gt; Second…") res = map(func2, tqdm(res)) The output on terminal: ---&gt; First… 0%| | 0/607 [00:00&lt;?, ?it/s] ---&gt; Second… 100%|████████████████████████████████████████| 607/607 [00:01&lt;00:00, 382.76it/s] 607it [00:01, 382.76it/s] Is there any chance to get them synchronous?
tagged with: asynchronous
has comment: http://stackoverflow.com/comment/81164340
has comment: http://stackoverflow.com/comment/81164310
type: Question

http://stackoverflow.com/comment/81231632
type: AnswerComment
has text: It still returns 'None' when I try, print(request.POST.get('dataObj')
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47140859

http://stackoverflow.com/comment/81282407
score: 0
comment on: http://stackoverflow.com/q/47146905
has text: @wim yes I could sample twice, but this is really a waste of resources - I'd rather keep the general question without the edit and ask a separate one focusing on my particular case.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47129403
possible better answer: http://stackoverflow.com/a/47129496
tagged with: list
has comment: http://stackoverflow.com/comment/81208817
has title: Functions repeats more times than expected Python
answer count: 3
has answer: http://stackoverflow.com/a/47129629
upvote count: 2
tagged with: arrays
downvote count: 0
accepted answer: http://stackoverflow.com/a/47129509
has body: I am doing a python exercise where I need to make an array with x and y. Here are the instructions: """ Write a program which takes 2 digits, X,Y as input and generates a 2- dimensional array. The element value in the i-th row and j-th column of the array should be i*j. **Note** : i=0,1.., X-1; j=0,1,¡­Y-1. **Example** Suppose the following inputs are given to the program: 3,5 Then, the output of the program should be: [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] """ Here is my code: def myfunc(x,y): newlist = [] answer = 0 icounter = 0 jcounter = 0 myarr = [] for i in range(0, x+1): for j in range(0,y+1): answer = jcounter * icounter newlist.append(answer) jcounter += 1 jcounter = 0 icounter += 1 myarr.append(newlist) newlist = [] print(myarr) myfunc(3,5) When I run it, my answer is this: [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8], [0, 3, 6, 9, 12]] It should only have 3 lists inside, but it has 4. Does anyone know why? Any help is appreciated!
has comment: http://stackoverflow.com/comment/81208814
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47129496
has comment: http://stackoverflow.com/comment/81209014
has comment: http://stackoverflow.com/comment/81208964
has answer: http://stackoverflow.com/a/47129509
tagged with: python
has comment: http://stackoverflow.com/comment/81208835
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/81311349
has text: @Miki How should I get an `IplImage` then? Or is the whole `IplImage` data structure obsolete?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47179464

http://stackoverflow.com/a/47188160
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
has body: Bahrom's suggestion in the comments would work, but the fastest way might be to use a regular expression. Compile a regex that searches for things that aren't spaces: import re pattern = re.compile(r"[^ \t\n]") Then run it on every foo: is_all_spaces = re.search(pattern, foo) is None This should be plenty fast, but remember to always measure. (The timeit module may useful.) In particular, measure whether this checking-for-whitespace part of your code takes any significant amount of time compared to, say, the XML parsing part. Why the double negative, you ask? Looking for things that aren't spaces, instead of just writing a regex that matches a bunch of spaces (r"^[ \t\n]*$"), means that we're not creating and destroying a match object if the string is all spaces. If that's the most common case, it could be slightly faster. How much faster? I couldn't tell you - I haven't measured it.
has comment: http://stackoverflow.com/comment/81328108
type: Answer
answers question: http://stackoverflow.com/q/47187975
accepted answer of: http://stackoverflow.com/q/47187975

http://stackoverflow.com/comment/127506373
type: QuestionComment
has text: maybe you can unset the `The Chinese Language Pack`
comment on: http://stackoverflow.com/q/47129007
score: 1
type: Comment

http://stackoverflow.com/comment/81352910
score: 0
has text: Check out `glob`...
comment on: http://stackoverflow.com/q/47202265
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81175521
score: 0
type: Comment
type: AnswerComment
has text: @Wen now in 100% what was about it :)
comment on: http://stackoverflow.com/a/47112698

http://stackoverflow.com/comment/81385996
has text: That is not the complete code. We cannot run it. The indentation looks bad too. Please provide a [mcve].
comment on: http://stackoverflow.com/q/47214685
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/47213292
accepted answer of: http://stackoverflow.com/q/47213130
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47213130
score: 1
has body: You have at least to store your random outputs and only then you can add them... E.G. total = 0 for x in range(rand): rnum = random.randint(1,9) print (rnum, end=' ') total = total + rnum print('Total: %s' %total)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81352572
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47200367
type: Comment
has text: now seems the two files are communicating, but getting error on line 19 in main.py and line 15 and 29 in dupi.py

path
tags question: http://stackoverflow.com/q/47217055
tags question: http://stackoverflow.com/q/47120247
tags question: http://stackoverflow.com/q/47153226
type: Tag
tags question: http://stackoverflow.com/q/47207872
tags question: http://stackoverflow.com/q/47136376
tag name: path

http://stackoverflow.com/q/47144329
has title: Find largest substring of numbers within a tolerance level
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81241623
has comment: http://stackoverflow.com/comment/81248144
has comment: http://stackoverflow.com/comment/81240139
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81241840
favorite count: 0
has comment: http://stackoverflow.com/comment/81243282
type: Question
tagged with: longest-substring
has body: I have the following input: a tolerance level T Number of numbers N N numbers The task is to find the longest period within those N numbers such that they are within the tolerance level. More precisely, given a left and a right bound of a substring l and r and two distinct elements a1 and a2 between the two bounds, it must hold that |a1 - a1| &lt;= T. How can I do this in an efficient way? My approach is: def getLength(T, N, numbers): max_length = 1 for i in range(0, N-1): start = numbers[i] numlist = [start] for j in range(i+1, N): end = numbers[j] numlist.append(end) if (max(numlist) - min(numlist)) &gt; T: break if (j-i+1) &gt; max_length: max_length = j-i+1 return max_length EDIT: To make it clear. The code works as expected. However, it is not efficient enough. I would like to do it more efficiently.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47149126
has comment: http://stackoverflow.com/comment/81241332
has comment: http://stackoverflow.com/comment/81244472
tagged with: arrays
downvote count: 0

anaconda
tags question: http://stackoverflow.com/q/47089821
tags question: http://stackoverflow.com/q/47077433
tags question: http://stackoverflow.com/q/47100854
tags question: http://stackoverflow.com/q/47191297
tags question: http://stackoverflow.com/q/47110834
tags question: http://stackoverflow.com/q/47194211
type: Tag
tags question: http://stackoverflow.com/q/47118935
tags question: http://stackoverflow.com/q/47173080
tags question: http://stackoverflow.com/q/47115720
tags question: http://stackoverflow.com/q/47142323
tag name: anaconda
tags question: http://stackoverflow.com/q/47138248
tags question: http://stackoverflow.com/q/47098049
tags question: http://stackoverflow.com/q/47141263
tags question: http://stackoverflow.com/q/47099166
tags question: http://stackoverflow.com/q/47082351
tags question: http://stackoverflow.com/q/47219904
tags question: http://stackoverflow.com/q/47082416
tags question: http://stackoverflow.com/q/47107009
tags question: http://stackoverflow.com/q/47126186
tags question: http://stackoverflow.com/q/47090958
tags question: http://stackoverflow.com/q/47100346
tags question: http://stackoverflow.com/q/47101566
tags question: http://stackoverflow.com/q/47202607
tags question: http://stackoverflow.com/q/47182284
tags question: http://stackoverflow.com/q/47125132
tags question: http://stackoverflow.com/q/47109343
tags question: http://stackoverflow.com/q/47101182
tags question: http://stackoverflow.com/q/47185393
tags question: http://stackoverflow.com/q/47123353
tags question: http://stackoverflow.com/q/47092416
tags question: http://stackoverflow.com/q/47189009
tags question: http://stackoverflow.com/q/47090535

http://stackoverflow.com/a/58183781
has body: If anyone's interested in saving and restoring the whole session, here's a snippet I'm using that you might find useful: import os import dill from google.colab import drive backup_dir = 'drive/My Drive/colab_sessions' backup_file = 'notebook_env.db' backup_path = backup_dir + '/' + backup_file def init_drive(): # create directory if not exist drive.mount('drive') if not os.path.exists(backup_dir): !mkdir backup_dir def restart_kernel(): os._exit(00) def save_session(): init_drive() dill.dump_session(backup_path) def load_session(): init_drive() dill.load_session(backup_path) Edit: Works fine until your session size is not too big. You need to check if it works for you..
score: 0
answers question: http://stackoverflow.com/q/47194063
type: Answer

http://stackoverflow.com/comment/81214720
comment on: http://stackoverflow.com/q/47132438
has text: Removing the spaces isn't hard, but if you could answer PoGibas' questions, it would make answering much easier
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81267416
comment on: http://stackoverflow.com/q/47158071
type: Comment
score: 0
has text: @Fomalhaut: What processing do you need to do with the CSV data? Do you need to hold the large chunks of the file in memory, or can you process line-by-line? Depends entirely on your application, but since you're not just counting lines, perhaps a database would be better than a flat file.
type: QuestionComment

http://stackoverflow.com/comment/81523685
has text: thanks for filling the issue. I thought it was something wrong with my system.
comment on: http://stackoverflow.com/a/47278404
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/81544440
score: 0
type: Comment
has text: I will award you the bounty when I try one of the solutions (i.e. tomorrow) and verify that it works.
type: AnswerComment
comment on: http://stackoverflow.com/a/47273983

http://stackoverflow.com/a/47184672
answers question: http://stackoverflow.com/q/47184192
has comment: http://stackoverflow.com/comment/81322041
has body: Based on the comments, I guess you want to avoid defining the same method twice. You could do that with Mixins (in a complex hierarchy) or just another base class. As for your question on whether or not you can avoid writing @property: You can leave it out, but then you would have to write braces behind your method namegetter(). Example using a base class: class NamedEntity(object): def __init__(self, name): self.name = name @property def namegetter(self): return 'get the name of {}'.format(self.name) class Animal(NamedEntity): pass class Cat(Animal): def __init__(self, food, name): super(Cat, self).__init__(name) self.food = food self.sound = 'meow' class Dog(Animal): def __init__(self, food, name): super(Dog, self).__init__(name) self.food = food self.space = 'park' class Person(NamedEntity): def __init__(self, name): super(Person, self).__init__(name) self.dog = Dog("dog's food", "dog's name" ) self.cat = Cat("dog's food", "cat's name") if __name__ == '__main__': john = Person('john') print(john.name) #john print(john.dog.name) #dog's name print(john.cat.name) #cat's name print(john.dog.namegetter) #get the name of dog print(john.cat.namegetter) #get the name of cat print(john.namegetter) #get the name of john In a more complex example, you could use a Mixin instead, this would basically change the way you inherit from it in the class definition: class NamedEntityMixin(object): def __init__(self, name): self.name = name @property def namegetter(self): return 'get the name of {}'.format(self.name) class Animal(NamedEntityMixin, object): # Imagine object being another parent class with additional properties and methods pass class Cat(Animal): def __init__(self, food, name): super(Cat, self).__init__(name) self.food = food self.sound = 'meow' class Dog(Animal): def __init__(self, food, name): super(Dog, self).__init__(name) self.food = food self.space = 'park' class Person(NamedEntityMixin, object): # Imagine object being another parent class with additional propert…
score: 1
has comment: http://stackoverflow.com/comment/81341183
has comment: http://stackoverflow.com/comment/81375751
has comment: http://stackoverflow.com/comment/81390544
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81321805
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47184192
type: Answer
has comment: http://stackoverflow.com/comment/81341110

http://stackoverflow.com/q/47213823
has comment: http://stackoverflow.com/comment/81377504
has comment: http://stackoverflow.com/comment/81378980
has comment: http://stackoverflow.com/comment/81379127
linked to: http://stackoverflow.com/q/27318290
has comment: http://stackoverflow.com/comment/81377594
has comment: http://stackoverflow.com/comment/81378797
tagged with: memory
tagged with: multiprocess
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81377390
has comment: http://stackoverflow.com/comment/81377772
has title: Memory issue with multiprocessing in Python
answer count: 0
has comment: http://stackoverflow.com/comment/81378638
upvote count: 2
has body: I am trying to use my other cores in my python program. And the following is the basic structure/logic of my code: import multiprocessing as mp import pandas as pd import gc def multiprocess_RUN(param): result = Analysis_Obj.run(param) return result class Analysis_Obj(): def __init__(self, filename): self.DF = pd.read_csv(filename) return def run_Analysis(self, param): # Multi-core option pool = mp.Pool(processes=1) run_result = pool.map(multiprocess_RUN, [self, param]) # Normal option run_result = self.run(param) return run_result def run(self, param): # Let's say I have written a function to count the frequency of 'param' in the target file result = count(self.DF, param) return result if __name__ == "__main__": files = ['file1.csv', 'file2.csv'] params = [1,2,3,4] results = [] for i in range(0,len(files)): analysis = Analysis_Obj(files[i]) for j in range(0,len(params)): result = analysis.run_Analysis(params[j]) results.append(result) del result del analysis gc.collect() If I comment out the 'Multi-core option' and run the 'Normal option' everything runs fine. But even if I run the 'Multi-core option' with processes=1 I get a Memory Error when my for loop starts on the 2nd file. I have deliberately set it up so that I create and delete an Analysis object in each for loop, so that the file that has been processed will be cleared from memory. Clearly this hasn't worked. Advice of how to get around this would be very much appreciated. Cheers EDIT: Here is the error message I have in the terminal: Exception in thread Thread-7: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 754, in run self.__target(*self.__args, **self.__kwargs) File "/usr/lib/python2.7/multiprocessing/pool.py", line 326, in _handle_workers pool._maintain_pool() File "/usr/lib/python2.7/multiprocessing/pool.py", line 230, in _maintain_pool self._repopulate_pool() File "/usr/lib/python2.7/m…
has comment: http://stackoverflow.com/comment/81378534
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81378902
has comment: http://stackoverflow.com/comment/81378975
has comment: http://stackoverflow.com/comment/81379461
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81377137
has comment: http://stackoverflow.com/comment/81377393
score: 2
has comment: http://stackoverflow.com/comment/81377456

http://stackoverflow.com/a/47103125
answers question: http://stackoverflow.com/q/47102954
has body: It is not necessary to play with file i/o There's an easier way import numpy as np import pandas as pd mypath='your path here' Y=np.zeros(2508, dtype=int) convert to a pandas dataframe U=pd.DataFrame(Y, columns=['zeros']) U.head() zeros 0 0 1 0 2 0 3 0 4 0 save directly to .csv U.to_csv(mypath+'U.csv')
score: 0
type: Answer

http://stackoverflow.com/a/47128435
answers question: http://stackoverflow.com/q/47128095
has comment: http://stackoverflow.com/comment/81206935
has body: In pandas we usually do this .. l=[] for _, df1 in county_df.groupby('STNAME'): l.append(df1) You code error county_df['STNAME']=state) should be county_df['STNAME']==state) And base on my understanding county_df.loc[county_df['STNAME']==state,:]
has comment: http://stackoverflow.com/comment/81206949
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81206991
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47135019
has comment: http://stackoverflow.com/comment/81221099
type: Answer
answers question: http://stackoverflow.com/q/47134556
score: 8
has comment: http://stackoverflow.com/comment/81220901
has comment: http://stackoverflow.com/comment/81220855
downvote count: 0
has body: Either you can take query string inside Lambda like below, var result = event["queryStringParameters"]['queryStringParam1'] According to your API URL, var postcode = event["queryStringParameters"]['postcode'] var house = event["queryStringParameters"]['house'] or you can use body mapping template in the integration request section and get request body and query strings. Construct a new JSON at body mapping template, which will have data from request body and query string. As we are adding body mapping template your business logic will get the JSON we have constructed at body mapping template. Inside body mapping template to get query string please do , $input.params('querystringkey') For example inside body mapping template, #set($inputRoot = $input.path('$')) { "firstName" : "$input.path('$.firstName')", "lastName" : "$input.path('$.lastName')" "language" : "$input.params('$.language')" } Please read https://aws.amazon.com/blogs/compute/tag/mapping-templates/ for more details on body mapping template
upvote count: 8

http://stackoverflow.com/comment/81080993
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47065329
has text: Maybe `df.plot.scatter(x='a', y='b', c='value', s=df['value']*200)`
type: Comment

http://stackoverflow.com/a/47099533
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: spark is the object you want. Not sc. The fact that you get an error means you need to get or create the session, which you already are. SparkSession.builder.getOrCreate() I'm not sure you need a SQLContext. spark.sql() or spark.read() are the dataset entry points. First bullet here on Spark docs SparkSession is now the new entry point of Spark that replaces the old SQLContext and HiveContext If you need an sc variable at all, that is sc = spark.sparkContext
accepted answer of: http://stackoverflow.com/q/47099332
score: 3
type: Answer
answers question: http://stackoverflow.com/q/47099332
has comment: http://stackoverflow.com/comment/81149783

http://stackoverflow.com/a/47122168
type: Answer
score: 2
has body: Because .jpg is not lossless image format. If you want to save image as is, save as lossless image format like bmp, tiff, etc.
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47122088

http://stackoverflow.com/q/47084454
tagged with: google-chrome
has comment: http://stackoverflow.com/comment/81126912
has comment: http://stackoverflow.com/comment/81120072
favorite count: 0
has comment: http://stackoverflow.com/comment/81150283
type: Question
tagged with: robotframework
type: UnansweredQuestion
has title: How to open a Chrome application into Robot using selenium2Library
tagged with: python
has comment: http://stackoverflow.com/comment/81159558
has comment: http://stackoverflow.com/comment/81148962
has body: I'm trying to open our windows Chrome exe in Robot using selenium2Library. I've tried creating a webdriver using Create Webdriver with this code but it's not working. ${options}= Evaluate sys.modules['selenium.webdriver'].ChromeOptions() sys, selenium.webdriver.chrome.options ${options.add_extension}= Set_Variable path/to/extension Create WebDriver Chrome chrome_options=${options} In Python I do this... and it launches my app in selenium. from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.action_chains import ActionChains def chromedr(): chrome_options = Options() chrome_options.binary_location = 'C:/Program Files (x86)/InTouch Health/Carestation/Carestation.exe' driver = webdriver.Chrome('C:/Program Files (x86)/InTouch Health/Carestation/chromedriver.exe', chrome_options=chrome_options) return driver How can I do this in Robot/selenium2Library? I was able to launch the Application using this code: ${options}= Evaluate sys.modules['selenium.webdriver'].ChromeOptions() sys, selenium.webdriver Create WebDriver Chrome my_alias chrome_options=${options} executable_path=C:/Program Files (x86)/Myapp.exe
has answer: http://stackoverflow.com/a/47130809
answer count: 1
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/81137937
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81126777

http://stackoverflow.com/q/47175817
has title: Extract strings that start with ${ and end with }
has comment: http://stackoverflow.com/comment/81300839
has comment: http://stackoverflow.com/comment/81300768
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/81301399
has comment: http://stackoverflow.com/comment/81300877
has comment: http://stackoverflow.com/comment/81301040
upvote count: 1
has comment: http://stackoverflow.com/comment/81301684
favorite count: 0
has comment: http://stackoverflow.com/comment/81302102
type: Question
accepted answer: http://stackoverflow.com/a/47188152
has comment: http://stackoverflow.com/comment/81300946
has answer: http://stackoverflow.com/a/47188152
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81300747
has comment: http://stackoverflow.com/comment/81300799
tagged with: regex
has comment: http://stackoverflow.com/comment/81302947
has body: I'm trying to extract the strings from a file that start with ${ and ends with } using Python. I am using the code below to do so, but I don't get the expected result. My input file looks like this: Click ${SWIFT_TAB} Click ${SEARCH_SWIFT_CODE} and I want to get a list as below: ${SWIFT_TAB} ${SEARCH_SWIFT_CODE} My current code looks like this: def findStringFromFile(file): import os,re with open(file) as f: ans = [] for line in f: matches = re.findall(r'\b\${\S+}\b', line) ans.extend(matches) print (ans) I am expecting a list of strings that start with ${ and end with }, but all I currently get is an empty list.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81300755

http://stackoverflow.com/comment/81198201
comment on: http://stackoverflow.com/a/47124040
score: 0
has text: The best part about this answer is that it works for a million values just as well as it would work for [-1, 0, 1].
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81167953
type: Comment
has text: Hmm, what error? Do you campare `date` with `dates` and `datetime`s with `datetime`?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47108675

http://stackoverflow.com/q/47148683
has answer: http://stackoverflow.com/a/71090558
tagged with: pandas
has title: Pandas explode list of dictionaries into rows
has answer: http://stackoverflow.com/a/47149584
downvote count: 0
has answer: http://stackoverflow.com/a/47149068
has comment: http://stackoverflow.com/comment/81270235
has answer: http://stackoverflow.com/a/47149289
upvote count: 10
has answer: http://stackoverflow.com/a/76255657
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/71090558
score: 10
tagged with: dataframe
tagged with: python
answer count: 6
has body: Have this: items, name 0 { [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], this } 1 { [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], that } But would like to have the list of dictionary objects exploded into (flattened?) into actual rows like this: a, b, name 0 { 2, 1, this} 1 { 4, 3, this} 0 { 2, 1, that} 1 { 4, 3, that} Having been trying to use melt but with no luck, any ideas? suggestions? Data to produce DataFrame: data = {'items': [[{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}]], 'name': ['this', 'that']}
has answer: http://stackoverflow.com/a/47149275
has comment: http://stackoverflow.com/comment/81247810
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81270224
accepted answer: http://stackoverflow.com/a/47149584

http://stackoverflow.com/q/47162048
accepted answer: http://stackoverflow.com/a/47162326
has title: Numpy array apply a function only to some elements
has comment: http://stackoverflow.com/comment/81273999
has answer: http://stackoverflow.com/a/47162326
favorite count: 0
type: Question
upvote count: 4
tagged with: numpy
tagged with: multidimensional-array
tagged with: exp
answer count: 1
downvote count: 0
tagged with: python
score: 4
has body: I have a numpy array let's say that has a shape (10,10) for example. Now i want to apply np.exp() to this array, but just to some specific elements that satisfy a condition. For example i want to apply np.exp to all the elements that are not 0 or 1. Is there a way to do that without using for loop that iterate on each element of the array?
has comment: http://stackoverflow.com/comment/84726950
type: AnsweredQuestion

http://stackoverflow.com/a/47217140
has comment: http://stackoverflow.com/comment/81383914
has body: Try this: bool(re.match(r'[ACKMF]\d+\.?\d?(I|II|III|IV|V)(/(I|II|III|IV|V))*$', test_str)) I also changed the start of your expression from (A|C|K|M|F){1} to [ACKMF] Characters between square brackets form a character class. Such a class matches one character out of a range of options. You most commonly see them with ranges like [A-Z0-9] to match capital letters or digits, but you can also add individual characters, as I've done for your regex.
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47217046
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81384357
answers question: http://stackoverflow.com/q/47217046

http://stackoverflow.com/comment/81119157
has text: ah ha got it. I just realized I forgot to add {% block content %} {% endblock %} in my base. So stupid, lol
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47084099

http://stackoverflow.com/comment/81196534
score: 0
type: AnswerComment
has text: thank you for your help but I tried your version and the returned result is not the one I'm looking for, I think there is still an error, would you mind helping?? @gammazero
comment on: http://stackoverflow.com/a/47112681
type: Comment

http://stackoverflow.com/comment/81254847
type: QuestionComment
score: 0
has text: Is `access-class` always present in *each* block?
comment on: http://stackoverflow.com/q/47152236
type: Comment

http://stackoverflow.com/q/47140580
has comment: http://stackoverflow.com/comment/81230986
has body: I am currently working with a Windows XP Computer at my school. My question is on how to find the exact path variable to run Python in the command line. I have tried multiple directories but they all keep displaying "'python' is not recognized as an internal or external command, operable program or batch file." Is there an easy way to find this?
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81231076
has answer: http://stackoverflow.com/a/47140802
accepted answer: http://stackoverflow.com/a/47140802
tagged with: windows-xp
tagged with: python
tagged with: cmd
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: python-2.7
has title: Python Path Directory

http://stackoverflow.com/q/47117625
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47117729
has answer: http://stackoverflow.com/a/47117648
answer count: 2
has body: I want to split any matrix (most likely will be a 3x4) into two. One part will be the left hand and then the right hand - only the last column. [[1,0,0,4], [[1,0,0], [4, [1,0,0,2], ---&gt; A= [1,0,0], B = 2, [4,3,1,6]] [4,3,1]] 6] Is there a way to do this in python and assign then as A and B? Thank you!
tagged with: matrix
has title: Splitting a Matrix in Python
downvote count: 1
accepted answer: http://stackoverflow.com/a/47117648
favorite count: 0
possible better answer: http://stackoverflow.com/a/47117729
type: Question
upvote count: 0
tagged with: gaussian
tagged with: python
score: -1

http://stackoverflow.com/comment/81272905
type: Comment
comment on: http://stackoverflow.com/a/47151808
score: 0
type: AnswerComment
has text: No, they've been around.

http://stackoverflow.com/q/47066239
type: Question
answer count: 0
has body: In the official example of "embedding mayavi in QT" http://docs.enthought.com/mayavi/mayavi/auto/example_qt_embedding.html#example-qt-embedding, the main code says: if __name__ == "__main__": # Don't create a new QApplication, it would unhook the Events # set by Traits on the existing QApplication. Simply use the # '.instance()' method to retrieve the existing one. app = QtGui.QApplication.instance() ... I am confused by this. What is the "existing QApplication"? This is the first line of the actual code, there was no existing QApplication. Also, what are the "Events set by Traits on the existing QApplication"?
has comment: http://stackoverflow.com/comment/81114643
tagged with: python
type: UnansweredQuestion
tagged with: traits
tagged with: traitsui
tagged with: pyqt
score: 0
has comment: http://stackoverflow.com/comment/81115149
tagged with: mayavi
has comment: http://stackoverflow.com/comment/81114940
has title: "Do not create a new QApplication" when embedding mayavi in QT?

http://stackoverflow.com/a/47163309
has body: You can just use list slicing: n = int(input("Enter a integer: ")) new_integer = int(str(n)[::-1]) note that use of eval is highly discouraged as it leaves your system susceptible to code injection.
upvote count: 5
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/81276348
type: Answer
answers question: http://stackoverflow.com/q/47163284

http://stackoverflow.com/a/47209945
type: Answer
upvote count: 6
type: AcceptedAnswer
has body: Simplest Way Using pd.str.get_dummies dct = { 'Anemones &amp; allies': ['Carnivore'], 'Ants, bees &amp; wasps': ['Omnivore', 'Herbivore', 'Nectar', 'Insects', 'Parasite'], 'Beetles &amp; bugs': ['Herbivore', 'Carnivore', 'Nectar', 'Insects'], 'Birds': ['Carnivore'], 'Fishes': ['Carnivore', 'Plankton or Particles'] } pd.Series(dct).str.join('|').str.get_dummies() Carnivore Herbivore Insects Nectar Omnivore Parasite Plankton or Particles Anemones &amp; allies 1 0 0 0 0 0 0 Ants, bees &amp; wasps 0 1 1 1 1 1 0 Beetles &amp; bugs 1 1 1 1 0 0 0 Birds 1 0 0 0 0 0 0 Fishes 1 0 0 0 0 0 1 More Complicated But probably recommended from sklearn.preprocessing import MultiLabelBinarizer dct = { 'Anemones &amp; allies': ['Carnivore'], 'Ants, bees &amp; wasps': ['Omnivore', 'Herbivore', 'Nectar', 'Insects', 'Parasite'], 'Beetles &amp; bugs': ['Herbivore', 'Carnivore', 'Nectar', 'Insects'], 'Birds': ['Carnivore'], 'Fishes': ['Carnivore', 'Plankton or Particles'] } s = pd.Series(dct) mlb = MultiLabelBinarizer() d = mlb.fit_transform(s) c = mlb.classes_ pd.DataFrame(d, s.index, c) Carnivore Herbivore Insects Nectar Omnivore Parasite Plankton or Particles Anemones &amp; allies 1 0 0 0 0 0 0 Ants, bees &amp; wasps 0 1 1 1 1 1 0 Beetles &amp; bugs 1 1 1 1 0 0 0 Birds 1 0 0 0 0 0 0 Fishes 1 0 0 0 0 0 1
score: 6
downvote count: 0
has comment: http://stackoverflow.com/comment/81369425
answers question: http://stackoverflow.com/q/47209847
has comment: http://stackoverflow.com/comment/81369492
accepted answer of: http://stackoverflow.com/q/47209847

http://stackoverflow.com/comment/81347587
comment on: http://stackoverflow.com/q/47199248
type: Comment
score: 0
has text: Did you identify the encoding of csv file?
type: QuestionComment

http://stackoverflow.com/comment/81198130
comment on: http://stackoverflow.com/a/47124032
type: AnswerComment
has text: If you run `Sum0` and then `Sum1`, this might not work. Since `df` is overwritten and value check is done on all of `df`
score: 3
type: Comment

http://stackoverflow.com/comment/81332072
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47191303
has text: Thank you, I am learning! A bonus Q: how can I make the user entered path case insensitive, i.e., `C:\a\b\` == `c:\a\b`?
type: AnswerComment

http://stackoverflow.com/q/47188581
has body: Suppose I have a project organized as follows: ProjectRoot/ __init__.py test.py A/ __init__.py a_test.py B/ __init__.py b_test.py And suppose that a_test depends on b_test. So the source code is relatively simple: # # a_test.py # from B.b_test import b_test_class class a_test_class: def func(self): print("a_test_class") b_instance = b_test_class() b_instance.func() if __name__ == "__main__": a_instance = a_test_class() a_instance.func() # # b_test.py # class b_test_class: def func(self): print("b_test_class") # # test.py # from A.a_test import a_test_class if __name__ == "__main__": a_instance = a_test_class() a_instance.func() As long as I launch test.py script, everything works as intended. Python loads all modules without any troubles and executes them. Now the question comes: how do I launch a_test.py without having test.py? So, basically, what I want to achieve is to cd into projectRoot/A and execute a_test.py. This results in getting ImportError: No module named 'B' Currently I've been able to create a project with following structure: ProjectRoot/ customLibModuleA/ ... customLibModuleB/ ... mainApp.py And what I want to be able to create is following: ProjectRoot/ customLibModuleA/ #custom protocol implementation ... customLibModuleB/ #custom logging functions ... application1/ #server ... application2/ #client ... How do I expected to manage complex projects? Any good references to project structuring manuals and styleguides are welcome.
type: Question
tagged with: python-import
accepted answer: http://stackoverflow.com/a/47251370
has title: Understanding python import system and project structuring
answer count: 1
has answer: http://stackoverflow.com/a/47251370
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/81099383
type: Comment
has text: you would need some sort of interprocess communication. giving the two process have the same process father, I guess it's feasable.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47075479

http://stackoverflow.com/comment/81097756
comment on: http://stackoverflow.com/q/47072916
type: Comment
has text: Loops are usually efficient (unless you do **lots** of iterations). The culprit is probably `Get_Y`.
type: QuestionComment
score: 0

http://stackoverflow.com/a/47177092
type: Answer
answers question: http://stackoverflow.com/q/47166174
score: 0
has body: You can do this as done below from subprocess import Popen from subprocess import Popen, CREATE_NEW_CONSOLE,PIPE,STDOUT import subprocess command="powershell.exe get-disk" #This will open the command in a new console proc=Popen(command,creationflags=CREATE_NEW_CONSOLE,stdout=subprocess.PIPE) read_stdout=[] for lines in proc.stdout.readlines(): read_stdout.append(lines) print read_stdout

http://stackoverflow.com/comment/81300244
has text: When I go to the directory and run python -c "import sigtools" I see no error. So I assume it works... right??
comment on: http://stackoverflow.com/q/47175250
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/95844802
type: Comment
type: AnswerComment
score: 1
has text: This worked for me -- thank you! But I do not understand the first paragraph of the answer. I ran my app using the `heroku local` command, which you'd think would apply the correct environment, but it doesn't populate `os.environ` as I expect.
comment on: http://stackoverflow.com/a/47117972

http://stackoverflow.com/q/47188328
upvote count: 1
has answer: http://stackoverflow.com/a/47189334
has body: I have to send multiple data through Python from a DB allocated in the client to the Main DB in the server, what's the best solution to this? I currently have my web server up and functioning, I can fill my DB locally, but I don't really know how to do it remotely, I'm using Python in my hardware. Here is what I have so far in the client: import mysql.connector cnx = mysql.connector.connect(user='user', password='pass', host='url?', database='db') #im able to enter with this cursor = cnx.cursor() query = ("INSERT INTO IGNORE table " "(id,date,son) " "VALUES( (%s,%s,%s)") for row in data: #ive already extracted data from the other DB cursor.execute(query, (row[0],row[1],row[2])) which yeilds an error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IGNORE table(id,date,son) VALUES (number, '2017-11-09 14:33:15', 18.987)' at line 1
has answer: http://stackoverflow.com/a/47201818
has comment: http://stackoverflow.com/comment/81326001
accepted answer: http://stackoverflow.com/a/47201818
has title: Extract data from client database
favorite count: 0
has comment: http://stackoverflow.com/comment/81326053
type: Question
type: AnsweredQuestion
score: 0
downvote count: 1
tagged with: python
tagged with: mysql
has comment: http://stackoverflow.com/comment/81327529
possible better answer: http://stackoverflow.com/a/47189334
answer count: 2

http://stackoverflow.com/q/47075300
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47077999
score: 5
upvote count: 5
has title: Processing a large SQL query in Python using Pandas?
tagged with: bigdata
tagged with: python
tagged with: postgresql
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47077999
downvote count: 0
tagged with: pandas
answer count: 1
tagged with: dataframe
has body: I would like to back-test some data which will be pulled from a Postgres database, using Python, psycopg2 and Pandas. The data which will be pulled from Postgres is very large (over 10Gbs) - my system will not be able to hold this in terms of RAM, even if a Pandas data frame is able to store this much data. As an overview, I expect my Python program will need to do the following: 1: Connect to a remote (LAN based) Postgres database server 2: Run a basic select query against a database table 3: Store the result of the query in a Pandas data frame 4: Perform calculation operations on the data within the Pandas data frame 5: Write the result of these operations back to an existing table within the database. I expect the data that will be returned in step 2 will be very large. Is it possible to stream the result of a large query to a Pandas data frame, so that my Python script can process data in smaller chunks, say of 1gb, as an example? Any ideas, suggestions or resources you can point to, on how best to do this, or if I am not approaching this in the right way, will be much appreciated, and I am sure that this will be useful to others going forward. Thank you.
has comment: http://stackoverflow.com/comment/81103548
has comment: http://stackoverflow.com/comment/81104296

http://stackoverflow.com/q/47148524
type: AnsweredQuestion
tagged with: list
has body: I imported the csv into python, and now I have a nested list that looks like this. data = [['header1,'header2','header3'...], [1,2,3...], [a,b,c...] ] So the first line is the header row, and the rest are the actual data. I want to sort the data using the following code: data = sorted(data, key = lambda x: x[1]) #-&gt; sorts data by the 2nd header But when I do this, the code sorts the header row too, and my header is at the middle of somewhere in my data. How can I preserve my header in the first row, while sorting the rest? I've seen some code that does this by using operator.itemgetter(), but I don't want to do this way
has title: python - sort csv files by columns, while preserving the header
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81247132
accepted answer: http://stackoverflow.com/a/47148624
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47148593
has answer: http://stackoverflow.com/a/47148624
answer count: 2
has answer: http://stackoverflow.com/a/47148593
has comment: http://stackoverflow.com/comment/81247125
downvote count: 0
upvote count: 1
tagged with: sorting
favorite count: 0
type: Question

http://stackoverflow.com/a/47175955
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47175484
has comment: http://stackoverflow.com/comment/81301193
has body: l=[11.7, 8.5, 11.3, 11.2, 10.8, 1.05, 11.7, 8.5, 11.3, 11.2, 10.8, 1.05] print(l) ul=[l[0]] l2=[] i=0 flag = True while i &lt; len(l)-1: x = 100.0 * l[i+1] / l[i] - 100 if x &gt; (-5): if l[i] not in l2: l2.append(l[i]) if l[i+1] not in l2: l2.append(l[i+1]) else: l2=[] if i !=0: ul.append(l[i+1]) if l2: if l2 not in ul: ul.append(l2) i+=1 print(ul) Output 1 [11.7, 8.5, 11.3, 11.2, 10.8, 1.05] [11.7, [8.5, 11.3, 11.2, 10.8], 1.05] Output 2 [11.7, 8.5, 11.3, 11.2, 10.8, 1.05, 11.7, 8.5, 11.3, 11.2, 10.8, 1.05] [11.7, [8.5, 11.3, 11.2, 10.8], 1.05, [1.05, 11.7], 8.5, [8.5, 11.3, 11.2, 10.8], 1.05] The items 8.5 and 1.05 are present in both lists; I think that's expected. Additional details 0 11.7 -27.350427350427353 1 8.5 32.94117647058823 2 11.3 -0.8849557522123916 3 11.2 -3.5714285714285694 4 10.8 -90.27777777777777 5 1.05 1014.2857142857142 6 11.7 -27.350427350427353 7 8.5 32.94117647058823 8 11.3 -0.8849557522123916 9 11.2 -3.5714285714285694 10 10.8 -90.27777777777777
type: Answer
downvote count: 0

http://stackoverflow.com/comment/81129393
type: AnswerComment
has text: So there has to be another problem, give me some time.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47090005

http://stackoverflow.com/comment/81304070
type: QuestionComment
comment on: http://stackoverflow.com/q/47177493
score: 0
has text: How are the lines and pt stored?
type: Comment

http://stackoverflow.com/comment/81247681
score: 2
type: Comment
comment on: http://stackoverflow.com/a/47148740
type: AnswerComment
has text: I don't see a way to do this more succinctly with the current api. I could be wrong, but this is the best I can do.

http://stackoverflow.com/comment/81119865
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47085156
has text: Define "rod", "cutting". Give us a sample of list.
score: 1

http://stackoverflow.com/a/47207016
type: AcceptedAnswer
has body: Just reset the position to before the line, everytime it crosses the line, before rendering. Something like this: if char_x &gt;= background_line_x: char_x = background_line_x - 1 Repeat for all 4 boundaries and you're set
type: Answer
accepted answer of: http://stackoverflow.com/q/47206864
score: 0
answers question: http://stackoverflow.com/q/47206864

http://stackoverflow.com/q/47211782
has comment: http://stackoverflow.com/comment/81373046
accepted answer: http://stackoverflow.com/a/47211865
tagged with: set
has comment: http://stackoverflow.com/comment/81373148
tagged with: python
has title: Variable unintendedly being set
has answer: http://stackoverflow.com/a/47211865
type: Question
answer count: 2
has body: I am trying to move stuff round a screen. The pygame is just for easy text input. This is a very short bit of my code: import pygame pygame.init() sensitivity = 5 # How fast it moves rot=rot_speed = [0, 0] done=pause = False screen = pygame.display.set_mode((800, 450)) screen.fill((255,255,255)) pygame.display.flip() while not done: # ---------- Main program loop ---------- # for event in pygame.event.get(): # If they pressed a key if event.type == pygame.QUIT: # Did they click quit? done = True if event.type == pygame.KEYDOWN: # Has a key been pressed? type_key = 1 print("SENSITIVITY", sensitivity, rot_speed,".", rot) if event.key == pygame.K_w: # Up key pressed rot_speed[1] = sensitivity*-1 if event.key == pygame.K_s: # Down key pressed rot_speed[1] = sensitivity if event.key == pygame.K_a: # Left key pressed rot_speed[0] = sensitivity*-1 if event.key == pygame.K_d: # Right key pressed rot_speed[0] = sensitivity if event.key == pygame.K_SPACE: if pause == False: pause = True else: pause = False print("KEYS", sensitivity, rot_speed,".", rot) if pause == False: print("rot_speed", rot_speed) The problem I am having is that the variables rot and rot_speed are being set when I only try set rot_speed. Any ideas? When I didn't have the speed as lists and as individual variables it worked but I may have changed the code in some other ways. Put print statements around the setting of variables, it's very strange.
has comment: http://stackoverflow.com/comment/81373032
upvote count: 1
possible better answer: http://stackoverflow.com/a/47211872
tagged with: variables
downvote count: 1
has comment: http://stackoverflow.com/comment/81373089
has answer: http://stackoverflow.com/a/47211872
favorite count: 0
has comment: http://stackoverflow.com/comment/81373077
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81373034
tagged with: list

http://stackoverflow.com/comment/81112173
has text: Does the file/directory exist?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47081080

http://stackoverflow.com/q/47116425
type: AnsweredQuestion
score: 0
has body: I have written a script in Python 3.6 which queries API data to return a postal address from a zip code. The script is as follows: import requests import urllib.parse main_api = 'http://link.to.api_site/json?' key = 'AbCdEfGhIjKlMnOpQrStUvWxYz0123456789' address = '90210' url = main_api + urllib.parse.urlencode({'address':address, 'key':key}) json_data = requests.get(url).json() for result in json_data["results"][0]["address_components"]: print(result["long_name"]) The issue is have is the order the JSON data is given. When I run a query from the web browser the data is shown: { "results" : [ { "address_components" : [ { "long_name" : "90210", "short_name" : "90210", "types" : [ "postal_code" ] }, { "long_name" : "Beverly Hills", "short_name" : "Beverly Hills", "types" : [ "locality", "political" ] }, { "long_name" : "Los Angeles County", "short_name" : "Los Angeles County", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "California", "short_name" : "CA", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "United States", "short_name" : "US", "types" : [ "country", "political" ] } so when the For loop runs it returns the data in the following order: 90210 Beverly Hills Los Angeles County California United States What I would prefer is for the address to be printed out in a different order: Beverly Hills Los Angeles County California United States 90210 So question is, is there a way to change the order when the results of the For loop are printed out.
answer count: 2
has answer: http://stackoverflow.com/a/47116594
possible better answer: http://stackoverflow.com/a/47116505
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47116594
has title: Python 3 - print order of for loop result
tagged with: python
has answer: http://stackoverflow.com/a/47116505
has comment: http://stackoverflow.com/comment/81182905

http://stackoverflow.com/a/47129792
has body: tf.gather() makes slices only along one axis, so for your case tf.gather_nd() would work better. So it should be as following: # make a placeholder for indices of the outputs you will pick, # or make it constant if they won't change indices = tf.placeholder(tf.int32,[None,4]) conv1 = tf.layers.conv2d( inputs=input_layer, filters=4, kernel_size=[14, 14], padding="valid", activation=tf.nn.relu ) # select required outputs new_input = tf.gather_nd(conv,indices) # or you can hard-wire them, if they're constant new_input = tf.gather_nd(conv, [[0,0,0,0],[1,0,0,0]]) # then you need to reshape it back a proper size # as previous operation will return flattened list # (unless you slice raws, but not single outputs). # Depending what size you got and what you need, but possibly something like that: required_shape = [-1,10,10,4] new_input = tf.reshape(new_input,required_shape) # or instead of the constant array feed a tensor with new shape as well conv2 = tf.layers.conv2d( inputs=new_input, filters=16, kernel_size=[5, 5], padding="valid", activation=tf.nn.relu ) In case of gather_nd you can specify explicit elements of the array along each axis. There is a good example in the official documentation: indices = [[1]] params = [[['a0', 'b0'], ['c0', 'd0']], [['a1', 'b1'], ['c1', 'd1']]] output = [[['a1', 'b1'], ['c1', 'd1']]] indices = [[0, 1], [1, 0]] params = [[['a0', 'b0'], ['c0', 'd0']], [['a1', 'b1'], ['c1', 'd1']]] output = [['c0', 'd0'], ['a1', 'b1']] indices = [[0, 0, 1], [1, 0, 1]] params = [[['a0', 'b0'], ['c0', 'd0']], [['a1', 'b1'], ['c1', 'd1']]] output = ['b0', 'b1']
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47129156

http://stackoverflow.com/q/47147332
tagged with: python
has comment: http://stackoverflow.com/comment/81274055
has comment: http://stackoverflow.com/comment/81245081
has title: pandas: one-to-many operation on a dataframe
tagged with: cross-apply
type: Question
answer count: 2
type: UnansweredQuestion
has body: I have a pandas dataframe such that GROUP_ID USER_ID USER_NAME 0 65 50 ABC1 1 65 74 ABC2 2 69 71 ABC3 Let's say I have another dataframe df2 with just one record and subset of columns USER_ID USER_NAME 0 007 BOND What I want is to have a one-to-many relationship from df2 to df1 on the GROUP_ID so that GROUP_ID USER_ID USER_NAME 0 65 50 ABC1 1 65 007 BOND 2 65 74 ABC2 3 69 71 ABC3 4 69 007 BOND I suppose this is equivalent of a sql CROSS APPLY. As always, any help or guidance is appreciated
has answer: http://stackoverflow.com/a/47163429
score: 0
tagged with: one-to-many
tagged with: pandas
tagged with: join
has answer: http://stackoverflow.com/a/47147458

http://stackoverflow.com/a/47133461
accepted answer of: http://stackoverflow.com/q/47132665
score: 11
answers question: http://stackoverflow.com/q/47132665
type: Answer
upvote count: 11
type: AcceptedAnswer
has body: I'm going to assume here that both a and b are 1-D tensors. To get the cartesian product of the two, I would use a combination of tf.expand_dims and tf.tile: a = tf.constant([1,2,3]) b = tf.constant([4,5,6,7]) tile_a = tf.tile(tf.expand_dims(a, 1), [1, tf.shape(b)[0]]) tile_a = tf.expand_dims(tile_a, 2) tile_b = tf.tile(tf.expand_dims(b, 0), [tf.shape(a)[0], 1]) tile_b = tf.expand_dims(tile_b, 2) cartesian_product = tf.concat([tile_a, tile_b], axis=2) cart = tf.Session().run(cartesian_product) print(cart.shape) print(cart) You end up with a len(a) * len(b) * 2 tensor where each combination of the elements of a and b is represented in the last dimension.
downvote count: 0

http://stackoverflow.com/comment/81162529
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47104484
type: AnswerComment
has text: can we do a private chat?

http://stackoverflow.com/q/47129131
tagged with: pandas
has title: Python Pandas - Merge two Data Frame and Substring on columns
type: Question
score: 0
answer count: 2
has body: I have two data frames in Python like the following df1 CUSTOMER_KEY LAST_NAME FIRST_NAME 30 f2b6769129 97bb97bebc 46 ca0464878d e276539bc2 51 62f2905a7a 8dfabd6d61 57 21032ca3bc 1f7e5e0c6e 62 f7e7fdd8ce eb6cf4af99 64 f536998bbb 7fc39eacd1 80 6069198f63 d873a71620 99 0ba61a6f66 a6cf7af3eb 102 e8b579b776 c8048fd459 df2 CUSTOMER_KEY LAST_NAME FIRST_NAME 30 Arthur Anderson 46 Teresa Johns 51 Louise Hurwitz 57 Timothy Addy 62 Jeffery Wilson 64 Andres Tuller 80 Daniel Green 99 Frank Nader 102 Faith Young I want to join these two data frames on Customer_key (which i can do in Merge) and later concatenate on few columns from the data frame to form a new string in the result data frame. From the below dataframes the result that i am looking is as follows result_df CUSTOMER_KEY LAST_NAME FIRST_NAME 30 Artf2b676 And97bb97 46 Terca0464 Johe27653 Basically, substring(last_name,1,4) in df2 and substring(last_name,1,6) in df1 and concatenate those into the new column. Similarly other columns. How can i achieve this please. Thanks and Regards Bala
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47129189
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/47129254
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47129189
has answer: http://stackoverflow.com/a/47129254

http://stackoverflow.com/q/47143370
favorite count: 0
type: Question
has body: I'm trying to make a picture the url to the post the picture represents, and I must be doing something wrong, but I don't know what. I am getting this error when trying to visit the home page of my site. Error during template rendering In template .../home.html, error at line 48 Reverse for 'view_post' with keyword arguments '{'post_id': ''}' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/$'] and the code it showcases &lt;a href="{% url 'view_post' post_id=post.post_id %}"&gt;&lt;img src="media/{{ item.image }}"&gt;&lt;/a&gt; Also this is my view def view_post(request, post_id): post = get_object_or_404(Post,id=post_id) return render(request,'gram/view_post.html',{'post': post}) And url url(r'^post/(?P&lt;post_id&gt;[0-9]+)/$', views.view_post, name='view_post'), Thank you for your help.
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81236822
possible better answer: http://stackoverflow.com/a/47144319
answer count: 2
has answer: http://stackoverflow.com/a/47144319
score: 1
has title: Django no reverse match at /
downvote count: 0
accepted answer: http://stackoverflow.com/a/47143511
has comment: http://stackoverflow.com/comment/81244428
upvote count: 1
has answer: http://stackoverflow.com/a/47143511

http://stackoverflow.com/comment/81086597
type: QuestionComment
has text: and for the error its ""error 400"" for too much coments
score: 0
comment on: http://stackoverflow.com/q/47069054
type: Comment

http://stackoverflow.com/q/47154743
score: 0
tagged with: pandas
answer count: 1
has title: Concat two pivot table with different count of columns,in pandas
type: Question
has body: I have two pivot table with a distinct number of columns, and I need create one table with the value separated by commas in the cell but in the cell that not appear in the first table put 0. For example Table 1 1 3 4 a t1a1 t1a3 t1a4 b t1b1 t1b3 t1b4 Table 2 1 2 3 4 a t2a1 t2a2 t2a3 t2a4 b t2b1 t2b2 t2b3 t2b4 I want: 1 2 3 4 a (t1a1,t2a1) (0,t2a2) (t1a3,t2a3) (t1a4,t2a4) b (t1b1,t2b1) (0,t2b2) (t1b3,t2b3) (t1b4,t2b4) The function df = '(' + df1.astype(str) + ' , ' + df2.astype(str) + ')' print (df) Return 1 2 3 4 a (t1a1 , t2a1) NaN (t1a3 , t2a3) (t1a4 , t2a4) b (t1b1 , t2b1) NaN (t1b3 , t2b3) (t1b4 , t2b4) I work in Python with pandas library.
tagged with: pivot-table
tagged with: python
has answer: http://stackoverflow.com/a/47154792
accepted answer: http://stackoverflow.com/a/47154792
type: AnsweredQuestion

http://stackoverflow.com/q/47172373
has answer: http://stackoverflow.com/a/47172714
has comment: http://stackoverflow.com/comment/81294661
has title: Python: How can I manipulate csv data in a list?
type: UnansweredQuestion
has body: I have created a list which has the totality of all the data in the csv file. How do I seperately call upon data in rows and columns? For instance: **a, b ,c** **1** a1 b1 c1 **2** a2 b2 c2 How can I identify a single cell within the list?
tagged with: python
has comment: http://stackoverflow.com/comment/81294246
has comment: http://stackoverflow.com/comment/81294207
score: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81294356
has comment: http://stackoverflow.com/comment/81294484
answer count: 1
has comment: http://stackoverflow.com/comment/81294412
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/47178467
accepted answer of: http://stackoverflow.com/q/47153105
answers question: http://stackoverflow.com/q/47153105
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Here is the full solution of creating the table with borders. table = '' with open('result.csv') as csvFile: reader = csv.DictReader(csvFile, delimiter=',') table = ' {} '.format(''.join([' {} '.format(header) for header in reader.fieldnames])) for row in reader: table_row = ' ' for fn in reader.fieldnames: table_row += ' {} '.format(row[fn]) table_row += ' ' table += table_row html = """ html title Hi! Here is your data. %s Regards, Python 3.5 """ % table message = MIMEMultipart( "alternative", None, [MIMEText(html,'html')]) message['Subject'] = "Some stats via mail" message['From'] = 'a@abc.com' message['To'] = 'b@abc.com' sender = "a@abc.com" receivers = ['b@abc.com'] try: smtp_obj = smtplib.SMTP('mail.abc.com') smtp_obj.sendmail(sender, receivers, message.as_string()) print ("Successfully sent email") except SMTPException: print ("Error: unable to send email")
score: 1
type: Answer

pipeline
type: Tag
tag name: pipeline
tags question: http://stackoverflow.com/q/47068867

http://stackoverflow.com/comment/84354794
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47826361
score: 0
has text: How does this connect to GDAX in the first place? The socket is only connected to the localhost.

http://stackoverflow.com/comment/81262839
type: QuestionComment
has text: I'd go for the first "demo" from @WiktorStribiżew
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47156680

http://stackoverflow.com/q/47186145
tagged with: import
type: Question
has answer: http://stackoverflow.com/a/47186209
has title: How to import a python file with out of scope dependencies in iPython
tagged with: python
tagged with: ipython
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/3144089
has body: Using iPython inside a virtual env (python 2.7.13 and iPython 0.31.1) I am trying to test some code that I have written inside a directory as follows. Root Dir1 Dir2 NeedsTesting.py Dir3 Dir4 Dependency1.py Inside of NeedsTesting.py there is an import for Dependency1. When I am inside the Dir2 directory and try to import NeedsTesting I get the following error. ImportError: No module named Dependency1. When I got back up to root and try import NeedsTesting.py the error ImportError: No Module named NeedsTesting.py. When I try and call the file like from Dir1/Dir2 import NeedsTesting.py I get a syntax error pointing to the first / in the line. How can I make it so iPython can find modules within an entire project, not just the immediate level?
answer count: 1
tagged with: directory
has comment: http://stackoverflow.com/comment/81321658
accepted answer: http://stackoverflow.com/a/47186209

http://stackoverflow.com/comment/81259914
type: QuestionComment
comment on: http://stackoverflow.com/q/47155173
score: 0
has text: They get their IP-addresses via DHCP from the router?
type: Comment

http://stackoverflow.com/comment/81380586
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47215501
has text: Not intended, just looking for the highest single digit even number in st.
type: QuestionComment

http://stackoverflow.com/comment/81243648
comment on: http://stackoverflow.com/q/47146514
score: 0
type: Comment
type: QuestionComment
has text: With [`time.stftime`](https://docs.python.org/3/library/time.html#time.strftime), like what `logging` itself uses.

http://stackoverflow.com/comment/81387999
type: AnswerComment
comment on: http://stackoverflow.com/a/47217949
score: 0
type: Comment
has text: @PM2Ring I'm also working on a no-loop version, but it still takes a bit longer than his.

http://stackoverflow.com/comment/81306953
comment on: http://stackoverflow.com/q/47172108
score: 1
type: QuestionComment
has text: Did you try to install cuda as the error says?
type: Comment

http://stackoverflow.com/comment/81313206
has text: Will it only work for timestamps defined as unix timestamps? (like in my input data). Or will it also work for datetime strings defined as `2017-11-06 11:45:59.0`?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47181580
score: 0

http://stackoverflow.com/comment/81370220
type: QuestionComment
has text: Ah good point. Yes I checked those lines explicitly, and they are exactly identical down to variable naming. And yes same compile flags. FWIW I've rewritten my algorithm in a way that avoids this issue completely, but the new version is too different to shed any light on why the version posted here is so slow.
comment on: http://stackoverflow.com/q/47185721
score: 0
type: Comment

http://stackoverflow.com/a/47111471
has comment: http://stackoverflow.com/comment/81172873
has comment: http://stackoverflow.com/comment/81179450
has comment: http://stackoverflow.com/comment/81173688
has comment: http://stackoverflow.com/comment/81172987
has comment: http://stackoverflow.com/comment/81172889
has body: from turtle import* class Shape: canvas = Screen() # creating object of screen class canvas.setup(800,800) # this will setup window on screen with dimension 800x800 turtle_obj = Turtle() # creating object of turtle class which will be used to plot square on window #self is how we refer to things in the clas from within itself. .self is the first parameter in any function defined inside a class #to access functions and variables inside the class, their name must be preceded with self and a full-stop (e.g. self.variable_name) def __init__(self,x,y): self.x=x #the shape has the attribute x (width) self.y=y #the shape has the attribute y (height) description="The shape has not yet been brought into being" author="No one has yet claimed authorship of this shape" def area(self): return self.x*self.y def perimeter(self): return 2*self.x+2*self.y def describe(self,text): self.description =text def authorName(self,text): self.author=text def scaleSize(self,scale): self.x=self.x*scale self.y=self.y*scale def print(self): print self.x print self.y # now we are referring to class object turtle using self.turtle_obj and # calling forward() function which will move plotting cursor in forward direction # upto x pixels and left() will rotate direction by 90 degree self.turtle_obj.forward(self.x) self.turtle_obj.left(90) self.turtle_obj.forward(self.y) self.turtle_obj.left(90) self.turtle_obj.forward(self.x) self.turtle_obj.left(90) self.turtle_obj.forward(self.y) self.turtle_obj.left(90) square=Shape(100,100) square.print() print(square.print()) This line is generating None on console as function is not returning anything. To remove it just remove outer print() and keep remaining. i.e. square.print() Yes it is possible and I made little changes in your code and now it should create square on screen.
has comment: http://stackoverflow.com/comment/81173338
answers question: http://stackoverflow.com/q/47111291
has comment: http://stackoverflow.com/comment/81173254
has comment: http://stackoverflow.com/comment/81179485
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/81179785
accepted answer of: http://stackoverflow.com/q/47111291
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/47127732
has body: Try to extract strings that you need by using a regex. Assuming you need each strings with those two brackets, following regex will do the job. \((\w\,?)*\) Here is an example code. public class Test { public static void main(String args[]) { String regex = "\\((\\w\\,?)*\\)"; Pattern pattern = Pattern.compile(regex); String str = "((1,2,3,4),(a,b,c,d))"; Matcher matcher = pattern.matcher(str); while(matcher.find()) { // you can extract strings here. System.out.println(matcher.group()); } } }
accepted answer of: http://stackoverflow.com/q/47126695
answers question: http://stackoverflow.com/q/47126695
type: Answer
has comment: http://stackoverflow.com/comment/81268573
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47116450
tagged with: pipe
tagged with: python
has body: My pipe's appear to me to be malfunctioning (although I know I'm doing something wrong). My program 'A1.py' requires input from pipe 'toA1', which it gets fine , it processes the input and sends it's output to 'A2.cpp' via pipe 'toA2'. 'A2.cpp' requires input from pipe 'toA2' and sends its output to the screen (the default stdout). Once 'A2.cpp' is running via execv(), it still takes input from the user (when it should be taking it from pipe 'toA2'. This is demonstrated by the variable 'use_input' within the second fork. When the following line runs: std::cout &lt;&lt; use_input &lt;&lt; std::endl; the program prints to the screen "blank", which is what was in the variable "use_input". I'm not really sure what is going wrong since it works fine for A1.py (the pipe 'toA1' works fine, not sure if it's output to pipe 'toA2' is fine. I send to stdout in A1.py with 'sys.stdout.write()'. A3.cpp: int main(int argc, char **argv) { pid_t child_pid; char* empty_arg1[2]; empty_arg1[0] = "A1.py"; empty_arg1[1] = nullptr; char* empty_arg2[2]; empty_arg2[0] = "A2"; empty_arg2[1] = nullptr; int toA1[2]; int toA2[2]; pipe(toA1); pipe(toA2); child_pid = fork(); if (child_pid == 0) { dup2(toA1[0], STDIN_FILENO); //A1 gets stdin from pipe 'toA1' close(toA1[0]); close(toA1[1]); dup2(toA2[1], STDOUT_FILENO); //sends stdout to pipe 'toA2' close(toA2[0]); close(toA2[1]); return execvp("./A1.py", empty_arg1); } child_pid = fork(); if (child_pid == 0) { std::string use_input = "blank"; dup2(toA2[0], STDIN_FILENO); //A2 gets stdin from pipe 'toA2' close(toA2[0]); close(toA2[1]); std::cout &lt;&lt; "use_input[1] = " &lt;&lt; use_input &lt;&lt; std::endl; return execv("./A2", empty_arg2); } dup2(toA2[1], STDOUT_FILENO); //Sends output to 'toA2' close(toA2[0]); close(toA2[1]); while (!std::cin.eof()) { getline(std::cin, user_input); std::cout &lt;&lt; user_input &lt;&lt; std::endl; } return 0; } A1.py: def main(): ..... sys.stdout.write("V " + str(len(vertex_list)) + "\n") sys.stdout.write(str_…
tagged with: execv
tagged with: c++
answer count: 0
score: 1
has title: Stdin and stdout to pipe are incorrect after using dup2() to copy to the pipe
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: fork
type: UnansweredQuestion

http://stackoverflow.com/q/47067506
answer count: 0
has comment: http://stackoverflow.com/comment/81119312
type: UnansweredQuestion
tagged with: firefox
tagged with: python
has comment: http://stackoverflow.com/comment/81095261
score: 0
has title: How to automate OS interactions without AutoIT in Python?
has body: Currently, I'm using selenium to automate web application interactions, but in order to save execution time I need to open several tabs and switch between them. I've figured out how to use ctypes to issue all of the key combinations I need to do this I just don't know how to 'focus' or activate the window. From what I've gathered, after opening a new tab and switching to it you have to execute browser.switch_to_window(browser.current_window_handle) which switches selenium's focus to the active tab. My issue however is activating the actual browser window within the OS, which is outside the scope of selenium. My primary constraint is that I cannot use AutoIT under any circumstances. This of it as an "I made a bet" type situation. Additionally, I would prefer to stick to using vanilla libraries. Every package I have to install has a negative impact on the project so please use built-ins and libraries that ship with Python if possible. Lastly, I don't intend to copy any code from here so if you can and are willing to help, please do so in a way to aid my understanding rather than just solve my problem. I appreciate any guidance you can offer me, this is my first post on stackoverflow! Hopefully I've provided a decent amount of information. Relevant info: -using windows 7 -using firefox (target window for activation) -using python 3 -can use robot framework -using selenium (part of robot framework) -using ctypes (ships with python 3) -can import as many vanilla modules as needed, only constraint is I don't want to install additional And just in case any of you know an easier way to do it, this is how I'm handling key combinations because they didn't work properly in selenium: import ctypes user32 = ctypes.windll.user32 #CTRL+T sleep(1) user32.keybd_event(0x11,0,0,0) sleep(1) user32.keybd_event(0x54,0,0,0) sleep(1) user32.keybd_event(0x54,0,2,0) sleep(1) user32.keybd_event(0x11,0,2,0) #CTRL+TAB sleep(1) user32.keybd_event(0x11,0,0,0) sleep(1) user32.keybd_event(0x09,0,0,…
tagged with: windows
tagged with: selenium
has comment: http://stackoverflow.com/comment/81087964
linked to: http://stackoverflow.com/q/17325629
type: Question
tagged with: robotframework

http://stackoverflow.com/q/47126662
has comment: http://stackoverflow.com/comment/81203534
has comment: http://stackoverflow.com/comment/81203493
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81203585
has title: subprocess call/popen don't work while os.system does
accepted answer: http://stackoverflow.com/a/47126730
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47126730
score: 0
type: Question
has body: Out of 3 following lines only the last one works: subprocess.call(['rm', '-f', 'temp/*']) subprocess.Popen(['rm', '-f', 'temp/*']) os.system("rm -f temp/*") There should be a natural explanation for this phenomenon.
has comment: http://stackoverflow.com/comment/81203474

http://stackoverflow.com/a/47213484
accepted answer of: http://stackoverflow.com/q/47213086
answers question: http://stackoverflow.com/q/47213086
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
type: Answer
has body: Many iterable objects in Python - things that you could put after in in a for loop - can only be iterated over once. After that, they're done; they can't go back to the beginning, and any further attempts to iterate over them will act as if they contain nothing. A csv.reader object is one example of this: in the first iteration of your outer loop, you iterate through all the available records that matrix_reader can provide. That's why, the next time the code comes around to that line, it looks as if matrix_reader is empty. Perhaps the easiest way to solve this is to make a new matrix_reader each time you want to iterate over it. Like so: for line in csv_reader: matrix_reader = ... for mline in matrix_reader: ... To understand why csv.reader gets exhausted after you go through it once, you should know that a csv.reader does not represent a CSV file. Actually, despite the name, it's really more of a "converter": it takes lines of text from some source, which could be anything, and converts them into lists, one by one. After the reader has converted a line, it forgets about it. This allows the reader object to process millions of lines without taking a huge chunk of memory. The tradeoff of this approach is that the reader object can't go back to lines it has processed before unless it can somehow tell its source of text to go back and repeat a previous line. But there's no guarantee that the underlying source can do that. If the source is the output from some other program, for example, you can't tell the program to go back and repeat an old line of output. Or if the source is text being streamed over the internet, you can't necessarily tell it to repeat a line that had been streamed before. So the reader can't count on being able to access old lines, and that's why, when it's gotten to the last one, the only reasonable behavior is for it to act as if it has nothing left.

http://stackoverflow.com/a/47220737
type: Answer
accepted answer of: http://stackoverflow.com/q/47220616
has comment: http://stackoverflow.com/comment/81391578
score: 2
answers question: http://stackoverflow.com/q/47220616
has body: Another approach with np.isin ie matrix[~np.isin(matrix, values_to_find).any(1)]
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81389511
score: 0
comment on: http://stackoverflow.com/q/47213770
type: Comment
has text: brew installed pip renamed to pip2: https://docs.brew.sh/Homebrew-and-Python.html
type: QuestionComment

http://stackoverflow.com/comment/110286173
has text: The work-around I found is to use the pd.to_datetime function as suggested by @cs95 and then use strftime function to customize the format extracted. For example, dt.strftime('%Y-%m') to keep only Year, Month.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47178311

http://stackoverflow.com/comment/116625102
has text: works, but it's very tedious to find the difference between the two objects afterwards
type: Comment
comment on: http://stackoverflow.com/a/60459308
score: 9
type: AnswerComment

http://stackoverflow.com/a/47117477
type: Answer
has comment: http://stackoverflow.com/comment/81185222
has comment: http://stackoverflow.com/comment/81185163
has body: I would read in each line as a list and then pass to the DataFrame constructor: In [11]: import ast In [12]: pd.DataFrame([ast.literal_eval(line) for line in open("second.txt")]) Out[12]: 0 1 2 3 4 5 6 7 8 9 10 0 Tue Sep 12 15:13:56 +0000 2017 text. 0 en 390 529 7138 15727 False -84.395235 33.771232 1 Tue Sep 12 15:13:59 +0000 2017 text 0 en 648 891 2087 5801 False -84.321948 33.752879 2 Tue Sep 12 15:14:01 +0000 2017 text 0 en 217 222 959 958 False -82.849182 27.865251 3 Tue Sep 12 15:14:06 +0000 2017 text 0 en 71 85 2357 1290 False -82.299760 27.857254 literal_eval will convert the string to the corresponding python list: In [21]: line = "['Tue Sep 12 15:13:56 +0000 2017', 'text. ', 0, 'en', 390, 529, 7138, 15727, False, -84.395235, 33.771232]" In [22]: ast.literal_eval(line) Out[22]: ['Tue Sep 12 15:13:56 +0000 2017', 'text. ', 0, 'en', 390, 529, 7138, 15727, False, -84.395235, 33.771232]
has comment: http://stackoverflow.com/comment/81185035
answers question: http://stackoverflow.com/q/47117421
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81185453
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81185135
accepted answer of: http://stackoverflow.com/q/47117421
has comment: http://stackoverflow.com/comment/81185034

http://stackoverflow.com/comment/81276024
has text: Did I make a mistake formatting the code?! I updated the answer inserting it again, can you recheck? If it is then still not working I would need to know how you run it, and what versions you are using.
type: Comment
comment on: http://stackoverflow.com/a/47135576
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81240556
type: Comment
type: QuestionComment
has text: @Divakar would you please also explain why my method doesn't work in the answer? if you have time... Thank you
comment on: http://stackoverflow.com/q/47145175
score: 0

http://stackoverflow.com/comment/81382749
type: Comment
type: QuestionComment
has text: Possible duplicate of [Set administrator privileges to subprocess.check\_call() in Python](https://stackoverflow.com/questions/20505893/set-administrator-privileges-to-subprocess-check-call-in-python)
score: 2
comment on: http://stackoverflow.com/q/47196230

http://stackoverflow.com/q/47087229
has answer: http://stackoverflow.com/a/47088026
tagged with: python
has answer: http://stackoverflow.com/a/47088271
has body: I am trying to scrape youtube views from any video links. I tried catching elements using selenium driver but for some reason i cannot catch it.Below is the code i have used: driver=webdriver.chrome() driver.get("https://www.youtube.com/watch?v=F-eMt3SrfFU") driver.find_element_by_id("count").text driver.find_element_by_id("watch-view-count").text i cannot catch elements on this link. am i doing something wrong here ? it is a youtube movie link and i want to get the view on the link
type: UnansweredQuestion
downvote count: 0
tagged with: selenium
tagged with: web-scraping
upvote count: 1
has answer: http://stackoverflow.com/a/47088418
favorite count: 0
type: Question
has title: cannot find element while scraping youtube
answer count: 3
score: 1

web
tags question: http://stackoverflow.com/q/47115809
tags question: http://stackoverflow.com/q/47169097
tag name: web
tags question: http://stackoverflow.com/q/47112472
tags question: http://stackoverflow.com/q/47213315
tags question: http://stackoverflow.com/q/47190633
tags question: http://stackoverflow.com/q/47151837
type: Tag
tags question: http://stackoverflow.com/q/47132954
tags question: http://stackoverflow.com/q/47217147
tags question: http://stackoverflow.com/q/47174004
tags question: http://stackoverflow.com/q/47105801

http://stackoverflow.com/q/47094172
tagged with: javascript
tagged with: python
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/81144922
has comment: http://stackoverflow.com/comment/81139585
has body: I want to run Selenium on Firefox in multiple threads on Windows (so i can't just change timezone in system). I tried do it with TimeShift.js, but after refresh page all data is lost. I'm using python.
tagged with: selenium
has title: How to change timezone in Selenium?
favorite count: 0
type: Question
upvote count: 2
tagged with: time
type: UnansweredQuestion

pybrain
type: Tag
tag name: pybrain
tags question: http://stackoverflow.com/q/47107009

http://stackoverflow.com/q/47084859
has title: Can Python SDK Register JS Client for Firebase Events?
tagged with: firebase-realtime-database
has body: I'm using only the Real-Time Database part of Firebase. I have a Python Firebase admin on the server, a Javascript Firebase on the web client. No Android or iOS. My web Javascript client receives a token from the Python server for its authentication. Only the Python server writes to Firebase, the Javascript client never does. But the client registers a "child_added" listener with Firebase to receive database changes in data. Everything works except for this event listener. The Firebase docs say: The Python Admin SDK currently only supports blocking reads. It cannot be used to add event listeners that receive realtime update notifications. But as I understand it, that applies to my server, not the client. Or does getting a custom token from a Python Admin disqualify the Javascript client for these events? Maybe it's a problem that the server initializes itself with service account credentials, while the client does so with an api key? If so, why doesn't Firebase issue an error? Here's the relevant Python code (views.py): import firebase_admin from firebase_admin import credentials, auth, db def getFirebaseInstance(): try: # using fresh download of key from service account for this app cred = credentials.Certificate('myapp/static/myap/firebase/firebase-adminsdk-4mcup-144fd3c404.json') firebase = firebase_admin.initialize_app(cred,{'databaseURL': 'https://my-db-url'}) except: raise @login_required() def firebaseClientToken(request): try: global __firebase if __firebase is None: __firebase = getFirebaseInstance() token = firebase_admin.auth.create_custom_token('1') return HttpResponse(token) except Exception as err: return HttpResponse("System error:" + str(err), status=406) def sendToFirebase(request, data): try: global __firebase if not __firebase: __firebase = getFirebaseInstance() db = firebase_admin.db ref = db.reference("messages/") ref.push(json.dumps(data)) except Exception: raise All that works fine as far as the server being able to write to firebase and for g…
tagged with: javascript
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: firebase-authentication
answer count: 1
linked to: http://stackoverflow.com/q/48219972
type: Question
has answer: http://stackoverflow.com/a/48246954
accepted answer: http://stackoverflow.com/a/48246954

http://stackoverflow.com/comment/81243316
type: Comment
type: AnswerComment
has text: Cool, i will try that! Thx
comment on: http://stackoverflow.com/a/47146469
score: 0

http://stackoverflow.com/comment/81374206
type: Comment
type: QuestionComment
score: 0
has text: If `line == ""` the following `for` would be executed but `lineList` wasn't set.
comment on: http://stackoverflow.com/q/47212355

http://stackoverflow.com/comment/81379950
type: Comment
score: 0
type: AnswerComment
has text: Well, you can try your above code but I doubt it will work since a queryset instance will be returned and it is not possible to iterate over it like you did. Is the code working like you posted?
comment on: http://stackoverflow.com/a/47214815

http://stackoverflow.com/a/47215222
has body: As EYLLANESC said on the comment: Change Item.setSizeHint(Item_Widget.sizeHint()) to Item.setSizeHint(Item_Widget.size()) – eyllanesc Thank you !
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47214061
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47214061

http://stackoverflow.com/q/47100398
answer count: 4
has answer: http://stackoverflow.com/a/47102159
type: AnsweredQuestion
score: 0
has title: BeautifulSoup returning none when element definitely exists
tagged with: beautifulsoup
type: Question
tagged with: nonetype
has answer: http://stackoverflow.com/a/65546368
has comment: http://stackoverflow.com/comment/81150763
has comment: http://stackoverflow.com/comment/81151408
has answer: http://stackoverflow.com/a/47141046
accepted answer: http://stackoverflow.com/a/47141046
has answer: http://stackoverflow.com/a/47100725
possible better answer: http://stackoverflow.com/a/47100725
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: I'm new to web scraping and have been using BeautifulSoup to scrape daily mortgage rates. However, a lot of the servicer sites that I am trying to scrape return 'none' or an empty list. The tags that I'm trying to scrape definitely exist and I just don't understand why this is happening. One example is below. html=urlopen('https://www.popular.com/en/mortgages/') bs0bj=BeautifulSoup(html, 'html.parser'); rate=bs0bj.find('span', {'class':'text-md text-popular-medium-blue'}).div print(rate)

http://stackoverflow.com/comment/81287226
type: Comment
has text: Setting `formset.instance` won't work, you need to alter the individual form or instance. Your second attempt looks along the right lines. You shouldn't need to do `instance.entity = instance.cleaned_data['entity']` - `instance.entity` should already be set.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47167331

http://stackoverflow.com/comment/81162113
comment on: http://stackoverflow.com/q/47105671
score: 0
type: QuestionComment
has text: Use `sum(numin(string, member) for member in sublist)`. That is the most efficient and it's also very clear.
type: Comment

http://stackoverflow.com/comment/81392857
has text: can you please make the output line by line (every duplicate fullpath/file.ext is a **new line**)? i need to compare your result to my other (slow) duplicate finder programs. also can you explain the logic behind this? it compare sizes then md5? thank you!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47200367
type: Comment

http://stackoverflow.com/a/47115520
has body: I. For generic case Approach #1 With np.unique - idx = np.unique(df.id.values, return_index=1)[1] To get the last indices for each ID, simply use flipped version and subtract from dataframe's length - len(df)-np.unique(df.id.values[::-1], return_index=1)[1]-1 II. For id col already being sorted Approach #2-A We can use slicing for noticeable performance boost, as we would be avoiding sorting - a = df.id.values idx = np.concatenate(([0],np.flatnonzero(a[1:] != a[:-1])+1)) Approach #2-B With masking (better for lots of id numbers) a = df.id.values mask = np.concatenate(([True],a[1:] != a[:-1])) idx = np.flatnonzero(mask) For the last index : np.flatnonzero(np.concatenate((a[1:] != a[:-1],[True]))) Approach #3 For sequential numbers, we can use np.bincount - a = df.id.values idx = np.bincount(a).cumsum()[:-1] Sample run - In [334]: df Out[334]: id term x 0 1 A 3 1 1 B 2 2 2 A 1 3 2 B 1 4 2 F 1 5 2 G 1 6 2 Z 1 7 3 K 1 8 3 M 1 9 3 N 1 10 3 Q 1 11 3 R 1 12 3 Z 1 13 4 F 1 In [335]: idx = np.unique(df.id.values, return_index=1)[1] In [336]: idx Out[336]: array([ 0, 2, 7, 13]) If you need the output in a dataframe - In [337]: a = df.id.values In [338]: pd.DataFrame(np.column_stack((a[idx], idx)), columns='id','first_idx') Out[338]: id first_idx 0 1 0 1 2 2 2 3 7 3 4 13
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47115448
answers question: http://stackoverflow.com/q/47115448
has comment: http://stackoverflow.com/comment/81196493
downvote count: 0
score: 9
upvote count: 9

http://stackoverflow.com/comment/81385892
comment on: http://stackoverflow.com/a/47218070
type: Comment
score: 0
type: AnswerComment
has text: thanks for that. not sure if that's the best way to solve this issue. I really appreciate this alternative. i think i will experiment with drf-schema adapter. if that fails, i will try yours.

http://stackoverflow.com/a/52557580
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47185894
type: Answer
answers question: http://stackoverflow.com/q/47185894
score: 11
upvote count: 11
has body: Yes, when you pass sort=False the order of first appearance is preserved. The groupby source code is a little opaque, but there is one function groupby.ngroup which fully answers this question, as it directly tells you the order in which iteration occurs. def ngroup(self, ascending=True): """ Number each group from 0 to the number of groups - 1. This is the enumerative complement of cumcount. Note that the numbers given to the groups match the order in which the groups would be seen when iterating over the groupby object, not the order they are first observed. "" Data from @coldspeed df['sort=False'] = df.groupby('col', sort=False).ngroup() df['sort=True'] = df.groupby('col', sort=True).ngroup() Output: col sort=False sort=True 0 16 0 7 1 1 1 0 2 10 2 5 3 20 3 8 4 3 4 2 5 13 5 6 6 2 6 1 7 5 7 3 8 7 8 4 When sort=False you iterate based on the first appearance, when sort=True it sorts the groups, and then iterates.

http://stackoverflow.com/comment/81360279
score: 0
type: Comment
has text: @ingvar Do you mean the pip3.exe file. I did not find it :( .
type: QuestionComment
comment on: http://stackoverflow.com/q/47112902

http://stackoverflow.com/q/47121045
type: Question
tagged with: numpy
tagged with: arrays
has comment: http://stackoverflow.com/comment/81191868
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47121140
type: AnsweredQuestion
has title: Effective way to find and delete certain elements from a numpy array
possible better answer: http://stackoverflow.com/a/47121122
score: 0
has answer: http://stackoverflow.com/a/47121140
answer count: 3
has answer: http://stackoverflow.com/a/47121122
has body: I have a numpy array with some positive numbers and some -1 elements. I want to find these elements with -1 values, delete them and store their indeces. One way of doing it is iterating through the array and cheking if the value is -1. Is this the only way? If not, what about its effectivness? Isn't there a more effective python tool then?
downvote count: 1
has answer: http://stackoverflow.com/a/47121278
favorite count: 0

http://stackoverflow.com/comment/81337801
comment on: http://stackoverflow.com/q/47194201
type: Comment
has text: the error is that, as you have defined your `summarize` function like this: `def summarize(self,text):` that is, it's taking one argument named `text` whenever it is called, and when you are calling it on line: ` book.summarize()`, here you are not supplying that parameter.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81364517
type: QuestionComment
has text: Update, it stops crashing SOMETIMES....
comment on: http://stackoverflow.com/q/47206902
score: 0
type: Comment

http://stackoverflow.com/comment/81143550
type: Comment
comment on: http://stackoverflow.com/a/47096938
type: AnswerComment
score: 0
has text: I dont want to check in "Name" `df['Count'] = df.Name.str.count(pat)` In some cases, If i have Ram,ravi under Match column then count value should be 2 so I want to separate the words by (,) and take count

http://stackoverflow.com/comment/81148258
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47099051
has text: What's the logic? Why only 7051.3 and 7058.3 when you specify 7050?

http://stackoverflow.com/comment/81158372
type: Comment
score: 0
has text: I was recieving: ValueError: Index contains duplicate entries, cannot reshape, and I have fixed it based on (https://stackoverflow.com/questions/28651079/pandas-unstack-problems-valueerror-index-contains-duplicate-entries-cannot-re)
comment on: http://stackoverflow.com/q/47086896
type: QuestionComment

http://stackoverflow.com/a/47210797
downvote count: 0
upvote count: 1
has body: You could fill a pandas data frame in line by line by reading the file normally and simply add each new line as a new row to the dataframe, though this would be a fair bit slower than just using Pandas own reading methods.
answers question: http://stackoverflow.com/q/47087741
type: Answer
score: 1

http://stackoverflow.com/q/47114982
tagged with: servlets
type: Question
type: UnansweredQuestion
answer count: 1
has body: I have written the following code for the servlet: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Summarize extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); String str = req.getParameter("txt"); try { //instead of writing just test.py, write the whole path to the python script it will work perfectly Process p = Runtime.getRuntime().exec("python test.py"); p.waitFor(); BufferedReader in = new BufferedReader(new InputStreamReader( p.getInputStream())); StringBuffer buf = new StringBuffer(""); String line = null; System.out.println(p.toString()); while ((line = in.readLine()) != null) { System.out.println(line); buf.append(line); } System.out.println(buf.length()); out.println("this is summarize class"); } catch (Exception e) { e.printStackTrace(); } } } This code won't return anything but If I write the same code in a simple java class the code works perfectly fine. I have also checked the python script, it's running perfectly fine. Is there any way to fix this? Update: The following code will now work just read the comment just after the try statement
has title: How to execute a python script from a servlet?
score: 0
tagged with: java
has answer: http://stackoverflow.com/a/47115184
tagged with: python

http://stackoverflow.com/a/47084623
has body: You can tell TextClause (produced by text()) the column types using .columns(): from sqlalchemy import inspect session = Session() stmt = text('select * from t').columns(*inspect(T).columns) t = session.query(T).from_statement(stmt).first() assert type(t.attrs) == dict, repr(t.attrs) Or, for SQLAlchemy&lt;0.9, use the typemap argument: from sqlalchemy import inspect session = Session() typemap = {c.name: c.type for c in inspect(T).columns} stmt = text('select * from t', typemap=typemap) t = session.query(T).from_statement(stmt).first() assert type(t.attrs) == dict, repr(t.attrs)
answers question: http://stackoverflow.com/q/47083643
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/108620858
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47083643
type: Answer

http://stackoverflow.com/comment/81345121
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47151409
score: 0
has text: is it a known bug in *_parallel_pairwise()* while trying to get even slices? If so, any idea about its fix? For the work around does the n_jobs have to be *less* than #cores and not *equal*?

http://stackoverflow.com/comment/81279524
type: QuestionComment
has text: If your question was answered, don't forget to vote on, and accept the one that helped the most. Thanks.
comment on: http://stackoverflow.com/q/47164230
score: 1
type: Comment

http://stackoverflow.com/comment/81081269
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/47066034
type: Comment
has text: Calling `concatenate` in a loop is terrible for performance because every call has to allocate an entire new array and copy the arguments into the new array. Gathering them into a list and building the final array in one call is the way to go.

http://stackoverflow.com/comment/81367830
type: Comment
has text: @AthulMuralidharan no problem!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47209007

http://stackoverflow.com/comment/81321011
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47184521
has text: The code shown here works (I'm going to assume you have an opening if statement). Your error mentions line 84, so you'll have to show us that line. Most likely you are trying to add a class to a float, instead of adding the result of a method call on that class to the float
score: 0

http://stackoverflow.com/a/47218575
answers question: http://stackoverflow.com/q/47105208
type: AcceptedAnswer
downvote count: 0
score: 3
upvote count: 3
type: Answer
has body: It is a @contextmanager, which handles the temporary file deletion for you. But one should use it with with: with pfx_to_pem(clientCert, password) as cert: requests.get(url, cert=cert)
accepted answer of: http://stackoverflow.com/q/47105208

http://stackoverflow.com/a/57796801
type: Answer
score: 0
has body: I know this is an old question, but it was top result when I ran into the same problem. Just want to show how I ended up doing it. alien_invasion.py keydown and keyup check events: def _check_keydown_events(self, event): """respond to keypresses""" if event.key == pygame.K_RIGHT: self.ship.moving_right = True elif event.key == pygame.K_d: self.ship.moving_right = True elif event.key == pygame.K_LEFT: self.ship.moving_left = True elif event.key == pygame.K_a: self.ship.moving_left = True elif event.key == pygame.K_UP: self.ship.moving_up = True elif event.key == pygame.K_DOWN: self.ship.moving_down = True elif event.key == pygame.K_q: sys.exit() def _check_keyup_events(self, event): """respond to key releases""" if event.key == pygame.K_RIGHT: self.ship.moving_right = False elif event.key == pygame.K_d: self.ship.moving_right = False elif event.key == pygame.K_LEFT: self.ship.moving_left = False elif event.key == pygame.K_a: self.ship.moving_left = False elif event.key == pygame.K_UP: self.ship.moving_up = False elif event.key == pygame.K_DOWN: self.ship.moving_down = False ship.py import pygame class Ship: """A class to manage the ship""" def __init__(self, ai_game): """initialize the ship and set its starting position""" self.screen = ai_game.screen self.settings = ai_game.settings self.screen_rect = ai_game.screen.get_rect() # load the ship image and get its rect self.image = pygame.image.load('images/ship.bmp') self.rect = self.image.get_rect() # start each new ship at the bottom center of the screen # self.rect.midbottom = self.screen_rect.midbottom self.rect.center = self.screen_rect.center # store a decimal value for the ship's horizontal position self.x = float(self.rect.x) self.y = float(self.rect.y) # movement flag self.moving_right = False self.moving_left = False self.moving_up = False self.moving_down = False def update(self): """update the ship's position on the movement flag""" if self.moving_right and self.rect.right &lt; self.screen_rect.right: self.…
answers question: http://stackoverflow.com/q/47215243

http://stackoverflow.com/comment/104099903
type: AnswerComment
has text: i use this 'pip install requests boto3 mock --upgrade --user' still getting error in REST end point call. Jenkins build was success, and when i invoke the REST my response in internal server error and when i see the logs, unable to import module requests.
score: 0
comment on: http://stackoverflow.com/a/56156259
type: Comment

http://stackoverflow.com/q/47124481
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Strange equality error with PyMongo-flask
tagged with: python
score: -1
has body: So I have this api endpoint: @app.route("/subject", methods=["GET"]) def GET_subject(): subject = request.args["subject"] page = int(request.args["page"]) pagesize = 10 subjectResults = db.subject.find()[pagesize*(page-1):pagesize*(page)] if subjectResults is "[]": return json.dumps({"page": page, "subject": subject, "subjectResults": bson.json_util.dumps(subjectResults)}) else: return json.dumps({"error": "404"}) and when I run it, with no data in the database, it returns the error 404 message I put in. As you can tell, I'm using Flask and Flask-PyMongo for this.
tagged with: flask-pymongo
linked to: http://stackoverflow.com/q/132988
accepted answer: http://stackoverflow.com/a/47124650
tagged with: mongodb
has answer: http://stackoverflow.com/a/47124650
duplicate of: http://stackoverflow.com/q/132988
upvote count: 0
has comment: http://stackoverflow.com/comment/81199472
answer count: 1
tagged with: pymongo
tagged with: flask
downvote count: 1

http://stackoverflow.com/q/47081168
type: UnansweredQuestion
tagged with: pip
tagged with: python
has answer: http://stackoverflow.com/a/47081362
has comment: http://stackoverflow.com/comment/81111673
score: -1
has title: not able to install numpy in ubuntu 14.04
upvote count: 0
has body: error: could not create '/usr/local/lib/python2.7/dist-packages/numpy': Permission denied Cleaning up... Command /usr/bin/python -c "import setuptools, tokenize;file='/tmp/pip_build_mark/numpy/setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record /tmp/pip-TKmHYa-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_mark/numpy
linked to: http://stackoverflow.com/q/46133715
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
duplicate of: http://stackoverflow.com/q/46133715

http://stackoverflow.com/q/47085374
downvote count: 0
tagged with: python
favorite count: 0
tagged with: maze
accepted answer: http://stackoverflow.com/a/47093428
type: AnsweredQuestion
has body: I have been trying to develop a maze generator in Python 3, and I am nearing completion. I have it to the point where I can create the maze as seen in the picture below, however if you look closely, you may be able to see the two issues I am worried about. In some cases, the corners of the path are touching. This is something that I am explicitly trying to avoid by checking each potential cells 8 edges and corners. There are also some spots that I can see where there are "islands" that have space for an additional cell, however it is empty. If you have any idea as to how I could fix that, that would be great. Thanks! import random import numpy as np from matplotlib import pyplot as plt # Width and height of the maze mx = 50 my = 50 # Maze Array maze = np.zeros((mx, my)) # Directions to move in the maze dx = [-1, 1, 0, 0, -1, 1, 1, -1] dy = [0, 0, -1, 1, -1, 1, -1, 1] # Visited Cells stack = [] # Find Which Neighbour Cells Are Valid def nextCell(cx, cy): # Set Current Cell To '1' maze[cy, cx] = 1 # List Of Available Neighbour Cell Locations n = [] # Check The 4 Available Neighbour Cells for i in range(4): nx = cx + dx[i] ny = cy + dy[i] # Check If Neighbours Cell Is Inbound if nx &gt;= 1 and nx &lt; my - 1 and ny &gt;= 1 and ny &lt; mx - 1: # Check If Neighbour Cell Is Occupied if maze[ny, nx] == 0: # Variable To Store Neighbour Cells Neighbours cn = 0 # Loop Through Neighbour Cells Neighbours for j in range(8): ex = nx + dx[j] ey = ny + dy[j] # Check If Neighbour Cells Neighbour Is Inbound if ex &gt;= 0 and ex &lt; my and ey &gt;= 0 and ey &lt; mx: # Check If Neighbour Cells Neighbour Is Occupied if maze[ey, ex] == 1: cn += 1 # If Neighbour Cells Neighbour Has Less Than 2 Neighbours, Add Cell To List if cn &lt;= 2: n.append((ny, nx)) # Return The List Of Valid Neighbours return n # Generate The Maze def GenerateMaze(sx, sy): # Initialize 'x,y' With Starting Location x = sx y = sy # Loop Until Maze Is Fully Generated while True: # Neighbour List n = nextCell(x, y) # …
has answer: http://stackoverflow.com/a/47093428
tagged with: matplotlib
has title: How Can I Stop Corners From Touching When Generating Maze
type: Question
tagged with: numpy
tagged with: python-3.x
score: 2
upvote count: 2
answer count: 1

http://stackoverflow.com/comment/81215002
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47132702
has text: It is typo, `pd.to_datetime`, not `pd.to_datatime`

http://stackoverflow.com/comment/81182653
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47116287
has text: @JasonS I wouldn't say anything about XY, and sometimes you are tied to a tool (like you are to python), so, when that's the case, you have to open a little the mind and try something "not tool" or "not pyhonic", I mean, you are trying to achieve a goal, if you want that, you either don't use python, or you can try parallel thinking, the Cython option is a parallel way very interesting too

http://stackoverflow.com/comment/81244373
has text: Possible duplicate of ['NoneType' object has no attribute 'group'](https://stackoverflow.com/questions/15080078/nonetype-object-has-no-attribute-group)
comment on: http://stackoverflow.com/q/47146947
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81091811
type: AnswerComment
has text: No, just a typo in the question, sorry my bad. The names of the variables are indeed index_1, index_2, index_3 and I have already tried your suggestion and it won't work
comment on: http://stackoverflow.com/a/47071831
score: 0
type: Comment

http://stackoverflow.com/comment/81258067
has text: Actually the `var` outside is responsbile to call other stuff such as `var.to_csv()` so that is why i needed the var to be in final state
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47154243

http://stackoverflow.com/a/47175765
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81301025
score: 3
has comment: http://stackoverflow.com/comment/81300843
has body: If you convert it to a for loop it might be easier to see..? res = [] for item in matrix_a: a, b = item # a = item[0]; b = item[1] res.append(a) you're basically unpacking the individual items in the list and picking one of them.
has comment: http://stackoverflow.com/comment/81300858
type: Answer
accepted answer of: http://stackoverflow.com/q/47175707
answers question: http://stackoverflow.com/q/47175707

http://stackoverflow.com/comment/83393274
comment on: http://stackoverflow.com/a/47168359
score: 0
type: AnswerComment
has text: Found a different solution. posted it as an additional answer.
type: Comment

http://stackoverflow.com/comment/81376801
score: 0
has text: Yeah i was using a PPA, but it seems that the problem with the new module name isn't causing any truble , thank very much anyway :3
type: Comment
comment on: http://stackoverflow.com/a/47124986
type: AnswerComment

http://stackoverflow.com/comment/81292424
has text: Please read why [a screenshot of code is a bad idea](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors). Paste the code and properly format it instead. Also post the actual error message.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47171076
score: 0

http://stackoverflow.com/q/47153700
has comment: http://stackoverflow.com/comment/81257312
has comment: http://stackoverflow.com/comment/81257688
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81257914
has title: python django response time long but don't know what's wrong
answer count: 1
tagged with: mysql
tagged with: response-time
has comment: http://stackoverflow.com/comment/81261554
favorite count: 0
type: Question
has body: My django app use django-rest-framework, and MySQL. I tested my app, but almost functions had long response time. I don't know what is the problem. This is one of most long response time functions. 180232 function calls (171585 primitive calls) in 1.110 seconds Ordered by: internal time List reduced from 757 to 151 due to restriction &lt;0.2&gt; ncalls tottime percall cumtime percall filename:lineno(function) 105 0.597 0.006 0.597 0.006 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:268(query) 2 0.154 0.077 0.174 0.087 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:81(__init__) 4 0.020 0.005 0.020 0.005 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:254(autocommit) 8800/3582 0.010 0.000 0.828 0.000 {built-in method builtins.getattr} 20156 0.010 0.000 0.022 0.000 {built-in method builtins.isinstance} 200/100 0.009 0.000 0.886 0.009 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/rest_framework/serializers.py:479(to_representation) 2 0.009 0.005 0.009 0.005 {function Connection.set_character_set at 0x109b506a8} 6920 0.009 0.000 0.009 0.000 {built-in method builtins.hasattr} .... This function is first page of list, total count is 1000, page size is 100. Each records join just one table. Query took long time so I changed Django ORM to Raw Query but time is same. (Maybe I used wrong raw query) Even auth check response time long 2199 function calls (2133 primitive calls) in 0.195 seconds Ordered by: internal time List reduced from 419 to 84 due to restriction &lt;0.2&gt; ncalls tottime percall cumtime percall filename:lineno(function) 2 0.153 0.076 0.169 0.084 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:81(__init__) 4 0.016 0.004 0.016 0.004 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:254(autocommit) 3 0.0…
has comment: http://stackoverflow.com/comment/81261175
has comment: http://stackoverflow.com/comment/81257126
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47156148
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/47156148
has comment: http://stackoverflow.com/comment/81258140
has comment: http://stackoverflow.com/comment/81262304

http://stackoverflow.com/comment/81379765
type: AnswerComment
comment on: http://stackoverflow.com/a/47213557
has text: Thanks a lot for the great answer :)
type: Comment
score: 0

http://stackoverflow.com/comment/81375004
score: 0
comment on: http://stackoverflow.com/q/47212464
type: Comment
has text: Do you want to reuse this model later?
type: QuestionComment

http://stackoverflow.com/a/47078119
answers question: http://stackoverflow.com/q/47076231
has body: The input file seems to be a blank separated file with fields optionaly enclosed in double quotes. This is easy to parse with the csv module itself: with open('samplelogs.txt',encoding='utf-8', newline='') as socfile, \ open('csvfile.csv',mode='w',encoding='utf-8', newline='') as csvfile: rd = csv.reader(socfile, delimiter = ' ', quoting=csv.QUOTE_ALL) # or "\t" if the delimiter is a tab wr = csv.writer(csvfile) for row in rd: wr.writerow(row)
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47127337
has body: This question is regarding parameters for V3 Python functions. I wonder why keyword-only parameters that have default values associated with them don't seem to get their default values added to the __defaults__ tuple? Here is an example: def test_def( ap, bp, cn=2.3, *, dn, fn = 'default keyword-only', **gn ): """ Test function definition :param ap: Mandatory positional parameter :param bp: Mandatory positional paramter :param cn: Optional named parameter (a.k.a keyword parameter) :param dn: Mandatory keyword-only parameter :param fn: Optoinal keyword-only paramter :param gn: **kwds :return: """ print( 'ap: ', ap ) print( 'bp: ', bp ) print( 'cn: ', cn ) print( 'dn: ', dn ) print( 'fn: ', fn ) for elem in gn: print("gn: ", gn) test_def( 89, 'text instead', abc=12, dn='my keyword-only value' ) Here is the output: >>> test_def( 89, 'text instead', abc=12, dn='my keyword-only value' ) pa: 89 bp: text instead cn: 2.3 dn: my keyword-only value fn: default keyword-only gn: {'abc': 12} >>> print(test_def.__defaults__) (2.3,) The __defaults__ tuple does include the default value for cn but not fn. How comes?
has comment: http://stackoverflow.com/comment/81204863
answer count: 0
has comment: http://stackoverflow.com/comment/81205682
has comment: http://stackoverflow.com/comment/81246428
has comment: http://stackoverflow.com/comment/81205099
type: Question
tagged with: function
type: UnansweredQuestion
tagged with: python
tagged with: parameters
score: 0
has title: python V3 def __defaults__ tuple doesn't include default values associated with keyword-only parameters?

http://stackoverflow.com/comment/81356028
score: 0
has text: Sorry, but your comment is pretty unclear and does not really explain anything.
comment on: http://stackoverflow.com/q/47202189
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81252831
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47150890
has text: I think I get what you're asking, though I think it could be clearer... I don't see a way around brute force. But I will think about it...
score: 0

http://stackoverflow.com/q/47090197
has answer: http://stackoverflow.com/a/47090461
linked to: http://stackoverflow.com/q/46814229
type: UnansweredQuestion
has body: I am trying to create a bar plot with differing bar width. After I updated my Matplotlib to version 2.1.0 from 1.1.0. the same codes no longer work and I need to specify border color to have borders but the border is only drawn on the first bar. Here are my codes: import csv, os, os.path, math, pdb # pdb.set_trace() import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111) x = [1, 2, 3, 4, 5, 6] x = np.array(x) bar_width = [0.1, 0.2, 0.1, 0.2, 0.1, 0.05] data = np.array([1.6, 9.4, 10.1, 4.7, 6, 3.5]) plt.bar(x - bar_width, data, color = 'b', edgecolor = 'r') plt.show() This is what I get. I must be missing something really basic but if somebody could tell me what I am doing wrong I highly appreciate it.
tagged with: bar-chart
answer count: 1
has comment: http://stackoverflow.com/comment/81137698
duplicate of: http://stackoverflow.com/q/46814229
has title: Matplotlib: Border line drawn on only the first bar after updating matplotlib
type: Question
has comment: http://stackoverflow.com/comment/81159630
score: 0
tagged with: matplotlib
tagged with: python

http://stackoverflow.com/q/47068293
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47070372
has answer: http://stackoverflow.com/a/47070372
has title: How to print a statement with custom Ansible module?
score: 1
tagged with: python
linked to: http://stackoverflow.com/q/45074728
has body: I am implementing a new module for specific needs in my environment. I would like to print certain outputs (such as some variables) by this module, similar as debug module prints with msg parameter, but in a more customized way. AnsibleModule class has fail_json() method which accepts msg argument to print on a failure, but I cannot find a way to print a message on success with exit_json() I also don't know how builtin debug module works, found almost nothing except DOCUMENTATION and EXAMPLES in the module script.
type: AnsweredQuestion
tagged with: ansible
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/81122604
type: QuestionComment
has text: @DavidZ i added a few more things to try and explain whats really going on here. Let me know if I should further simplify things.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47086383

http://stackoverflow.com/comment/81275459
type: Comment
comment on: http://stackoverflow.com/q/47162900
has text: Cannot reproduce...
type: QuestionComment
score: 5

http://stackoverflow.com/comment/81356510
comment on: http://stackoverflow.com/q/47193471
score: 0
type: Comment
type: QuestionComment
has text: It's only to clean up the file, but unfortunately the same issue persists with the filelock.py file in `WindowsFileLock._release()`

http://stackoverflow.com/comment/94523246
score: 1
has text: To connect to a Cloud SQL DB from Dataflow workers using the Python SDK, I've had to install and run the cloud_sql_proxy CLI on all the workers (or whitelist all IPs for the DB, which is not ideal). I know the Java SDK has some proxy/sockets functionality built in; do you know of any similar tricks for Python @mohaseeb? I'm using beam_nuggets btw, it's working great except for that separate proxy issue :)
type: Comment
comment on: http://stackoverflow.com/a/53623786
type: AnswerComment

http://stackoverflow.com/comment/81239705
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47126578
type: AnswerComment
has text: I added comments at points where the changes are. But you are right, more is better.

http://stackoverflow.com/comment/81282076
has text: Possible duplicate of [How to save a list to a file and read it as a list type?](https://stackoverflow.com/questions/27745500/how-to-save-a-list-to-a-file-and-read-it-as-a-list-type)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47166112
score: 4

matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/47181850
tags question: http://stackoverflow.com/q/47146818
tags question: http://stackoverflow.com/q/47191930
tag name: matplotlib-basemap
tags question: http://stackoverflow.com/q/47201586

http://stackoverflow.com/q/47181187
favorite count: 0
score: 9
type: Question
has title: Finding string over multiple columns in Pandas
upvote count: 9
has comment: http://stackoverflow.com/comment/81311395
has comment: http://stackoverflow.com/comment/81311535
has comment: http://stackoverflow.com/comment/81311676
tagged with: python
has body: I am trying to find if a string exists across multiple columns. I would like to return a 1 if the string exists and 0 if it doesn't as a new series within the dataframe. After searching the forums, I understand that str.contains could be used, but i'm searching over 100+ columns therefore it isn't efficient for me to work with individual series at a time. There are some NAs within the columns if this is relevant. Example simplified dataframe: d = {'strings_1': ['AA', 'AB', 'AV'], 'strings_2': ['BB', 'BA', 'AG'], 'strings_1': ['AE', 'AC', 'AI'], 'strings_3': ['AA', 'DD', 'PP'], 'strings_4': ['AV', 'AB', 'BV']} simple_df = pd.DataFrame(data=d) If I am interested in finding 'AA' for example, I would like to return the following dataframe. Example target dataframe: d = {'strings_1': ['AA', 'AB', 'AV'], 'strings_2': ['BB', 'BA', 'AG'], 'strings_1': ['AE', 'AC', 'AI'], 'strings_3': ['AA', 'DD', 'PP'], 'strings_4': ['AV', 'AB', 'BV'], 'AA_TRUE': [1, 0, 0]} target_df = pd.DataFrame(data=d) Many thanks for help.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81311561
tagged with: pandas
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47181314
has answer: http://stackoverflow.com/a/47181314

http://stackoverflow.com/q/47196042
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47196083
answer count: 2
upvote count: 0
type: UnansweredQuestion
tagged with: iframe
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/81348433
has body: I have a very simple Python script (which I don't know how to start), regarding selenium, so I want to know how would you know the 'name'/'ID' of the frame, the one that you can use to identify that specific frame. I would like to ask where can I get that I don't know if you understand that but, I want to know if how would I recognize that specific frame? And also how could I click on that?
has answer: http://stackoverflow.com/a/47197674
downvote count: 3
tagged with: selenium
has comment: http://stackoverflow.com/comment/81348581
has title: How to know the name of a frame to be used in Selenium + Python

http://stackoverflow.com/q/47112615
has comment: http://stackoverflow.com/comment/81175460
has body: I would like to create a new column under the following condition: So basically I have two column Majoy car and Major housetype. I would let all the 'nocar' within Majoy car AND 'Rented' within Major housetype to merge to a new column. My DataFrame is imd_car_house I have tried: imd_car_house.loc[(cond1) | (cond2), :] but this is not working.
tagged with: pandas-loc
type: Question
has title: How to create a new column in python under multiple conditions?
tagged with: python
accepted answer: http://stackoverflow.com/a/47112873
has answer: http://stackoverflow.com/a/47112873
tagged with: conditional-statements
tagged with: pandas
linked to: http://stackoverflow.com/q/17071871
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81175477
answer count: 1
duplicate of: http://stackoverflow.com/q/17071871

http://stackoverflow.com/q/47207631
tagged with: py2app
score: 2
answer count: 0
linked to: http://stackoverflow.com/q/25251615
tagged with: macos
favorite count: 0
type: Question
has body: I want to build and deploy a hello world using a homebrewed python + py2app. Build machine: MacOS X 10.12.6 Target machine: MacOS X 10.11 Following many posts I modified the python.rb formula by setting inside MACOSX_DEPLOYMENT_TARGET=10.10 to insure backward compatibility with older macos kernels. The build is OK but when I run the application on the target machine it crashes due to an Illegal Instruction 4. Digging a bit further, this crash is raised by calling the python bundled with the application. Following that post this might be due to the very nature of the homebrewed python that might be built with hardware specific optimization flags. Checking the output of my command brew install -v --build-from-source python I do not see any exotic flag but I can confirm that the deployment works when the application is built with a python that does not come from brew (e.g. from www.python.org). Would you have any idea from where this problem comes from and how to modify the python brew recipe to make it work ? Here are my codes: hello.py #!/usr/bin/env python2.7 if __name__ == "__main__": print "Hello world" build.py import sys import os from setuptools import setup version = "1.0" APP = ['hello.py'] PLIST = { u'CFBundleName': u'Hello', u'CFBundleShortVersionString': version, u'CFBundleVersion': version, u'CFBundleIdentifier': u'-', u'LSApplicationCategoryType': u'public.app-category.science' } OPTIONS = { 'argv_emulation': True, 'plist': PLIST, 'bdist_base': './Build/build', 'dist_dir': './Build/dist', 'graph': False, 'xref': False } setup( name="hello", app=APP, options={'py2app': OPTIONS}, setup_requires=['py2app'] )
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has title: brewed python application bundled with py2app crashes with Illegal Instruction 4

http://stackoverflow.com/q/47128157
tagged with: datastax
type: UnansweredQuestion
has body: I need to process about 4,000 cassandra queries. I convert each query ResultSet into a generator to keep the memory footprint low. Within each row of the generator, I'm only concerned with a few fields of about 50 present. I know that I can't filter directly on value fields in CQL but does the DataStax Python Cassandra driver have something built in that does this? or would it make more sense to just do this when I build the generator i.e def make_gen(response): for row in response: yield row.value.field1, row.value.filed2 I am issuing direct queries at the moment but will move to model based approach later with concurrent queries and prepared statements. The code that is issuing the request is very basic sess = connect_cas(env) for user in users: q = 'select * from table ' + \ 'where key1 = {} and '.format(key_1) + \ 'key2 = {} and '.format(key_2) + \ 'sample_time &gt; {} '.format(t1) + \ 'sample_time &lt; {} '.format(t2) resp_gen = make_gen(sess.execute(q)) # just a yield json.loads(Row.value) for resp in resp_gen: if field in resp: // process data from this field I only care about rows where this "field" is present. I've since updated my generator to only yield data when this condition is true, however, if there is something built into the DataStax driver that does this more efficiently, at 4,000 queries the savings will add up.
answer count: 1
type: Question
tagged with: cassandra
has comment: http://stackoverflow.com/comment/81216370
tagged with: python
has answer: http://stackoverflow.com/a/47168325
score: 0
has title: Possible to filter row values using DataStax python cassandra-driver?

http://stackoverflow.com/a/47213275
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47190414
has body: To access the trip dictionary you would need to use: class CreateMediaPostTaskHandler(webapp2.RequestHandler): def post(self): params = self.request.params start_address_city = params['trip[startAddress][city]']
type: Answer
score: 1
answers question: http://stackoverflow.com/q/47190414

http://stackoverflow.com/a/47181267
answers question: http://stackoverflow.com/q/47180870
has comment: http://stackoverflow.com/comment/81311886
has comment: http://stackoverflow.com/comment/81311958
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/81312258
has comment: http://stackoverflow.com/comment/81326184
has body: Do you mean something like this? This "Figure options" dialog is present in the Qt backend. To use it, import matplotlib matplotlib.use("Qt4Agg") # or "Qt5Agg" depending on the version
has comment: http://stackoverflow.com/comment/81359928
has comment: http://stackoverflow.com/comment/81312422
score: 1
has comment: http://stackoverflow.com/comment/81312180
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81317963
has comment: http://stackoverflow.com/comment/81360123
has comment: http://stackoverflow.com/comment/81433927
has comment: http://stackoverflow.com/comment/81428180
has comment: http://stackoverflow.com/comment/81313020
has comment: http://stackoverflow.com/comment/81330165
accepted answer of: http://stackoverflow.com/q/47180870

http://stackoverflow.com/a/47104519
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81159875
accepted answer of: http://stackoverflow.com/q/47104285
has body: You can get the first record for each symbol and month: df.groupby([pd.Grouper(freq="M"), "symbol"]).agg({"open": "first", "close": "last"}) Note: the ffill only makes sense if you are grouping by symbol too, otherwise you might be filling in one symbols open values with the previous (different symbol). Note: You can just get the entire first row using .first on the DataFrame groupby: df.resample('M').first() (without mentioning the column), you can then filter the columns after e.g. df.resample('M').first()"open", "symbol" df.resample('M').last()"closed", "symbol"
type: Answer
has comment: http://stackoverflow.com/comment/81160315
has comment: http://stackoverflow.com/comment/81160127
downvote count: 0
answers question: http://stackoverflow.com/q/47104285
score: 1
has comment: http://stackoverflow.com/comment/81159927
upvote count: 1

http://stackoverflow.com/q/47208425
has comment: http://stackoverflow.com/comment/106699202
favorite count: 0
tagged with: google-admin-sdk
has comment: http://stackoverflow.com/comment/81435406
linked to: http://stackoverflow.com/q/60262432
score: 1
has answer: http://stackoverflow.com/a/52200894
tagged with: google-api-python-client
tagged with: python
linked to: http://stackoverflow.com/q/26409201
has body: i'm trying to write a simple script that will get the users list from my Google G Suite domain from Directory API of Admin SDK using google-api-python-client. I've read tons of documentation, tried hundreds of various requests, but always receive: googleapiclient.errors.HttpError: &lt;HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/users?domain=example.com&amp;alt=json returned "Not Authorized to access this resource/api"&gt; error. This is what i did: In the Google Developer console https://console.developers.google.com: created a new project enabled 'Admin SDK' API. created a Service account Key saved the generated key into a 'service-key.json' file In the G Suite Admin console: API access is enabled Admin SDK is enabled 'Client ID' of the service key ^^ is authorized to 'View users on your domain', scope: https://www.googleapis.com/auth/admin.directory.user.readonly in the API client access console section. Created a simple test script: #!/usr/bin/env python3 import json from httplib2 import Http from oauth2client.service_account import ServiceAccountCredentials from apiclient.discovery import build scopes = ['https://www.googleapis.com/auth/admin.directory.user.readonly'] credentials = ServiceAccountCredentials.from_json_keyfile_name( 'service-key.json', scopes) account = credentials.authorize(Http()) service = build('admin', 'directory_v1', http=account) response = service.users().list(domain='example.com').execute() print(response) Other: tried also 'Enable G Suite Domain-wide Delegation' (used create_delegated() method on a ServiceAccountCredentials object) i see in the Google Developer Console - Dashboard, that the script is issuing the proper requests - can see the 'directory.users.list' API methods are being issued, but fails with 403 error Thanks in advance for any help!
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/101474815
tagged with: google-api
type: UnansweredQuestion
has title: Receiving 403 error when accessing G Suite Admin SDK using google-api-python-client
downvote count: 0
answer count: 1
upvote count: 1

http://stackoverflow.com/a/47112342
upvote count: 1
has comment: http://stackoverflow.com/comment/81174686
has comment: http://stackoverflow.com/comment/81179298
has comment: http://stackoverflow.com/comment/81178076
answers question: http://stackoverflow.com/q/47112249
type: Answer
score: -1
has body: You need to read the json file at once using json.loads() All the tags appear one level below in data["tweets"] import json json_file = open("test.json").read() tags = ["created_at", "text", "retweet_count", "friends_count","followers_count","verified","place"] data = json.loads(json_file) for i in data["tweet"].keys(): if i not in tags: del data["tweet"][i] print data
has comment: http://stackoverflow.com/comment/81178141
downvote count: 2

http://stackoverflow.com/a/47212181
has comment: http://stackoverflow.com/comment/81442033
answers question: http://stackoverflow.com/q/47211885
score: 1
upvote count: 1
downvote count: 0
type: Answer
has body: A trie (pronounced "try") is a data structure that looks like this: Each path in a trie corresponds to a distinct word. In the trie above, observe that you can trace along any path to form a valid word. This is constructed by having two nodes share a parent node if they share a letter at a specific position. So, for "NEWS" and "NOT", the characters in the first position of each word are the same - this is why they share the node "N" in the diagram. However, the second characters of each word are "E" and "O" respectively, which are not the same, so they branch off into separate paths. Each node also has an indicator which tells you if it corresponds to the end of a word (this is not shown in the diagram). The reason this is efficient is because it is a very compact/efficient way to represent a dictionary. It also allows us to quickly determine if a query word is in our dictionary, since we will only need to go down exactly one path every time to determine if a word is in our dictionary. You can build a trie from the list of country names, then, you can query the board for country names using the trie. For example, if you were looking for "Video" in the trie diagram that I gave above, then you would return False because none of the starting nodes (A, D, N, Z) match the first character V. If the first character matches, then you check if any of the child nodes match the next character, and so on. This allows you to quickly eliminate options when you are searching from some starting character in your crossword board. As another optimization, you may want to record crossword board positions that led to dead ends (i.e. no way to form a valid country name from that position). This will allow you to avoid looking over board positions that don't help you find solutions, which should also speed up your code. Hope this helps!

http://stackoverflow.com/q/47102441
type: Question
has comment: http://stackoverflow.com/comment/81155114
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47102525
answer count: 2
has body: I have a list of letters and letter clusters, like this: ['x', 'str', 'a', 'pr'] I have a string that I need to know how many total occurrences of any member of the list are in it: stripe = 1, rope = 0,, rprpraxp = 4, etc Now I can loop over the members of the list counting occurrences of each member and then total them, like this: sublist = ['x', 'str', 'a', 'pr'] string = "rprpraxp" inst = 0 for member in sublist: inst = inst + string.count(member) print(inst) However I am wondering if I am missing a shorter, simpler, more intuitive and more Pythonic way of counting the members of a set of items in another string, something like: inst = string.multicount(['x', 'str', 'a', 'pr']) Anything like this exist? Thanks.
has answer: http://stackoverflow.com/a/47102525
downvote count: 0
tagged with: python
tagged with: string
score: 6
has comment: http://stackoverflow.com/comment/81154943
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47102526
has title: How to count members of a set in a string in Python?
has comment: http://stackoverflow.com/comment/81157307
has answer: http://stackoverflow.com/a/47102526
upvote count: 6

http://stackoverflow.com/q/47133418
upvote count: 1
favorite count: 0
type: Question
has title: Non-ascii character in Pycharm terminal
score: 1
tagged with: python
tagged with: utf-8
has body: I have set the global encoding and project encoding to utf-8, but still it can not display non-ascii character, like below:
tagged with: pycharm
tagged with: encoding
answer count: 0
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/47073936
type: Question
tagged with: numpy
downvote count: 0
tagged with: pandas
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/47074425
has title: Matrix of pairwise row operations on pandas.DataFrame
favorite count: 0
has body: I want to create a matrix of the results of operations on all pairs of rows in a DataFrame. Here's an example of what I want: df = pandas.DataFrame({'val': [ 2, 3, 5, 7 ], 'foo': ['f1', 'f2', 'f3', 'f4']}, index= ['n1', 'n2', 'n3', 'n4']) def op1(row1, row2): return row1['val']*row2['val'] def op2(row1, row2): return f"{row1['foo']}{row2['foo']}" def apply_op_to_all_row_pairs(df, op): # what goes in here? apply_op_to_all_row_pairs(df, op1) # n1 n2 n3 n4 # n1 4 6 10 14 # n2 6 9 15 21 # n3 10 15 25 35 # n4 14 21 35 49 apply_op_to_all_row_pairs(df, op2) # n1 n2 n3 n4 # n1 'f1f1' 'f1f2' 'f1f3' 'f1f4' # n2 'f2f1' 'f2f2' 'f2f3' 'f2f4' # n3 'f3f1' 'f3f2' 'f3f3' 'f3f4' # n4 'f4f1' 'f4f2' 'f4f3' 'f4f4' I have seen a lot of solutions which hinge on extant functions for computing distance matrices but I want something more generic. E.g., scipy.spatial.distance.pdist does the format of what I want, but only deals in floats and doesn't let you select columns by name (or at least I couldn't figure out how).
type: AnsweredQuestion
score: 1
tagged with: pairwise
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47074425

http://stackoverflow.com/comment/81154552
type: QuestionComment
has text: I tried adding time.sleep(0.1) in between every line of every loop and it's still hanging, which makes me relatively certain that each individual Pipe is safely defined and sequestered from the others
comment on: http://stackoverflow.com/q/47101337
score: 0
type: Comment

http://stackoverflow.com/a/47207917
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81364998
accepted answer of: http://stackoverflow.com/q/47207311
type: AcceptedAnswer
downvote count: 0
has body: Using for loop from scipy import stats l=[] listofname=['A','B'] for x in listofname: l.append(stats.ttest_ind(df[x],df2[x], equal_var=False))
type: Answer
answers question: http://stackoverflow.com/q/47207311

http://stackoverflow.com/comment/81247327
has text: I've included a reduced version and it works fine with everything in the correct order, but when I increase the list sizes it goes back to having duplicates and being out of order.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47144391

http://stackoverflow.com/a/47251507
upvote count: 1
has body: remove all apt-get autoremove pip* install what you want.
answers question: http://stackoverflow.com/q/47208409
type: Answer
score: 1
downvote count: 0

http://stackoverflow.com/a/47124892
answers question: http://stackoverflow.com/q/47124875
score: 2
upvote count: 2
downvote count: 0
has body: Identifiers in Python can't start with a digit. They must start with a letter or an underscore. E.g.: first_miles = 102
type: Answer

http://stackoverflow.com/a/47186881
score: 3
has comment: http://stackoverflow.com/comment/81323098
type: Answer
has body: Try using combinations. import itertools combinations = itertools.combinations('abcd', n) will give you an iterator, you can loop over it or convert it into a list with list(combinations) In order to only include pairs as in your example, you can pass 2 as the argument: combinations = itertools.combinations('abcd', 2) &gt;&gt;&gt; print list(combinations) [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
accepted answer of: http://stackoverflow.com/q/47186849
has comment: http://stackoverflow.com/comment/81323108
has comment: http://stackoverflow.com/comment/81330912
upvote count: 3
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47186849

http://stackoverflow.com/a/47118156
has body: Try using this: for idx,i in enumerate(range(4,len(grades_list))): marks[idx].append(int(grades_list[i])) Considering you know how many assignments are there and initialized the marks list accordingly.
has comment: http://stackoverflow.com/comment/81186772
has comment: http://stackoverflow.com/comment/81186372
has comment: http://stackoverflow.com/comment/81186275
has comment: http://stackoverflow.com/comment/81186639
has comment: http://stackoverflow.com/comment/81186657
answers question: http://stackoverflow.com/q/47118093
has comment: http://stackoverflow.com/comment/81186525
has comment: http://stackoverflow.com/comment/81186475
has comment: http://stackoverflow.com/comment/81186787
has comment: http://stackoverflow.com/comment/81186610
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/81186379
downvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/81186591
has comment: http://stackoverflow.com/comment/81186313

http://stackoverflow.com/q/47125472
has comment: http://stackoverflow.com/comment/81201034
downvote count: 0
has comment: http://stackoverflow.com/comment/81200988
upvote count: 1
has comment: http://stackoverflow.com/comment/81201003
favorite count: 0
linked to: http://stackoverflow.com/q/24274072
type: Question
has body: I've seen a couple questions with the same error reported in them. Yet none of them seem to solve the problem. When I run my code: from Tkinter import * master = Tk() screen = Canvas(master, width = 200, height = 200) screen.grid(row = 0, column = 0) ammo = PhotoImage(file='ammo.gif') screen.create_image(80,40 , image=ammo) master.mainloop() When i run it it gives me the error 'image "pyimage#" doesn't exist' (The # changes every time. Increasing by one each time you run the program) When I put in the file path directly the image displays. But it cant seem to find the image when i have it in my Directory. Help?
has comment: http://stackoverflow.com/comment/81201737
has comment: http://stackoverflow.com/comment/81201806
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81227919
has title: image "pyimage" doesn't exist
tagged with: image
has comment: http://stackoverflow.com/comment/81201234
tagged with: tkinter
linked to: http://stackoverflow.com/q/20251161
answer count: 0
linked to: http://stackoverflow.com/q/38602594
type: UnansweredQuestion

ssh
tags question: http://stackoverflow.com/q/47147951
tags question: http://stackoverflow.com/q/47075754
tags question: http://stackoverflow.com/q/47146558
tags question: http://stackoverflow.com/q/47095410
type: Tag
tags question: http://stackoverflow.com/q/47175638
tags question: http://stackoverflow.com/q/47145626
tags question: http://stackoverflow.com/q/47178577
tag name: ssh
tags question: http://stackoverflow.com/q/47117226

http://stackoverflow.com/a/47077614
has comment: http://stackoverflow.com/comment/81106419
has comment: http://stackoverflow.com/comment/81107128
has comment: http://stackoverflow.com/comment/81126772
has comment: http://stackoverflow.com/comment/81103680
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/47077563
type: Answer
answers question: http://stackoverflow.com/q/47077563
has body: Use matplotlib.use('agg') right after importing matplotlib, to render matplotlib graphics in a headless environment. You can also set this as the default in your matplotlibrc file, or via the MPLBACKEND environment variable. See the matplotlib docs for more details: https://matplotlib.org/faq/usage_faq.html#what-is-a-backend See also the page on using matplotlib in a web application.
has comment: http://stackoverflow.com/comment/81106305
has comment: http://stackoverflow.com/comment/81107707
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81107639

http://stackoverflow.com/comment/81396566
comment on: http://stackoverflow.com/a/47223185
type: Comment
score: 0
type: AnswerComment
has text: You can... the `ord` function does just that.

http://stackoverflow.com/q/47180554
tagged with: http://stackoverflow.com/tag/html
tagged with: python
linked to: http://stackoverflow.com/q/15122864
linked to: http://stackoverflow.com/q/8960288
score: 0
has comment: http://stackoverflow.com/comment/81309940
answer count: 0
duplicate of: http://stackoverflow.com/q/8960288
tagged with: javascript
has body: I am new to web service. Say I have a page url like below: http://xxx/xx/post?id=9898 If I use urllib.request.urlopen() method to download this url's html source, the html I get is different from what I see when open this page in a browser. The difference is, when I open it in browser, I guess some JS code will run (with the given url parameter) and dynamically fetch and generate a lot of contents. But when I do urlopen(), basically this fetching and generating process is not triggered. I am not sure if the term dynamic/static is correct to use here. Correct me if I am wrong, so urlopen() can only download static html page, if it is dynamic page, it will not work? Can anyone show me how to download the html of fully generated version of a web page?
type: Question
has comment: http://stackoverflow.com/comment/81310023
has comment: http://stackoverflow.com/comment/81309904
has title: how to download a dynamically generated web page html in python
type: UnansweredQuestion

http://stackoverflow.com/comment/81104891
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47077942
has text: It seems to work...

http://stackoverflow.com/q/47081772
tagged with: pyqt
tagged with: multithreading
has body: I am having some trouble with a GUI that is freezing during a file save operation that is taking some time, and I'd love to understand why that is. I've followed the instructions of Schollii's wonderful answer on a similar question, but there must be something I'm missing because I cannot get the GUI behaving as I expect. The below example is not runnable, since it shows only the relevant parts, but hopefully it's enough to get a discussion going. Basically I have a main application class that generates some large data, and I need to save it to HDF5 format, but this takes some time. To leave the GUI responsive, the main class creates an object of the Saver class and a QThread to do the actual data saving (using moveToThread). The output of this code is pretty much what I would expect (i.e. I see a message that the "saving thread" has a different thread id than the "main" thread) so I know that another thread is being created. The data is successfully saved, too, so that part is working correctly. During the actual data saving however (which can take some minutes), the GUI freezes up and goes "Not responding" on Windows. Any clues as to what is going wrong? Stdout during running: outer thread "main" (#15108) &lt;__main__.Saver object at 0x0000027BEEFF3678&gt; running SaveThread Saving data from thread "saving_thread" (#13624) Code sample: from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import QThread, pyqtSignal, pyqtSlot, QObject class MyApp(QtWidgets.QMainWindow, MyAppDesign.Ui_MainWindow): def save_file(self): self.save_name, _ = QtWidgets.\ QFileDialog.getSaveFileName(self) QThread.currentThread().setObjectName('main') outer_thread_name = QThread.currentThread().objectName() outer_thread_id = int(QThread.currentThreadId()) # print debug info about main app thread: print('outer thread "{}" (#{})'.format(outer_thread_name, outer_thread_id)) # Create worker and thread to save the data self.saver = Saver(self.data, self.save_name, self.compressionSlider.…
answer count: 1
downvote count: 0
tagged with: pyqt5
upvote count: 1
accepted answer: http://stackoverflow.com/a/47082705
score: 1
has title: Avoiding PyQt5 GUI freeze during threaded operation?
favorite count: 0
has answer: http://stackoverflow.com/a/47082705
type: Question
type: AnsweredQuestion
tagged with: python-multithreading
tagged with: python
linked to: http://stackoverflow.com/q/41526832

http://stackoverflow.com/q/47117979
type: UnansweredQuestion
has title: How can you form a new dataframe reflecting the changes of values in an original dataframe?
has comment: http://stackoverflow.com/comment/81186163
has comment: http://stackoverflow.com/comment/81194937
tagged with: python
has comment: http://stackoverflow.com/comment/81186108
has comment: http://stackoverflow.com/comment/81186029
has comment: http://stackoverflow.com/comment/81186066
has body: If you could peek into the future and know exactly what stocks to buy and sell given their entire price history, how would you implement it, given constraints that your only values of Shares is 1000, 0, and -1000? You also start with 1000 shares. You can also trade 2000 shares to get from 1000 directly to -1000 and vice versa. I want to take a dataframe df_prices like this: JPM 2008-01-02 38.47 2008-01-03 38.20 2008-01-04 37.33 2008-01-07 37.71 2008-01-08 36.21 2008-01-09 36.72 and transform it into df_trades: Symbol Order Shares 2008-01-02 JPM NOTHING 1000 2008-01-03 JPM HOLD 1000 2008-01-04 JPM HOLD 1000 2008-01-07 JPM BUY 0 2008-01-08 JPM SELL -1000 2008-01-09 JPM HOLD 0 using this code: if df_prices['JPM'].shift(1) &gt; df_prices['JPM'] &amp; curr_hold == 0: df_orders['Order'] = 'SELL' df_orders['Shares'] += 1000 elif df_prices['JPM'].shift(1) &lt; df_prices['JPM'] &amp; curr_hold == 0: df_orders['Order'] = 'BUY' df_orders['Shares'] -= 1000 elif df_prices['JPM'].shift(1) &gt; df_prices['JPM'] &amp; curr_hold == -1000: df_orders['Order'] = 'HOLD' elif df_prices['JPM'].shift(1) &lt; df_prices['JPM'] &amp; curr_hold == 1000: df_orders['Order'] = 'HOLD' It doesn't work however. I get the error: TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]
score: 0
has comment: http://stackoverflow.com/comment/81195661
has comment: http://stackoverflow.com/comment/81186105
has comment: http://stackoverflow.com/comment/81186051
tagged with: pandas
has comment: http://stackoverflow.com/comment/81186170
has comment: http://stackoverflow.com/comment/81186084
has comment: http://stackoverflow.com/comment/81186147
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/47126528
has comment: http://stackoverflow.com/comment/81186027
tagged with: typeerror
has comment: http://stackoverflow.com/comment/81186034

http://stackoverflow.com/comment/81245822
type: Comment
score: 0
type: AnswerComment
has text: This will not work as expected - the `for row in file1` will loop line-wise over the contents of the file. In the consequence `row[3]` will access the line as an array of characters - no CSV parsing is happening here.
comment on: http://stackoverflow.com/a/47147649

http://stackoverflow.com/q/47119748
has comment: http://stackoverflow.com/comment/81190082
has comment: http://stackoverflow.com/comment/81190418
tagged with: sklearn-pandas
has comment: http://stackoverflow.com/comment/81190129
has comment: http://stackoverflow.com/comment/81190062
downvote count: 0
has title: How to convert Countvectorized data back to text data in Python?
tagged with: pandas
has comment: http://stackoverflow.com/comment/81189891
answer count: 1
has body: how can I convert count vectorized text data back to textual form. I have text data which I had made into sparse matrix using countvectorizer for classification. Now I want the sparse martix of text data to be converted back into text data. My code cv = CountVectorizer( max_features = 500,analyzer='word') cv_addr = cv.fit_transform(data.pop('Clean_addr')) for i, col in enumerate(cv.get_feature_names()): data[col] = pd.SparseSeries(cv_addr[:, i].toarray().ravel(), fill_value=0)
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/81189908
has comment: http://stackoverflow.com/comment/81190220
favorite count: 0
has comment: http://stackoverflow.com/comment/81190056
type: Question
has comment: http://stackoverflow.com/comment/81189941
has comment: http://stackoverflow.com/comment/81190076
has comment: http://stackoverflow.com/comment/81189945
score: 5
upvote count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47120005
has comment: http://stackoverflow.com/comment/81189771
tagged with: python
has comment: http://stackoverflow.com/comment/81190036

http://stackoverflow.com/q/47181244
has comment: http://stackoverflow.com/comment/81311910
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81312478
type: UnansweredQuestion
tagged with: time
has title: Conditions in a new column df with Numpy and Timedelta
answer count: 1
tagged with: timedelta
has body: I am creating a new column ['inc_cr_date_adjusted'] of a df based on 2 columns of the df, the inc_cr_date_day and inc_cr_date but the the below code it's not working as expected. Doesn't give error but it's not working as defined by the conditions as only the conditions for Saturday and Sunday work. The conditions that have included hour &amp; time do not work as the days are not summing up (Timedelta('1 days'). Other issue is that most of the dates should assume the last line of code "df['inc_cr_date'])" and do not change at all, but thats not appening also. My conditions are based on the Day of the week and hour &amp; minute visible in column inc_cr_date. hour&amp;minute is 9:30 and 18:30 which is divided using the &amp;. Code is: df['inc_cr_date_day'] = df['inc_cr_date'].dt.weekday_name df['inc_cr_date_adjusted'] = np.select([(df['inc_cr_date_day'] == 'Saturday'),#condition working (df['inc_cr_date_day'] == 'Sunday'),#condition working ((df['inc_cr_date_day'] == 'Monday')&amp; (df['inc_cr_date'].dt.hour &gt; 18 ) &amp; df['inc_cr_date'].dt.minute &gt; 30), ((df['inc_cr_date_day'] == 'Monday')&amp; (df['inc_cr_date'].dt.hour &lt; 9 ) &amp; df['inc_cr_date'].dt.minute &lt; 30), ((df['inc_cr_date_day'] == 'Tuesday')&amp; (df['inc_cr_date'].dt.hour &gt; 18 ) &amp; df['inc_cr_date'].dt.minute &gt; 30), ((df['inc_cr_date_day'] == 'Tuesday')&amp; (df['inc_cr_date'].dt.hour &lt; 9 ) &amp; df['inc_cr_date'].dt.minute &lt; 30), ((df['inc_cr_date_day'] == 'Wednesday')&amp; (df['inc_cr_date'].dt.hour &gt; 18 ) &amp; df['inc_cr_date'].dt.minute &gt; 30), ((df['inc_cr_date_day'] == 'Wednesday')&amp; (df['inc_cr_date'].dt.hour &lt; 9 ) &amp; df['inc_cr_date'].dt.minute &lt; 30), ((df['inc_cr_date_day'] == 'Thursday')&amp; (df['inc_cr_date'].dt.hour &gt; 18 ) &amp; df['inc_cr_date'].dt.minute &gt; 30), ((df['inc_cr_date_day'] == 'Thursday')&amp; (df['inc_cr_date'].dt.hour &lt; 9 ) &amp; df['inc_cr_date'].dt.minute &lt; 30), ((df['inc_cr_date_day'] == 'Friday')&amp; (df['inc_cr_d…
score: 0
has answer: http://stackoverflow.com/a/47181848
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/81312465

http://stackoverflow.com/comment/81105373
type: AnswerComment
has text: Thanks for the reply. But I'm wondering if I need to setup an EC2 server for installing the module? Because at the moment I just went to AWS Lambda and created a function. Is there something more that should be set?
comment on: http://stackoverflow.com/a/47078082
type: Comment
score: 0

http://stackoverflow.com/comment/81347502
type: QuestionComment
comment on: http://stackoverflow.com/q/47199246
score: 0
has text: Well 'hope' or 'faith' should be a regex, even though it is a very simple one, right? And I would like each element of the list to be searched in the textfile, that's why I thought I'd take a re.findall.
type: Comment

http://stackoverflow.com/q/47176875
has title: Pandas HDFStore concurrent multiple write
has comment: http://stackoverflow.com/comment/81336675
tagged with: hdfstore
type: Question
has comment: http://stackoverflow.com/comment/81313518
type: UnansweredQuestion
has body: How to write data to hdfstore file asynchronously. I tried but getting exception as /usr/share/nginx/www/test/59ece246b82453024e2df1ec.h5 Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/gevent/greenlet.py", line 536, in run result = self._run(*self.args, **self.kwargs) File "hdfExample.py", line 32, in fetch usg = Usage("59ece246b82453024e2df1ec", mode="a", cnt=gcpage) File "hdfExample.py", line 12, in init super(Usage, self).init(partnerId, mode, cnt=cnt) File "/usr/share/nginx/www/cloudconsolestandalone/cwunite/flask/hdfinterface.py", line 37, in init self.dataframe = self.hdfConn.get(self.partnerId) File "/usr/local/lib/python2.7/dist-packages/pandas/io/pytables.py", line 671, in get return self._read_group(group) File "/usr/local/lib/python2.7/dist-packages/pandas/io/pytables.py", line 1348, in _read_group s.infer_axes() File "/usr/local/lib/python2.7/dist-packages/pandas/io/pytables.py", line 2350, in infer_axes self.get_attrs() File "/usr/local/lib/python2.7/dist-packages/pandas/io/pytables.py", line 3188, in get_attrs a.infer(self) for a in self.indexables if not a.is_an_indexable File "/usr/local/lib/python2.7/dist-packages/pandas/io/pytables.py", line 1565, in infer new_self.get_attr() File "/usr/local/lib/python2.7/dist-packages/pandas/io/pytables.py", line 2168, in get_attr self.set_kind() File "/usr/local/lib/python2.7/dist-packages/pandas/io/pytables.py", line 1877, in set_kind self.typ = getattr(self.description, self.cname, None) File "/usr/local/lib/python2.7/dist-packages/pandas/io/pytables.py", line 1608, in description return self.table.description AttributeError: 'UnImplemented' object has no attribute 'description' Wed Nov 8 15:33:51 2017 failed with AttributeError Traceback (most recent call last): File "/usr/lib/python2.7/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/usr/local/lib/python2.7/dist-packages/tables/file.py", line 134, in close_all fileh.close() File "/usr/local/lib/python2.7/di…
tagged with: python
tagged with: pytables
score: 0
tagged with: pandas
answer count: 0
tagged with: hdf5

http://stackoverflow.com/q/47183314
has title: Python CSV data import to table like object
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/47183531
accepted answer: http://stackoverflow.com/a/47183703
has answer: http://stackoverflow.com/a/47183531
has answer: http://stackoverflow.com/a/47183703
tagged with: statistics
type: AnsweredQuestion
score: 0
has body: I have data from csv: time, meas, meas2 15:10, 10, 0.3 15:22, 12, 0.4 15:30, 4 So every row can contain different number of data, less or equal to number of columns in first row. I am writing some simple stats app. But for one graph I need for example sum of data in column with name meas. But for the second graph I would like to filter this data by the time. Is there any ready-to-get- class with some kind of object to utilise getting data from columns or rows depending on need? Or I just need to keep data in rows and calculate input for the 1st graph on the fly?
tagged with: http://stackoverflow.com/tag/csv
tagged with: python

http://stackoverflow.com/a/73775084
type: Answer
has body: Use the fastparquet write function from fastparquet import write write(file_name, df, append=True) The file must already exist as I understand it. API is available here (for now at least): https://fastparquet.readthedocs.io/en/latest/api.html#fastparquet.write
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47191675

http://stackoverflow.com/q/47204252
has title: How to configure `train_and_evaluate` to also save the metric on training set into tensorboard?
score: 2
has answer: http://stackoverflow.com/a/49787479
has body: I have the following code that trains a model on the iris data set and uses accuracy as the metric to evaluate the model: # This is based on the complete code for the following blogpost: # https://developers.googleblog.com/2017/09/introducing-tensorflow-datasets.html import tensorflow as tf import os from tensorflow.contrib.learn import Experiment, RunConfig from urllib.request import urlopen from tensorflow.contrib.learn import RunConfig () PATH = "./tf_dataset_and_estimator_apis" # Fetch and store Training and Test dataset files PATH_DATASET = PATH + os.sep + "dataset" FILE_TRAIN = PATH_DATASET + os.sep + "iris_training.csv" FILE_TEST = PATH_DATASET + os.sep + "iris_test.csv" URL_TRAIN = "http://download.tensorflow.org/data/iris_training.csv" URL_TEST = "http://download.tensorflow.org/data/iris_test.csv" def downloadDataset(url, file): if not os.path.exists(PATH_DATASET): os.makedirs(PATH_DATASET) if not os.path.exists(file): data = urlopen(url).read() with open(file, "wb") as f: f.write(data) f.close() downloadDataset(URL_TRAIN, FILE_TRAIN) downloadDataset(URL_TEST, FILE_TEST) # The CSV features in our training &amp; test data feature_names = [ 'SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'] # Create an input function reading a file using the Dataset API # Then provide the results to the Estimator API def my_input_fn(file_path, perform_shuffle=False, repeat_count=1): def decode_csv(line): parsed_line = tf.decode_csv(line, [[0.], [0.], [0.], [0.], [0]]) label = parsed_line[-1:] # Last element is the label del parsed_line[-1] # Delete last element features = parsed_line # Everything but last elements are the features d = dict(zip(feature_names, features)), label return d dataset = (tf.contrib.data.TextLineDataset(file_path) # Read text file .skip(1) # Skip header row .map(decode_csv)) # Transform each elem by applying decode_csv fn if perform_shuffle: # Randomizes input using a window of 256 elements (read into memory) dataset = dataset.shuffle(buffer_siz…
tagged with: tensorboard
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/81273590
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47161318
type: AnswerComment
has text: @Vandith hm, can you c&p the actual session with inputs and outputs and edit it in your question above?

http://stackoverflow.com/comment/81297382
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47171485
type: Comment
has text: Thank you JeffC for your reply. I've tried yours.And it say: AttributeError: visibility of element located object has no attribute 'text'

http://stackoverflow.com/a/47194157
has body: context manager was added to socketserver in 3.6: https://bugs.python.org/issue26404, with commit. below 3.6, in 3.4.2, you have to call server_close() manually: try: server = socketserver.UDPServer((HOST, PORT), MyUDPHandler) server.serve_forever() finally: server.server_close()
type: Answer
answers question: http://stackoverflow.com/q/47194006
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47194006

http://stackoverflow.com/comment/81159738
type: Comment
comment on: http://stackoverflow.com/a/47104482
score: 2
has text: I agree -- again this was more of a comment directed at people new to datasetAPI who might not be familiar with the way "element" is actually a dynamic concept depending on how you define the dataset. Its intuitive once you get it, but took me a second.
type: AnswerComment

http://stackoverflow.com/a/50313947
answers question: http://stackoverflow.com/q/47211939
downvote count: 0
has body: followers_panel = browser.find_element_by_xpath(XPATH) i = 1 while i < number_of_followers: try: follower = browser.find_element_by... i += 1 except NoSuchElementException: self.browser.execute_script( "arguments[0].scrollTop = arguments[0].scrollHeight",followers_panel ) This way you can crawl all of the followers.
upvote count: 5
score: 5
type: Answer

http://stackoverflow.com/comment/81943581
score: 0
type: Comment
has text: Thanks! Your answer really helps me a lot!
type: AnswerComment
comment on: http://stackoverflow.com/a/47106484

http://stackoverflow.com/q/47126647
linked to: http://stackoverflow.com/q/26221300
accepted answer: http://stackoverflow.com/a/47126675
downvote count: 0
linked to: http://stackoverflow.com/q/44517350
tagged with: python
has answer: http://stackoverflow.com/a/47126675
type: AnsweredQuestion
has body: I want to add a new column to a DataFrame based on existing columns. The new column is just a tuple of three values of three columns: df0.shape # (5410185, 17) new_col = pd.Series(list(zip(df0['a'], df0['b'], df0['c']))) new_col.shape # (5410185,) new_col.isnull().sum() # 0 df0['abc'] = new_col df0['abc'].isnull().sum() # 14334 I tried the same method on a sample df and it works as expected: test = pd.DataFrame(np.random.randint(0,1000,100000000).reshape(1000000,100)) test['new'] = pd.Series(list(zip(test[1], test[2], test[3]))) test['new'].isnull().sum() # 0 'assign' also produce the same result: df0 = df0.assign(new_col2 = pd.Series(list(zip(df0['a'], df0['b'], df0['c'])))) df0['new_col2'].isnull().sum() # 14334 I found two similar questions, this and this. I suspect my problem has also something to do with indexing. It seems there are 89 non-identical values: np.sum(df0.index == new_col.index) # 89 Assigning the same Series as the index of df0 works: df0.index = new_col df0['abc'] = df0.index df0['abc'].isnull().sum() # 0 UPDATE Here is some benchmarking for @jezreal's solutions: %time df0['abc'] = pd.Series(list(zip(df0['a'], df0['b'], df0['c'])), index=df0.index) Wall time: 2.32 s % time df0['abc'] = df0'a','b','c'.apply(tuple, axis=1) Wall time: 1min 42s %time df0['abc'] = df0.set_index(['a','b','c']).index.values Wall time: 8.68 s % time df0['abc'] = pd.Series([tuple(x) for x in df0'a','b','c'.values.tolist()], index=df0.index) Wall time: 9.83 s
tagged with: pandas
score: 1
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has title: Adding new column from existing columns using pd.Series() creates NaN values

http://stackoverflow.com/comment/81272804
type: Comment
has text: @bvg So you duplicated a question knowingly without even referencing the old ones you already checked?
type: AnswerComment
comment on: http://stackoverflow.com/a/47158190
score: 0

http://stackoverflow.com/a/47217485
has body: it would be easier for you to keep your data as pandas dataframes (i.e. perform your operations on yod_user, yod_bank). Regardless, using your variable names: userd = pd.DataFrame([ {"id":2, "username":"pk@gmail.in","password":"YkxJNWNDT"}, {"id":4, "username":"test@gmail.com", "password":"VjNUYWh"}, {"id":6, "username":"zz113@gmail.com", "password":"dddd"}, {"id":8, "username":"faulmike@aol.com", "password":"ssss"}, {"id":10, "username":"newr10@gmail.com", "password":"errfs"} ]) bankd = pd.DataFrame([ {"userid":"2", "bankid": "99", "acc_number": "4590", "bank_name":"xyz"}, {"userid":"4", "bankid": "100", "acc_number": "4520", "bank_name": "abc"}, {"userid":"6", "bankid": "56", "acc_number": "4980", "bank_name": "xyz"}, {"userid":"8", "bankid": "99", "acc_number": "4570" ,"bank_name": "ypr"}, {"userid":"2", "bankid": "17", "acc_number": "4530", "bank_name": "abc"} ]) # Your data was not in the same format between bankd and userd. bankd['userid'] = pd.to_numeric(bankd['userid']) # Iterate through the dict and append results from searching through dataframes def append_bankd(df_in): userid = df_in['id'] df_in['bankd'] = bankd[bankd['userid']==userid].to_dict('r') return df_in result = [append_bankd(m) for m in userd.to_dict('r')] # Sample result [ { 'bankd': [ {'acc_number': '4590', 'bank_name': 'xyz', 'bankid': '99', 'userid': 2}, { 'acc_number': '4530', 'bank_name': 'abc', 'bankid': '17', 'userid': 2}], 'id': 2, 'password': 'YkxJNWNDT', 'username': 'pk@gmail.in'}, ... ]
score: 0
answers question: http://stackoverflow.com/q/47216716
type: Answer

http://stackoverflow.com/comment/81159770
has text: Unfortunately no, I get this message AttributeError: module 'tweepy' has no attribute 'auth' I think I may have not installed tweepy correctly in my virtual environment. Would you have some suggestion on installing tweepy in a way other than pip install tweepy which installs it in the python2.7 version and not the third.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47103691
score: 0

http://stackoverflow.com/q/47171592
score: 0
linked to: http://stackoverflow.com/q/16736080
tagged with: python
has title: How to change specific file extensions in a folder using Python ?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47171646
has answer: http://stackoverflow.com/a/47171646
answer count: 1
tagged with: file
upvote count: 1
downvote count: 1
has body: I read some information about changing file extension using python code. I have giant folder with several file types like .csv, .json and .sf1. All I need to do is to replace all .sf1 to .txt file. Any suggested code in python would help.
favorite count: 0
has comment: http://stackoverflow.com/comment/81292837
type: Question
duplicate of: http://stackoverflow.com/q/16736080

http://stackoverflow.com/comment/89875108
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47119362
type: AnswerComment
has text: I agree with the highlighted part but we can further train .vec files also on other data/corpus .

http://stackoverflow.com/q/47081341
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81112409
type: Question
linked to: http://stackoverflow.com/q/24061099
has comment: http://stackoverflow.com/comment/81114061
accepted answer: http://stackoverflow.com/a/47138373
has answer: http://stackoverflow.com/a/47138373
tagged with: python
has comment: http://stackoverflow.com/comment/81113010
score: -1
type: AnsweredQuestion
has title: tkinter image resizing via controller
tagged with: tkinter
linked to: http://stackoverflow.com/q/29444725
upvote count: 0
has body: I wrote an application with tkinter that uses classes as structure. I stick very close to the often seen sentdex structure (See link: Tkinter and ttk in python 2.7), where every new page is basically a frame which is raised to the top via a controller function. Currently I am trying to find a solution for automatically resizing background images when the root window is maximized/minimized. I found a solution but it doesn't fit my needs to 100% because here the function is in the same class as the image: (See link: Tkinter resize background image to window size (Python 3.4)) I need a general function which takes a reference to page (to know where to resize an image) and then resizes an image which is - in best case - saved on this particular page. All my attempts to use lambda: controller failed. I would be very glad if someone could hinder me from hardcoding the resizeimage-function on every page. This is my code: import tkinter as tk from tkinter import font as tkfont from PIL import Image, ImageTk Here I create the controller class : class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, PageOne): page_name = F.__name__ frame = F(container,self) self.frames[page_name] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame("StartPage") def show_frame(self, page_name): #Show a frame for the given page name frame = self.frames[page_name] frame.tkraise() This is the resizeImage-function I try to code: def resizeImage(self): # give me an image img = self.frames[StartPage].img # give me an image copy img_copy = self.frames[StartPage].img_copy # give me background image background_image = self.frames[StartPage].background_image new_width = event.width new_height = event.height img = img_copy.resize((new_width, new_he…

http://stackoverflow.com/comment/81238565
score: 1
comment on: http://stackoverflow.com/q/47143655
type: Comment
type: QuestionComment
has text: SO is not a coding service, it shows what you have tried.

http://stackoverflow.com/comment/81174138
score: 1
type: Comment
has text: Dual groupby is always used to be my thing : )
type: AnswerComment
comment on: http://stackoverflow.com/a/47111863

http://stackoverflow.com/q/47164099
upvote count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/81283086
tagged with: naivebayes
tagged with: python
score: 1
has body: I have this task: Do Anyone can help me with - how to resolve this in R or Python using machine learning and some of the R/Python packages for Naive Bayes using Bayesian theorem. Or any other useful way (KNN/something else) I've used this code in R, but do I need something more for this 10^9 library(e1071) data.conversions &lt;- data.frame(Country = c("US","FR","US"), Browser = c("Firefox","Chrome","Chrome"), Site = c("Website1", "Website2", "Website2"), Ad = c("Ad4","Ad7","Ad4"), Converted = c("y","n","y") ) data.conversions class(data.conversions$Converted) model &lt;- naiveBayes(Converted~., data=data.conversions) convertion &lt;- data.frame(Country = c("FR"), Browser = c("Firefox"), Site = c("Website1"), Ad = c("Ad4")) predict(model, convertion) #The prediction shows "y" -&gt; yes for conversion for the user in this model. test&lt;- predict(model, convertion) convertion$Converted &lt;- test Predicted &lt;- rbind(data.conversions, convertion) newdf &lt;- rbind(data.conversions, convertion) dim(data.conversions) dim(convertion) Thanks in advance.
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81282804
downvote count: 0
has title: How to resolve this conversion probability task - Naive Bayes in R or Python
tagged with: bayesian

http://stackoverflow.com/comment/81287086
type: Comment
type: AnswerComment
score: 0
has text: This answer doesn't work across century boundaries and the result is a float (in python 3).
comment on: http://stackoverflow.com/a/47168321

http://stackoverflow.com/q/47203951
answer count: 6
has comment: http://stackoverflow.com/comment/81356757
has comment: http://stackoverflow.com/comment/81362456
score: 0
tagged with: list
has answer: http://stackoverflow.com/a/47204620
tagged with: while-loop
has comment: http://stackoverflow.com/comment/81362285
has answer: http://stackoverflow.com/a/47204152
duplicate of: http://stackoverflow.com/q/6009589
has answer: http://stackoverflow.com/a/47204173
has comment: http://stackoverflow.com/comment/81357976
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47204101
has title: check in while loop for only numbers in list
has answer: http://stackoverflow.com/a/47204023
type: UnansweredQuestion
has body: I´m new to python and wanted to know how I can check with a while loop if the list contains only numbers ... else: print("sorry only numbers allowed") numbers = [34, 39, 110, 303, 889, 223, 982, 7676] def getsSumVersionTwo(listOfStuff): sumNumbers = 0 for x in listOfStuff: sumNumbers += x return sumNumbers print(getsSumVersionTwo(numbers)) getsSumVersionTwo(numbers)
linked to: http://stackoverflow.com/q/6009589
has answer: http://stackoverflow.com/a/47204059
tagged with: python

http://stackoverflow.com/q/47124169
has comment: http://stackoverflow.com/comment/81199867
has title: Why is exit status -11 returned?
has comment: http://stackoverflow.com/comment/81198875
has comment: http://stackoverflow.com/comment/81199826
has comment: http://stackoverflow.com/comment/81198914
has comment: http://stackoverflow.com/comment/81198485
tagged with: testing
has comment: http://stackoverflow.com/comment/81198624
type: Question
has comment: http://stackoverflow.com/comment/81199491
has comment: http://stackoverflow.com/comment/81199074
has comment: http://stackoverflow.com/comment/81198797
has comment: http://stackoverflow.com/comment/81198444
tagged with: python
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/c
has body: I'm writing a python script to check a C program I made. Sometimes, when calling my executable from the script, I get subprocess.CalledProcessError: Command Command '['./parallel_snake', 'input/input1', 'output/output1', '20000']' returned non-zero exit status -11 This is the line where I call the executable: p = subprocess.check_output(["./parallel_snake", "input/" + input_file, "output/" + input_file.replace("in", "out"), "20000"]) Why do I get this error, and how can I get rid of it? EDIT My code: input_files = [f for f in listdir("input")] num_threads = [2, 4, 6, 8] for input_file in input_files: print "Checking " + input_file + "\n" for num in num_threads: os.environ['OMP_NUM_THREADS'] = str(num) p = subprocess.check_output(["./parallel_snake", "input/" + input_file, "output/" + input_file.replace("in", "out"), "20000"]) print "\t" + str(num) + " threads: " + str(p) Input for the parallel_snake C program: 3 // there are 3 snakes 1 2 1 N // head of a snake (1, 2)/its encoding (1)/its move direction (N) 5 7 2 E // second snake 3 4 3 S // third snake 9 9 // dimensions of the map 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 3 3 3 3 0 0 1 1 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 2 0 0 0 0 0 0 2 0 0 0 0 0 0 2 2 2 0 0 0 0 0 0 0 0 0 0 0 0 // the map with the 3 snakes The purpose is to move the snakes in the indicated direction as long as they do not collide. As you can see, if snake 1 goes up and 2 goes to right, they will collide in 5 steps I used #pragma omp parallel for to count from 0 to the maximum number of movements, which was 20 000. If I decide to not paralelise the counting, but to paralelise the iteration through the snakes (i have an array of them), the problem does not appear.
has comment: http://stackoverflow.com/comment/81198687
has comment: http://stackoverflow.com/comment/81199853
has comment: http://stackoverflow.com/comment/81198716
has comment: http://stackoverflow.com/comment/81200291
has comment: http://stackoverflow.com/comment/81198772
tagged with: subprocess
has comment: http://stackoverflow.com/comment/81198605
score: 0
has comment: http://stackoverflow.com/comment/81198963
has comment: http://stackoverflow.com/comment/81199105
tagged with: scripting
answer count: 0

http://stackoverflow.com/comment/81312180
type: AnswerComment
score: 0
type: Comment
has text: Matplotlib version 2.0.2. I am on a windows machine and i am not really sure how to figure out which "backend "i am using to be honest. I do not call a matplotlib.use() comment.
comment on: http://stackoverflow.com/a/47181267

http://stackoverflow.com/comment/106133738
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47202205
has text: This may not be related to machine learning but shouldn't the super call be like `super(Policy, self).__init__()` instead of `super(Policy2, self).__init__()`? In Python3 it can even be simplified to just `super().__init__()`.
score: 0

http://stackoverflow.com/a/47079083
has comment: http://stackoverflow.com/comment/81110233
accepted answer of: http://stackoverflow.com/q/47077806
has comment: http://stackoverflow.com/comment/81110026
answers question: http://stackoverflow.com/q/47077806
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/81109800
has comment: http://stackoverflow.com/comment/81109640
has body: It is referring to echoscu: From the documentation The echoscu application implements a Service Class User (SCU) for the Verification SOP Class. It sends a DICOM C-ECHO message to a Service Class Provider (SCP) and waits for a response. The application can be used to verify basic DICOM connectivity. Assuming you are running Linux, then you should have this installed. You can type which echoscu to get the path to it, if it's not in /usr/local/bin/ (I don't know if different distro's put stuff elsewhere)
score: 0

http://stackoverflow.com/comment/81442667
score: 0
type: AnswerComment
has text: Thank you so much once again Mr. Smith!
type: Comment
comment on: http://stackoverflow.com/a/47194867

http://stackoverflow.com/q/47146815
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81245660
has comment: http://stackoverflow.com/comment/81245666
has comment: http://stackoverflow.com/comment/81244883
linked to: http://stackoverflow.com/q/8665072
type: UnansweredQuestion
has body: I'm automating some scripts on Craigslist. I want to upload 2 pictures without the dialogue box opening. Here is a screenshot, the button says "Choose Files": enter image description here I have referenced the following StackOverflow post: How to upload file ( picture ) with selenium, python But my code is still not working. Here is my code: from selenium import webdriver import os driver = webdriver.Chrome() driver.get("https://dallas.craigslist.org/") # Click on "computer" link driver.find_element_by_link_text("computer").click() #Post driver.find_element_by_link_text("post").click() #Gig Offered radion button driver.find_element_by_xpath("/html/body/article/section/form/ul/li[2]/label/span[2]").click() # I want to hire someone driver.find_element_by_xpath("/html/body/article/section/form/label[1]").click() #Please choose a category: Computer Gigs" driver.find_element_by_xpath("//*[@id='picker']/ul/li[1]/label/span[2]").click() # Choose the location driver.find_element_by_xpath("/html/body/article/section/form/ul/li[1]/label/input").click() # Enter text # Enter Posting Title posting = driver.find_element_by_id("PostingTitle") posting.send_keys("[SEEKING] Parents with Kids who Play Sports. Save Money on College!") # Enter Location area = driver.find_element_by_id("GeographicArea") area.send_keys("Dallas Area") # Enter Zip Code zipcode = driver.find_element_by_id("postal_code") zipcode.send_keys("75001") # Enter Body body = driver.find_element_by_id("PostingBody") body.send_keys("this is a test") # No Pay driver.find_element_by_xpath("//*[@id='vol_label']/input").click() #From Email fromemail = driver.find_element_by_id("FromEMail") fromemail.send_keys("foo@gmail.com") # Confirm Email confirmemail = driver.find_element_by_id("ConfirmEMail") confirmemail.send_keys("foo@gmail.com") # Maps driver.find_element_by_id("wantamap").click() # Click Continue driver.find_element_by_xpath("//*[@id='postingForm']/div/button").click() # Use Classic Uploader driver.find_element_by…
has comment: http://stackoverflow.com/comment/81246975
tagged with: python
has comment: http://stackoverflow.com/comment/81248223
has comment: http://stackoverflow.com/comment/81327123
score: 0
has answer: http://stackoverflow.com/a/47189465
answer count: 1
tagged with: selenium
upvote count: 1
downvote count: 1
favorite count: 0
has title: Choose Files Button not Uploading my Pictures (Selenium, Python, Mac)

http://stackoverflow.com/comment/81336243
comment on: http://stackoverflow.com/a/47193254
score: 1
type: Comment
has text: From the GitHub issue you linked, sounds like GCS support doesn't work on Windows (probably because it requires libcurl). On Windows you'll be stuck downloading the files periodically with gsutil. If you have access to Ubuntu that would be better.
type: AnswerComment

http://stackoverflow.com/comment/84020612
comment on: http://stackoverflow.com/a/47213557
score: 1
type: Comment
type: AnswerComment
has text: You should consult the source code for that information: https://github.com/RaRe-Technologies/gensim/blob/develop/gensim/models/word2vec.py & https://github.com/RaRe-Technologies/gensim/blob/develop/gensim/models/keyedvectors.py will show what `syn1neg`, `syn0`, and other other properties that might be stored as separate files are.

http://stackoverflow.com/comment/81146627
has text: In that instance is `header` and `list` the actual header and list I'm searching for?
score: 0
comment on: http://stackoverflow.com/a/47098430
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47087167
has answer: http://stackoverflow.com/a/47095565
tagged with: python
type: Question
type: UnansweredQuestion
score: 0
answer count: 1
has body: Need to add button to django admin page, if you want to edit Model, you push Edit then edit what you need, and save it. When you open it after saving, it must be uneditable again. So, how to do that? I have simple admin.py code: from django.contrib import admin from .models import Order class OrderAdmin(admin.ModelAdmin): list_display = ['__str__', 'email', 'project_type', 'price'] list_filter = ['email', 'first_name', 'project_type', 'price'] readonly_fields = ('first_name', 'last_name', 'email', 'phone', 'project_type', 'price') fields = ('first_name', 'last_name', 'email', 'phone', 'project_type', 'services', 'price', 'slug') def has_add_permission(self, request): return False admin.site.register(Order, OrderAdmin)
has title: How to toggle readonly_fields in Django admin?
tagged with: django
has comment: http://stackoverflow.com/comment/81134158
tagged with: admin

http://stackoverflow.com/comment/81227594
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47139010
has text: @Adirio I initially left that part of the code unchanged.

screen-scraping
tags question: http://stackoverflow.com/q/47076246
tags question: http://stackoverflow.com/q/47116637
tags question: http://stackoverflow.com/q/47141049
tag name: screen-scraping
type: Tag

http://stackoverflow.com/a/54907545
has body: In odoo core, you can find the Accounting Date field in other info tab of supplier invoices. Ref. https://github.com/OCA/l10n-italy/issues/254#issuecomment-345619476
answers question: http://stackoverflow.com/q/47094325
type: Answer
score: 0

http://stackoverflow.com/q/47096228
has comment: http://stackoverflow.com/comment/81142530
score: 1
has body: self.df['X'] = self.df['x'].apply(lambda x: my_map.get(x)) How can i a drop those rows where my_map.get(x) returns None. I am looking for a solution where i do not have to iterate over the column again to drop rows. Thanks
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47096423
accepted answer: http://stackoverflow.com/a/47096423
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/47096797
has answer: http://stackoverflow.com/a/47096383
possible better answer: http://stackoverflow.com/a/47096383
tagged with: python
has answer: http://stackoverflow.com/a/47096305
has answer: http://stackoverflow.com/a/47096886
has comment: http://stackoverflow.com/comment/81142004
has comment: http://stackoverflow.com/comment/81142028
answer count: 4
has title: Drop row if lambda returns None Pandas
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46091924
tagged with: pandas

http://stackoverflow.com/q/47109501
tagged with: django-signals
type: Question
has comment: http://stackoverflow.com/comment/81169233
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4721771
tagged with: django
linked to: http://stackoverflow.com/q/22999630
has body: I am trying to use the ID of the django user for an action when a model is saved. For that I have a receiver as follows: @receiver(post_save, sender=ServersModel) def create_zabbix_host(sender, instance=None, created=False, **kwargs): if created: print(instance.name) print(kwargs) I can get the ServersModel name but I am unable to get the ID of the User am connected with. Is there a way to get the connected user id in the ServersModel receiver? I have tried the following solutions but in vain: Get current user log in signal in Django Part I tried as solution: But the request is always None @receiver(post_save, sender=ServersModel) def create_zabbix_host(sender, instance=None, created=False, **kwargs): import inspect for frame_record in inspect.stack(): if frame_record[3]=='get_response': request = frame_record[0].f_locals['request'] break else: request = None
has title: Get userID in django.dispatch.receiver
has comment: http://stackoverflow.com/comment/81169389
score: 0
tagged with: django-models
tagged with: python

http://stackoverflow.com/q/47182894
has comment: http://stackoverflow.com/comment/81340251
has comment: http://stackoverflow.com/comment/81314811
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/47184201
has title: Function is slower in separate file
linked to: http://stackoverflow.com/q/11241523
has comment: http://stackoverflow.com/comment/81315642
has body: I have a following issue, there is a function to read a big file(few Mb), the content looks like: 0x05 0x00 0x00 0x00 0xCF 0x00 0x00 0x00 ; .......... 0xCF 0x00 0x00 0x00 0x22 0x00 0x00 0x00 ; ......"... 0x51 0x84 0x07 0x00 0x02 0x00 0x01 0x00 ; ..Q....... My function has to read only the hex values, and to ignore ";" with following characters till the end of line. Data from the first line what I need is "0x05 0x00 0x00 0x00 0xCF 0x00 0x00 0x00 " I tried two methods, one is with a separate file with this function def ReadFileAsList(fileName): fileName = "2Output.txt" fileContentStr = "" with open(fileName,'r') as f: for line in f: fileContentStr += line.split(';')[0] fileContentList = fileContentStr.split() return fileContentList and the second method, when these line are directly in my main .py file fileName = "2Output.txt" fileContentStr = "" with open(fileName,'r') as f: for line in f: fileContentStr += line.split(';')[0] fileContentList = fileContentStr.split() The second method is very fast, the first(with the separate function in a separate file) is very slow, what am I missing? Thanks for any hint
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81315565
has answer: http://stackoverflow.com/a/47184201
has comment: http://stackoverflow.com/comment/81315210
downvote count: 0
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81315537

http://stackoverflow.com/comment/81151820
has text: NB passing 1 to `readline()` is passing the same size argument to `read()` as `readlines()` does - read the docs link.
type: Comment
comment on: http://stackoverflow.com/a/47098790
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81355572
has text: @DavidG I have now tried to generate the variables latitude, longitude and RH now (see the modified code).
comment on: http://stackoverflow.com/q/47201586
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81162250
has text: @juanpa.arrivillaga it is not necessary that the colum '3' will be the one that's missing since df2 is variable. Any idea to get around that?
comment on: http://stackoverflow.com/a/47105336
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47066449
accepted answer: http://stackoverflow.com/a/47074456
tagged with: jsonschema
answer count: 1
type: Question
type: AnsweredQuestion
score: 0
tagged with: validation
tagged with: http://stackoverflow.com/tag/json
has body: I am using the jsonschema library (http://python-jsonschema.readthedocs.io/en/latest/validate/) in my Django application for server-side validation and am trying to do server-side validation of JSON with a provided schema. However, I get the error that the schema "is not valid under any of the given schemas." Here is my schema (it is the "scores_ap" property of the "schema" property of the class): class JSONListFieldSchemas: """ Schemas for all the JSON List Fields. Each key represents the field name. """ schema = { "scores_ap": { "$schema": "http://json-schema.org/draft-06/schema#", "title": "AP Scores", "type": "array", "items": { "type": "object", "properties": { "exam": { "type": "string" }, "score": { "type": "integer", "minimum": "1", "maximum": "5", "required": False } } } } } I am getting this error: {'type': 'object', 'properties': {'score': {'minimum': '1', 'type': 'integer', 'ma ximum': '5', 'required': False}, 'exam': {'type': 'string'}}} is not valid under a ny of the given schemas Failed validating u'anyOf' in schema[u'properties'][u'items']: {u'anyOf': [{u'$ref': u'#'}, {u'$ref': u'#/definitions/schemaArray'}], u'default': {}} On instance[u'items']: {'properties': {'exam': {'type': 'string'}, 'score': {'maximum': '5', 'minimum': '1', 'required': False, 'type': 'integer'}}, 'type': 'object'} I am using the schema as follows: from jsonschema import validate from .schemas import JSONListFieldSchemas raw_value = [{"score": 1, "exam": "a"}] validate(raw_value, JSONListFieldSchemas.schema['scores_ap'])
has title: jsonschema library -- schema is not valid?
has answer: http://stackoverflow.com/a/47074456
tagged with: django
tagged with: python

http://stackoverflow.com/comment/81244739
has text: This is arguably a dupe of that, but nobody should close it because delnan's answer is somewhat outdated (2014). There's new Python syntax allowing a cleaner implementation now. I'll `await` the OP to update the requirements / address the comments on the question.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47147107
type: AnswerComment

http://stackoverflow.com/a/47118327
downvote count: 0
has comment: http://stackoverflow.com/comment/81186893
has comment: http://stackoverflow.com/comment/81186812
has comment: http://stackoverflow.com/comment/81186652
has comment: http://stackoverflow.com/comment/81186871
upvote count: 4
type: AcceptedAnswer
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/47118220
has comment: http://stackoverflow.com/comment/81186723
has body: As mentioned in the linked question, this regex scans the whole text. The timing discrepancies seen here are just because "a" is such a common letter in English text, and you used readable data. So, if you study how regex engines work, you will understand: using the pattern a^ causes many more delays due to finding the tentative matches on the first "a", which then get rejected later. The engine has two "reading heads" which both move from left to right - one moves in the string, the other moves in the regex pattern. Using the a^ pattern in combination with your choice of human-readable data, the regex engine has to do more work. Since "x" is an uncommon letter in the corpus, using the pattern x^ wastes less time - more positions in the text can be rejected immediately. If you start the pattern with another common letter, such as "e", it will be just as slow (using e^ will be even slower than a^, because "e" is more frequently appearing in English). If you use random ascii bytes for the corpus, instead of real text, both a^ and x^ patterns will perform similarly. In summary, these two "equivalent" never-matching regex patterns a^ and x^ are actually not so equivalent when taking into account the wider context of the regex engine's inner workings and the chosen test data.
answers question: http://stackoverflow.com/q/47118220

http://stackoverflow.com/comment/81303835
has text: Thanks, works as described. Time column was already a string in 4 values so I could skip that step.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47177206
type: AnswerComment

http://stackoverflow.com/comment/81203905
has text: FlashTek, you don't get an error "out_file.writelines(myList)builtins.AttributeError: 'str' object has no attribute 'writelines'" When running the code?
comment on: http://stackoverflow.com/a/47126745
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81159757
has text: @NoahHuntington but in that case ffill is nonsensical?
comment on: http://stackoverflow.com/q/47104285
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81220406
type: Comment
score: 0
has text: Take a look [here](https://stackoverflow.com/questions/11403932/python-attributeerror-module-object-has-no-attribute-serial).
type: QuestionComment
comment on: http://stackoverflow.com/q/47134336

http://stackoverflow.com/comment/81389609
comment on: http://stackoverflow.com/a/47215013
score: 0
has text: Thanks! I knew I had to concatenate and reshape but I didn't know which indexes to use. Could you explain the use of the -1?
type: AnswerComment
type: Comment

http://stackoverflow.com/a/59190465
downvote count: 0
answers question: http://stackoverflow.com/q/47163728
upvote count: 8
has body: Below is the solution and it's based on the answer of @Alexei Novikov Code below is more complete import branca.colormap from collections import defaultdict import folium import webbrowser from folium.plugins import HeatMap map_osm = folium.Map(llocation=[35,110],zoom_start=1) steps=20 colormap = branca.colormap.linear.YlOrRd_09.scale(0, 1).to_step(steps) gradient_map=defaultdict(dict) for i in range(steps): gradient_map[1/steps*i] = colormap.rgb_hex_str(1/steps*i) colormap.add_to(map_osm) #add color bar at the top of the map HeatMap(data1,gradient = gradient_map).add_to(map_osm) # Add heat map to the previously created map file_path = r"C:\\test.html" map_osm.save(file_path) # Save as html file webbrowser.open(file_path) # Default browser open
type: Answer
score: 8

http://stackoverflow.com/comment/81325551
score: 0
has text: Hi. Can you elaborate on what I need to do to fix this issue please ? Thanks. I'm very new to SQLAlchemy.
comment on: http://stackoverflow.com/q/47170229
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47164951
has comment: http://stackoverflow.com/comment/81312881
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81315131
tagged with: ssl
tagged with: python
has title: postgres could not accept SSL connection: EOF detected
has comment: http://stackoverflow.com/comment/81290921
has comment: http://stackoverflow.com/comment/81283368
has comment: http://stackoverflow.com/comment/81314343
answer count: 0
downvote count: 0
has body: I am trying to set up ssl (self-signed certs) for a postgres DB (version 9.6) I have attached to my python flask gunicorn app. I have been running the postgres server without ssl just fine, but am trying to increase security on the application. I've used the following tutorials: https://www.postgresql.org/docs/9.6/static/libpq-ssl.html https://blog.jelastic.com/2016/08/31/establish-secure-ssl-connection-to-postgresql-db-server/ https://www.howtoforge.com/postgresql-ssl-certificates and while they were very useful, I can't seem to get passed this issue (in my log file): LOG: database system was shut down at 2017-11-07 13:15:47 EST LOG: MultiXact member wraparound protections are now enabled LOG: database system is ready to accept connections LOG: autovacuum launcher started LOG: could not accept SSL connection: EOF detected // THIS LINE HERE The application runs, but not over ssl. Here is my postgres.conf (what I thought was relevant): listen_addresses = '*' port = 7654 ssl = on ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' ssl_prefer_server_ciphers = on #ssl_ecdh_curve = 'prime256v1' ssl_cert_file = 'server.crt' ssl_key_file = 'server.key' ssl_ca_file = 'root.crt' and here is my pg_hba.conf: # TYPE DATABASE USER ADDRESS METHOD local all all trust host all all 127.0.0.1/32 trust host all all ::1/128 trust hostssl all all 0.0.0.0/0 trust clientcert=1 # I've also tried: #hostssl all myUser 0.0.0.0/0 md5 clientcert=1 #hostssl all all 0.0.0.0/0 md5 Here is some trace logging. Which indicates an issue with be-secure-openssl.c, on this line: if (!SSL_context) { ereport(COMMERROR, (errcode(ERRCODE_PROTOCOL_VIOLATION), // THIS LINE errmsg("could not initialize SSL connection: SSL context not set up"))); return -1; }
has comment: http://stackoverflow.com/comment/93865271
has comment: http://stackoverflow.com/comment/81299317
has comment: http://stackoverflow.com/comment/81283006
favorite count: 0
type: Question
tagged with: postgresql
score: 5
upvote count: 5

http://stackoverflow.com/a/47183706
type: Answer
has body: Sort the dict key-value pairs by values and then keys (lower keys come first), group them by values, and then take the first key in each group, which will be the lowest key for that value. You can do it in a dictionary comprehension without an intermediate dictionary: from itertools import groupby dct = {5:1, 2:2, 3:2, 4:2, 1:1} new_dict = dict(next(g) for _, g in groupby(sorted(dct.items(), key=lambda x: x[::-1]), lambda x: x[1])) # {1: 1, 2: 2}
has comment: http://stackoverflow.com/comment/81317444
score: 2
answers question: http://stackoverflow.com/q/47183377
downvote count: 0
upvote count: 2

http://stackoverflow.com/a/47177818
downvote count: 0
score: 2
has body: You can use np.where in conjunction with np.cumsum: import numpy as np li = [1,1,1,1,2,2,3,0,0,1,4] print(np.where(np.cumsum(li) % 4 == 0)) # (array([ 3, 5, 9, 10], dtype=int32),) The gotcha here of course is that it will also find indexes where the sum is 8, 12, 16, 20 etc. Unfortunately I'm not sure there is way to "reset" cumsum, if there was you could do something like np.where(np.cumsum(li) - 4 == 0) (but currently it will only return 3). However, you could slice the array every time cumsum reaches 4, but you didn't want to use loops.
type: Answer
answers question: http://stackoverflow.com/q/47177639
has comment: http://stackoverflow.com/comment/81304531
upvote count: 2

http://stackoverflow.com/comment/81814510
has text: @EleshNorn Why are your using pip from inside a Python script and not directly from the command line? Have a look at [Using pip behind a proxy](https://stackoverflow.com/q/14149422/5276734).
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47193441
type: Comment

http://stackoverflow.com/comment/81247355
type: Comment
comment on: http://stackoverflow.com/a/47146889
score: 0
type: AnswerComment
has text: What if you try this in place of the second for-loop: {% for sport in sport_category.sport_set.all %} {{ sport }} {% endfor %}

http://stackoverflow.com/a/47217367
accepted answer of: http://stackoverflow.com/q/47217302
answers question: http://stackoverflow.com/q/47217302
downvote count: 0
type: Answer
score: 3
upvote count: 3
type: AcceptedAnswer
has body: You seem to have accidentally escaped the ( character instead of creating a non-capture group. Here's the new regex: [0-9]{1,2}\.[0-9]{1,2}(?:.[0-9]{2,4})?

http://stackoverflow.com/q/47094437
favorite count: 0
type: Question
tagged with: numpy
score: 3
has comment: http://stackoverflow.com/comment/81138253
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47095095
has title: Adding np arrays to existing pandas dataframe
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/81139352
downvote count: 0
tagged with: pandas
answer count: 1
tagged with: arrays
has body: I've been trying to figure out a problem I came across for a while now, but somehow I cannot find the solution. I've created a pandas dataframe which is already filled with values, let's say dimension (4,3) df= A B C 0 valX valX valX 1 valY valY valY 2 valZ valZ valZ 3 valW valW valW What I want to do right now is append ten additional columns, each containing a numpy array filled with 38 zero's. My solution seems to be working when I first cast my array to a string and then add it to the original df. However, Pandas doesn't accept a plain numpy array. I need the value of the column to be a numpy array, as I will later do some sklearn computations on them. Later in my code, I substitute certain columns with a one-hot encoding of certain characters. The remaining columns act as a zero-padding. Example of my code (which works for adding 10 columns): #create empty array x = np.zeros(38) for i in range(0, 10): col_name = "char_" + str(i) df[col_name] = str(x) The problem here is that I need to cast x to a string. If I keep it as a numpy array, it throws me this error: ValueError: Length of values does not match length of index
accepted answer: http://stackoverflow.com/a/47095095
linked to: http://stackoverflow.com/q/47095122

http://stackoverflow.com/q/47086383
score: 0
has title: Physics bullet with drag in Python immediately goes below zero
tagged with: physics
has comment: http://stackoverflow.com/comment/81122604
tagged with: python
has comment: http://stackoverflow.com/comment/81123907
has answer: http://stackoverflow.com/a/47161547
has answer: http://stackoverflow.com/a/47106104
answer count: 2
has comment: http://stackoverflow.com/comment/81122443
type: UnansweredQuestion
has body: I am coding a program to find how far a bullet shoots at a 20 degree angle with various parameters with and without drag. For some reason my program immediately calculates the y value of the bullet as being below zero and I think it may be a problem with the physics equations I have used. I don't have the strongest background in physics so after trying my best to figure out where I went wrong I figured I would ask for help. In the graph below I am attempting to display the different distances associated with different timesteps. import math import matplotlib.pyplot as plt rho = 1.2754 Af = math.pi*(16*0.0254)**2/4 g = -9.8 #m/s^2 V = 250.0 #m/s #equation of motion def update(r,V,a,dt): return r+V*dt +.5*a*dt*dt, V + a*dt #drag force from velocity vector return x and y def drag(Vx,Vy): Vmag = math.sqrt(Vx**2+Vy**2) Ff = .5*Cd*rho*Af*Vmag**2 return -Ff * Vx/Vmag, -Ff *Vy/Vmag def getTrajectory(dt, th): #initialize problem [time,x,y,Vx,Vy] state = 0.0,0.0,0.0, V*math.cos(th), V*math.sin(th) while state[-1][2] &gt;= 0 : # while y &gt; 0 time = state[-1][0] + dt Fd = drag(state[-1][3],state[-1][4]) # Vx,Vy ax = Fd[0]/m # new x acceleration ay = (Fd[1]/m) +g # new y acceleration nextX, nextVx = update(state[-1][1], state[-1][3],ax,dt) #x,Vx,acceleration x, dt nextY, nextVy = update(state[-1][2], state[-1][4],ay,dt) #y,Vy, acceleration y, dt state.append([time,nextX,nextY,nextVx,nextVy]) # linear interpolation dtf = -state[-1][2]*(state[-2][0]-state[-1][0])/(state[-2][2]-state[-1][2]) xf,vxf = update(state[-1][1],state[-1][3], ax, dtf) print(xf,vxf) yf,vyf = update(state[-1][2],state[-1][4], ay, dtf) print(yf,vyf) state[-1] = [time+dtf,xf,yf,vxf,vyf] return state delt = 0.01 #timestep th = 20.0 * math.pi/180.0 #changing to radians m = 2400 #kg Cd = 1.0 tsteps = [0.001,0.01,0.1,1.0,3.0] # trying different timesteps to find the optimal one xdistance = [getTrajectory(tstep,th)[-1][1] for tstep in tsteps] plt.plot(tsteps,xdistance) plt.show() A print of the state variable …
type: Question

http://stackoverflow.com/comment/81170367
type: Comment
has text: This looks promising, would it be possible to dynamically assign these to dataframes 1-12 though?
type: AnswerComment
comment on: http://stackoverflow.com/a/47110082
score: 0

http://stackoverflow.com/q/47169543
has answer: http://stackoverflow.com/a/47169781
type: Question
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has body: I'm building some code to adaptively detect skin from webcam video. I have it almost working, however, when outputting the video, it shows 9 screens of the "skin" mask instead of just one. Seems like I'm just missing something simple, but I can't figure it out. image shown here Code below: # first let's train the data data, labels = ReadData() classifier = TrainTree(data, labels) # get the webcam. The input is either a video file or the camera number # since using laptop webcam (only 1 cam), input is 0. A 2nd cam would be input 1 camera = cv2.VideoCapture(0) while True: # reads in the current frame # .read() returns True if frame read correctly, and False otherwise ret, frame = camera.read() # frame.shape: (480,640,3) if ret: # reshape the frame to follow format of training data (rows*col, 3) data = np.reshape(frame, (frame.shape[0] * frame.shape[1], 3)) bgr = np.reshape(data, (data.shape[0], 1, 3)) hsv = cv2.cvtColor(np.uint8(bgr), cv2.COLOR_BGR2HSV) # once we have converted to HSV, we reshape back to original shape of (245057,3) data = np.reshape(hsv, (hsv.shape[0], 3)) predictedLabels = classifier.predict(data) # the AND operator applies the skinMask to the image # predictedLabels consists of 1 (skin) and 2 (non-skin), needs to change to 0 (non-skin) and 255 (skin) predictedMask = (-(predictedLabels - 1) + 1) * 255 # predictedMask.shape: (307200,) # resize to match frame shape imgLabels = np.resize(predictedMask, (frame.shape[0], frame.shape[1], 3)) # imgLabels.shape: (480,640,3) # masks require 1 channel, not 3, so change from BGR to GRAYSCALE imgLabels = cv2.cvtColor(np.uint8(imgLabels), cv2.COLOR_BGR2GRAY) # imgLabels.shape: (480,640) # do bitwsie AND to pull out skin pixels. All skin pixels are anded with 255 and all others are 0 skin = cv2.bitwise_and(frame, frame, mask=imgLabels) # skin.shape: (480,640,3) # show the skin in the image along with the mask, show images side-by-side # **********THE BELOW LINE OUTPUTS 9 screens of the skin mask instead of just 1…
has comment: http://stackoverflow.com/comment/81337488
has title: cv2.imshow shows 9 screens instead of 1
tagged with: opencv
score: 1
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81364575
has comment: http://stackoverflow.com/comment/81381030
favorite count: 0

http://stackoverflow.com/comment/81290189
has text: `list[-1]` refers to the last element in a list, in this case it is another list, to which we append
type: AnswerComment
comment on: http://stackoverflow.com/a/47170167
score: 1
type: Comment

http://stackoverflow.com/comment/81325690
type: AnswerComment
comment on: http://stackoverflow.com/a/47188181
score: 0
type: Comment
has text: Or, more simply, the 3rd line could be `result = Counter(input_string)`.

http://stackoverflow.com/a/47109579
score: 1
has body: To copy a file to multiple locations the following should work: import os import shutil dst_dirs = ["C:/A", "C:/B", "C:/C", "C:/D"] src_file = "C:/AA.csv" for d in dst_dirs: shutil.copy(src_file, d)
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47109319
type: Answer
answers question: http://stackoverflow.com/q/47109319

http://stackoverflow.com/q/47109691
type: Question
upvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2612802
answer count: 1
downvote count: 1
duplicate of: http://stackoverflow.com/q/2612802
has body: Consider Below Code(Python) k=[45,51,66,11,99,44] z=k z.reverse() Here Instead of Z the variable K also Reveresed So What I need is only child variable z need to be reversed without modifying K variable (list)
favorite count: 0
has title: Need Help in Python Variables
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47109705

http://stackoverflow.com/q/47144566
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has title: Set pandas row with itterable object
has comment: http://stackoverflow.com/comment/81239769
has body: I have a pandas.DataFrame which rows consists of both scalar values and matrices of different sizes. The matrices as stored with np.object datatype. I run into problems however when I try to assign an entire row at the same time. How would I do that. Here's the reason behind my choice of data structure as requested by MaxU: I record several parameters (scalar, uint16, int32 &amp; double) of a machine as well as one camera image. There is one blob on the image which however differs in size and position from shot-to-shot. I create a dynamic region of interest which is big enough to capture the blob but saves space with respect to the full image, normally resulting in a 50x100 instead of a 1024x1024 uint16. Furthermore I extract several parameters from that image which are all again scalar values represented in the table. Each row corresponds to one recording of all the parameters. mwe example below: #!/usr/bin/env python3 import pandas as pd import numpy as np raw = np.zeros(10, dtype=[('a', 'f8'), ('b', 'i4'), ('c', 'O')]) print(f'raw\n {raw}') print(f'raw.dtype\n {raw.dtype}\n') frame = pd.DataFrame(raw) print(f'frame\n {frame}') print(f'frame.dtypes\n {frame.dtypes}') # Works fine frame.loc[0, ('a', 'b', 'c')] = (1, 2, 'a') # ValueError: setting an array element with a sequence. frame.loc[0, ('a', 'b', 'c')] = (1, 2, np.zeros((20, 20))) returns: raw [( 0., 0, 0) ( 0., 0, 0) ( 0., 0, 0) ( 0., 0, 0) ( 0., 0, 0) ( 0., 0, 0) ( 0., 0, 0) ( 0., 0, 0) ( 0., 0, 0) ( 0., 0, 0)] raw.dtype [('a', '&lt;f8'), ('b', '&lt;i4'), ('c', 'O')] frame a b c 0 0.0 0 0 1 0.0 0 0 2 0.0 0 0 3 0.0 0 0 4 0.0 0 0 5 0.0 0 0 6 0.0 0 0 7 0.0 0 0 8 0.0 0 0 9 0.0 0 0 frame.dtypes a float64 b int32 c object dtype: object Traceback (most recent call last): File "test_25.py", line 17, in &lt;module&gt; frame.loc[0, ('a', 'b', 'c')] = (1, 2, np.zeros((20, 20))) File "/home/bin/conda/lib/python3.6/site-packages/pandas/core/indexing.py", line 179, in __setitem__ self._setitem_with_indexer(indexer, value…
has comment: http://stackoverflow.com/comment/81242123
answer count: 0
tagged with: pandas
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81243080
upvote count: 1
favorite count: 0
type: Question
tagged with: indexing
has comment: http://stackoverflow.com/comment/81242636

http://stackoverflow.com/comment/81296739
has text: Sorry, the phrasing of my comment was unclear. I'm suggesting that I don't think it makes sense, I was wondering why you did it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47173571
score: 0

http://stackoverflow.com/q/47096820
type: Question
has body: Quite new with django and so having difficulties with trying to wire my pages together. I have an Applicant page that has a button to go to a Create Application page. I'm passing it like this: Create Application From the Create Application page, how do I wire it back to the Applicant page? I've tried doing it this way but I get this error "Reverse for 'applicant-update' with arguments '('',)' not found. " Back My urls: app_name = 'applicant' urlpatterns = [ url(r'view/(?P<pk>\d+)/$', views.ApplicantUpdate.as_view(), name='applicant-update'), url(r'view/(?P<pk>\d+)/new/$', views.ApplicationCreate.as_view(), name='application-new'), ] View for Create Application: @method_decorator(login_required, name='dispatch') class ApplicationCreate(SuccessMessageMixin, CreateView): form_class = ApplicationForm template_name = 'applicant_application.html' success_message = 'Successfully created application.' I hope you can help me. Thank you very much.
type: UnansweredQuestion
tagged with: python
has title: Trouble wiring back button with django
has answer: http://stackoverflow.com/a/47098066
tagged with: django-views
score: 0
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/81143345

http://stackoverflow.com/comment/81342126
score: 0
type: Comment
has text: The desired output, I entered manually. The actual dataframe values should be adjusted automatically in a way that the desired dataframe/crosstab is obtained. This is the problem of constraint satisfaction, adjusting data in a way that row and column totals value are satisfied.
comment on: http://stackoverflow.com/q/47195005
type: QuestionComment

http://stackoverflow.com/a/47132924
has body: You can create a middleware that handles the conversion of date and time, import pytz from django.utils import timezone from django.utils.deprecation import MiddlewareMixin class TimezoneMiddleware(MiddlewareMixin): def process_request(self, request): tzname = request.session.get('django_timezone') if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate() and then you can as easily create the view with the conditions that you indicated earlier. Best if you read the documentation as Kevin suggested.
answers question: http://stackoverflow.com/q/47132548
type: Answer
score: 0

http://stackoverflow.com/comment/81315776
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47182751
has text: Are you attempting to sum the values in each array or combine them into a single larger array?
type: Comment

http://stackoverflow.com/comment/81157138
comment on: http://stackoverflow.com/q/47102979
score: 0
type: Comment
type: QuestionComment
has text: This is without context and i don't know what you are really doing. It sounds like the optimization somehow builds the edges of a graph. Then just introduce N binary-decision-vars for all possible N-edges (A, B should be known a-priori; counting and preparing a possibly flat vector of vars can be done in preprocessing). If that's not it; it's probably time for the next edit... But much more precise and bringing more context.

http://stackoverflow.com/q/47095122
possible better answer: http://stackoverflow.com/a/47095247
downvote count: 0
accepted answer: http://stackoverflow.com/a/47095156
has answer: http://stackoverflow.com/a/47095253
type: AnsweredQuestion
has body: I have a df, Name Count Ram 1 ram 2 raM 1 Arjun 3 arjun 4 My desired output df, Name Count Ram 4 Arjun 7 I tried groupby but I cannot achieve the desired output, please help
tagged with: data-analysis
answer count: 3
linked to: http://stackoverflow.com/q/47096797
tagged with: pandas
has title: Removing duplicates with ignoring case sensitive and adding the next column values with the first one in pandas dataframe in python
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47095247
favorite count: 0
type: Question
score: 2
has answer: http://stackoverflow.com/a/47095156
upvote count: 2

http://stackoverflow.com/q/47073021
has title: Downloading Files from FTP with C#
type: Question
tagged with: c#
has comment: http://stackoverflow.com/comment/81094189
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/47073366
tagged with: python
linked to: http://stackoverflow.com/q/37038676
has body: I've got a Python script that iterates over an FTP directory downloading any new files to a specific location based on the file name and what directory it was in. Because the FTP library I'm using is misbehaving in unexpected ways, I would like to move it to C# and merge it with a form application I have. The problem is that I can't seem to find much on FTP in C# for what I need so I was hoping I could receive some help here. Below I have included my Python code as it can likely show what I want to do better than my words. def work(ftp, extensions): if not ftp.path.exists('/downloads'): ftp.mkdir('/downloads') ftp.chdir('/downloads') os.chdir('Z:\\') r = re.compile(r'\./(.+?)/.+?(\d+?)/.+?E?(\d{2})\..+(\..+?$)') for root, dirs, files in ftp.walk('.'): for file in files: _, ext = os.path.splitext(file) if ext in extensions: file_path = ftp.path.join(root, file) date_stripped_file_path = ftp.path.join(root, re.sub(r'\.20[12]\d', '', file)) local_file_path = r.sub(r'./\1/\2/\1 S0\2E\3\4', date_stripped_file_path) if download(ftp, file_path, local_file_path, 'TV'): m = r.match(date_stripped_file_path) insert_into_database(m.group(1), int(m.group(2)), int(m.group(3)), os.path.abspath(local_file_path)) def download(ftp, source, target, type): if (not os.path.isfile(target)) or \ os.path.getsize(target) &lt; ftp.path.getsize(source): file_name = os.path.splitext(os.path.basename(target))[0] print(f'{get_timestamp()}... Downloading: {file_name}') # Create dir if not exists dirname = os.path.dirname(target) if not (os.path.exists(dirname) and os.path.isdir(dirname)): os.makedirs(dirname) try: def display_progress(chunk): bar.update(len(chunk)) bar = click.progressbar(length=ftp.path.getsize(source)) ftp.download(source, target, callback=display_progress) print('') except Exception as e: print(f'{get_timestamp()}... Dowmload failed') log_error(e, True) else: ftp.remove(source) return True else: ftp.remove(source) return True I have work in an indefinite while-loop that will r…
duplicate of: http://stackoverflow.com/q/37038676
tagged with: ftp
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/81094451
has comment: http://stackoverflow.com/comment/81095835
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/81170370
has text: I don't know. no job done here, Just attribute access... Perhaps the difference is at python level ?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47110093
type: QuestionComment

http://stackoverflow.com/q/47079367
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/81120666
favorite count: 0
has comment: http://stackoverflow.com/comment/81107815
accepted answer: http://stackoverflow.com/a/47079481
type: Question
has answer: http://stackoverflow.com/a/47079481
downvote count: 2
has body: I am trying to compare three different lists each with a potentially different length to the others but I'm not exactly sure how to do this. Originally I thought to just get the largest list length but then realized if the others are less then it will try find empty elements and return an error. I am trying to find if all the lists have a common element Currently I have: for i in range(n) //n is largest list length if (listA[i] in listB) and (listA[i] in listC): common = True else: common = False If possible, could you give an answer where it can be applied to numerous lists rather than be limited to three
has comment: http://stackoverflow.com/comment/81107858
answer count: 1
has title: Python comparing three lists with different lengths
tagged with: list
has comment: http://stackoverflow.com/comment/81107565
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/81120722
tagged with: compare

http://stackoverflow.com/q/47080557
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81110220
has title: How do I define a function that can be used with different variables and produce an output in python?
has body: I have tried to use this function to create an output inside the variable finish but nothing seems to work punctuations = '''!()-[]{};:'"\,&lt;&gt;./?@#$%^&amp;*_~ ''' def puncrem(x,y): for char in str(x): if char not in punctuations: y = y + char return y start = "h%e*l(l&amp;o" finish = "" puncrem(start,finish) print(finish)
tagged with: python
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47080614
has comment: http://stackoverflow.com/comment/81110206
has answer: http://stackoverflow.com/a/47080614

http://stackoverflow.com/q/47176964
tagged with: python
type: AnsweredQuestion
has body: Simple question: bins = np.logspace(np.log10(np.amin(lightcurve)),np.log10(np.amax(lightcurve)),10) ## should work with every possible (n,1) array. for i in range(len(bins)-1): bins_mean.append((bins[i+1]-bins[i])/2 +bins[i]) How can I speed this up? How do I address every i+1-th and every i-th element in one sweep?
score: 1
answer count: 1
upvote count: 1
has title: finding mean between array entries
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47177069
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47177069
downvote count: 0

http://stackoverflow.com/comment/86670224
has text: It does not seem to be available anymore. I got an error saying " Could not find a version that satisfies the requirement python-ndg_httpsclient (from versions: ) No matching distribution found for python-ndg_httpsclient"
comment on: http://stackoverflow.com/a/47816648
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/47221416
tagged with: python-2.7
has title: pyinstaller on UBuntu , giving error "pyconfig.h not found"
tagged with: ubuntu-16.04
favorite count: 0
type: Question
has body: I am trying to convert my python script to executable file on ubuntu in virtual environmentn using pyinstaller. But its giving error saying "/python2.7/pyconfig.h" when adding binary and data files".... I have attached the screenshot here. So far whatever I have tried to resolve this are : sudo apt-get install python2.7-dev Even added empty "pyconfig.h" file to /usr/lib/python2.7/distutils or to virtualenv folder i.e /home/infinite-uptime/ammu_env/local/lib/python2.7 but couldn't get it fixed. Any Idea please ? Thanks
answer count: 0
upvote count: 2
tagged with: pyinstaller
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 2

http://stackoverflow.com/a/47190740
score: 1
downvote count: 0
upvote count: 1
has body: This may work. Credit to Juan import re pattern = re.compile(r'^(.+)\.(.+) (.+):(.+)$') line = 'STOP.F 11966.0000:STOP DEPTH' pattern.search(line).groups() Out[6]: ('STOP', 'F', '11966.0000', 'STOP DEPTH')
answers question: http://stackoverflow.com/q/47190553
type: Answer

http://stackoverflow.com/a/47116534
answers question: http://stackoverflow.com/q/47115164
score: 0
has body: When you issue a print command in your code, its output will be printed in the console of the development server. When programming with Django there isn't a need to use print in your code, except for debugging. Using the Python built-in input is useful only on the command line. This method shouldn't be used for creating a web page. If you want to get some user input in the browser, you can use django forms to process it. You could make something like: class TranslateForm(forms.Form): translation_input = forms.CharField() then use the form in the view and get the user input. Please check the official documentation for forms. You could skip the form, since it is just a single input field, and get the user input through the request. For this purpose the &lt;input&gt; element needs the attribute name. Then in the view (def output) you can access it through: request.GET.get('name', None) # name is the value of attribute name GET is the HTTP method, if you need change it to POST, but for your case GET is the appropriate method.
type: Answer
has comment: http://stackoverflow.com/comment/81230137

http://stackoverflow.com/q/47076218
tagged with: python
has comment: http://stackoverflow.com/comment/81132829
has comment: http://stackoverflow.com/comment/81129698
tagged with: python-3.x
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81102396
upvote count: 1
has title: How to design classes for a testable, pythonic, OOP simple test log parser?
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81103853
has comment: http://stackoverflow.com/comment/81104458
tagged with: oop
has body: Situation: The test suite is executed several times. After every run it appends results of test cases to its log file. Mission to accomplish: Crawl through the log, find the results for all test cases for all runs, return a dict in a form {test_case_name:{'passed':times_passed, 'failed':times_failed}}. Bonus tasks to accomplish: Check log for consistency, unexpected fails etc. My first idea was to create two classes, to fulfill the Chain of responsibility pattern: Every piece of code must do one, and only one, thing. First of them would be Log responsible for opening and reading a file with log_checker and list_cases_names methods. The second class would be TestCaseResult with methods such as add_result, count_passrate etc. While trying to accomplish the task in TDD I found it impossible to create good-looking unit tests for that (I'm using py.test). To create TestCaseResult object I need to have list of cases names from Log class. And here comes the question: does it mean that I should improve my class design? Is there a better approach or some best practices to create testable classes interacting with each other?
tagged with: pytest

selenium
tags question: http://stackoverflow.com/q/47129876
tags question: http://stackoverflow.com/q/47087229
tags question: http://stackoverflow.com/q/47116637
tags question: http://stackoverflow.com/q/47193892
tags question: http://stackoverflow.com/q/47120755
tags question: http://stackoverflow.com/q/47119987
tags question: http://stackoverflow.com/q/47122629
tags question: http://stackoverflow.com/q/47167972
tags question: http://stackoverflow.com/q/47108512
tags question: http://stackoverflow.com/q/47115771
tags question: http://stackoverflow.com/q/47138796
tags question: http://stackoverflow.com/q/47148872
tags question: http://stackoverflow.com/q/47169767
tags question: http://stackoverflow.com/q/47084454
tags question: http://stackoverflow.com/q/47067506
tags question: http://stackoverflow.com/q/47110280
tags question: http://stackoverflow.com/q/47113260
tags question: http://stackoverflow.com/q/47115719
tags question: http://stackoverflow.com/q/47171602
tags question: http://stackoverflow.com/q/47169550
tags question: http://stackoverflow.com/q/47147801
tags question: http://stackoverflow.com/q/47088986
tags question: http://stackoverflow.com/q/47086195
tags question: http://stackoverflow.com/q/47186590
tags question: http://stackoverflow.com/q/47067720
tags question: http://stackoverflow.com/q/47141461
tags question: http://stackoverflow.com/q/47136239
tags question: http://stackoverflow.com/q/47185690
tags question: http://stackoverflow.com/q/47088347
tags question: http://stackoverflow.com/q/47197696
tags question: http://stackoverflow.com/q/47097439
tags question: http://stackoverflow.com/q/47171974
tags question: http://stackoverflow.com/q/47088907
tags question: http://stackoverflow.com/q/47075624
tags question: http://stackoverflow.com/q/47094172
tags question: http://stackoverflow.com/q/47101858
tags question: http://stackoverflow.com/q/47116420
tags question: http://stackoverflow.com/q/47126559
tags question: http://stackoverflow.com/q/47160884
tags question: http://stackoverflow.com/q/47208863
tags question: http://stackoverflow.com/q/47208695
tags question: http://stackoverflow.com/q/47122520
tags question: http://stackoverflow.com/q/47189151
tags question: http://stackoverflow.com/q/47170425
tags question: http://stackoverflow.com/q/47142311
tags question: http://stackoverflow.com/q/47127017
tags question: http://stackoverflow.com/q/47217718
tags question: http://stackoverflow.com/q/47072836
tags question: http://stackoverflow.com/q/47090423
tags question: http://stackoverflow.com/q/47105858
tags question: http://stackoverflow.com/q/47075280
tags question: http://stackoverflow.com/q/47191535
tags question: http://stackoverflow.com/q/47068571
tags question: http://stackoverflow.com/q/47074208
tags question: http://stackoverflow.com/q/47130601
tags question: http://stackoverflow.com/q/47100760
type: Tag
tags question: http://stackoverflow.com/q/47195184
tags question: http://stackoverflow.com/q/47087510
tags question: http://stackoverflow.com/q/47112972
tags question: http://stackoverflow.com/q/47146815
tags question: http://stackoverflow.com/q/47074558
tags question: http://stackoverflow.com/q/47076246
tags question: http://stackoverflow.com/q/47095720
tags question: http://stackoverflow.com/q/47092265
tags question: http://stackoverflow.com/q/47125511
tags question: http://stackoverflow.com/q/47196042
tags question: http://stackoverflow.com/q/47156750
tag name: selenium
tags question: http://stackoverflow.com/q/47211939
tags question: http://stackoverflow.com/q/47203573
tags question: http://stackoverflow.com/q/47194189
tags question: http://stackoverflow.com/q/47178684
tags question: http://stackoverflow.com/q/47168399
tags question: http://stackoverflow.com/q/47192202
tags question: http://stackoverflow.com/q/47138179
tags question: http://stackoverflow.com/q/47161536
tags question: http://stackoverflow.com/q/47178577
tags question: http://stackoverflow.com/q/47117698
tags question: http://stackoverflow.com/q/47082900

http://stackoverflow.com/comment/81342061
score: 0
type: Comment
type: QuestionComment
has text: Maybe try cython?
comment on: http://stackoverflow.com/q/47195728

http://stackoverflow.com/comment/81528297
comment on: http://stackoverflow.com/a/47285577
score: 0
has text: i have updated my answer, hope this will help
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47114589
has comment: http://stackoverflow.com/comment/81179080
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/47114623
has body: Why does this throw queue_length = items_in_queue.get_jenkins_queue_len(items_in_queue) AttributeError: 'list' object has no attribute 'get_jenkins_queue_len' class JenkinsQueue : def get_jenkins_items_in_queue(self) : logger.info("Starting...") with open('/Users/praveen-bhasker/datafile.json', encoding='utf-8') as data_file: data = json.loads(data_file.read()) return data["items"] def get_jenkins_queue_len(self, data): print(data) return jenkinsqueue = JenkinsQueue() items_in_queue = jenkinsqueue.get_jenkins_items_in_queue() queue_length = items_in_queue.get_jenkins_queue_len(items_in_queue)
score: -1
has answer: http://stackoverflow.com/a/47114623
has title: Why does this code throw "'list' object has no attribute" error
type: AnsweredQuestion
upvote count: 0
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81178988

http://stackoverflow.com/q/47191934
has comment: http://stackoverflow.com/comment/81333545
has body: Currently, I am trying to make a Jenkins API request with Python; however, I am getting in return a certificate error. In order to bypass this (and take the easy way out) I'm calling a jenkins request with the parameter ssl_verify = False. But the program still returns __init__() got an unexpected keyword argument 'ssl_verify' The code looks something like this: server = jenkins.Jenkins(URL, username, password, ssl_verify=False) I also tried the following call: server = jenkins.Jenkins(URL, requester=Requester(username, password, baseurl, ssl_verify=False) For the latter, I receive the error: __init__() got an unexpected keyword argument 'requester' I know declaring ssl verify = False is not the safest option but I'm trying to make this easy. Any help or answers will be much appreciated. Thanks.
has comment: http://stackoverflow.com/comment/81333517
upvote count: 3
tagged with: ssl
has title: __init__() got an unexpected keyword argument 'ssl_verify'
tagged with: python
type: Question
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/81333286
has comment: http://stackoverflow.com/comment/81333341
tagged with: jenkins
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81333261
tagged with: jenkins-api
has comment: http://stackoverflow.com/comment/81333224
downvote count: 1
tagged with: https
favorite count: 0

http://stackoverflow.com/a/47142405
has comment: http://stackoverflow.com/comment/81240175
downvote count: 0
answers question: http://stackoverflow.com/q/47140927
has comment: http://stackoverflow.com/comment/81239707
score: 2
has body: Use &amp; Call operator or . Dot sourcing operator as follows (choose one): . "C:\Program Files\QGIS 2.18\bin\python.exe" "C:\mydata\myscript.py" &amp; "C:\Program Files\QGIS 2.18\bin\python.exe" "C:\mydata\myscript.py" . "C:\Program Files\QGIS 2.18\bin\python.exe" "myscript.py" &amp; "C:\Program Files\QGIS 2.18\bin\python.exe" "myscript.py" Explanation: In Powershell, "a string" at start of a line means the same as Write-Output "a string" (see Example 1 in Write-Output cmdlet documentation). Hence, in the first example "C:\Program Files\QGIS 2.18\bin\python.exe" myscript.py "C:\Program Files\QGIS 2.18\bin\python.exe" = the 1st token of type string => the powershell interpreter expects that the whole line represents a positional argument of the Write-Output at position 0 i.e. an array of PS objects (PSObject[]), and myscript.py = an unexpected token.
type: Answer
has comment: http://stackoverflow.com/comment/81235103
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47140927

http://stackoverflow.com/q/47137165
answer count: 2
has answer: http://stackoverflow.com/a/47137671
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81224418
has comment: http://stackoverflow.com/comment/81223884
tagged with: python
tagged with: carrierwave
tagged with: ruby-on-rails
has comment: http://stackoverflow.com/comment/81224623
score: 0
has comment: http://stackoverflow.com/comment/81224384
tagged with: file
has title: Upload Image Files to a Ruby on Rails JSON API with Carrierwave
has comment: http://stackoverflow.com/comment/81224151
tagged with: http
has answer: http://stackoverflow.com/a/47137336
has body: I have a Ruby on Rails JSON API, that is supposed to take HTTP-Requests with both, JSON-data and files within one reuqest. Therefore I installed the gem Carrierwave. When I start a Request with Python, which looks like the following: url = [...] headers = {'Content-type': 'multipart/form-data'} payload = { 'image': { 'name': 48, 'camera_name': 'test', 'image_info': { 'iso': '1:100', 'shutter': '21:1/250', 'aperture': '5:3.2' } } } files = { 'image': open('C:\\Users\\Mfaorlkzus\\Desktop\\_DSC1036.jpg', 'rb') } print('uploading database object...') r = requests.post(url, files=files data=payload, headers=headers) print(r) print(str(r.text.encode('utf-8'))) ... the Request fails because of some formatting errors. The Output on the console looks like this: Started POST "/images/1?token=[...]" for [...] at 2017-11-06 13:18:12 +0100 Rack::QueryParser::InvalidParameterError (invalid %-encoding ("image" name --8038f415e00d4695aa798709c31b44ff Content-Disposition: form-data; name="image" camera_name --8038f415e00d4695aa798709c31b44ff Content-Disposition: form-data; name="image" image_info --8038f415e00d4695aa798709c31b44ff Content-Disposition: form-data; name="image"; filename="_DSC1036.jpg" ▒▒▒▒JFIF,,▒▒▒ExifMM* ▒ ▒▒(1▒2܇i▒0▒▒2$▒4D\NIKON CORPORATIONNIKON D7100,,paint.net 4.0.92017:03:27 22:25:31#▒▒▒▒▒▒▒"▒'d▒0230▒▒▒▒▒ Ғڒ ▒▒▒ ▒ ▒50▒▒50▒▒▒▒▒▒▒ ▒▒▒▒▒(▒▒▒ ▒ ▒ 2017:03:11 07:01:222017:03:11 07:01:22A▒B@ ▒▒▒▒▒▒, ▒ ▒R▒▒R▒4365366▒ # 8 18.0-105.0 mm f/3.5-5.6▒(HH▒▒ XICC_PROFILE HLinomntrRGB XYZ ▒ 1acspMSFTIEC sRGB▒▒▒-HP cprtP3desc▒lwtpt▒bkptrXYZgXYZ,bXYZ@dmndTpdmdd▒▒vuedL▒view▒$lumi▒meas $tech0 rTRC&lt; gTRC&lt; bTRC&lt; textCopyright (c) 1998 Hewlett-Packard CompanydescsRGB IEC61966-2.1sRGB IEC61966-2.1XYZ ▒Q▒XYZ XYZ o▒8▒▒XYZ b▒▒▒▒XYZ $▒▒▒▒descIEC http://www.iec.chIEC http://www.iec.chdesc.IEC 61966-2.1 Default RGB colour space - sRGB.IEC 61966-2.1 Default RGB colour space - sRGBdesc,Reference Viewing Condition in IEC61966-2.1,Reference Viewing Condition in IEC61966-2.1view▒▒_.▒▒▒ \▒X…
type: Question

http://stackoverflow.com/q/47080007
has answer: http://stackoverflow.com/a/47080102
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47080089
answer count: 6
possible better answer: http://stackoverflow.com/a/47080089
tagged with: tuples
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/47080102
has body: I have a list containing strings: lst = ['a', 'a', 'b'] where each string is, in fact, a category of a corpus, and I need a list of integers that corresponds to the index of that category. For this purpose, I built a list of tuples where I have each (unique) category and its index, f.ex: catlist = [(0, 'a'), (1, 'b')] I now need to iterate over the first list of strings, and if the element matches any of the second elements of the tuple, return the tuple's first element to an array, like this: [0, 0, 1] for now I have catindexes = [] for item in lst: for i in catlist: if cat == catlist[i][i]: catindexes.append(i) but this clearly doesn't work and I'm failing to get to the solution. Any tips would be appreciated.
score: 1
has answer: http://stackoverflow.com/a/47080192
downvote count: 0
has title: Matching list elements with element of tuple in list of tuples
has answer: http://stackoverflow.com/a/47080170
has answer: http://stackoverflow.com/a/47080228
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47080189

http://stackoverflow.com/comment/81316683
type: Comment
has text: This is correct, just keep in mind this will still create a list with 200 elements in memory. It can be fixed by changing the `[...]` to `(...)`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47183790

http://stackoverflow.com/a/47065189
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47065157
type: Answer
has body: If r is response then try calling r.json() method . It will convert to a list and then you can find the length of it . You can also use json.loads(r.text) by importing json(import json).

http://stackoverflow.com/a/47108545
answers question: http://stackoverflow.com/q/47106105
upvote count: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
has body: def fill_this(d): n = d.N.values r = d.Range.values a = np.append(n[0], r[1:]) m = a.size k = np.arange(m) t = np.tri(m) v = np.power(2, (k[:, None] - k) * t) * t return pd.Series((v * a).sum(1), d.index) df.assign(N2=df.groupby('Name', group_keys=False).apply(fill_this)) Name Range N N2 0 Name1 0.11 0.9 0.9 1 Name1 0.20 0.0 2.0 # &lt;-- 2 * 0.9 + .2 2 Name1 0.30 0.0 4.3 # &lt;-- 2 * 2.0 + .3 3 Name2 0.40 0.3 0.3 4 Name2 0.50 0.0 1.1 # &lt;-- 2 * 0.3 + .5 5 Name3 0.60 0.5 0.5 5 Name3 0.70 0.0 1.7 # &lt;-- 2 * 0.5 + .7 6 Name3 0.80 0.0 4.2 # &lt;-- 2 * 1.7 + .8 Explanation Assuming the first value is N0 N1 = 2 * N0 + R1 N2 = 2 * (2 * N0 + R1) + R2 N3 = 2 * (2 * (2 * N0 + R1) + R2) + R3 Or, written another way N1 = 2 ** 1 * N0 + 2 ** 0 * R1 + 0 * R2 N2 = 2 ** 2 * N0 + 2 ** 1 * R1 + 2 ** 0 * R2 N3 = 2 ** 3 * N0 + 2 ** 2 * R1 + 2 ** 1 * R2 I can see the pattern of powers of 2 1 0 0 2 1 0 3 2 1 I just need to line up my powers of 2, zero out the upper triangle, multiply by the correct array, and sum across rows.
accepted answer of: http://stackoverflow.com/q/47106105

http://stackoverflow.com/comment/109242687
type: Comment
score: 0
type: AnswerComment
has text: And of course, (x / y) is the wrong formula...
comment on: http://stackoverflow.com/a/47101059

http://stackoverflow.com/q/47079982
type: Question
tagged with: python-3.x
upvote count: 0
type: UnansweredQuestion
has title: My first "if" statement says that it is not working
answer count: 1
has comment: http://stackoverflow.com/comment/81109131
has answer: http://stackoverflow.com/a/47080180
favorite count: 0
has comment: http://stackoverflow.com/comment/81112978
tagged with: python
has comment: http://stackoverflow.com/comment/81109877
has body: My first if statement says that it is not working. import random RandomNum = random.randint(1, 10) Hall = { if(RandomNum &lt;= 8) 1 : { "item" : "sword" } elif(RandomNum == "5") 2 : { "mob" : "skeleton" } }
score: -6
downvote count: 6

http://stackoverflow.com/comment/81240806
comment on: http://stackoverflow.com/a/47144014
has text: Updated my original question ... please see above (thank you very much for taking a peek)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81139698
score: 0
type: Comment
has text: You are removing a key that does not exist.
comment on: http://stackoverflow.com/q/47095083
type: QuestionComment

http://stackoverflow.com/comment/81391620
has text: Python 3.5.2 (default, Sep 14 2017, 22:51:06) [GCC 5.4.0 20160609] on linux
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47212833

http://stackoverflow.com/comment/81182255
comment on: http://stackoverflow.com/a/47116053
type: Comment
score: 0
has text: You are right, actually didn't even notice, just copy pasted all around from question :) I am editing that.
type: AnswerComment

storage
tag name: storage
type: Tag
tags question: http://stackoverflow.com/q/47171843

http://stackoverflow.com/q/47073591
has title: API response text to JSON
tagged with: rest
accepted answer: http://stackoverflow.com/a/47102479
possible better answer: http://stackoverflow.com/a/47073841
has answer: http://stackoverflow.com/a/47102479
tagged with: http://stackoverflow.com/tag/json
tagged with: python
favorite count: 0
type: Question
score: 2
answer count: 2
upvote count: 2
has body: I'm using an API that returns me this text: HTTP/1.1 0 nullContent-Type: application/json;charset=UTF-8 Date: Thu, 02 Nov 2017 10:48:39 GMT Connection: close {"codigoRetorno":104,"mensajeRetorno":"ENVIO DUPLICADO, ENCONTRADO MISMO NUMERO DE ENVIO CON FECHA:02/11/2017","datosResultado":null,"listaBultos":null,"etiqueta":null} I use "requests" to use this API: headers = {'Content-type': 'application/json'} result = requests.post( url, data=data, auth=HTTPBasicAuth(username, password), headers=headers, verify=False) result_content = json.loads(result.content) But when I try to format the response to JSON it gives me this error: "ValueError: No JSON object could be decoded" I guess that the problem is the response is text. What's the best way to solve this problem. I thought about using a regular expression but maybe there is another method.
tagged with: api
downvote count: 0
has answer: http://stackoverflow.com/a/47073841
tagged with: django-rest-framework
type: AnsweredQuestion

http://stackoverflow.com/q/47184080
type: Question
linked to: http://stackoverflow.com/q/40617515
tagged with: python-3.x
score: 3
has body: I used the following solution from this earlier question to track whether a tkinter text widget has been modified: import tkinter as tk class CustomText(tk.Text): def __init__(self, *args, **kwargs): """A text widget that report on internal widget commands""" tk.Text.__init__(self, *args, **kwargs) # create a proxy for the underlying widget self._orig = self._w + "_orig" self.tk.call("rename", self._w, self._orig) self.tk.createcommand(self._w, self._proxy) def _proxy(self, command, *args): cmd = (self._orig, command) + args result = self.tk.call(cmd) if command in ("insert", "delete", "replace"): self.event_generate("&lt;&lt;TextModified&gt;&gt;") return result root = tk.Tk() label = tk.Label(root, anchor="w") text = CustomText(root, width=40, height=4) label.pack(side="bottom", fill="x") text.pack(side="top", fill="both", expand=True) def onModification(event): chars = len(event.widget.get("1.0", "end-1c")) label.configure(text="%s chars" % chars) text.bind("&lt;&lt;TextModified&gt;&gt;", onModification) root.mainloop() However, after integrating it into my own code, I discovered a problem in both my code and the bare solution above. If you attempt to paste into the text widget, the entire program will crash. The terminal gives the following error: Traceback (most recent call last): File "Test.py", line 39, in &lt;module&gt; root.mainloop() File "AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1277, in mainloop self.tk.mainloop(n) File "Test.py", line 16, in _proxy result = self.tk.call(cmd) _tkinter.TclError: text doesn't contain any characters tagged with "sel" (I removed identifying information in the file paths above, but otherwise that's copied straight from the console.) After a bit of testing, it turns out that you can paste without crashing the program as long as you have some text selected/highlighted when you paste. This behavior does not occur in the unmodified text widget; you can paste without selecting text beforehand as norm…
has comment: http://stackoverflow.com/comment/81331294
has title: How do I track whether a tkinter text widget has been modified using a proxy that doesn't crash on copy/paste?
has comment: http://stackoverflow.com/comment/81324055
tagged with: python
has comment: http://stackoverflow.com/comment/81326980
accepted answer: http://stackoverflow.com/a/47185310
type: AnsweredQuestion
tagged with: tkinter
has answer: http://stackoverflow.com/a/47185310
upvote count: 3
downvote count: 0
answer count: 1
tagged with: tk-toolkit
favorite count: 0

http://stackoverflow.com/q/47220535
tagged with: python
has title: indexing in lambda function to optimize multiple variables of a sum
tagged with: lambda
answer count: 2
tagged with: sympy
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/47250591
upvote count: 1
has answer: http://stackoverflow.com/a/47245593
tagged with: scipy
favorite count: 0
type: Question
has body: I want to solve an optimization problem as proposed in this thread. Now, I not only want to solve for the x[1]...x[n], but also for the variable y. It looks like something is wrong with the indexing. from sympy import Sum, symbols, Indexed, lambdify from scipy.optimize import minimize import numpy as np def _eqn(y, variables, periods, sign=-1.0): x, i = symbols("x i") n = periods-1 s = Sum(Indexed('x', i)/(1+0.06)**i, (i, 1, n)) f = lambdify(x, s, modules=['sympy']) return float(sign*(y + f(variables))) z = 3 results = minimize(lambda xy: _eqn(xy[0], xy[1:z], z),np.zeros(z)) print(results.x)
score: 1
linked to: http://stackoverflow.com/q/47187841

http://stackoverflow.com/q/47142567
has answer: http://stackoverflow.com/a/47142719
tagged with: loops
type: Question
tagged with: tkinter
answer count: 2
has title: Create and call Variables In a for loop
has answer: http://stackoverflow.com/a/47143715
accepted answer: http://stackoverflow.com/a/47143715
has comment: http://stackoverflow.com/comment/81235599
tagged with: python
tagged with: variables
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/47142719
has body: i am trying to make it so that a user inputs a number, and that number of buttons are created Using TKinter, I have tried doing it by using the following, Where the Buttons are successfully created, however i am struggling with calling them in order to place them / display them on the grid (Added randint to simulate user input (User Input not limited to 9 and may be as high as 40)) from tkinter import * from random import randint inputValue = randint(3,9) print(inputValue) root = Tk() while inputValue &gt; 0: # for every number in inputted value inputValue = int(inputValue) - 1 # take one globals()['Sailor%s' % inputValue] = Button(root, text="Lap :" + str(inputValue), command=lambda: retrieve_input()) # Create the button function in the format 'Sailors{Inputnumber}' ('Sailors%s' % inputValue).grid(row=inputValue, column=1, columnspan=2) # Place the button (Doesn't work) root.mainloop() # Does work (required) Howerver the following does not work (It is meant to place the button), ('Sailors%s' % inputValue).grid(row=inputValue, column=1, columnspan=2) # Place the button (Doesn't work) Can you think of a method i can use in order to create and place Amount of buttons? Thanks in advance

http://stackoverflow.com/q/47098379
has body: How can I display a message box that prevents the user from clicking anything in another tkinter window, until yes/no has been clicked.
has comment: http://stackoverflow.com/comment/81147249
type: Question
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
score: 0
has title: tkinter yes/no message box that must be answered
has answer: http://stackoverflow.com/a/47098827
tagged with: python

http://stackoverflow.com/comment/81099716
type: AnswerComment
comment on: http://stackoverflow.com/a/47075163
has text: of course you are right about the correlation numbers. My original task was to find the slope of the linear regression, but that takes too long, so I am looking for a faster solution.
type: Comment
score: 0

http://stackoverflow.com/comment/81384768
comment on: http://stackoverflow.com/a/47217638
score: 0
type: Comment
type: AnswerComment
has text: don't u need transition for label??

http://stackoverflow.com/a/74443267
downvote count: 1
upvote count: 0
type: Answer
score: -1
has body: You need to install requests module. Type : pip install requests into your terminal, or after activating virtual environment if you are using one.
answers question: http://stackoverflow.com/q/47077829

http://stackoverflow.com/a/47163748
downvote count: 0
upvote count: 1
has body: Have you re-deployed your API?
has comment: http://stackoverflow.com/comment/81277568
answers question: http://stackoverflow.com/q/47163552
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/47163552
type: AcceptedAnswer

http://stackoverflow.com/comment/118376667
score: 0
comment on: http://stackoverflow.com/q/47148446
has text: just came across this issue [here](https://stackoverflow.com/q/66967998/10197418) - it gets even more confusing if `resample` leaves you with *some* data left (not all NaN).
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81114854
has text: Thanks Shahin, It seems to get most of the data but for some reason if we look closer for example Brent Burns has 5 assists and 5 points but only one of the 5's shows up? and upon export the players name gets split up and his last name becomes the Pos(position). I am curious if there is a solution for that and to also add a 0 or nil in columns without data?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47069916
type: AnswerComment

http://stackoverflow.com/comment/81377158
type: AnswerComment
score: 0
type: Comment
has text: Using your package manager. This might be difficult because most Linux distributions only support a slightly outdated gcc...
comment on: http://stackoverflow.com/a/47213555

http://stackoverflow.com/q/47108215
has title: Python pandas read list in list data type from csv file
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81166697
tagged with: python
score: 3
tagged with: list
has answer: http://stackoverflow.com/a/47108250
has body: I have a csv file, like this: A B aaa [['a1','b1'],['a2','b2']] bbb 'a3','b3' I tried to read this file into python. And I want the 'B' column in list data type. I tried pd.read_csv('filename.csv'), what I got is "[['a1','b1'],['a2','b2']]" in str type, not in list type. And I also tried pd.read_csv('filename.csv', converters={'B':list}), what I got here is like: [[, [',a','1,','b,'...., not the list I want. Could you tell me how to read the list from a csv file directly? Thank you so much.
answer count: 3
has answer: http://stackoverflow.com/a/76919984
upvote count: 3
has answer: http://stackoverflow.com/a/47108310
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/comment/81162568
type: Comment
has text: @Dammi: In my business case, instead of `insert` and `read` with MongoDB, I use Redis for caching. Then every 5 minutes, I write them to db.
type: AnswerComment
comment on: http://stackoverflow.com/a/47101223
score: 0

http://stackoverflow.com/q/47106515
tagged with: python
has answer: http://stackoverflow.com/a/47115644
has title: Raspberry PI 3, SerialPort and strange response
has body: I'm trying to control my old Samsung DLP SP-A600B with the Serial Port (jack). To do so, I have resused my Raspberry Pi 3, and I have plugged a USB to Jack cable (UART) that I found on the net. I made a small Python file but I don't understand the output I'm receiving. Here's my code: import time import serial ser = serial.Serial( port='/dev/ttyUSB0', baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.SEVENBITS ) ON = b"\x08,\x22,\x00,\x00,\x00,\x00,\xD6" # other hard-coded commands ser.write(ON) time.sleep(1) out = ser.read(3) # 0x03 0x0C 0x7F doesn't match the spec! print out ser.close() According to the manual: 5-2 RS-232C Command Table Communication Format (Complies with the RS232C Standard) Baud rate : 9,600 bps parity : None Data bits : 8, stop bit : 1 Flow Control : None Serial Communication Protocol Command Packet Structure [7bytes] A command packet consists of 7 bytes in total. The two bytes 0x08 and 0x22 signify that the packet is for serial communication. The following 4 bytes represent a pre-defined command that can be defined by the user. The last byte is the checksum which checks the validity of the current packet. Header [2 Byte]: Pre-defined values fixed to 0x08 and 0x22. Cmd1 [1 Byte]: The first value of the code defined in the command list (Hexadecimal) Cmd2 [1 Byte]: The second value of the code defined in the command list (Hexadecimal) Cmd3 [1 Byte]: The third value of the code defined in the command list (Hexadecimal) Value [1 Byte]: Input parameter for the command (Default: 0) (Hexadecimal) CS [1 Byte]: Checksum (the 2’s complement of the sum of all the values except for the CS value.) Response Packet Structure [3 Bytes] Success 0x03 0x0C 0xF1 Fail 0x03 0x0C 0xFF I used this website to calculate the 2’s complement (I'm more NodeJS / Android guy) for the 7th byte (D6). Unfortunately, I only receive 0x03 0x0C 0x7F for this command. If I try to set strange values like serial.PARITY_ODD or serial.EIGHTBITS I rec…
type: AnsweredQuestion
tagged with: raspberry-pi
tagged with: pyserial
tagged with: bit-manipulation
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81169587
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81169320
type: Question
has comment: http://stackoverflow.com/comment/81178446
accepted answer: http://stackoverflow.com/a/47115644
score: 1
has comment: http://stackoverflow.com/comment/81169476
has comment: http://stackoverflow.com/comment/81167412

http://stackoverflow.com/comment/81336077
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47190283
has text: "*some playbooks do task some does not do tasks*" -- you need to do some troubleshooting to find some problems in some parts of your code, or in some configuration setting. I have some ideas of what might be your issue, but I have some doubts if they apply.
score: 1

http://stackoverflow.com/a/47126957
has comment: http://stackoverflow.com/comment/81216383
has comment: http://stackoverflow.com/comment/81209031
upvote count: 2
answers question: http://stackoverflow.com/q/47126777
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81208894
has comment: http://stackoverflow.com/comment/81211917
has body: I'm not sure that I've understood exactly what you want to do... should I have, you can do an elementwise difference using broadcasting, see below In [24]: a = np.random.random((5,3)) In [25]: b = np.random.random((5,3)) In [26]: c = a[:,None,:]-b In [27]: c[3,4] Out[27]: array([ 0.55732535, 0.30270483, 0.48249629]) In [28]: a[3]-b[4] Out[28]: array([ 0.55732535, 0.30270483, 0.48249629]) In [29]: c[0,3] Out[29]: array([ 0.28562698, 0.33227255, 0.35890964]) In [30]: a[0]-b[3] Out[30]: array([ 0.28562698, 0.33227255, 0.35890964]) In [31]:
has comment: http://stackoverflow.com/comment/81214502
type: Answer
accepted answer of: http://stackoverflow.com/q/47126777
score: 2
has comment: http://stackoverflow.com/comment/81229009

http://stackoverflow.com/a/47136543
upvote count: 6
type: Answer
has body: Your test_f takes two arguments: col_1 and col_2. You pass a single argument, ddf. Try something like In [5]: dd.map_partitions(test_f, ddf['col_1'], ddf['col_2']) Out[5]: Dask Series Structure: npartitions=8 0 int64 1250 ... ... 8750 ... 9999 ... dtype: int64 Dask Name: test_f, 32 tasks
has comment: http://stackoverflow.com/comment/95033851
has comment: http://stackoverflow.com/comment/81225025
has comment: http://stackoverflow.com/comment/99499130
downvote count: 0
answers question: http://stackoverflow.com/q/47125665
has comment: http://stackoverflow.com/comment/125572746
score: 6

http://stackoverflow.com/comment/81330703
comment on: http://stackoverflow.com/q/47190633
score: 0
has text: Have you tried `/signup/` with the trailing slash?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47195153
upvote count: 4
downvote count: 0
has body: Steps: Make sure you have Python2 installed. Download and install if needed. File -> Default Settings -> Project interpreter: choose Python2.7 If it's not listed, add it. See configuring python interpreter on the PyCharm website.
answers question: http://stackoverflow.com/q/47195051
type: Answer
score: 4

http://stackoverflow.com/a/51834486
type: Answer
has body: #multiple image conversions import cv2 import os,glob from os import listdir,makedirs from os.path import isfile,join path = '/root/Desktop/Anil' # Source Folder dstpath = '/root/Desktop/Anil2' # Destination Folder try: makedirs(dstpath) except: print ("Directory already exist, images will be written in same folder") # Folder won't used files = list(filter(lambda f: isfile(join(path,f)), listdir(path))) for image in files: try: img = cv2.imread(os.path.join(path,image)) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) dstPath = join(dstpath,image) cv2.imwrite(dstPath,gray) except: print ("{} is not converted".format(image)) for fil in glob.glob("*.jpg"): try: image = cv2.imread(fil) gray_image = cv2.cvtColor(os.path.join(path,image), cv2.COLOR_BGR2GRAY) # convert to greyscale cv2.imwrite(os.path.join(dstpath,fil),gray_image) except: print('{} is not converted')
answers question: http://stackoverflow.com/q/47087528
score: 8
downvote count: 0
upvote count: 8

http://stackoverflow.com/comment/81189560
has text: @Neolex check the update this is how you should use function inside replace. Hope it helps.
type: AnswerComment
comment on: http://stackoverflow.com/a/47119814
score: 0
type: Comment

http://stackoverflow.com/q/47123304
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47123421
downvote count: 0
score: 1
upvote count: 1
has body: In models.py I have class Memo: class Memo(models.Model): MonthName = models.ForeignKey(Months, on_delete=models.CASCADE) ProjectName = models.ForeignKey(Project, on_delete=models.CASCADE) Hours = models.IntegerField(blank=True, null=True) # ProjectManager = models.ForeignKey(ItEmployee, on_delete=models.CASCADE) def __str__(self): return str(self.MonthName) + ' - ' + str(self.ProjectName) In views.py I am getting warning Unresolved attribute reference 'objects' for class Memo: from django.http import HttpResponse from History.models import Memo def memos(request): all_memos = Memo.objects.all() html = '' for memo in all_memos: url = '/memo/' + str(Memo.MonthName) + '/' html += '&lt;a href="' + url + '"&gt;' + Memo.ProjectName + '&lt;/a&gt;&lt;br&gt;' return HttpResponse(html)
answer count: 1
has comment: http://stackoverflow.com/comment/97155541
has title: Unresolved attribute reference 'objects'
favorite count: 0
type: Question

http://stackoverflow.com/comment/81328681
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47189326
type: AnswerComment
has text: As other people have mentioned, you don't need the while loop, it will loop infinitely regardless of the outcome of the for loop. I was merely giving a method of exiting the while. You could also add the flag to the access denied portion if you need the while.

http://stackoverflow.com/q/47169971
tagged with: if-statement
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81289774
has comment: http://stackoverflow.com/comment/81289910
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81289740
type: Question
upvote count: 2
score: 2
tagged with: function
has body: def you (): gi=input("what up") if gi in ["Nothing much", "nothing much", "nothing"]: print("cool") you() elif gi in ["stuff"]: print("sounds good") I apparently cannot do this, however In a bigger program I am working on, I have a function that is used twice, however based of the user input, different results happen, so I tried to include my large function, and like the above program have an if else be continued throughout the function, because there are different options for user input, based on where the person is in the program. I am just trying to figure out a good way to run a game, where the beginning is the same (function), however the game can progress in different ways, therefore a function won't work for all of it, so I just want to know if I can have an if else statement run through a function like in the small example above?
downvote count: 0
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/47170064
has title: Can I continue an IF-ELSE statement through a function?
has answer: http://stackoverflow.com/a/47170064

http://stackoverflow.com/q/47212940
tagged with: executable
has comment: http://stackoverflow.com/comment/81376286
has answer: http://stackoverflow.com/a/47213058
tagged with: python
answer count: 2
type: Question
possible better answer: http://stackoverflow.com/a/47213058
accepted answer: http://stackoverflow.com/a/47213555
score: 0
has title: Running compiled Linux executable on other Linux computers
has comment: http://stackoverflow.com/comment/81376368
has answer: http://stackoverflow.com/a/47213555
has comment: http://stackoverflow.com/comment/81375978
has body: I've been working on a custom program that allows me to control my other Linux-based computers on my network. I've been using Python and used PyInstaller to compile the code into a Linux executable. Running the executable on my own computer works just fine and does exactly what it's supposed to. But once I send it over to another computer to test it, I get this error. ImportError: /lib/x86_64-linux-gnu/libc.so.6: version 'GLIBC_2.25' not found (required by /tmp/_MEIXcUz91/libudev.so.1) [3716] Failed to execute script RP And the command I used to compile the code with PyInstaller python pyinstaller.py -D -F -n RP -c RP.py Again, the executable runs perfectly on the computer I used to create and compile it, but once I send it over to my other Linux-based computer and execute it, it crashes.
tagged with: python-2.7
tagged with: linux
tagged with: pyinstaller
type: AnsweredQuestion

http://stackoverflow.com/comment/81347020
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47198606
type: Comment
has text: Unfortunately even excluding the sqlite db from git will not allow it to "stay the same"; it's stored on disk, and dynos have their own ephemeral filesystems which do not persist. So pushing new commits would then wipe out the db completely.

http://stackoverflow.com/comment/81367631
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47209163
type: QuestionComment
has text: super().__init__(self), in this line how self works?? @Carcigenicate

http://stackoverflow.com/a/47125879
answers question: http://stackoverflow.com/q/47122052
downvote count: 0
type: AcceptedAnswer
has body: (Since you don't clarify it, I assume here that you are talking about the test accuracy - the train accuracy can indeed be 1.0, depending on the details of your data &amp; model.) Well, such issues are usual when one messes up problems, losses, and metrics - see this answer of mine for a similar confusion when binary_crossentropy is used as loss in Keras for a multi-class classification problem. Before trying any remedy, try predicting a couple of examples manually (i.e. with model.predict instead of model.evaluate); cannot do it myself since I don't have your data, but I bet the results you'll get will not conform to the perfect accuracy implied by your model.evaluate results. To the heart of your issue: since you have a binary classification problem, you should definitely ask for loss='binary_crossentropy' in your model compilation, and not mse. Cannot be sure on what exactly is the value of 1.0 you get from model.evaluate, but as I show in the answer linked above, what evaluation metric Keras returns for a model compiled with metrics=['accuracy'] is highly dependent on the respective entry for loss; and even if I was eventually able to figure out what was the issue in that question, I cannot even start imagining what exactly goes on here, where you request the accuracy (i.e. a classification metric) for a regression loss (mse)...
accepted answer of: http://stackoverflow.com/q/47122052
score: 6
upvote count: 6
type: Answer

regex
tags question: http://stackoverflow.com/q/47146947
tags question: http://stackoverflow.com/q/47160399
tags question: http://stackoverflow.com/q/47205335
tags question: http://stackoverflow.com/q/47154382
tags question: http://stackoverflow.com/q/47075296
tags question: http://stackoverflow.com/q/47198132
tags question: http://stackoverflow.com/q/47162916
tags question: http://stackoverflow.com/q/47090878
tags question: http://stackoverflow.com/q/47181635
tags question: http://stackoverflow.com/q/47092367
tags question: http://stackoverflow.com/q/47207819
tags question: http://stackoverflow.com/q/47217846
tags question: http://stackoverflow.com/q/47072491
tags question: http://stackoverflow.com/q/47086372
tags question: http://stackoverflow.com/q/47212409
tags question: http://stackoverflow.com/q/47099120
tags question: http://stackoverflow.com/q/47212344
tags question: http://stackoverflow.com/q/47214610
tags question: http://stackoverflow.com/q/47122799
tags question: http://stackoverflow.com/q/47107231
tags question: http://stackoverflow.com/q/47137391
tags question: http://stackoverflow.com/q/47128060
tags question: http://stackoverflow.com/q/47204277
tag name: regex
tags question: http://stackoverflow.com/q/47154607
tags question: http://stackoverflow.com/q/47110707
tags question: http://stackoverflow.com/q/47132523
tags question: http://stackoverflow.com/q/47090396
tags question: http://stackoverflow.com/q/47200139
tags question: http://stackoverflow.com/q/47217302
tags question: http://stackoverflow.com/q/47213335
tags question: http://stackoverflow.com/q/47096806
tags question: http://stackoverflow.com/q/47080210
tags question: http://stackoverflow.com/q/47074214
tags question: http://stackoverflow.com/q/47150813
tags question: http://stackoverflow.com/q/47199314
tags question: http://stackoverflow.com/q/47164130
tags question: http://stackoverflow.com/q/47131517
tags question: http://stackoverflow.com/q/47119712
tags question: http://stackoverflow.com/q/47104824
tags question: http://stackoverflow.com/q/47146248
tags question: http://stackoverflow.com/q/47149756
tags question: http://stackoverflow.com/q/47131936
tags question: http://stackoverflow.com/q/47083451
tags question: http://stackoverflow.com/q/47184496
tags question: http://stackoverflow.com/q/47085990
tags question: http://stackoverflow.com/q/47110693
tags question: http://stackoverflow.com/q/47093854
tags question: http://stackoverflow.com/q/47096290
tags question: http://stackoverflow.com/q/47215081
tags question: http://stackoverflow.com/q/47116814
tags question: http://stackoverflow.com/q/47159417
tags question: http://stackoverflow.com/q/47156680
tags question: http://stackoverflow.com/q/47152236
tags question: http://stackoverflow.com/q/47125360
tags question: http://stackoverflow.com/q/47122698
tags question: http://stackoverflow.com/q/47208877
tags question: http://stackoverflow.com/q/47107997
tags question: http://stackoverflow.com/q/47072627
tags question: http://stackoverflow.com/q/47159235
tags question: http://stackoverflow.com/q/47156126
tags question: http://stackoverflow.com/q/47100474
tags question: http://stackoverflow.com/q/47080126
tags question: http://stackoverflow.com/q/47191040
tags question: http://stackoverflow.com/q/47209018
tags question: http://stackoverflow.com/q/47090202
tags question: http://stackoverflow.com/q/47181008
tags question: http://stackoverflow.com/q/47114687
tags question: http://stackoverflow.com/q/47188715
tags question: http://stackoverflow.com/q/47175817
tags question: http://stackoverflow.com/q/47082599
tags question: http://stackoverflow.com/q/47164436
tags question: http://stackoverflow.com/q/47118220
type: Tag
tags question: http://stackoverflow.com/q/47187823
tags question: http://stackoverflow.com/q/47199246
tags question: http://stackoverflow.com/q/47111279
tags question: http://stackoverflow.com/q/47087757
tags question: http://stackoverflow.com/q/47128812
tags question: http://stackoverflow.com/q/47097474

http://stackoverflow.com/a/47144808
upvote count: 1
answers question: http://stackoverflow.com/q/47144665
type: Answer
has comment: http://stackoverflow.com/comment/81239802
has body: Plain and simple: you have your input line within the loop and thus it is requesting user input on every pass of the loop. Move uname = input("Which username do you want to see?\n") to the line above for n in range(len(ulist)): However, as @pvg says, please review the guidelines on using examples when asking questions.
score: 1
downvote count: 0

http://stackoverflow.com/comment/81322746
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/47186611
has text: To obtain the OP's step size (or close to it) maybe: `x = np.linspace(-np.pi, np.pi, int(2 * np.pi / 0.08))`.
type: Comment

http://stackoverflow.com/comment/134808069
type: AnswerComment
has text: @Sophia one suggestion to speed things up you can start running the above by dividing your dataset to smaller batches and try running them across multiple threads.
comment on: http://stackoverflow.com/a/47159997
score: 0
type: Comment

http://stackoverflow.com/comment/81779418
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47396686
type: Comment
has text: In that case, I would suggest going for cron as the simple solution, and then monitor that the report is actually generated. That's much easier than designing a system that cannot fail.

http://stackoverflow.com/comment/81299874
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47170961
has text: Thanks for your anwser! I probably haven't explained my problem well enough though. In your code when I do `print('u_choice',u_choice)` in the end, after clicking the turtle, I still get `u_choice ['grey', 'b', 'c', 'd']` when it should be red or blue.

http://stackoverflow.com/a/47122212
answers question: http://stackoverflow.com/q/47122088
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47122088
has body: The way you save the image affects the results. The jpg compresses the image and alters the values. About the image formats see here: http://pillow.readthedocs.io/en/3.1.x/handbook/image-file-formats.html Use this: arr = np.array(PIL.Image.open('1.jpg') arr[0][0][0] = 128 img = PIL.Image.fromarray(np.uint8(arr)) im.save('2.bmp') arr2 = np.array(PIL.Image.open('2.bmp')) print(arr) print(arr2) This works fine.
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/81116027
score: 0
comment on: http://stackoverflow.com/q/47083201
type: Comment
type: QuestionComment
has text: do you know that your program is looking for same elements in array so give appropriate input and you will be good to go

http://stackoverflow.com/comment/81391702
comment on: http://stackoverflow.com/a/47212833
has text: I don't know the version of pandas but I have installed it yesterday, I am gonna check
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/81162377
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47105744
type: AnswerComment
has text: Oh ... I hadn't noticed the time lag on my posting. Never mind, you're okay.

http://stackoverflow.com/a/47159851
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47152353
has body: Are you sure that's what you want to do? That's 40*21*6=5040 axes in one figure... In addition, your description (grid with 40 cells and 21 inner cells in each cells) doesn't match the code provided where you have 48 cells, and 25 cells in each... In any case, this is how I would go about generating what you are describing. Note that you don't necessarily have to generate intermediate Axes object. Only generate axes where you are going to plot something. Finally, depending on what you are actually trying to achieve, I'm pretty sure there must be a better way than to create thousands of axes. import matplotlib.gridspec as gridspec fig = plt.figure(figsize=(40,100)) outer_grid = gridspec.GridSpec(10,4, wspace=0, hspace=0) for outer in outer_grid: # ax = fig.add_subplot(outer) # ax.set_xticklabels([]) # ax.set_yticklabels([]) # ax.set_aspect('equal') inner_grid_1 = gridspec.GridSpecFromSubplotSpec(5,5, subplot_spec=outer) for inner in inner_grid_1: # ax1 = fig.add_subplot(inner) # ax1.set_xticklabels([]) # ax1.set_yticklabels([]) # ax1.set_aspect('equal') inner_grid_2 = gridspec.GridSpecFromSubplotSpec(2,6, subplot_spec=inner) ax_top = fig.add_subplot(inner_grid_2[0,:]) # top row for i in range(6): ax2 = fig.add_subplot(inner_grid_2[1,i]) # bottom row ax2.set_xticklabels([]) ax2.set_yticklabels([]) plt.show()
downvote count: 0

http://stackoverflow.com/comment/81531014
has text: Am trying to open with different application just for learning purpose
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47289000

http://stackoverflow.com/q/47217673
tagged with: python
has body: import time import datetime import argparse import netaddr import sys import logging from scapy.all import * from pprint import pprint from logging.handlers import RotatingFileHandler NAME = 'probemon' DESCRIPTION = "a command line tool for logging 802.11 probe request frames" DEBUG = False def build_packet_callback(time_fmt, logger, delimiter, mac_info, ssid, rssi): def packet_callback(packet): if not packet.haslayer(Dot11): return # we are looking for management frames with a probe subtype # if neither match we are done here if packet.type != 0 or packet.subtype != 0x04: return # list of output fields fields = [] # determine preferred time format log_time = str(int(time.time())) if time_fmt == 'iso': log_time = datetime.datetime.now().isoformat() fields.append(log_time) # append the mac address itself fields.append(packet.addr2) # parse mac address and look up the organization from the vendor octets if mac_info: try: parsed_mac = netaddr.EUI(packet.addr2) fields.append(parsed_mac.oui.registration().org) except netaddr.core.NotRegisteredError, e: fields.append('UNKNOWN') # include the SSID in the probe frame if ssid: fields.append(packet.info) if rssi: rssi_val = -(256-ord(packet.notdecoded[-4:-3])) fields.append(str(rssi_val)) logger.info(delimiter.join(fields)) return packet_callback def main(): parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument('-i', '--interface', help="capture interface") parser.add_argument('-t', '--time', default='iso', help="output time format (unix, iso)") parser.add_argument('-o', '--output', default='probemon.log', help="logging output location") parser.add_argument('-b', '--max-bytes', default=5000000, help="maximum log size in bytes before rotating") parser.add_argument('-c', '--max-backups', default=99999, help="maximum number of log files to keep") parser.add_argument('-d', '--delimiter', default='\t', help="output field delimiter") parser.add_argument('-f', '--mac-info', action='store_true', help="include …
has title: probemon.py: error: argument -f/ --mac-info: Ignored explicit argument '-s-r-l'
score: 5
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47225409
has answer: http://stackoverflow.com/a/47225409
favorite count: 0
type: Question
type: AnsweredQuestion
upvote count: 5

http://stackoverflow.com/comment/81574237
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47123545
has text: I was having bad days and was also desperate for an answer when I asked this question. Thank you very much for your suggestions. I will try to ask better question in future.
score: 0

http://stackoverflow.com/comment/81212284
score: 3
comment on: http://stackoverflow.com/q/47131263
has text: The indentation in the required format seems random to me. Is that truly what is required?
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47142387
has comment: http://stackoverflow.com/comment/81234733
type: Answer
has comment: http://stackoverflow.com/comment/81234778
accepted answer of: http://stackoverflow.com/q/47142340
has comment: http://stackoverflow.com/comment/81235351
score: 2
has body: They're accepting them all in one query called "params". That's a non-standard way to send params, so, there's no built-in way to do that with requests. You'll have to join the keys and values with '^' character manually.
answers question: http://stackoverflow.com/q/47142340
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81234838
has comment: http://stackoverflow.com/comment/81234744
upvote count: 2

http://stackoverflow.com/comment/81721114
has text: `File "/Users/euanoflynn/anaconda/lib/python3.6/site-packages/requests/adapters.py", line 500, in send raise ProxyError(e, request=request) requests.exceptions.ProxyError: HTTPConnectionPool(host='10.181.157.13', port=80): Max retries exceeded with url: http://finance.yahoo.com/ (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x10eefd1d0>: Failed to establish a new connection: [Errno 64] Host is down',)))`
type: AnswerComment
comment on: http://stackoverflow.com/a/47195618
score: 0
type: Comment

http://stackoverflow.com/q/47090396
has body: I have the following problem in python: searchstring = "([A-Z0-9]*)_" basename = "AK4RAE00005_ALL_MEASUREMENT.a2l" m = re.search(searchstring, basename) if m and m.group(0): print m.group(0) I expected the result to be: AK4RAE00005 but instead it is AK4RAE00005_ I checked my RegEx on https://regexr.com/ and it finds the correct group without the underscore.
linked to: http://stackoverflow.com/q/1327369
tagged with: python
tagged with: regex
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 2
has title: Python regex returns incorrect group
type: Question
duplicate of: http://stackoverflow.com/q/1327369
has answer: http://stackoverflow.com/a/47090490
has answer: http://stackoverflow.com/a/47090421
possible better answer: http://stackoverflow.com/a/47090490
accepted answer: http://stackoverflow.com/a/47090421

http://stackoverflow.com/a/47205203
type: AcceptedAnswer
downvote count: 0
score: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/47205055
has body: Here: for r in items: tk.Label(frame1, text=items[r]).grid(row=r,column=0) That's not how python's for loop works. In the for loop's body, r is not the index of the item in items, it is the item, so you'd need : for item in items: tk.Label(frame1, text=item).grid(row=???,column=0) but it seems you also want the index of the item to pass as the row argument for .grid(). For this you can use enumerate(seq) which yields a (index, item) tuple for each element of seq: for index, item in enumerate(items): tk.Label(frame1, text=item).grid(row=index,column=0) Note that you also have a similar issue here: status = [[True, False, True, False], ['14:00:00', '13:24:31', '15:58:32', '08:33:01']] for r in status: for s in status[r]: tk.Label(frame2, text=status[r][s]).grid(row=s,column=r)
has comment: http://stackoverflow.com/comment/81359639
upvote count: 2
answers question: http://stackoverflow.com/q/47205055

http://stackoverflow.com/comment/81378361
has text: To ensure the right people are looking at your question, make sure the tags are right (e.g. include pandas) and ask the question using the [minimum, complete example guideline from](https://stackoverflow.com/help/mcve)
type: Comment
comment on: http://stackoverflow.com/q/47214185
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81136143
comment on: http://stackoverflow.com/a/47092339
type: Comment
score: 0
type: AnswerComment
has text: That fixed that error though I am getting instead now: File "C:/Users/Bain3/PycharmProjects/untitled4/11The unibet.py", line 1311, in <module> indexes = [index for index in range(get_options_length())] File "C:/Users/Bain3/PycharmProjects/untitled4/11The unibet.py", line 1302, in get_options_length list_length = len(wait.until(EC.presence_of_all_elements_located((By.XPATH, '//*[@class="KambiBC-mod-event-group-header__event-count"]')))) TypeError: until() missing 1 required positional argument: 'method'

http://stackoverflow.com/q/47084099
has comment: http://stackoverflow.com/comment/81117907
has comment: http://stackoverflow.com/comment/81119157
type: Question
has comment: http://stackoverflow.com/comment/81117489
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/448271
has comment: http://stackoverflow.com/comment/81121742
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81117531
has comment: http://stackoverflow.com/comment/81118450
has comment: http://stackoverflow.com/comment/81117753
has answer: http://stackoverflow.com/a/47086111
has comment: http://stackoverflow.com/comment/81117485
score: 0
has comment: http://stackoverflow.com/comment/81124299
has comment: http://stackoverflow.com/comment/81117656
answer count: 1
has comment: http://stackoverflow.com/comment/81122205
has comment: http://stackoverflow.com/comment/81122223
tagged with: forms
has comment: http://stackoverflow.com/comment/81118086
has body: As stated in the title, I keep getting an error when trying to create a form. It's on the line that has: from collection.forms import contact_form An I'm getting the error: File "/home/mike/CINS465/465proj/project/firstapp/views.py", line 2, in <module> from collection.forms import contact_form ImportError: No module named 'collection' Any idea where I'm going wrong? I'm new to django and this was pulled from a tutorial on creating a contact form. I thought collection was built-in to django Edit: from views.py from django.shortcuts import render from django.http import HttpResponse, JsonResponse from .models import * from .forms import contact_form # Create your views here. def contact(request): form_class = contact_form return render(request, 'contact.html', { 'form': form_class, }) from urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'contact/$',views.contact, name='contact'), ] from contact.html {% block title %}Contact - {{ block.super }}{% endblock %} {% block content %} Contact {% csrf_token %} {{ form.as_p }} Submit {% endblock %} from forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User class contact_form(forms.Form): contact_name = forms.CharField(label='Contact Name', max_length=255) contact_email = forms.CharField(label='Contact Email',max_length=255) contact_message = forms.CharField( label='Contact Message', required=True, widget=forms.Textarea ) I didn't include code that was irrelevant (i.e. index page).
has title: Django ImportError: No module named 'collection'

http://stackoverflow.com/a/50889569
score: 2
has comment: http://stackoverflow.com/comment/92632287
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47161855
type: Answer
has comment: http://stackoverflow.com/comment/88782175
has body: I just had the same problem, and after a little investigation I realized it probably happened because I stopped my program like a jerk (terminated it in the middle of using the shelve). So I deleted my shelve and created it again and everything worked fine. I assume you had the same error, maybe you exited your infinite while loops by terminating the program or something?

http://stackoverflow.com/q/47183342
has comment: http://stackoverflow.com/comment/81317871
downvote count: 0
has comment: http://stackoverflow.com/comment/81316817
upvote count: 1
has title: Creating a diamond in python
has comment: http://stackoverflow.com/comment/81316823
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/18202924
linked to: http://stackoverflow.com/q/23294658
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81316488
tagged with: python
has comment: http://stackoverflow.com/comment/81316349
has comment: http://stackoverflow.com/comment/81316797
has comment: http://stackoverflow.com/comment/81317172
duplicate of: http://stackoverflow.com/q/32613579
has body: I am new to python. I recently created a grid in python to test myself, which worked out brilliantly. The reason why the answers given in the other questions are not useful for me is because the code which is given to them is much more complex and since I am new to coding, I find it quite difficult to understand it. Also the diamonds miss one of the layers which I have. I thought I would attempt to create a diamond something which would look like: Click on the link to view Please could someone show me what to do next - as I am quite confused. D= int(input("Please enter the width of the diamond:")) for x in range(): for y in range(height): print('*', end=' ') print() I have tried multiple things but it is not working. Please can someone help me :) Thanks to everyone that has answered my question. Could Someone just answer me this : If I wanted the diamond to have a width no more than 30 and the user inputted 35. How would I stop it from even printing thanks
has comment: http://stackoverflow.com/comment/81317721
has comment: http://stackoverflow.com/comment/81316029
answer count: 0
score: 1
linked to: http://stackoverflow.com/q/18202924
has comment: http://stackoverflow.com/comment/81317014

http://stackoverflow.com/comment/81382314
has text: I'm not sure you need a function. Given three strings, `foo`, `tok`, and `rep`, simply using `foo.replace(tok, rep)` will return `foo` with all instances of `tok` replaced with `rep`. If `foo` contains *no* instances of `tok`, it will simply return the original string `foo`. Additionally, I think the for loop is unnecessary (and probably causing you the most trouble).
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47216436

http://stackoverflow.com/q/47193490
downvote count: 0
tagged with: web-scraping
tagged with: python
tagged with: scrapy
has comment: http://stackoverflow.com/comment/81336824
has answer: http://stackoverflow.com/a/47195769
has comment: http://stackoverflow.com/comment/81338129
answer count: 1
tagged with: web-crawler
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81338115
upvote count: 2
score: 2
has body: Is it possible for Scrapy to crawl an alert message? The link for example, http://domainhere/admin, once loaded in an actual browser, an alert message with form is present to fill up the username and password. Or is there a way to inspect the form in an alert message to know what parameters to be filled up? PS: I do have credentials for this website, I just want to automate processes through web crawling. Thanks.
type: UnansweredQuestion
has title: Scrapy to bypass an alert message with form authentication

http://stackoverflow.com/comment/81095984
score: 0
type: AnswerComment
has text: Alright, since it is all in one line, i can just read that line, convert it to string, and use ast.literal_eval(), thank you!
comment on: http://stackoverflow.com/a/47073848
type: Comment

http://stackoverflow.com/a/47206404
has body: To understand better go through SIFT Taylor Expansion working out subpixel locations, later find below c++ code which is real implementation of SIFT. static void interp_step( IplImage*** dog_pyr, int octv, int intvl, int r, int c, double* xi, double* xr, double* xc ) { CvMat* dD, * H, * H_inv, X; double x[3] = { 0 }; dD = deriv_3D( dog_pyr, octv, intvl, r, c ); H = hessian_3D( dog_pyr, octv, intvl, r, c ); H_inv = cvCreateMat( 3, 3, CV_64FC1 ); cvInvert( H, H_inv, CV_SVD ); cvInitMatHeader( &amp;X, 3, 1, CV_64FC1, x, CV_AUTOSTEP ); cvGEMM( H_inv, dD, -1, NULL, 0, &amp;X, 0 ); cvReleaseMat( &amp;dD ); cvReleaseMat( &amp;H ); cvReleaseMat( &amp;H_inv ); *xi = x[2]; *xr = x[1]; *xc = x[0]; } static CvMat* hessian_3D( IplImage*** dog_pyr, int octv, int intvl, int r, int c ) { CvMat* H; double v, dxx, dyy, dss, dxy, dxs, dys; v = pixval32f( dog_pyr[octv][intvl], r, c ); dxx = ( pixval32f( dog_pyr[octv][intvl], r, c+1 ) + pixval32f( dog_pyr[octv][intvl], r, c-1 ) - 2 * v ); dyy = ( pixval32f( dog_pyr[octv][intvl], r+1, c ) + pixval32f( dog_pyr[octv][intvl], r-1, c ) - 2 * v ); dss = ( pixval32f( dog_pyr[octv][intvl+1], r, c ) + pixval32f( dog_pyr[octv][intvl-1], r, c ) - 2 * v ); dxy = ( pixval32f( dog_pyr[octv][intvl], r+1, c+1 ) - pixval32f( dog_pyr[octv][intvl], r+1, c-1 ) - pixval32f( dog_pyr[octv][intvl], r-1, c+1 ) + pixval32f( dog_pyr[octv][intvl], r-1, c-1 ) ) / 4.0; dxs = ( pixval32f( dog_pyr[octv][intvl+1], r, c+1 ) - pixval32f( dog_pyr[octv][intvl+1], r, c-1 ) - pixval32f( dog_pyr[octv][intvl-1], r, c+1 ) + pixval32f( dog_pyr[octv][intvl-1], r, c-1 ) ) / 4.0; dys = ( pixval32f( dog_pyr[octv][intvl+1], r+1, c ) - pixval32f( dog_pyr[octv][intvl+1], r-1, c ) - pixval32f( dog_pyr[octv][intvl-1], r+1, c ) + pixval32f( dog_pyr[octv][intvl-1], r-1, c ) ) / 4.0; H = cvCreateMat( 3, 3, CV_64FC1 ); cvmSet( H, 0, 0, dxx ); cvmSet( H, 0, 1, dxy ); cvmSet( H, 0, 2, dxs ); cvmSet( H, 1, 0, dxy ); cvmSet( H, 1, 1, dyy ); cvmSet( H, 1, 2, dys ); cvmSet( H, 2, 0, dxs ); cvmSet(…
answers question: http://stackoverflow.com/q/47122837
type: Answer
score: -1
upvote count: 0
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47122837

http://stackoverflow.com/comment/135058697
type: AnswerComment
has text: do not upvote this, no context is given
comment on: http://stackoverflow.com/a/47198672
score: 0
type: Comment

http://stackoverflow.com/q/47134001
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47247603
type: Question
has comment: http://stackoverflow.com/comment/81218082
tagged with: dask
has answer: http://stackoverflow.com/a/47247603
tagged with: dataframe
tagged with: python
tagged with: merge
has body: Given a dataframe where the first column is linked to the 3rd and the 5th and the 2nd is linked to the 4th and sixth. The columns are: SRC ID: Unique index to the SRC column TRG ID: Unique index to the TRG column SRC LANG: The language of the SRC column TRG LANG: The language of the TRG column SRC: The text in the language specified by SRC LANG TRG: The text in the language specified by TRG LANG Note: SRC and TRG are translations of each other. In code: from io import StringIO import pandas as pd instr = """SRC ID TRG ID SRC LANG TRG LANG SRC TRG 8366 170897 fra jpn C'est sec comme la poussière. 砂をかむように味気ないね。 8366 243583 fra eng C'est sec comme la poussière. It's dry as dust. 8366 1840509 fra epo C'est sec comme la poussière. Estas seke, kiel polvo. 8366 4401595 fra tur C'est sec comme la poussière. Toz kadar kuru. 1 77 cmn deu 我們試試看！ Lass uns etwas versuchen! 1 1276 cmn eng 我們試試看！ Let's try something. 1 2481 cmn spa 我們試試看！ ¡Intentemos algo! 1 5350 cmn kor 我們試試看！ 뭔가 해보자! 1 344899 cmn jpn 我們試試看！ やってみましょう。 1 345549 cmn cmn 我們試試看！ 试一下吧。 """ pd.read_csv(StringIO(instr), sep='\t') [out]: SRC ID TRG ID SRC LANG TRG LANG SRC TRG 0 8366 170897 fra jpn C'est sec comme la poussière. 砂をかむように味気ないね。 1 8366 243583 fra eng C'est sec comme la poussière. It's dry as dust. 2 8366 1840509 fra epo C'est sec comme la poussière. Estas seke, kiel polvo. 3 8366 4401595 fra tur C'est sec comme la poussière. Toz kadar kuru. 4 1 77 cmn deu 我們試試看！ Lass uns etwas versuchen! 5 1 1276 cmn eng 我們試試看！ Let's try something. 6 1 2481 cmn spa 我們試試看！ ¡Intentemos algo! 7 1 5350 cmn kor 我們試試看！ 뭔가 해보자! 8 1 344899 cmn jpn 我們試試看！ やってみましょう。 9 1 345549 cmn cmn 我們試試看！ 试一下吧。 Given the dataframe as such, if we want to extract the English-Japanese translation, how could I pivot through the SRC column from the TRG column to get this desired output? 170897 243583 eng jpn It's dry as dust 砂をかむように味気ないね。 1276 344899 eng jpn Let's try something. やってみましょう。 I've tried this: jpn = df[df['TRG LANG'] == 'jpn'] eng = df[df['T…
type: AnsweredQuestion
tagged with: pandas
has title: How to merge large dataframe on join and eliminate non-relevant columns?
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47217927
has comment: http://stackoverflow.com/comment/81385300
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81386540
has title: Define a function to create a new dictionary from one string
score: 0
answer count: 2
has body: I have the following PDB format code about one hypotethical new chemical substance called "new_mol": new_mol= """ ATOM 45 C BARG A -3 12.759 86.530 96.365 0.50 36.39 C ATOM 46 O BARG A -3 12.924 87.757 96.420 0.50 37.26 O ATOM 47 CB BARG A -3 13.428 85.746 93.980 0.50 36.60 C ATOM 48 CG BARG A -3 12.866 85.172 92.651 0.50 37.31 C ATOM 49 CD BARG A -3 13.374 85.886 91.406 0.50 37.66 C ATOM 50 NE BARG A -3 12.644 85.487 90.195 0.50 38.24 N ATOM 51 CZ BARG A -3 13.114 85.582 88.947 0.50 39.55 C ATOM 52 NH1BARG A -3 14.338 86.056 88.706 0.50 40.23 N """ import os where the last letter of each line is the atom symbol. I would like to define a function def count_atom(new_mol): num_atoms = dict() that creates a dictionary in order to obtain a result as: #num_atoms = {'C':5, 'O':1; 'N':2} Therefore I would like to create in Python a dictionary which displays the total number of each atom of the new_mol variable. Thanks in advance for your help.
tagged with: function
upvote count: 1
tagged with: string
has answer: http://stackoverflow.com/a/47218444
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47220271
type: UnansweredQuestion

http://stackoverflow.com/comment/81138359
type: Comment
type: QuestionComment
has text: Why would you expect you output file to be in the same folder as your input file? Your input file has a fully-qualified path, your output file doesn't.
comment on: http://stackoverflow.com/q/47090860
score: 0

http://stackoverflow.com/q/47066476
type: Question
has answer: http://stackoverflow.com/a/47066538
accepted answer: http://stackoverflow.com/a/47066523
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/30996401
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/47066529
has comment: http://stackoverflow.com/comment/81248289
has comment: http://stackoverflow.com/comment/81081120
tagged with: python
has comment: http://stackoverflow.com/comment/81248302
has comment: http://stackoverflow.com/comment/81081130
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/47066529
has answer: http://stackoverflow.com/a/47066523
has title: CSV file to MySQL database, inserts aren't working
tagged with: mysql
upvote count: 1
tagged with: insert
has body: I am trying to get a CSV file to a MYSQL database, but it never appears! I dont know if I messed something up, but you guys should take a look. # its time for fetching data :) import csv import urllib2 path = 'C:\\Users\\User\\Desktop\\Downloads\\' response = urllib2.urlopen('https://files.ontario.ca/opendata/births_by_year_and_month_per_place_of_event_city_2010_0.csv') html = response.read() file=open( path +"births.CSV", "r") reader = csv.reader(file) for row in reader: print row #Server Connection to MySQL: import MySQLdb conn = MySQLdb.connect(host= "localhost", user="root", passwd="admin", db="cool") x = conn.cursor() try: x.execute("""INSERT INTO import (test) VALUES (%s,%s,%s,%s)""",(row)) conn.commit() except: conn.rollback() conn.close() It ends with exit code 0, prints everything, but never inserts into the database. Here is a sample of the print ['2010', 'Sep', 'THUNDER BAY', '132'] ['2010', 'Sep', 'TIMMINS', '59'] ['2010', 'Sep', 'TORONTO', '3412'] ['2010', 'Sep', 'WELLAND', '58'] ['2010', 'Sep', 'WELLINGTON NORTH', '6'] ['2010', 'Sep', 'WINDSOR', '337'] ['2010', 'Sep', 'WOODSTOCK', '50'] Process finished with exit code 0 EDIT Im not sure if the %s part has something to do with it, but i need help. Thanks! Edit 2 Great! Thanks to all of you people who have helped me. But now there's a new edit, and i cant seem to find out whats going wrong. Here is the new code! import csv import urllib2 path = 'C:\\Users\\hongyu\\Desktop\\Downloads\\' response = urllib2.urlopen('https://files.ontario.ca/opendata/births_by_year_and_month_per_ place_of_event_city_2010_0.csv') html = response.read() file=open( path +"births.CSV", "r") reader = csv.reader(file) #Server Connection to MySQL: import MySQLdb conn = MySQLdb.connect(host= "localhost", user="root", passwd="admin", db="cool") for row in reader: x = conn.cursor() try: x.execute("""INSERT INTO testing (year, month, city, num) VALUES (%s,%s,%s,%s)""", (row)) conn.commit() except : conn.rollback() print(row) print("Thi…
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/47080379
upvote count: 1
favorite count: 0
type: Question
has body: I have two lists ids = [1,2,2,2,5] names = ['yes', 'no','yes','yes','no'] I want to set(id) and filter name by 'no' maintaining there positions So i end up with [1,2,5] ['yes','no','no'] I just need to get a count of how many 'No's there are based of distinct ID's Some kind of list comprehension maybe? zip?
score: -3
tagged with: python
tagged with: list-comprehension
accepted answer: http://stackoverflow.com/a/47080459
has answer: http://stackoverflow.com/a/47080459
type: AnsweredQuestion
tagged with: list
downvote count: 4
has title: Python - filter by unique values in one list and specific string in a second list
has comment: http://stackoverflow.com/comment/81132955
answer count: 1

http://stackoverflow.com/a/47243226
has comment: http://stackoverflow.com/comment/90555021
downvote count: 0
has comment: http://stackoverflow.com/comment/81503972
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47106592
upvote count: 2
has comment: http://stackoverflow.com/comment/105257824
answers question: http://stackoverflow.com/q/47106592
has body: Here's the code that appears to be working. At least I can't reproduce the problem unlike the original one. Notice app.conf.broker_pool_limit = 0 and connection_pool.disconnect. Here's what broker_pool_limit does: The maximum number of connections that can be open in the connection pool. If set to None or 0 the connection pool will be disabled and connections will be established and closed for every use. import os import time import random import datetime import logging import redis logging.basicConfig() logger = logging.getLogger(__name__) from celery import Celery from celery.contrib import rdb app = Celery('tasks', backend='redis://localhost', broker='redis://localhost') app.conf.broker_pool_limit = 0 def get_redis(): url = os.environ.get("REDIS_URL") if url: r = redis.from_url(url) # use secure for heroku else: r = redis.Redis() # use unauthed connection locally return r @app.task(bind=True, max_retries=10) def test_delay_task(self, task_id): ''' Each task with try to grab a lock and once it does, will sleep 5 seconds, then print and exit. ''' have_lock = False redis_cli = get_redis() lock = redis_cli.lock('mws_api') try: have_lock = lock.acquire(blocking=False) if have_lock: logger.warning("{} Lock Acquired".format(task_id)) time.sleep(5) logger.warning('Test Task {} successful!'.format(task_id)) else: logger.warning("{} Lock In Use, Retrying".format(task_id)) self.request.retries = 1 self.retry(countdown=5 * random.uniform(0.8, 1.2)) finally: if have_lock: lock.release() redis_cli.connection_pool.disconnect() # We'll come back to this code, but it partially works # c = r.info()['connected_clients'] # print("Disconnecting Redis | Connections: {}".format(c)) # r.connection_pool.disconnect() @app.task(bind=True, max_retries=10) def test_parallel_tasks(self): ''' Runs 10 consecutive tasks, each which will try to grab a lock and run. ''' for i in range(5): test_delay_task.delay(i) def get_connected_clients(): try: connections = 0 while True: time.sleep(.25) c = get…
type: Answer
score: 2

http://stackoverflow.com/a/47204883
upvote count: 1
has body: Your code is correct, but it won't work for creation of new objects. I'm not familiar with a way of accessing @property at __init__. (Python 2.7) What you can do, is inserting an assert statement. It will throw an error if the user input is invalid. You can enclode this in try.. catch block if you want to set a default value. class TestVolume: def __init__(self, volume: float): assert volume &gt; 0 self._volume = volume * 1000 self.volume = self._volume And the rest of your code stays the same.
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47204471
type: Answer

flask
tags question: http://stackoverflow.com/q/47122295
tags question: http://stackoverflow.com/q/47088560
tags question: http://stackoverflow.com/q/47123860
tags question: http://stackoverflow.com/q/47141247
tags question: http://stackoverflow.com/q/47069114
tags question: http://stackoverflow.com/q/47084276
tags question: http://stackoverflow.com/q/47126947
tags question: http://stackoverflow.com/q/47116344
tags question: http://stackoverflow.com/q/47179427
tags question: http://stackoverflow.com/q/47191903
tags question: http://stackoverflow.com/q/47080031
tags question: http://stackoverflow.com/q/47108294
tags question: http://stackoverflow.com/q/47105259
tags question: http://stackoverflow.com/q/47149021
tags question: http://stackoverflow.com/q/47142893
tags question: http://stackoverflow.com/q/47219947
tags question: http://stackoverflow.com/q/47065726
tags question: http://stackoverflow.com/q/47105801
tags question: http://stackoverflow.com/q/47162833
tags question: http://stackoverflow.com/q/47179655
tags question: http://stackoverflow.com/q/47165900
tags question: http://stackoverflow.com/q/47066452
tags question: http://stackoverflow.com/q/47163556
tags question: http://stackoverflow.com/q/47169221
tags question: http://stackoverflow.com/q/47147492
tags question: http://stackoverflow.com/q/47137356
tags question: http://stackoverflow.com/q/47100139
tags question: http://stackoverflow.com/q/47087202
tags question: http://stackoverflow.com/q/47218275
tags question: http://stackoverflow.com/q/47097263
tags question: http://stackoverflow.com/q/47142936
tags question: http://stackoverflow.com/q/47074442
tags question: http://stackoverflow.com/q/47106364
tags question: http://stackoverflow.com/q/47169097
tags question: http://stackoverflow.com/q/47150962
tags question: http://stackoverflow.com/q/47180202
tags question: http://stackoverflow.com/q/47112908
tags question: http://stackoverflow.com/q/47066725
tags question: http://stackoverflow.com/q/47221033
tags question: http://stackoverflow.com/q/47066711
tags question: http://stackoverflow.com/q/47090465
tags question: http://stackoverflow.com/q/47207056
tags question: http://stackoverflow.com/q/47191039
tags question: http://stackoverflow.com/q/47133398
tags question: http://stackoverflow.com/q/47157092
tags question: http://stackoverflow.com/q/47194222
tags question: http://stackoverflow.com/q/47216204
tags question: http://stackoverflow.com/q/47124481
tags question: http://stackoverflow.com/q/47066212
tags question: http://stackoverflow.com/q/47141503
tags question: http://stackoverflow.com/q/47077967
tags question: http://stackoverflow.com/q/47150390
tags question: http://stackoverflow.com/q/47161700
tags question: http://stackoverflow.com/q/47099682
tags question: http://stackoverflow.com/q/47222328
tags question: http://stackoverflow.com/q/47166043
tags question: http://stackoverflow.com/q/47150564
tags question: http://stackoverflow.com/q/47215352
tags question: http://stackoverflow.com/q/47188761
tags question: http://stackoverflow.com/q/47096087
tags question: http://stackoverflow.com/q/47178632
tags question: http://stackoverflow.com/q/47151524
tags question: http://stackoverflow.com/q/47065488
tag name: flask
tags question: http://stackoverflow.com/q/47085505
tags question: http://stackoverflow.com/q/47178361
tags question: http://stackoverflow.com/q/47083304
tags question: http://stackoverflow.com/q/47066328
tags question: http://stackoverflow.com/q/47095410
tags question: http://stackoverflow.com/q/47213861
tags question: http://stackoverflow.com/q/47104359
tags question: http://stackoverflow.com/q/47187441
tags question: http://stackoverflow.com/q/47145351
tags question: http://stackoverflow.com/q/47091958
tags question: http://stackoverflow.com/q/47088577
tags question: http://stackoverflow.com/q/47083403
tags question: http://stackoverflow.com/q/47167014
tags question: http://stackoverflow.com/q/47106862
tags question: http://stackoverflow.com/q/47151837
tags question: http://stackoverflow.com/q/47113190

http://stackoverflow.com/comment/81306055
has text: Is there a particular Structure to pyspark project like where to specify jar dependencies and configuration files etc. or its all ones own confort.
type: AnswerComment
comment on: http://stackoverflow.com/a/47177612
type: Comment
score: 0

http://stackoverflow.com/a/47130693
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47130632
has body: r = 'aapple' w = list('axplpett') try: for x in r: w.pop(w.index(x)) print(True) # return True except ValueError: print(False) # return False
has comment: http://stackoverflow.com/comment/81211331
has comment: http://stackoverflow.com/comment/81211100
type: Answer

http://stackoverflow.com/q/47155767
score: 2
tagged with: numpy
type: AnsweredQuestion
answer count: 3
tagged with: shuffle
upvote count: 2
accepted answer: http://stackoverflow.com/a/47156309
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/51525965
has answer: http://stackoverflow.com/a/47156309
linked to: http://stackoverflow.com/q/4601373
possible better answer: http://stackoverflow.com/a/47156345
has body: I have multiple numpy arrays with the same number of rows (axis_0) that I'd like to shuffle in unison. After one shuffle, I'd like to shuffle them again with a different random seed. Till now, I've used the solution from Better way to shuffle two numpy arrays in unison : def shuffle_in_unison(a, b): rng_state = numpy.random.get_state() numpy.random.shuffle(a) numpy.random.set_state(rng_state) numpy.random.shuffle(b) However, this doesn't work for multiple unison shuffles, since rng_state is always the same. I've tried to use RandomState in order to get a different seed for each call, but this doesn't even work for a single unison shuffle: a = np.array([1,2,3,4,5]) b = np.array([10,20,30,40,50]) def shuffle_in_unison(a, b): r = np.random.RandomState() # different state from /dev/urandom for each call state = r.get_state() np.random.shuffle(a) # array([4, 2, 1, 5, 3]) np.random.set_state(state) np.random.shuffle(b) # array([40, 20, 50, 10, 30]) # -&gt; doesn't work return a,b for i in xrange(10): a,b = shuffle_in_unison(a,b) print a,b What am I doing wrong? Edit: For everyone that doesn't have huge arrays like me, just use the solution by Francesco (https://stackoverflow.com/a/47156309/3955022): def shuffle_in_unison(a, b): n_elem = a.shape[0] indeces = np.random.permutation(n_elem) return a[indeces], b[indeces] The only drawback is that this is not an in-place operation, which is a pity for large arrays like mine (500G).
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47156345
has title: Numpy: shuffle arrays in unison multiple times with different seeds
tagged with: python

http://stackoverflow.com/q/47083839
has body: makinsane@makinsane:~$ sudo apt install python-pip &amp;&amp; sudo apt install python3-pip Reading package lists... Done Building dependency tree Reading state information... Done The following additional packages will be installed: build-essential cpp-5 dpkg-dev fakeroot g++ g++-5 gcc-5 gcc-5-base libalgorithm-diff-perl libalgorithm-diff-xs-perl libalgorithm-merge-perl libasan2 libatomic1 libcc1-0 libcilkrts5 libexpat1-dev libfakeroot libgcc-5-dev libgomp1 libitm1 liblsan0 libmpx0 libpython-all-dev libpython-dev libpython2.7-dev libquadmath0 libstdc++-5-dev libstdc++6 libtsan0 libubsan0 python-all python-all-dev python-dev python-pip-whl python-pkg-resources python-setuptools python-wheel python2.7-dev Fetched 37.6 MB in 2min 4s (303 kB/s) E: Failed to fetch http://in.archive.ubuntu.com/ubuntu/pool/main/g/gcc-5/cpp-5_5.4.0-6ubuntu1~16.04.5_amd64.deb Hash Sum mismatch
upvote count: 1
possible better answer: http://stackoverflow.com/a/47083950
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: gcc
has title: Hash Sum mismatch in ubuntu 16.04.3
tagged with: python
accepted answer: http://stackoverflow.com/a/47085132
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/81117047
has answer: http://stackoverflow.com/a/47085132
has answer: http://stackoverflow.com/a/47083950
tagged with: c++
score: 0
answer count: 2

http://stackoverflow.com/comment/81366139
type: QuestionComment
comment on: http://stackoverflow.com/q/47208371
score: 0
has text: @Maveric: of all reasons...
type: Comment

http://stackoverflow.com/comment/81143834
type: Comment
has text: Can you recommend on best regularization to this network?And how I can to do it in tensorflow?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47069671

http://stackoverflow.com/comment/81198088
type: Comment
comment on: http://stackoverflow.com/q/47123860
type: QuestionComment
score: 3
has text: What does the `UserModel` base class look like?

http://stackoverflow.com/q/47130393
has body: It seems like urlopen ignores everything after ?. Same object returned for URL https://apm.activecommunities.com/danvilleca/Activity_Search?Page=11 and https://apm.activecommunities.com/danvilleca/Activity_Search?Page=1. tried to escape question mark but no avail. much appreciated if anyone can share insights urllib.urlopen('https://apm.activecommunities.com/danvilleca/Activity_Search?Page=11').read() urllib.urlopen('https://apm.activecommunities.com/danvilleca/Activity_Search?Page=1').read()
has answer: http://stackoverflow.com/a/47130518
answer count: 1
has comment: http://stackoverflow.com/comment/81210746
has title: urllib.urlopen not able to open url with page id
tagged with: urllib
type: Question
has comment: http://stackoverflow.com/comment/81211675
type: UnansweredQuestion
score: 0
tagged with: urlopen
tagged with: python

http://stackoverflow.com/q/47218780
tagged with: pycryptodome
tagged with: python-cryptography
tagged with: cryptography
type: Question
type: UnansweredQuestion
has body: I am trying to use the pycryptodome example of encrypting a file with an RSA key. The example is as follows from Crypto.PublicKey import RSA from Crypto.Random import get_random_bytes from Crypto.Cipher import AES, PKCS1_OAEP file_out = open("encrypted_data.bin", "wb") recipient_key = RSA.import_key(open("receiver.pem").read()) session_key = get_random_bytes(16) # Encrypt the session key with the public RSA key cipher_rsa = PKCS1_OAEP.new(recipient_key) file_out.write(cipher_rsa.encrypt(session_key)) # Encrypt the data with the AES session key cipher_aes = AES.new(session_key, AES.MODE_EAX) ciphertext, tag = cipher_aes.encrypt_and_digest(data) [ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ] And the error I receive is AttributeError: module 'Crypto.PublicKey.RSA' has no attribute 'import_key' I found another thread where this error was identified as a version problem with pyCrypto but I am trying to use PyCryptodome and I do have the latest version.
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/47285756
tagged with: rsa
has title: PyCryptodome RSA encryption
answer count: 1

http://stackoverflow.com/comment/81114234
type: AnswerComment
comment on: http://stackoverflow.com/a/47067999
type: Comment
has text: Sorry I didn't mention but the text values (1.56,etc) will be different numbers for every one. Would I just leave it blank?
score: 0

http://stackoverflow.com/a/60872000
has body: If you're using SQLAlchemy with an engine, then you can retrieve the PyODBC cursor like this before running the query and fetching the table ID. connection = sql_alchemy_engine.raw_connection() cursor = connection.cursor() result = cursor.execute( """ INSERT INTO MySchema.MyTable (Col1, Col2) OUTPUT INSERTED.MyTableId VALUES (?, ?); """, col1_value, col2_value, ) myTableId = cursor.fetchone()[0] cursor.commit() print("my ID is:", myTableId)
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/47188976
downvote count: 0
type: Answer

http://stackoverflow.com/a/47089455
has body: You need to change from . import views to from homepage.views import homepage(mapping function)
answers question: http://stackoverflow.com/q/47089049
type: Answer
score: 0

http://stackoverflow.com/comment/81131138
comment on: http://stackoverflow.com/a/47090475
type: Comment
type: AnswerComment
has text: I flipped my vote to up. Thanks for listening. For what it's worth I think you turned this into a very good answer.
score: 0

http://stackoverflow.com/comment/81193377
type: QuestionComment
comment on: http://stackoverflow.com/q/47121766
score: 0
has text: I get the error: TypeError: descriptor 'tofile' requires a 'numpy.ndarray' object but received a 'str' However the type of my output_matrix is numpy.core.defchararray.chararray so I am unsure why it consider it a str
type: Comment

http://stackoverflow.com/comment/81308392
score: 0
comment on: http://stackoverflow.com/q/47179215
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ are you saying that it is not possible to convert lists to pandas structures to use in the example?
type: QuestionComment

http://stackoverflow.com/comment/81199801
has text: Using your example, for the value in row 1, column1, I am interested in finding all row numbers where that same value is found in that column.
comment on: http://stackoverflow.com/a/47124590
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47086673
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/47086766
score: 2
tagged with: cluster-analysis
has answer: http://stackoverflow.com/a/47091880
downvote count: 0
tagged with: python
type: UnansweredQuestion
has body: I have data which forms a sparse matrix in shape of 1000 x 1e9. I want to cluster the 1000 examples into 10 clusters using K-means. The matrix is very sparse, less than 1/1e6 values. My laptop got 16 RAM. I tried sparse matrix in scipy. Unfortunately, the matrix makes the clustering process need much more memory than I have. Could anyone suggest a way to do this? My system crashed when running the following test snippet import numpy as np from scipy.sparse import csr_matrix from sklearn.cluster import KMeans row = np.array([0, 0, 1, 2, 2, 2, 3, 3, 4, 5, 5, 5, 6, 6, 7, 8, 8, 8]) col = np.array([0, 2, 2, 0, 1, 2] * 3) data = np.array([1, 2, 3, 4, 5, 6] * 3) X = csr_matrix((data, (row, col)), shape=(9, 1e9)) resC = KMeans(n_clusters=3).fit(X) resC.labels_ Any helpful suggestion is appreciated.
has answer: http://stackoverflow.com/a/47105252
has answer: http://stackoverflow.com/a/47087643
has title: How to cluster very big sparse data set using low memory in Python?
answer count: 4
favorite count: 0

http://stackoverflow.com/comment/81416828
type: AnswerComment
has text: Thanks for the reply, I actually new about PhantomJS but I thought you wanted an alternative for Selenium. I'm glad you found a solution. Also there is a way to run a headless browser using the ChromeDriver.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47107054

http://stackoverflow.com/q/47178983
type: UnansweredQuestion
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82215832
tagged with: celery
favorite count: 0
tagged with: django-unittest
has title: How can I ensure changes to my Celery countdown wont break anything?
score: 1
tagged with: django-celery
has body: I have a number of celery tasks in my Django application that are currently being tested synchronously using CELERY_ALWAYS_EAGER. However this option means that I can't test that changes to the countdown value in apply_async won't break anything. How can I test that nothing else in my application was depending on the longer countdown now that I suspect I no longer need it? I'm using Django 1.10 and Celery 3.1 with Python 3.5.
type: Question
answer count: 0

http://stackoverflow.com/comment/113657616
score: 1
has text: Don't know why, but this solved my problem. Thanks.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/59164440

http://stackoverflow.com/q/47198365
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81345962
has comment: http://stackoverflow.com/comment/81346362
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/81345408
type: Question
has comment: http://stackoverflow.com/comment/81345672
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81346881
has comment: http://stackoverflow.com/comment/81346835
has body: I've been experiencing a weird error when using django for loop template, whenever I use my "{% for groups in groups %}" for loop, my datetime field won't open, however when I try to use other context for my loop, it just works. I also just simply copy pasted this modal from my other html page since it has the same function. Already checked if there are any conflicts with id and other loops. Also tried inspecting element on the modal's button, and it shows the correct group id. I have been using the same loop for other functions in this html page and it seems to be working fine as well. Any idea on how to debug this issue? admin.html {% for groups in groups %} × Allocate Device Device List Device Quantity Router Switch Terminal Date to Close Allocate {% endfor %} views.py def adminPage(request): currentUser = request.user if currentUser.profile.usertype != 'admin': return HttpResponseRedirect("/user/") signupForm = SignUpForm() newgroupForm = CreateGroupForm() users = User.objects.all() groups = Group.objects.all() grouptodevice = GroupToDevice.objects.all() devices = Device.objects.all() context = { 'groups':groups, 'users':users, 'current_user': currentUser, 'newgroupForm': newgroupForm, 'signupForm' : signupForm, 'grouptodevice' : grouptodevice, 'devices':devices, } return render(request, 'admin.html', context)
has comment: http://stackoverflow.com/comment/81346106
tagged with: django
tagged with: javascript
tagged with: python
has title: Django template won't let my datetime field pop up or open
has comment: http://stackoverflow.com/comment/81346415
has comment: http://stackoverflow.com/comment/81346701
has comment: http://stackoverflow.com/comment/81346038
has comment: http://stackoverflow.com/comment/81346606

http://stackoverflow.com/q/47092023
upvote count: 2
tagged with: django-countries
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47093593
tagged with: django
score: 1
tagged with: django-rest-framework
downvote count: 1
possible better answer: http://stackoverflow.com/a/71331024
favorite count: 0
has answer: http://stackoverflow.com/a/71331024
type: Question
has answer: http://stackoverflow.com/a/47134903
has answer: http://stackoverflow.com/a/76605211
tagged with: python
has title: How to return actions and parameters in OPTIONS request with django rest framework
answer count: 4
tagged with: metadata
has body: I try to return a list of select options for countries using django-countries and django rest framework. I use JWT_AUTH for the authentication. When I try a options request: curl \ -H "Authentication: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFsYmVydG9fdmVudGEiLCJ1c2VyX2lkIjoyLCJlbWFpbCI6IiIsImV4cCI6MTUwODE2Mzg4Mn0.svxqTThCahSl1Vu27sMjuJyd1PRLk28-Xgn2OKKb5-g"\ -X OPTIONS \ -v http://127.0.0.1:8000/api/v1/core/perfilViajeroUserPass/ The response is: { "name":"Perfil Viajero User Pass Create", "description":"", "renders":["application/json","text/html"], "parses":[ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ] } But I think that it should be something like this by default: { "name": "To Do List", "description": "List existing 'To Do' items, or create a new item.", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "note": { "type": "string", "required": false, "read_only": false, "label": "title", "max_length": 100 } } } } Someone could help me? thanks.
accepted answer: http://stackoverflow.com/a/47134903

http://stackoverflow.com/q/47123982
has comment: http://stackoverflow.com/comment/81225361
has comment: http://stackoverflow.com/comment/81267330
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47158745
has answer: http://stackoverflow.com/a/47158745
type: Question
has title: Python - How to extract chunked elements?
has body: I am new to python and I'm giving nltk a shot. I came across the following: namedEnt = nltk.ne_chunk(tagged) Where tagged is tagged = nltk.pos_tag(words) and words are token's of a sentence. I would like to remove the stop words of namedEnt. I was able to first remove the stop words from the tokens and then chunk, but was not able to chunk and then remove the stop words. Is it possible ? If so, how could I do this ? Eg: Sentence- "get me todays menu." is tagged into ('get', 'VB') ('me', 'PRP') ('todays', 'JJ') ('menu', 'NN') ('.', '.') and I would like to get ('get','VB')('todays','JJ')('menu','NN')('.','.')
has comment: http://stackoverflow.com/comment/81288849
tagged with: nltk
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/81334359
has text: @Cyzanfar the point is that it gets absorbed into zero
comment on: http://stackoverflow.com/q/47188914
type: QuestionComment
type: Comment
score: 0

state
tag name: state
type: Tag
tags question: http://stackoverflow.com/q/47147538

http://stackoverflow.com/comment/81185043
score: 0
comment on: http://stackoverflow.com/q/47117421
type: QuestionComment
has text: Why does your file have square brackets? Can you fix whatever generated that file to make a regular csv?
type: Comment

http://stackoverflow.com/comment/81313450
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47177905
has text: @Sven: Yes I used Qt Designer and it has self.seupUi method. I also tried your suggestion before but the problem is that one of buttons that opens a QFileDialog does nothing after calling it again through a function. I edited my post and added the section regarding the procedure. any idea?
score: 0

http://stackoverflow.com/q/47112122
tagged with: python-requests
downvote count: 1
has comment: http://stackoverflow.com/comment/81176655
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81177712
tagged with: python
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81174148
has comment: http://stackoverflow.com/comment/81174275
answer count: 0
has title: Getting error while importing numpy on python shell on windows 10
has comment: http://stackoverflow.com/comment/81174217
type: UnansweredQuestion
score: 0
has body: I got this exception: >>> import numpy Traceback (most recent call last): File "C:\Users\...\Python36\lib\site-packages\numpy\core\__init__.py", line 16, in <module> from . import multiarray ImportError: DLL load failed: Le module spécifié est introuvable. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import numpy File "C:\Users\...\Python36\lib\site-packages\numpy\__init__.py", line 142, in <module> from . import add_newdocs File "C:\Users\...\Python36\lib\site-packages\numpy\add_newdocs.py", line 13, in <module> from numpy.lib import add_newdoc File "C:\Users\...\Python36\lib\site-packages\numpy\lib\__init__.py", line 8, in <module> from .type_check import * File "C:\Users\...\Python36\lib\site-packages\numpy\lib\type_check.py", line 11, in <module> import numpy.core.numeric as _nx File "C:\Users\...\Python36\lib\site-packages\numpy\core\__init__.py", line 24, in <module> raise ImportError(msg) ImportError: Importing the multiarray numpy extension module failed. Most likely you are trying to import a failed build of numpy. If you're working with a numpy git repo, try git clean -xdf (removes all files not under version control). Otherwise reinstall numpy.
upvote count: 1
has comment: http://stackoverflow.com/comment/81174252

http://stackoverflow.com/comment/81186775
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47118098
has text: @xhancar thank you, I guess have been doing that wrong for a while now and completely overlooked it because I thought it looked nice haha. appreciated! will be checking that to switch <> and [] in all of my existing code.
type: Comment

http://stackoverflow.com/q/47154172
upvote count: 0
type: UnansweredQuestion
answer count: 1
has title: smtplib.SMTP.sendmail raise exception but its str is (250, 'ok')
downvote count: 1
favorite count: 0
type: Question
tagged with: smtplib
tagged with: exception
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47192374
tagged with: sendmail
has body: try: if not self.check_smtp_connected("main", self.sender_addr): self.close("main", self.sender_addr) if not self.connect("main", self.sender_addr): self.last_error = "req_id:%d,connect to %s main failed" % (mail_id, self.name) raise Exception("req_id:%d,connect to %s main failed" % (mail_id, self.name)) sender_addr = parseaddr(self.msg['From'])[1] recv_addr = parseaddr(self.msg['To'])[1] self.smtp_conns[self.sender_addr].sendmail(self.msg['From'], self.msg['To'], self.msg.as_string()) except Exception as e: glogger.warning("req_id:%d,send mail by %s failed, error: %s" % (mail_id, self.name, str(e))) else: sent_succ = True break check_smtp_connected use noop()[0] to check connection to smtp server. the first time I get : req_id:7066283,send mail by tx_smtp failed, error: timed out so the exception is time out and then I use check_smtp_connected to check the connection, it's broken. the second time I get: req_id:7066283,send mail by tx_smtp failed, error: (250, 'Ok') so the exception is (250, 'Ok') I read source code of sendmail, but can't find the branch that will raise this exception. so I'm heavily puzzled. and the result is my mailbox get two mail
has comment: http://stackoverflow.com/comment/81258020

http://stackoverflow.com/a/47115589
has comment: http://stackoverflow.com/comment/81181147
has comment: http://stackoverflow.com/comment/81181113
has body: You can use regex: import re if re.findall('[\!\$\%\^\&amp;\*\_\-\+\=]', name): points += 1
upvote count: 4
has comment: http://stackoverflow.com/comment/81181174
has comment: http://stackoverflow.com/comment/81181079
has comment: http://stackoverflow.com/comment/81181061
accepted answer of: http://stackoverflow.com/q/47115532
has comment: http://stackoverflow.com/comment/81180978
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/47115532
score: 3
type: Answer

http://stackoverflow.com/comment/133205123
type: AnswerComment
comment on: http://stackoverflow.com/a/47227886
score: 0
has text: FYI: Since `Tensorflow 2.10` there is no support for GPU under Windows, see https://www.tensorflow.org/install/pip#older_versions_of_tensorflow
type: Comment

http://stackoverflow.com/a/47209725
type: Answer
answers question: http://stackoverflow.com/q/47209353
score: 1
upvote count: 1
downvote count: 0
has body: If Name is the column not the index as your sample dataframe suggests, you can compare the two columns (df1['Name'] == df2['Name']).all() It returns True in this case. Lets say your df2 is Name A B 0 t1 3 4 1 t5 2 2 2 net 3 3 3 fry 4 5 I just flipped the rows at index 2 and 3 keeping the values same, (df1['Name'] == df2['Name']).all() will return False

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/47179707
tags question: http://stackoverflow.com/q/47069278
type: Tag
tags question: http://stackoverflow.com/q/47145626
tags question: http://stackoverflow.com/q/47080561

http://stackoverflow.com/a/47178938
has body: This is because you need to use one of tkinter's variable classes. This would look something like the below: from tkinter import * root = Tk() var = IntVar() var.trace("w", lambda name, index, mode: print(var.get())) Checkbutton(root, variable=var).pack() root.mainloop() Essentially IntVar() is a "container" (very loosely speaking) which "holds" the value of the widget it's assigned to.
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/47178646
downvote count: 0

http://stackoverflow.com/comment/81248965
comment on: http://stackoverflow.com/q/47149154
score: 1
has text: Your intuition is correct. In a language like Swift, this would be perfectly valid because the Swift compiler interprets the possible options from the enum. My guess is that MyPy doesn't do that (yet) and is simply comparing string value to string value completely unaware of the enum context.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47164335
score: 2
answers question: http://stackoverflow.com/q/47164260
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: You can use use a regular expression by escaping the characters you listed above: import re s = "_%&amp;&amp;^$" if not re.findall("^[\!\$\%\^\&amp;\*\(\)\_\-\+\=]+$", s): points -= 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47164260

http://stackoverflow.com/a/47114463
has comment: http://stackoverflow.com/comment/81249826
has body: Here is a working example does hopefully exactly what you want. test.py from flask import render_template, Flask, jsonify from flask_wtf import FlaskForm from wtforms import StringField from wtforms.validators import DataRequired app = Flask(__name__) app.secret_key = 'example' class MyForm(FlaskForm): first_name = StringField('first name', validators=[DataRequired('please enter your name')]) last_name = StringField('last name', validators=[DataRequired()]) @app.route('/') def home(): form = MyForm() return render_template('example.html', form=form) @app.route('/something/', methods=['post']) def something(): form = MyForm() if form.validate_on_submit(): return jsonify(data={'message': 'hello {}'.format(form.first_name.data)}) return jsonify(data=form.errors) if __name__ == '__main__': app.run(debug=True) example.html {% from '_formhelpers.html' import render_field %} Example Post AJAX Out get JSON Back {{ form.hidden_tag() }} {{ render_field(form.first_name)}} {{ render_field(form.last_name) }} If the validation fails we send back the entire form.errors dictionary.
type: Answer
has comment: http://stackoverflow.com/comment/81237041
has comment: http://stackoverflow.com/comment/81192116
has comment: http://stackoverflow.com/comment/81216016
accepted answer of: http://stackoverflow.com/q/47112908
has comment: http://stackoverflow.com/comment/81186655
has comment: http://stackoverflow.com/comment/81250034
score: 0
answers question: http://stackoverflow.com/q/47112908
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81200864
has comment: http://stackoverflow.com/comment/81201998

http://stackoverflow.com/comment/81227192
type: Comment
type: QuestionComment
score: 0
has text: Remove the magic `%matplotlib inline` or use `%matplotlib agg` instead.
comment on: http://stackoverflow.com/q/47138023

http://stackoverflow.com/a/47133010
score: 20
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81255665
has comment: http://stackoverflow.com/comment/81251996
upvote count: 20
type: Answer
accepted answer of: http://stackoverflow.com/q/47088830
has comment: http://stackoverflow.com/comment/81248635
has body: A possible explanation for this would be if you haven't assigned your cluster with the correct scope. If this is the case, the nodes in the cluster would not have the required authorisation/permission to write to Google Cloud Storage which could explain the 403 error you're seeing. If no scope is set when the cluster is created, the default scope is assigned and this only provides read permission for Cloud Storage. In order to check the clusters current scopes using Cloud SDK you could try running a 'describe' command from the Cloud Shell, for example: gcloud container clusters describe CLUSTER-NAME --zone ZONE The oauthScopes section of the output contains the current scopes assigned to the cluster/nodes. The default read only Cloud Storage scope would display: https://www.googleapis.com/auth/devstorage.read_only If the Cloud Storage read/write scope is set the output will display: https://www.googleapis.com/auth/devstorage.read_write The scope can be set during cluster creation using the --scope switch followed by the desired scope identifier. In your case, this would be “storage-rw”. For example, you could run something like: gcloud container clusters create CLUSTER-NAME --zone ZONE --scopes storage-rw The storage-rw scope, combined with your service account should then allow the nodes in your cluster to write to Cloud Storage. Alternatively you if you don't want to recreate the cluster you can create a new node pool with the new desired scopes, then delete your old node pool. See the accepted answer for Is it necessary to recreate a Google Container Engine cluster to modify API permissions? for information on how to achieve this.
answers question: http://stackoverflow.com/q/47088830

http://stackoverflow.com/q/47117698
linked to: http://stackoverflow.com/q/8665072
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81241755
tagged with: python
duplicate of: http://stackoverflow.com/q/8665072
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81241186
tagged with: selenium
has comment: http://stackoverflow.com/comment/81186680
has body: I'm trying to automate tasks in Craigslist using Python and Selenium. Everything was going ok until I had to "Add Image". I wrote code to click the "Add Image" button and it opened up a dialogue box (I think that's what it's called). I want to select 2 images and click the "Open" button but I don't know how to write the code for it. I saw a few examples online but nothing really spoke to me. Below is a screenshot of the dialogue box and highlighted in blue are the images I'd like to select: Craiglist Picture Also, here is my code: from selenium import webdriver driver = webdriver.Chrome() driver.get("https://dallas.craigslist.org/") # Click on "computer" link driver.find_element_by_link_text("computer").click() #Post driver.find_element_by_link_text("post").click() #Gig Offered radion button driver.find_element_by_xpath("/html/body/article/section/form/ul/li[2]/label/span[2]").click() # I want to hire someone driver.find_element_by_xpath("/html/body/article/section/form/label[1]").click() #Please choose a category: Computer Gigs" driver.find_element_by_xpath("//*[@id='picker']/ul/li[1]/label/span[2]").click() # Choose the location driver.find_element_by_xpath("/html/body/article/section/form/ul/li[1]/label/input").click() # Enter text # Enter Posting Title posting = driver.find_element_by_id("PostingTitle") posting.send_keys("[SEEKING] Parents with Kids who Play Sports. Save Money on College!") # Enter Location area = driver.find_element_by_id("GeographicArea") area.send_keys("Dallas Area") # Enter Zip Code zipcode = driver.find_element_by_id("postal_code") zipcode.send_keys("75001") # Enter Body body = driver.find_element_by_id("PostingBody") body.send_keys("this is a test) # No Pay driver.find_element_by_xpath("//*[@id='vol_label']/input").click() #From Email fromemail = driver.find_element_by_id("FromEMail") fromemail.send_keys("foo@gmail.com") # Confirm Email confirmemail = driver.find_element_by_id("ConfirmEMail") confirmemail.send_keys("foo@gmail.com") # Maps …
has title: How to select pictures in dialogue box using Selenium (mac)
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/86049815
score: 0
type: Comment
has text: Also I used python-can on the Beagle Bone Black a few years ago. Great little board!
type: AnswerComment
comment on: http://stackoverflow.com/a/48837789

http://stackoverflow.com/a/47103867
has comment: http://stackoverflow.com/comment/81232525
has body: Both Chrome and Firefox inject the same script in the page to build the rendered text. It seems that Safari doesn't rely on this script. One option would be to get the innerText property: driver.findElement(By.cssSelector("svg")).getAttribute("innerText") or: JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("return arguments[0].innerText;", element); But be aware that this property is not implemented by all the browsers and that the returned text may be different depending on the browser, especially on line breaks if the text is composed of multiple text nodes.
type: Answer
score: 1
answers question: http://stackoverflow.com/q/47101858
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47101858
upvote count: 1

http://stackoverflow.com/comment/81170059
type: AnswerComment
comment on: http://stackoverflow.com/a/47109835
score: 0
has text: Ok, very helpful, thank you for the quick answer. I was trying to determine if _any_ of the angles in the array was between 0 and PI/2 but I guess I did all wrong.
type: Comment

http://stackoverflow.com/a/47204089
answers question: http://stackoverflow.com/q/47203904
type: Answer
has comment: http://stackoverflow.com/comment/81358970
has comment: http://stackoverflow.com/comment/81359118
score: 0
has comment: http://stackoverflow.com/comment/81358434
has comment: http://stackoverflow.com/comment/81359890
has comment: http://stackoverflow.com/comment/81358235
has comment: http://stackoverflow.com/comment/81358638
has body: Pause for a moment and ponder what's actually going wrong here. You seem to have a rather voodoo approach to indentation from the way you describe things. I'm obviously guessing here since I have no data to check it myself, but I suspect you're running into an empty line at some point. It, being empty, does not have a first element, and thus throws an IndexError presumably. If it's something else, well, goes to show why you should include the errors too.

http://stackoverflow.com/a/47114979
downvote count: 0
score: 3
has body: The only thing they guarantee is that you will get a pseudo random number. You have basically no guarantees of how it will work. Even if you compile the same C program on two different compilers, you're not guaranteed the exact same result when calling rand(). You are basically wondering why you don't get the same result when rolling two different dice even if you roll them the exact same way. Well, they are different, and so is the result.
type: Answer
answers question: http://stackoverflow.com/q/47114939
upvote count: 3

http://stackoverflow.com/comment/81132287
comment on: http://stackoverflow.com/q/47091296
score: 1
type: QuestionComment
has text: You almost certainly want to be using `ModelChoiceField`, not `ChoiceField`. Your loop will only run when the class is defined, not on each form creation, so as written your choices will only be those `CreateAssignment` instances in the database when Django starts.
type: Comment

http://stackoverflow.com/comment/81150526
comment on: http://stackoverflow.com/a/47100056
has text: Not only better in Python but likely _proper_, given the lack of tail-call optimization in most (all?) Python interpreters, and the smallish stacks.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81089922
type: QuestionComment
score: 0
has text: because L[0] and L[2] have equal key id =1,so sum of their value of quantity
type: Comment
comment on: http://stackoverflow.com/q/47070764

http://stackoverflow.com/q/47178684
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47179547
tagged with: python
has body: I get rows from table with something like: def get_rows_from_table(self) -&gt; List[WebElement]: table_rows = self.table.find_elements(By.TAG_NAME, "tr") return table_rows table_rows is a List[WebElement], and a single row has many cells, so a single row itself should also be a list. Therefore, when I write something like this: def get_a_specific_row_from_table(self, table_rows, row_num: int) -&gt; List[WebElement]: return table_rows[row_num - 1] I got an error: Expected type 'List[WebElement]', got 'WebElement' instead => it is because an element from that List is defined as a WebElement. if I want to get a cell, it should be like: cell = table_row[1] then this single row is a list. My question is: how should we treat a single row of table rows? as an element or a list of elements? Is it a clean way to define all table rows as List[List[WebElement]]
tagged with: selenium-webdriver
score: 0
answer count: 1
tagged with: selenium
has title: How to treat a single row of table rows: as a web element or a list of web elements (python)
type: Question
tagged with: html-table

http://stackoverflow.com/a/47110825
score: 1
downvote count: 0
upvote count: 1
has body: Your regular expression is matching the first portion of the input string surrounded by double quotes and followed by a colon, so it hits "data" before "first". I would go for a regular expression of: '{\s*("\w+"):' This will match the opening brace followed by some optional whitespace, then select the alphanumeric text in double quotes followed by a colon. Also, you don't need to escape your double quotes as you are using a single quote as the delimiter for your regular expression.
type: Answer
answers question: http://stackoverflow.com/q/47110707

http://stackoverflow.com/comment/81337375
has text: Glad to hear it. Yes, you can group by any column(s) in `df`, which correspond to the individual values in `arr_first` rows (e.g. `[1 1 1 32]`). As for how you choose to make the groupings, you have a lot of flexibility with Pandas - you can create a function to group any way you want. See [`groupby docs`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html). If you encounter difficulty, open a new question about it or search for [existing SO posts](https://stackoverflow.com/questions/19615760/groupby-with-user-defined-functions-pandas) on the topic.
type: Comment
comment on: http://stackoverflow.com/a/47193935
score: 0
type: AnswerComment

web-services
tags question: http://stackoverflow.com/q/47141854
type: Tag
tag name: web-services

http://stackoverflow.com/comment/114955860
comment on: http://stackoverflow.com/a/47263399
score: 2
type: Comment
type: AnswerComment
has text: To anyone else finding this issue. This approach only works on the development version fpdf. the release on pypi (1.7.2) at time of writing handles loading images differently. To make this answer work with the version on pypi, you need to override FPDF._parsepng/jpg with the code from the master branch on Github.

http://stackoverflow.com/a/47172050
has comment: http://stackoverflow.com/comment/81293920
has body: I Am not sure about the datetime format it is m-d-y or d-m-y ...also you can replace the resample('D') to resample('MS') get the month start. df.melt('Category').set_index('value').resample('D').first().ffill().drop('variable',1) Out[31]: Category value 2017-01-01 a 2017-01-02 a 2017-01-03 a 2017-01-04 a 2017-01-05 a 2017-01-06 a 2017-01-07 a 2017-01-08 a Change to MS df.melt('Category').set_index('value').resample('MS').first().ffill().drop('variable',1) Out[40]: Category value 2017-01-01 a 2017-02-01 a 2017-03-01 a 2017-04-01 a 2017-05-01 a 2017-06-01 a 2017-07-01 a 2017-08-01 a
upvote count: 3
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81293881
answers question: http://stackoverflow.com/q/47171944
type: Answer

http://stackoverflow.com/q/47182750
tagged with: boto3
has title: Python multiprocessing with different constant for each thread
accepted answer: http://stackoverflow.com/a/47352319
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81395844
tagged with: amazon-s3
tagged with: multithreading
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/47352319
tagged with: amazon-rekognition
has body: I want to create a pool with a function calling the boto3 api and using a different bucket name for each thread: my function is: def face_reko(source_data, target_data): bucket = s3.Bucket(bucket_name) for key in bucket.objects.all(): key.delete() s3_client.put_object(Bucket=bucket_name, Key=target_img, Body=target_data) s3_client.put_object(Bucket=bucket_name, Key=source_img, Body=source_data) response = reko.compare_faces( SourceImage={ 'S3Object': { 'Bucket': bucket_name, 'Name' : source_img } }, TargetImage={ 'S3Object' : { 'Bucket' : bucket_name, 'Name' : target_img } } ) if len(response['FaceMatches']) &gt; 0: return True else: return False So basically it deletes all in the bucket, upload 2 new image then use the Rekognition api to compare the 2 images. Since I can't create the same image twice in the same bucket, i'd like to create a bucket for each thread then pass a constant to the function for the bucket name instead of the bucket_name const.
tagged with: python

http://stackoverflow.com/comment/81150685
comment on: http://stackoverflow.com/q/47100375
has text: Write `help(sorted)` in the Interactive Python Interpreter and it'll show you the documentation for it.
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47219308
score: 3
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/47124683
downvote count: 0
has body: I am not sure that you can do this without animation. Notebooks capture the output of matplotlib to include in the cell once the plotting is over. The animation framework is rather generic and covers anything that is not a static image. matplotlib.animation.FuncAnimation would probably do what you want. I adapted your code as follows: %matplotlib notebook import matplotlib.pyplot as plt import numpy as np import matplotlib.animation f = plt.figure() ax = f.gca() im = np.random.randn(100,100) image = plt.imshow(im, interpolation='None', animated=True) def function_for_animation(frame_index): im = np.random.randn(100,100) image.set_data(im) ax.set_title(str(frame_index)) return image, ani = matplotlib.animation.FuncAnimation(f, function_for_animation, interval=200, frames=10, blit=True) Note: You must restart the notebook for the %matplotlib notebook to take effect and use a backend that supports animation. EDIT: There is normally a way that is closer to your original question but it errors on my computer. In the example animation_demo there is a plain "for loop" with a plt.pause(0.5) statement that should also work.

doctest
type: Tag
tag name: doctest
tags question: http://stackoverflow.com/q/47170219

http://stackoverflow.com/q/47192439
has answer: http://stackoverflow.com/a/47192860
has comment: http://stackoverflow.com/comment/81334432
score: -6
favorite count: 0
type: Question
has body: The array journal is set to empty automatically. import os import time journal=[] x=input() for word in x: os.system('clear') print word, else: print "" journal.extend(x) print journal
has comment: http://stackoverflow.com/comment/81334187
answer count: 2
has answer: http://stackoverflow.com/a/47192665
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81334339
has comment: http://stackoverflow.com/comment/81360529
tagged with: python
downvote count: 6
has title: My Python Array Resets Every Time I Run it
linked to: http://stackoverflow.com/q/13167153
has comment: http://stackoverflow.com/comment/81334393

http://stackoverflow.com/comment/81217374
type: QuestionComment
comment on: http://stackoverflow.com/q/47133630
has text: @Sraw Why would that help? In any case, I tried it and it does not.
type: Comment
score: 0

http://stackoverflow.com/comment/81167816
comment on: http://stackoverflow.com/q/47108372
type: Comment
type: QuestionComment
has text: Can you provide the code?
score: 0

http://stackoverflow.com/comment/81161919
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47105636
has text: If you *must* use it as a parameter, then you cannot, because parameters are forced to be local variables. This doesn't sound like a good idea anyway.
score: 0

http://stackoverflow.com/comment/81226216
score: 0
type: Comment
type: QuestionComment
has text: thanks for the answer. first of all, I am aware that `exec` function isn't safe function, but it is doesn't matter for my purpose. maybe you have any other suggestion that can help me to implement what I am trying to do ( even with using other functions )
comment on: http://stackoverflow.com/q/47137355

http://stackoverflow.com/q/47148781
tagged with: ocr
has comment: http://stackoverflow.com/comment/81258605
favorite count: 0
type: Question
score: 5
accepted answer: http://stackoverflow.com/a/47384354
has body: I have several exams in PDF format. I want to programatically extract each question as a separate image/document. OCR is not ideal because it does not maintain code/equation formatting well. The end goal is to make flash cards with each card containing an image of an entire question. Questions can be on the same page, and can also be multi-part (e.g. 1a, 2f, etc.). Currently, I'm considering using OCR to extract question tags (e.g. 1, 2, 3, etc.) and then finding their positions in the pdf and extracting an iamge from the start of one question to the start of the next. Is there any framework or software that can do this or provide some sort of alternative approach to make this easier?
upvote count: 5
has answer: http://stackoverflow.com/a/47384354
tagged with: python
tagged with: pdf-parsing
type: AnsweredQuestion
tagged with: image-recognition
has title: Identify and extract specific sections of a PDF document
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
downvote count: 0

http://stackoverflow.com/a/69767961
score: -1
answers question: http://stackoverflow.com/q/47153250
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/123323641
type: Answer
has body: For me, moving the pyuic5 application from the path in which it was before to the path my file was. Like before pyuic5 application was in the path: C:\Users\ASUS\AppData\Roaming\Python\Python39\Scripts And then I moved it to the path: C:\Users\ASUS\Desktop\Jarvis-everything\Github Jarvis\Jarvis2\Code Where my file was, then it worked. For you, it might be different but it is easy to find. Just open cmd, type pip install pyqt5 then enter. You will see that it shows "Requirement already satisfied"(if you have already installed) on the same line you will find your path where it is installed. There, find the pyuic5 application and move it to the path where the file you want to convert is present.

http://stackoverflow.com/q/47167853
answer count: 5
has title: Taking the average of two years, written as [1858-60]
has comment: http://stackoverflow.com/comment/81285609
tagged with: python
has answer: http://stackoverflow.com/a/47168321
has answer: http://stackoverflow.com/a/47168307
possible better answer: http://stackoverflow.com/a/47168307
accepted answer: http://stackoverflow.com/a/47168321
has answer: http://stackoverflow.com/a/47168073
has body: There are a few cases where the date is written as 'created ca. 1858-60', where a human reader would understand it as 'created ca 1858-1860.' As such, imagine two integers representing years. a = 1858 b = 60 I want to be able to get a+b == 1859. I could parse them to strings, take the first two characters ('18'), concatinate the shorter string and parse them back to numbers, sure, but..that seems a bit round-a-bound. What would be the Pythonic way to deal with this?
has comment: http://stackoverflow.com/comment/81288326
type: Question
has answer: http://stackoverflow.com/a/47168217
downvote count: 3
has comment: http://stackoverflow.com/comment/81285836
has answer: http://stackoverflow.com/a/47168454
has comment: http://stackoverflow.com/comment/81285914
favorite count: 0
has comment: http://stackoverflow.com/comment/81286380
upvote count: 17
has comment: http://stackoverflow.com/comment/81285605
score: 14
type: AnsweredQuestion

http://stackoverflow.com/q/47201270
has answer: http://stackoverflow.com/a/47201405
favorite count: 0
type: Question
has title: pandas: checking for nulls: what did I do wrong applying this function by row?
has body: I want to check if some records in some (not all) of the columns in a dataframe are null; to do this, I want to create T/F fields, which I will then need to group by. E.g. if I have a field 'x' then I want to create a 'x POPULATED' field, and so on. In my context, null means NaN, the string 'not available', or the string 'nan'. I have tried the code below, but it doesn't work - I get: ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index 0') My questions are: What am I doing wrong? Is there a better way to vectorise this? Even if there is, and I'm pretty sure there is, I'd still like to understand what I was doing wrong in my code. Code: import numpy as np, pandas as pd df=pd.DataFrame() df['a']=np.arange(0,10) df['b']='test' df['c']='nothing to test here' df.iloc[0,:]=np.nan df.iloc[1,1]='not available' df.iloc[2,1]='nan' def checknull(x): if pd.isnull(x) or x=='not available' or x=='nan': return False else: return True for c in ['a','b']: df[c + 'populated'] = df.apply( lambda x: checknull(df[c]) , axis=1 )
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47201405
score: 1
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81290706
has text: Sentences that almost mean the same?
score: 0
comment on: http://stackoverflow.com/q/47159996
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81293806
comment on: http://stackoverflow.com/a/47171997
has text: Thanks for the speedy response, I have included index=False. My actual data does have more than 3 columns is that what would be causing the issue?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81352769
score: 0
has text: I want to obtain r. the equation of r can be everything, doesn't matter, i want to call r[1] or r[5] or r[15] or... and see the value of that. As i wrote for array.
comment on: http://stackoverflow.com/q/47202016
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47147136
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
tagged with: python
has body: I'm not sure how to complete my code for the "persistence bugger" problem. The goal is to create a function called "persistence" to return the number of iterations until the digits of a number multiplied together equal a single-digit number. For example: persistence(39) = 3, because 3*9 = 27, 2*7 = 14, and 1*4 = 4; hence, three iterations. Below is my code so far, and I'm not sure where to go from here or if what I have is correct. Any help would be appreciated. def persistence(num): num_str = str(num) total = 1 for i in num_str: total = total * int(i) while len(str(total)) &lt;&gt; 1: total = total * total(i) #not sure what to do from here...
has comment: http://stackoverflow.com/comment/81244929
has answer: http://stackoverflow.com/a/47148231
possible better answer: http://stackoverflow.com/a/47148231
score: 2
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47147192
accepted answer: http://stackoverflow.com/a/47147192
downvote count: 0
has title: How can I complete my Python code for the "persistence bugger"?

http://stackoverflow.com/comment/81151637
type: AnswerComment
comment on: http://stackoverflow.com/a/47100803
score: 0
type: Comment
has text: This was my last resort and 6 other people have looked at this. This is a giant relief thank you so much!

http://stackoverflow.com/comment/81226898
type: Comment
comment on: http://stackoverflow.com/a/47118728
has text: Ok, then I add solution for it ;)
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81176776
type: Comment
type: AnswerComment
score: 2
has text: nit: Lastly add space after `,` to conform to pep8.
comment on: http://stackoverflow.com/a/47113427

http://stackoverflow.com/comment/81347107
comment on: http://stackoverflow.com/q/47198867
has text: @Alfe in this case I would need to copy paste program.py in each folder right? or at least to modify the program itself so that accepts a path as an input
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47163809
has answer: http://stackoverflow.com/a/47164047
upvote count: 1
score: 1
answer count: 1
downvote count: 0
has body: I am currently trying to compare the product id to the id given in the URL. But the if statement in the template always returns "else" even though testing provides both to be equal. views.py (where data is given) def editstatus(request, product_id): try: request.session['user_id'] except KeyError: return redirect("/login") products = Product.objects.all() context = { "product":products, "theid" : product_id, } return render(request, 'posystem/status.html', context) status.html (with not working if statement) {%for product in product%} {{product.id}} {{theid}} {{product.product_description}} {{product.product_number}} {{product.product_quantity}} {{product.unit_cost}} {{product.final_cost}} {{product.status}} {% ifequal product.id theid %} hello {% else %} hello2 {% endifequal %} {% if theid %} {% if product.id == theid %} 5 Votes Needed Ready to Order Needs to Be Signed Ordered Recieved {% csrf_token %} Save {% endif %} {% else %} {% csrf_token %} Edit {% endif %} {% endfor %} I am confused on why it will neither work with a ifequal tag nor a normal if tag.
favorite count: 0
type: Question
has title: Django ifequal and if Statement Always Going to Else tags
accepted answer: http://stackoverflow.com/a/47164047
tagged with: tags
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81277362
has comment: http://stackoverflow.com/comment/81277645
type: AnsweredQuestion

http://stackoverflow.com/comment/101238880
score: 0
type: AnswerComment
has text: right so multiple starts means multiple initial centroids but how can these centroids be different if the random_state is fixed. I am missing something here
type: Comment
comment on: http://stackoverflow.com/a/47209277

http://stackoverflow.com/comment/81240667
score: 0
has text: this is very smart !
type: AnswerComment
comment on: http://stackoverflow.com/a/47145274
type: Comment

http://stackoverflow.com/comment/81271131
type: Comment
comment on: http://stackoverflow.com/a/47155309
type: AnswerComment
score: 0
has text: Thank you for your attempt to help.

http://stackoverflow.com/comment/81382486
type: QuestionComment
comment on: http://stackoverflow.com/q/47215744
has text: The version is 1.12.1,about the shape im not too sure,but now that you pointed out the input shape of the image,i checked and its not( 256,256,1),I'm guessing that's the problem.Thank you so much
score: 0
type: Comment

http://stackoverflow.com/q/47200810
tagged with: templates
has body: Code in my views.py from django.shortcuts import render def webapppage(request): parameter = { 'key1':'hello', 'key2':['hiiii','whats up','buddy'] } return render(request, 'template2.html', parameter) How can I get both {{key1}} and {{key2}} in one single variable like (parameter) in my template file? Code inside template2.html {% for c in parameter %} `{{c}} {% endfor %} I want output like hello ['hiiii','whats up','buddy']
score: 0
tagged with: view
answer count: 2
has title: Python - Get all the variable in template passed from views.py render() function
tagged with: render
has answer: http://stackoverflow.com/a/64048885
type: Question
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47208143

http://stackoverflow.com/comment/81141988
type: Comment
type: QuestionComment
has text: oh man, @DanielRoseman, I could have known that on my own -.-" . So, let me put my "thinking" into words now: I find the string in the list, and break the inner loop. I am back in the loop, "for value in my Dict[key][0]" and perform my searching for the next key etc. My print will be THE LAST thing, which is written to validationHelper.true, right? In order to fully terminate all loops upon finding a match, I would add break statements, correct?
comment on: http://stackoverflow.com/q/47096150
score: 0

http://stackoverflow.com/q/47116443
score: 1
has title: How to save a pandas dataframe into a string that i can save and retrieve from a single column in sql database?
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81183096
type: Question
has comment: http://stackoverflow.com/comment/81183274
has answer: http://stackoverflow.com/a/47116987
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has body: I have a dataframe called df and I want to save it in the database's single column such that I can retrieve it into a dataframe format and used in my functions. I have found the functions like df.to_string and df._to_sql. I could save it as a string but there is no way I could retrieve the data back into a dataframe. Any idea how can I do this?
tagged with: pandas
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47093195
tagged with: django-admin
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Django-mptt admin get child categories
score: 0
linked to: http://stackoverflow.com/q/46988897
has answer: http://stackoverflow.com/a/47095098
answer count: 1
tagged with: django-mptt
has body: I have next models in my Django project: class Category(MPTTModel): title_of_category = models.CharField(max_length=50, unique=True, verbose_name='Subcategory', default='') parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, default='', verbose_name='Category') class Product(models.Model): category = models.ForeignKey(Category, verbose_name='Category', default='') title = models.CharField(max_length=200, verbose_name='Title of product', default='') Also admin: class CategoryAdmin(DjangoMpttAdmin): list_display = ('title_of_category',) list_filter = ('title_of_category',) admin.site.register(Category, CategoryAdmin) @admin.register(Product) class ProductsAdmin(admin.ModelAdmin): list_display = ('title', ) I would like to show in my admin panel only child category(category without children) in ForeignKey. How can I filter category in admin?
type: Question

http://stackoverflow.com/a/47102818
score: 5
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47102564
has body: First, modify your function to take an arbitrary number of keyword arguments instead of a plain list: def PlotSuperposition(**kwargs): def f(x): y = 0 for i, weight in enumerate(kwargs.values()): if i==0: y+=weight else: y += weight*math.sin(x*i) return y vf = np.vectorize(f) xx = np.arange(0,6,0.1) plt.plot(xx, vf(xx)) plt.gca().set_ylim(-5,5) Notice the asterisks in front of kwargs. Then, call interact with a dictionary of key/value arguments: kwargs = {'w{}'.format(i):slider for i, slider in enumerate(weight_sliders)} interact(PlotSuperposition, **kwargs)
downvote count: 0

http://stackoverflow.com/q/47167972
has comment: http://stackoverflow.com/comment/81286053
has comment: http://stackoverflow.com/comment/81285958
type: Question
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/81285915
has comment: http://stackoverflow.com/comment/81286020
has title: Compare a selenium object list with a list of strings
has body: I am automating Twitter posting and have a list of extracted selenium objects in items_on_queue that I need to compare with a list of objects in things_to_tweet. I need to compare these two lists and eliminate any duplicates I find to output a unique list that I can use to post. The problem is that they're of a different format and I don't know how to normalize them to compare them. items_on_queue = [&lt;selenium.webdriver.remote.webelement.WebElement (session="0ea37ee02c8889e324028b8a7a66568f", element="0.3932763505379022-2")&gt;, &lt;selenium.webdriver.remote.webelement.WebElement (session="0ea37ee02c8889e324028b8a7a66568f", element="0.3932763505379022-3")&gt;] things_to_tweet = [('The Nanome User Story', '...', 'https://blog.matryx.ai/the-nanome-stack-user-story-530a95812484'), ('Goldman Sachs CEO sees Bitcoin as part of a financial n', '...', 'https://cryptodaily.co.uk/2017/11/goldman-sachs-ceo-sees-bitcoin-part-financial-new-world/'), ('$8,000? Goldman Sachs Analysts See Possible Bitcoin Pri', '...', 'https://www.coindesk.com/8000-goldman-sachs-analysts-see-possible-bitcoin-price-jump/')] The interesting thing about the selenium oject list is that each item is in the same format as those in things_to_tweet. I only need to ad .text to the object and the result appears as such(example): el = &lt;selenium.webdriver.remote.webelement.WebElement (session="0ea37ee02c8889e324028b8a7a66568f", element="0.3932763505379022-2")&gt; el.text = ('The Nanome User Story', '...', 'https://blog.matryx.ai/the-nanome-stack-user-story-530a95812484') This is the same format I have in things_to_tweet How can I compare these two different format lists to eliminate duplicates? I guess I need to do a comparison of all el.text in a list compared with all el from the other list, but don't know how to do it. Any ideas? Thank you
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/81286084
has answer: http://stackoverflow.com/a/47168132
has comment: http://stackoverflow.com/comment/81286244
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81285868
tagged with: python
accepted answer: http://stackoverflow.com/a/47168132

http://stackoverflow.com/q/47105259
has title: hosting multiple Flask apps for unique domains
type: AnsweredQuestion
score: 0
tagged with: apache
accepted answer: http://stackoverflow.com/a/47105775
tagged with: dns
tagged with: virtualhost
tagged with: flask
answer count: 1
has answer: http://stackoverflow.com/a/47105775
type: Question
has body: I have two unique domains (eg. domain1.com and domain2.com). I am trying to host two unique webpages (via two separate flask apps) on one linode server (eg. 12.34.567.890) using Flask. Currently, domain1.com works, but domain2.com gives me the Apache2 default page. Here's what I have so far: etc\apache2\ports.conf: Listen 80 Listen 8080 Listen 443 Listen 443 # vim: syntax=apache ts=4 sw=4 sts=4 sr noet etc\apache2\sites-available\000-default.conf: ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined etc\apache2\sites-available\FlaskApp.conf: ServerName domain1.com ServerAdmin admin@email.com WSGIScriptAlias / /var/www/AppOne/flaskapp.wsgi Order allow,deny Allow from all Alias /static /var/www/AppOne/FlaskApp/static Order allow,deny Allow from all ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined ServerName domain2.com ServerAdmin admin@email.com WSGIScriptAlias / /var/www/AppTwo/flaskapp.wsgi Order allow,deny Allow from all Alias /static /var/www/AppTwo/FlaskApp/static Order allow,deny Allow from all ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined __init__.py for each app is the same (but in different directories): from flask import Flask, render_template, flash, request, url_for, redirect, session from content_management import Content #...etc... import gc TOPIC_DICT = Content() app = Flask(__name__) @app.route('/') def homepage(): return render_template("home.html") if __name__ == "__main__": app.run() The \var\www\ directory looks like this: \var\www | └─── AppOne | | flaskapp.wsgi | | | └─── FlaskApp | | __init__.py | | | └─── static | └─── templates | | home.html | | | └─── venv | └─── AppTwo #same as AppOne | flaskapp.wsgi | └─── F…
tagged with: python

http://stackoverflow.com/q/47150155
has comment: http://stackoverflow.com/comment/81250249
has comment: http://stackoverflow.com/comment/81249956
answer count: 0
has comment: http://stackoverflow.com/comment/81250592
linked to: http://stackoverflow.com/q/2349991
tagged with: pygame
has body: To preface, I am completely new to programming and am attempting to teach myself. Currently, I have a limited understanding of CS jargon so any explanation in layman terminology would be most appreciated. I am using programarcadegames.com to learn basic computer science. I've created a a game that collects sprites using the pygame library and would like to break my code up into multiple files. My file, 'Sprite Moving.py' imports block_library.py to obtain the Block class. However, running the program, I receive the error ImportError: No Module named Block. I've read through Stackoverflow and some of the issues people have ran into include library imported is the same name or files not located in path. I believe I've checked these off. Any advice? Did some google, and I believe this is what you are asking for - pastebin.com/J9qkjQ7F. I originally had all of my files in a separate folder, but one of the issues I saw while researching was the file may not be included in the path? So I dumped all of my relevant files into idlelib. Thanks in advance! Sprite Moving.py """ Use sprites to collect blocks. #Tony's lab 13 that will use sprites to collect blocks and print the score. """ import pygame import random import Block # Define some colors BLACK = ( 0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) BLUE = (0, 0, 255) GREEN = (0, 255, 0) class Player(pygame.sprite.Sprite): """ The class is the player-controlled sprite. """ # -- Methods def __init__(self, filename): """Constructor function""" # Call the parent's constructor super().__init__() # Set height, width self.image = pygame.image.load(filename).convert() self.image.set_colorkey(WHITE) # Make our top-left corner the passed-in location. self.rect = self.image.get_rect() self.rect.x = 10 self.rect.y = 25 # -- Attributes # Set speed vector self.change_x = 0 self.change_y = 0 def changespeed(self, x, y): """ Change the speed of the player""" self.change_x += x self.change_y += y def update(self): """ Find a new positi…
has comment: http://stackoverflow.com/comment/81250748
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/81250544
has title: ImportError: No Module named Block
tagged with: python
has comment: http://stackoverflow.com/comment/81318760
has comment: http://stackoverflow.com/comment/81250318
duplicate of: http://stackoverflow.com/q/2349991
score: 0
tagged with: importerror

http://stackoverflow.com/comment/81160209
type: AnswerComment
comment on: http://stackoverflow.com/a/47103734
score: 3
has text: It would be highly recommended to add some explanations of how your code operates. Simply providing code is not the best method to learning programming, and will not benefit the post creator as much as it would if it were explained well. A well-detailed answer will establish your credibility in the community, and your answers will attract up-votes.
type: Comment

http://stackoverflow.com/a/47171142
has comment: http://stackoverflow.com/comment/133344916
has comment: http://stackoverflow.com/comment/81293626
has comment: http://stackoverflow.com/comment/81293469
type: Answer
accepted answer of: http://stackoverflow.com/q/47170853
upvote count: 4
has comment: http://stackoverflow.com/comment/81293552
answers question: http://stackoverflow.com/q/47170853
type: AcceptedAnswer
downvote count: 0
has body: class ProfileView(APIView): permission_classes = (IsAuthenticated,) def post(self, request, format=None): try: # exist then update profile = Profile.objects.get(user=request.user) serializer = ProfileSerializer(profile, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) except Profile.DoesNotExist: # not exist then create serializer = ProfileSerializer(data=param) if serializer.is_valid(): serializer.save(user=request.user) return Response(serializer.data) else: return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) or just use UpdateAPIView: class ProfileView(UpdateAPIView): permission_classes = (IsAuthenticated,) serializer_class = ProfileSerializer queryset = Profile.objects.all()
score: 4

clr
tags question: http://stackoverflow.com/q/47067193
type: Tag
tag name: clr

http://stackoverflow.com/comment/81179144
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47113641
has text: Thank you so much. Because I didn't learn anything about html or xml, so it's really hard fro me to find these things. Thank you very much.

http://stackoverflow.com/comment/81316368
type: QuestionComment
comment on: http://stackoverflow.com/q/47183033
type: Comment
score: 0
has text: DocumentRoot should be /home/myproject/myproject/. There are also couple of other things to edit but firstly try it.

http://stackoverflow.com/q/47079788
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: Trying to get the following python code working. What I am trying to do is, for the password input box, instead of the characters inputted appearing, I want asterisks to appear. I have tried using other variables and displaying them, but it hasn't worked. I have been able to get the correct number of asterisks stored in a variable, but need help with over-writing the text in the password box with the asterisks. The code is: import pygame, pygame.font, pygame.event, pygame.draw, string from pygame.locals import * import hashlib, uuid string='' hashed_password='' current_string_p=[] display_p=[] symbol='*' def get_key(): while 1: event = pygame.event.poll() if event.type == KEYDOWN: return event.key else: pass def display_box(screen, message): "Print a message in a box in the middle of the screen" fontobject = pygame.font.Font(None,18) pygame.draw.rect(screen, (0,0,0), ((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 10, 200,20), 0) pygame.draw.rect(screen, (255,255,255), ((screen.get_width() / 2) - 102, (screen.get_height() / 2) - 12, 204,24), 1) if len(message) != 0: screen.blit(fontobject.render(message, 1, (255,255,255)), ((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 10)) pygame.display.flip() def ask(screen, question): "ask(screen, question) -&gt; answer" pygame.font.init() current_string_un = [] display_box(screen, question + ": " + string.join(current_string_un)) while 1: inkey = get_key() if inkey == K_BACKSPACE: current_string_un = current_string_un[0:-1] elif inkey == K_RETURN: break elif inkey == K_LSHIFT or inkey == K_RSHIFT: inkey=get_key() if inkey &lt;= 127: upper_case=inkey-32 current_string_un.append(chr(upper_case)) elif inkey &lt;= 127: current_string_un.append(chr(inkey)) display_box(screen, question + ": " + string.join(current_string_un)) return string.join(current_string_un) #password global display_p global current_string_p current_string_p = [] display_p=[] pro=''.join(display_p) display_box(screen, question + ": " +…
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/47080540
has title: Create a log in system in pygame python3
answer count: 1
downvote count: 0
tagged with: pygame
favorite count: 0

http://stackoverflow.com/comment/81376186
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47213112
has text: Quick side question, is there a way I could skip "Round 1" scores and just start appending scores from "Round 2"?

http://stackoverflow.com/comment/98797769
has text: I believe the copy_to method seeks backwards near the start frame you want until it finds an sps frame. Reducing intra_period (the time between iframes) might reduce the variation. See this github answer. https://github.com/waveform80/picamera/issues/319
comment on: http://stackoverflow.com/q/47065332
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81244732
comment on: http://stackoverflow.com/q/47147146
type: Comment
has text: No, unfortunately. I've seen this in comments to the linked questions and I've tried it earlier but it changes nothing.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81176061
type: Comment
type: QuestionComment
has text: Your code behaves correctly. When you call `import myapp`, the `log_level` is set to `None` and the logging is configured with it. **After** the import, you set `log_level` to `INFO`, but it has no effect since logging was already configured on import.
score: 0
comment on: http://stackoverflow.com/q/47112745

http://stackoverflow.com/q/47065244
favorite count: 0
type: Question
has title: Do I need a figure? What are they for?
has comment: http://stackoverflow.com/comment/81078760
tagged with: matplotlib
tagged with: python
score: 4
has body: I have begun using matplotlib and I am somewhat confused as to why figures exist. Sometimes I see code where a figure is declared and then a plot is made, and sometimes I see things like this: import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('initial.dat','float') plt.plot(data[:,0], data[:,1]) plt.xlabel("x (Angstroms)") plt.ylabel("V (eV)") plt.savefig('v.png',bbox_inches='tight') plt.clf() I read the documentation on figure and plot, but I don't get it. Why do figures exist?
upvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47065412
has answer: http://stackoverflow.com/a/47065412
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81078797

http://stackoverflow.com/comment/81363863
score: 0
type: Comment
type: QuestionComment
has text: That is very likely. I tried izip but keeps giving me memory location when I want to use. e.g <itertools.izip object at 0x103ca23b0>
comment on: http://stackoverflow.com/q/47207011

http://stackoverflow.com/a/47117021
answers question: http://stackoverflow.com/q/47116919
type: Answer
score: 1
downvote count: 0
has body: I think that using the built-in function id to show the object ID will help here. If the ID of two variable names gives the same result then they refer to the same object; otherwise the objects are different. &gt;&gt;&gt; def mutation(input_list): ... print(id(input_list)) ... list_copy = input_list[:] ... print(id(list_copy)) ... input_list = list_copy ... print(id(input_list)) ... &gt;&gt;&gt; a = list(range(10)) &gt;&gt;&gt; print(id(a)) 140737233394376 &gt;&gt;&gt; mutation(a) 140737233394376 140737233289160 140737233289160 In the above, we see that after input_list = list_copy, the name input_list refers to identically the same object in memory as list_copy, which means it no longer refers to the list given as the function argument. This is why the mutation you expect does not work - you are modifying an entirely different object.
upvote count: 1

http://stackoverflow.com/a/47129718
downvote count: 0
type: Answer
score: 2
has body: You can do it by getter and setter method as below : class ClassName(models.TransientModel): _inherit = 'res.config.settings' key = fields.Char() value = fields.Char() @api.model def get_default_key_values(self, fields): return { 'key': "myapplication.email_address", 'value': "randomaddress@gmail.com", } @api.multi def set_key_values(self): self.ensure_one() ICP = self.env['ir.config_parameter'] ICP.set_param('key', self.key) ICP.set_param('value', self.value)
answers question: http://stackoverflow.com/q/47121531
upvote count: 2

http://stackoverflow.com/q/47169336
answer count: 1
downvote count: 1
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/47181632
has body: I have a module called neural.py I initialize the variables in the body. import tensorflow as tf tf_x = tf.placeholder(tf.float32, [None, length]) tf_y = tf.placeholder(tf.float32, [None, num_classes]) ... I save the checkpoint in a function train() after training: def train(): ... pred = tf.layers.dense(dropout, num_classes, tf.identity) ... cross_entropy = tf.losses.softmax_cross_entropy(tf_y, pred) ... with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) saver = tf.train.Saver(tf.trainable_variables()) for ep in range(epochs): ... (training steps)... saver.save(sess, "checkpoints/cnn") I want to also restore and run the network after training in the run() function of this module: def run(): # I have tried adding tf.reset_default_graph() here # I have also tried with tf.Graph().as_default() as g: and adding (graph=g) in tf.Session() saver = tf.train.Saver() with tf.Session() as sess: saver.restore(sess, "checkpoints/cnn") ... (run network etc) It just doesn't work. It gives me either NotFoundError (see above for traceback): Key beta2_power not found in checkpoint or ValueError: No variables to save if I add tf.reset_default_graph() under run(), as commented above. However, if I put the exact same code for run() in a new module without train() and with tf.reset_default_graph() at the top, it works perfectly. How do I make it work in the same module? Final snippet: if __name__ == '__main__': print("Start training") train() print("Finished training. Generate prediction") run()
tagged with: tensorflow
favorite count: 0
type: Question
has title: Tensorflow: How to have saver.save() and .restore() in one module?
tagged with: neural-network
tagged with: python
has answer: http://stackoverflow.com/a/47181632
upvote count: 2
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/81300108
comment on: http://stackoverflow.com/a/47173904
has text: So there is another problem, can you share your file for create dataframe?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/81239663
has text: it was that(callback).It was just an example domain. Thank you very much!
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47144225
type: AnswerComment

http://stackoverflow.com/comment/81276763
score: 0
comment on: http://stackoverflow.com/q/47163254
type: QuestionComment
has text: Brad is right datetime would be best in a professional setting. As any programmer has probably learned: https://www.youtube.com/watch?v=-5wpm-gesOY
type: Comment

http://stackoverflow.com/comment/81210587
has text: You could try instead do it row by row, tear it in parts and asynchronously do all parts at once. Is it stored in database or in a file?
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47130344

http://stackoverflow.com/q/47211837
has answer: http://stackoverflow.com/a/47212033
tagged with: pyspark
has title: Pyspark DataFrame select rows with distinct values, and rows with non-distinct values
tagged with: dataframe
tagged with: python
tagged with: apache-spark
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47212033
has body: Suppose I have a pyspark DataFrame (DF): ----------------------------- record_id | foo | bar ----------------------------- 1 | random text | random text 2 | random text | random text 3 | random text | random text 1 | random text | random text 2 | random text | random text ----------------------------- My end goal is to write these rows to MySQL with .write.jdbc(), which I've been doing successfully. But now, before doing so, adding a new column unique based on the uniqueness of the record_id column. I've made a bit of progress identifying unique record_id's with something similar: df.select('record_id').distinct().rdd.map(lambda r: r[0]) But unlike Panda's DataFrames, I don't believe this has an index I can reuse, it appears to just be the values. I'm still fairly new to Spark/Pyspark. Would it make sense to try and figure out the following workflow? Identify rows with distinct record_id, and write to MySQL Then, identify the remaining rows, and write to MySQL Or would it be possible to alter the original DF, adding a new column unique based on some chained commands? Something like the following, which I could then write to MySQL wholesale: ---------------------------------- record_id | foo | bar | unique ---------------------------------- 1 | random text | random text | 0 2 | random text | random text | 0 3 | random text | random text | 1 # where 1 for boolean True 1 | random text | random text | 0 2 | random text | random text | 0 ---------------------------------- Any suggestions or advice would be much appreciated!
type: Question

http://stackoverflow.com/a/47087565
answers question: http://stackoverflow.com/q/47085909
has comment: http://stackoverflow.com/comment/81127852
type: Answer
score: 0
has body: What you are attempting seems very similar to the Otsu thresholding algorithm. In that case you can use ret, otsu = cv2.threshold(gray_scale_img , 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) If your data are strongly trimodal and Otsu's method is not satisfactory, the counterpart would be to apply kmeans clustering with 3 clusters. Both Otsu's method and kmeans classify data by minimizing the within-class variance. In code: import numpy as np from sklearn.cluster import KMeans # Make trimodal data # (if image is large, consider downsampling it) n1 = np.random.normal(80, 10, 200) n2 = np.random.normal(120, 10, 200) n3 = np.random.normal(180, 10, 400) imflat = np.r_[n1, n2, n3] # shuffle and reshape np.random.shuffle(imflat) im = imflat.reshape(-1, 1) km = KMeans(n_clusters=3, random_state=0).fit(im) lab = km.labels_ # maxmimum data value in each cluster [im[np.argwhere(lab==i)].flatten().max() for i in range(3)] This doesn't identify which of the 3 clusters has the highest peak in the histogram though. Apologies for incomplete solution. Another suggestion could be to fit 6th order polynomial to your histogram then find turning points.
has comment: http://stackoverflow.com/comment/81126904

http://stackoverflow.com/comment/81186277
comment on: http://stackoverflow.com/q/47118100
type: QuestionComment
has text: https://stackoverflow.com/questions/44744737/tensorflow-mac-os-gpu-support
type: Comment
score: 0

http://stackoverflow.com/comment/81417646
type: QuestionComment
comment on: http://stackoverflow.com/q/47094900
has text: do you want to enter the links located in references section? or any link in the first wikipedia page? Note that most of the links in references section are hosted in somewhere else than wikipedia!
score: 0
type: Comment

http://stackoverflow.com/q/47069425
tagged with: django-views
accepted answer: http://stackoverflow.com/a/47069520
upvote count: 0
has comment: http://stackoverflow.com/comment/81086686
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/47069504
type: Question
has comment: http://stackoverflow.com/comment/81086670
has title: How do I add different users data on my Django backend?
tagged with: django
has answer: http://stackoverflow.com/a/47069520
tagged with: python
has body: I have a bunch of users on my django backend. Let's say each user has a field 'age'. I would like to add every users age and divide by the number of users to get an average. Would this best be done in a ModelView as a function that makes a call using a While loop (while User.age for example)?
score: -1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81341108
has answer: http://stackoverflow.com/a/47069504
answer count: 2

http://stackoverflow.com/q/47121745
has title: Copy portion of list
has comment: http://stackoverflow.com/comment/81193795
tagged with: python
has body: How do I copy only a portion of a list to another list. For example, if the length of the list is 105 but only 30 of the randomly selected elements need to be copied to a new list. This is the code that I have written for x in range (104): if len(trainingSet1)&gt;30: break trainingSet1[x]= (trainingSet[random.randint(1,103)]) But it keeps giving this error: Traceback (most recent call last): File "Q1_2.py", line 82, in &lt;module&gt; main() File "Q1_2.py", line 72, in main trainingSet1[x]= (trainingSet[random.randint(1,103)]) IndexError: list index out of range
possible better answer: http://stackoverflow.com/a/47122036
has comment: http://stackoverflow.com/comment/81193079
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81193268
has comment: http://stackoverflow.com/comment/81193120
answer count: 2
has answer: http://stackoverflow.com/a/47121871
downvote count: 0
has comment: http://stackoverflow.com/comment/81193116
score: 1
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47122036
accepted answer: http://stackoverflow.com/a/47121871
has comment: http://stackoverflow.com/comment/81193095

http://stackoverflow.com/a/47202915
has comment: http://stackoverflow.com/comment/81354149
has comment: http://stackoverflow.com/comment/81354292
type: Answer
accepted answer of: http://stackoverflow.com/q/47202751
has comment: http://stackoverflow.com/comment/81354455
has body: a = "22.926 g 47.377 g 73.510 g 131.567 g 322.744 g".split() c = [" ".join((v, g)) for v,g in zip(a[:-1:2], a[1::2])]
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47202751
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/81172429
type: QuestionComment
has text: I redacted your access token, but since you posted it publicly, you should revoke it. By the way, for the sake of security, you should disable that access token. You can do so by revoking access to the app entirely, if the access token is for your account, here: https://www.dropbox.com/account/security Or, you can disable just this access token using the API: https://www.dropbox.com/developers/documentation/http/documentation#auth-token-revoke
comment on: http://stackoverflow.com/q/47107281
type: Comment
score: 0

http://stackoverflow.com/q/47160456
tagged with: python
has title: Appending a list to another list while checking for duplicates
tagged with: append
has answer: http://stackoverflow.com/a/47160660
possible better answer: http://stackoverflow.com/a/47160660
type: AnsweredQuestion
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/81270590
answer count: 3
has body: I need some help adding a list to another list while checking for duplicates. I only want to add items to my base list that are not already there. I cannot do this using sets because the items in the base list are also lists. An example of my base list is as follows: toCrawl=[["http://website.html",0]["http://websiteAlt.html",1]["http://websiteAlt.html",1]] The list that I want to add to this is as follows: newLinks=["http://websiteAlt.html","http://websiteExample.html","http://websiteExampleAlt.html"] So I want to add the 'newLinks' list to the base 'toCrawl' list, however I only want to add it if the item in newLinks is not already in toCrawl. As well as this I also want to add the items from 'newLinks' to the 'toCrawl' list as a list. So rather than adding the item in 'newLinks' as: "http://websiteExample.html" I want to add it to the list as a list for example: ["http://websiteExample.html",0]
accepted answer: http://stackoverflow.com/a/47160720
type: Question
has answer: http://stackoverflow.com/a/47161587
has answer: http://stackoverflow.com/a/47160720
tagged with: duplicates

http://stackoverflow.com/comment/81314210
comment on: http://stackoverflow.com/q/47170878
type: Comment
type: QuestionComment
score: 0
has text: Yes, I only want to have "stages", but there is no "stages" in my model so it cannot match the queryset.

http://stackoverflow.com/comment/81336340
comment on: http://stackoverflow.com/a/47193014
type: AnswerComment
score: 0
type: Comment
has text: @AnnYoon try it without the quotes around the user.id just as Blurp have suggested

http://stackoverflow.com/comment/81117846
score: 0
type: Comment
type: QuestionComment
has text: Why don't you create `OutputArchive.zip ` in `E:\webapps\geodata-dev\data` and move it in `temp_dir` once it's finished ?
comment on: http://stackoverflow.com/q/47083829

http://stackoverflow.com/comment/81131381
type: Comment
has text: can you show your settings.py code
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47091016

http://stackoverflow.com/a/47098268
has comment: http://stackoverflow.com/comment/81146369
has comment: http://stackoverflow.com/comment/81152633
has body: You need to give the "path" a None or a list as described in the error.
type: Answer
has comment: http://stackoverflow.com/comment/81151716
score: 0
answers question: http://stackoverflow.com/q/47098049

http://stackoverflow.com/comment/81318468
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47184650
has text: The function is defined within the `~/.bash_profile`.
score: 0

http://stackoverflow.com/comment/81276813
has text: I _am_returning a tuple of tensors from `parse_single_example` - so this merging of dicts is not needed - will edit OP (so edit out the dicts merging). I am testing this - still a bit disappointing I have to use `tf.py_func `
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47137142
type: AnswerComment

http://stackoverflow.com/comment/81337449
comment on: http://stackoverflow.com/q/47194201
has text: Please *format* your code properly. Edit your question, mark all the code, and press the `{}` button in the inline-editor toolbar.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81133416
comment on: http://stackoverflow.com/a/47079842
has text: last but not the least, I have gone through the django 1.11 docs for "User" model. All it has got is a bunch of function mentioned there. It is not explaining, how to use them and where to use them, If you can help me with that part, it would be great.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/81187419
type: AnswerComment
comment on: http://stackoverflow.com/a/47118838
has text: `filter`'s one method I've never seemed to use... maybe I should start.
score: 0
type: Comment

http://stackoverflow.com/q/47142340
tagged with: python-requests
favorite count: 0
type: Question
upvote count: 2
has body: The URL that I need to GET from looks something like this: https://example.com//report.php?file=MyFile&amp;params=query=QueryMyFile^SomeParam=x^SomeOtherParam=y^AnotherOne=z I want to use requests to pass the params; something along the lines of: base_url = 'https://example.com//report.php' params = { 'SomeParam': x, 'SomeOtherParam': y, 'AnotherOne': z } my_file = requests.get(base_url, params=params) How can I achieve this?
possible better answer: http://stackoverflow.com/a/47142447
tagged with: python
has answer: http://stackoverflow.com/a/47152262
accepted answer: http://stackoverflow.com/a/47142387
has answer: http://stackoverflow.com/a/47142447
score: 2
has answer: http://stackoverflow.com/a/47142387
type: AnsweredQuestion
has title: How to pass URL query string parameters with requests
answer count: 3
downvote count: 0

http://stackoverflow.com/q/47122641
score: 1
downvote count: 0
answer count: 1
upvote count: 1
tagged with: unit-testing
favorite count: 0
type: Question
tagged with: python-3.x
has body: I am trying to patch the fun_1 function from the worker_functions dictionary and I seem to be struggling: cli.py: import sys from worker_functions import ( fun_1, fun_2, fun_3, ) FUNCTION_MAP = { 'run_1': fun_1, 'run_2': fun_2, 'run_3': fun_3, } def main(): command = sys.argv[1] tag = sys.argv[2] action = FUNCTION_MAP[command] action(tag) I've tried mocking cli.fun_1 and cli.main.action and cli.action but this is leading to failure. test_cli.py: from mock import patch from cli import main def make_test_args(tup): sample_args = ['cli.py'] sample_args.extend(tup) return sample_args def test_fun_1_command(): test_args = make_test_args(['run_1', 'fake_tag']) with patch('sys.argv', test_args),\ patch('cli.fun_1') as mock_action: main() mock_action.assert_called_once() Do I seem to be missing something?
tagged with: python
has title: How to mock a function, in a function map/dictionary?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47122670
tagged with: mocking
has answer: http://stackoverflow.com/a/47122670

http://stackoverflow.com/comment/81188804
score: 1
comment on: http://stackoverflow.com/q/47119525
type: Comment
type: QuestionComment
has text: I don't think you're going to be able to avoid materializing all the items you've seen thus far into some sort of data-structure if you want to iterate over only *unique* values.

http://stackoverflow.com/comment/81191647
type: QuestionComment
comment on: http://stackoverflow.com/q/47121028
has text: Because slicing makes a new list.
score: 3
type: Comment

http://stackoverflow.com/q/47212987
has answer: http://stackoverflow.com/a/47213306
answer count: 1
downvote count: 1
favorite count: 0
score: -1
tagged with: for-loop
type: Question
has comment: http://stackoverflow.com/comment/81375859
tagged with: google-maps
has title: Python geocoder limit
upvote count: 0
tagged with: google-geocoder
has body: I have data of post number in excel. I input in python as a list. I use geocoder library to get the latitude and longitude by the post number so i can put on map later on. g = geocoder.google('1700002') g.latlng g.latlng brings me a list with [latitude,longitude] in it. Since is take string only. I changed the values from float to int to get rid of point 0 (133.0 = 130). then make it to string to read it. yubin_frame = yubin['yubin'] #post data #1st put it to ing to get rid of float yubin_list_int = map(int, yubin_list) #then make it to string to in put all to string yubin_list_str = map(str, yubin_list_int) I made this for-loop to make list of both latitude and longitude like this. #create a new list that include all data in Yubin_zahyou list Yubin_zahyou = [] for i in range(len(yubin_list_str)): Yubin_zahyou.append(geocoder.google(yubin_list_str[i]).latlng) My problem is that i have nearly 30000 data and geocoder brings only nearly 2500 input!. Does this mean geocoder has a limit or I made a mistake somehow?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47177148
accepted answer: http://stackoverflow.com/a/47177206
has title: How do I set the time of a datetime column in python pandas based on a string column
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81303343
tagged with: datetime
tagged with: python
type: AnsweredQuestion
has body: I have a DataFrame containing a DateTime column with dates but without time ['date_from']. I have the time in column ['Time'] (string). How can I add only the time to the already existing DateTime column? I tried: df['date_from'].dt.time = pd.to_datetime(df['Time'], format='%H%M').dt.time
tagged with: pandas
has comment: http://stackoverflow.com/comment/81303994
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47177206

http://stackoverflow.com/comment/81303600
score: 0
type: Comment
type: QuestionComment
has text: will take a look
comment on: http://stackoverflow.com/q/47136006

http://stackoverflow.com/a/51178627
answers question: http://stackoverflow.com/q/47078562
has body: assuming you're trying to make the character move continuously while the mouse button is held down (if you want to make it move step by step then simply check the keys individually and add/subtract to the x &amp; y), you would be best served abandoning the counter and instead, outside your event loop placed something like this: keys=pg.key.get_pressed() if keys[pg.K_w]: if x &gt;= 0: x -= 3 if keys[pg.K_s]: if x &lt;= 360: x += 3 if keys[pg.K_a]: if y &gt;= 0: y -= 3 if keys[pg.K_d]: if y &lt;= 238: y += 3
downvote count: 0
upvote count: 1
type: Answer
score: 1

scrapy
tags question: http://stackoverflow.com/q/47134695
tags question: http://stackoverflow.com/q/47160587
tags question: http://stackoverflow.com/q/47119036
tags question: http://stackoverflow.com/q/47137849
tags question: http://stackoverflow.com/q/47154856
tags question: http://stackoverflow.com/q/47186431
tags question: http://stackoverflow.com/q/47147679
tags question: http://stackoverflow.com/q/47115511
tags question: http://stackoverflow.com/q/47098301
tags question: http://stackoverflow.com/q/47206593
tags question: http://stackoverflow.com/q/47156621
tags question: http://stackoverflow.com/q/47188543
tags question: http://stackoverflow.com/q/47126298
tags question: http://stackoverflow.com/q/47166702
tags question: http://stackoverflow.com/q/47110263
tags question: http://stackoverflow.com/q/47202472
tags question: http://stackoverflow.com/q/47076659
tag name: scrapy
tags question: http://stackoverflow.com/q/47105544
tags question: http://stackoverflow.com/q/47126973
tags question: http://stackoverflow.com/q/47139619
tags question: http://stackoverflow.com/q/47135838
tags question: http://stackoverflow.com/q/47142766
tags question: http://stackoverflow.com/q/47164238
tags question: http://stackoverflow.com/q/47219198
tags question: http://stackoverflow.com/q/47213852
tags question: http://stackoverflow.com/q/47093405
tags question: http://stackoverflow.com/q/47193490
tags question: http://stackoverflow.com/q/47144204
tags question: http://stackoverflow.com/q/47128116
tags question: http://stackoverflow.com/q/47191674
tags question: http://stackoverflow.com/q/47120376
tags question: http://stackoverflow.com/q/47104266
tags question: http://stackoverflow.com/q/47096616
type: Tag
tags question: http://stackoverflow.com/q/47207153
tags question: http://stackoverflow.com/q/47154959
tags question: http://stackoverflow.com/q/47145519
tags question: http://stackoverflow.com/q/47206025
tags question: http://stackoverflow.com/q/47156149
tags question: http://stackoverflow.com/q/47202569
tags question: http://stackoverflow.com/q/47185209
tags question: http://stackoverflow.com/q/47072702
tags question: http://stackoverflow.com/q/47211752
tags question: http://stackoverflow.com/q/47138179
tags question: http://stackoverflow.com/q/47104156
tags question: http://stackoverflow.com/q/47128033

newrelic
tag name: newrelic
tags question: http://stackoverflow.com/q/47088458
type: Tag

http://stackoverflow.com/a/61639117
score: 0
answers question: http://stackoverflow.com/q/47090088
type: Answer
has body: A better and a more efficient way would be to push the values into the heap as they come in and then as you get the values out, they are already in a sorted order. And if you're smart, you'll use this fact to only sort once in this problem as well as to finish the problem earlier. from heapq import heappush student_scores = [] if __name__ == '__main__': for _ in range(int(input())): name = input() score = float(input()) heappush(student_scores, (score, name))

http://stackoverflow.com/comment/81312961
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47181684
has text: There's [Unidecode](https://pypi.python.org/pypi/Unidecode) for ASCII but I'm not aware of an equivalent for ISO-8859-1.
score: 0

http://stackoverflow.com/comment/81348128
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47199782
score: 2
has text: Why would you ever use `os.system` to copy a file?

http://stackoverflow.com/comment/81205537
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47127575
score: 0
has text: Can you show the definition of `data`?

http://stackoverflow.com/comment/81336999
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47131231
score: 0
has text: No, it didn't. I was expecting a result of 1.566 but what I got was -22.1. I do not understand what is it that I am missing.

http://stackoverflow.com/comment/81240246
has text: it should be upper()
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47144761

http://stackoverflow.com/comment/81152060
score: 0
comment on: http://stackoverflow.com/a/47100835
type: AnswerComment
has text: This is an index for image quality... that's another story...
type: Comment

http://stackoverflow.com/a/47166553
has body: Some issues: the loop on j serves no purpose. The only time the if inside it is true, is when i == j, because after that j only increases. Furthermore, the assignment i = j changes nothing, as they are already equal when that happens Your code can never append the same value twice, yet that may be necessary. To restart calculating the product each time from scratch is a loss of time. You should do that incrementally as you append a new factor. It is even better to work from the opposite direction and divide x by each factor as you find it. That way you avoid ever finding non-prime factors. There is no use in sorting the list, since i increases in your code, so when you append i to the list, the list will always stay sorted. Here is how it can work: def primeFactorization(x): lst = [] i = 2 while x &gt; 1: while x % i == 0: lst.append(i) x //= i i += 1 return lst print (primeFactorization(110019))
downvote count: 0
score: 3
type: Answer
answers question: http://stackoverflow.com/q/47166229
upvote count: 3

http://stackoverflow.com/a/47126744
upvote count: 3
score: 3
has body: This is a really annoying problem and it arises from the fact that for some reason a code compiled to be executed on CPU is not garbage-collected properly. So even though you are running a garbage collector - a compiled model is still on GPU. In order to overcome this, you may try a solution presented here (TLDR: run training in a separate process - as when process is finished - memory is cleared)
type: Answer
accepted answer of: http://stackoverflow.com/q/47118723
answers question: http://stackoverflow.com/q/47118723
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47193914
favorite count: 0
has answer: http://stackoverflow.com/a/47195094
has title: Get Elements from one array based on list of index from another array
has answer: http://stackoverflow.com/a/47194040
tagged with: python
answer count: 4
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47194043
has answer: http://stackoverflow.com/a/47193961
upvote count: 2
score: 2
type: UnansweredQuestion
has body: I have a 2 numpy array something like this a = [array([ 0.1, 0.1, 0.1]), array([ 0.2, 0.2, 0.2])] b = [0 0 0 1] What I want is something like this -- c = [[0.1, 0.1, 0.1],[0.1, 0.1, 0.1],[0.1, 0.1, 0.1],[0.2, 0.2, 0.2]] i.e. elements of a based on index of b. Is there a way I can achieve this using numpy and vectorization i.e. without looping over the values?
downvote count: 0

http://stackoverflow.com/comment/81350155
type: Comment
type: AnswerComment
has text: same as `\t`. It does not change.
score: 0
comment on: http://stackoverflow.com/a/47200460

http://stackoverflow.com/comment/114255163
score: 0
type: Comment
has text: Thank you! I got stuck for several hours into an error that had the same output. I can confirm that this error happens when your script inside the rule is trying to access input files, but instead, it gets an empty list. Did contrasts_dict correspond to a defaultdict by any chance?
type: AnswerComment
comment on: http://stackoverflow.com/a/47135119

http://stackoverflow.com/q/47129644
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/81209266
has title: How to get rectangle to appear on screen (pygame) for a set amount of time?
has comment: http://stackoverflow.com/comment/81246109
score: 0
answer count: 1
has body: How do you get a rectangle (rect) to appear on the output screen for a set amount of time, for example 2 seconds, before disappearing? I am making a version of wormy a nibbles clone. I would also like to know how to make an apple disappear when the worm "eats" it.
type: Question
has answer: http://stackoverflow.com/a/47133577
linked to: http://stackoverflow.com/q/30720665
tagged with: time
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81209475

http://stackoverflow.com/comment/81123254
comment on: http://stackoverflow.com/a/47074806
has text: Appreciate it! not sure what was going on with mine then. Oh well!
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81123433
type: Comment
type: AnswerComment
has text: I finally got it. Thanks for all of the help
comment on: http://stackoverflow.com/a/47084256
score: 0

http://stackoverflow.com/a/47120983
has comment: http://stackoverflow.com/comment/81191750
answers question: http://stackoverflow.com/q/47120859
has comment: http://stackoverflow.com/comment/81191715
has body: I can't really see a use for a dict created like this (indexing becomes a pain). I'd really suggest just keeping separate lists x and y (see my answer). But you can create a dict by passing tuples of x and y to the dict constructor: x, y, *_ = zip(*population) x = [', '.join(map(str, z)) for z in x] y = [z[0] for z in y] d = dict(zip(x, y)) d {'0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1': 1, '0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1': 3, '0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0': 4, '1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0': 3}
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47160171
has comment: http://stackoverflow.com/comment/81269911
has comment: http://stackoverflow.com/comment/81269882
favorite count: 0
has answer: http://stackoverflow.com/a/47160230
type: Question
tagged with: python-3.x
has title: Is there a command which will sort a Python list by data type?
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47160230
has answer: http://stackoverflow.com/a/47160437
has body: Given the following list: l = [True, 3, 7.3, (5,6), True, 'orange', 25, 'banana', False, (4,5), 9.2] which contains a mixture of types: for element in l: print (type(element)) output: &lt;class 'bool'&gt; &lt;class 'int'&gt; &lt;class 'float'&gt; &lt;class 'tuple'&gt; &lt;class 'bool'&gt; &lt;class 'str'&gt; &lt;class 'int'&gt; &lt;class 'str'&gt; &lt;class 'bool'&gt; &lt;class 'tuple'&gt; &lt;class 'float'&gt; Is there a command which will sort it according to types, that is, so the types land up in groups?
type: AnsweredQuestion
answer count: 3
score: 1
possible better answer: http://stackoverflow.com/a/47160309
has answer: http://stackoverflow.com/a/47160309

http://stackoverflow.com/q/47191004
accepted answer: http://stackoverflow.com/a/47202547
has comment: http://stackoverflow.com/comment/81346461
type: Question
tagged with: discord.py
has answer: http://stackoverflow.com/a/47202547
has body: I am trying to make a discord bot in python and I keep running into a problem. What I am trying to do is use discord.ext.commands.Bot() to run a command to create a channel (which uses discord.Client() ). Whenever I start the bot using bot.run('token'), the client part does not work. But if I run the bot using client.run('token'), I am able to create the channel, but not use the command. Is there any way to have both running at the same time, or am I out of luck? The code for the command is: @bot.command(pass_context=True) async def channel(ctx): client.create_channel(ctx.message.server, 'test', type=discord.ChannelType.text)
answer count: 1
tagged with: python
has title: discord python api Bot() and Client()
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81351534

http://stackoverflow.com/a/47147981
score: 0
answers question: http://stackoverflow.com/q/47147948
has body: The while loop will always be true, so it never gets to your input - you need to indent the name/print to be within the while loop. def hello(): while True: print("Hi I'm Bob! What's your name?") name = input("Name:") print("Nice to meet you "+(name))
type: Answer
has comment: http://stackoverflow.com/comment/81335565

http://stackoverflow.com/comment/81174200
has text: Ah so groupby then **concat** is the way to go - thank you very much! :)
type: Comment
comment on: http://stackoverflow.com/a/47111863
type: AnswerComment
score: 0

http://stackoverflow.com/q/47104668
type: UnansweredQuestion
tagged with: python
tagged with: xinput
score: 2
has answer: http://stackoverflow.com/a/47104749
has title: How to simulate game controller key input?
upvote count: 3
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I am currently working on a program that acts as a USB game controller but I am having trouble finding a way to simulate keypress and stick movement... I am hoping to work with python but anything will work.
has comment: http://stackoverflow.com/comment/81159907

http://stackoverflow.com/q/47084192
has comment: http://stackoverflow.com/comment/81117865
tagged with: type-hinting
downvote count: 0
linked to: http://stackoverflow.com/q/15299878
favorite count: 0
type: Question
tagged with: mypy
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has body: Is it possible in mypy or Python3.6+ or in any of their extensions to specify that my function can take any dict as a parameter as long as it has specific keys in it? If there is an hypothetical type Record For e.g. def full_name(my_dict: Record[first_name: str, last_name: str]) -&gt; str: return my_dict['last_name'] + ',' + my_dict['first_name'] valid_dict = {'first_name': 'John', 'last_name': 'Doe'} big_and_valid_dict = {'first_name': 'Matt', 'last_name': 'Legi', 'age': 32} invalid_dict1 = {'first_name': 'BadName'} # No 'last_name' key invalid_dict2 = {'no_name': 'NoName'} # none of the specified keys So, static analysis should report the following as full_name(valid_dict) # =&gt; works full_name(big_and_valid_dict) # =&gt; works full_name(invalid_dict1) # =&gt; error full_name(invalid_dict2) # =&gt; error
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/21014761
has title: Type Hints: Function requires a dict with the following mandatory keys
has comment: http://stackoverflow.com/comment/81118753
has comment: http://stackoverflow.com/comment/85081152
has comment: http://stackoverflow.com/comment/81119482
score: 1
has comment: http://stackoverflow.com/comment/81118136

http://stackoverflow.com/q/47109886
has comment: http://stackoverflow.com/comment/81170704
score: 0
has answer: http://stackoverflow.com/a/47109926
accepted answer: http://stackoverflow.com/a/47109926
duplicate of: http://stackoverflow.com/q/45899174
tagged with: python
has body: I have a bool array that was created with respect to a double array: array1 = ... # the double array initialization array2 = array1 &lt; threshold # threshold is set somewhere else Assuming the output of my second array is like this: # array2 = [True, False, True, True, True, False] I want to select percentage of the True items. For example, if I want to randomly select 75% of the True items, the output would be any of these: # array3 = [True, False, True, True, False, False] # array3 = [False, False, True, True, True, False] # array3 = [True, False, False, True, True, False] The third array contains 3 out of the 4 True items that were found in the second array. How can I achieve this?
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/45899174
tagged with: random
has title: Partial random selection of items from numpy array from items that meet certain condition
answer count: 1
tagged with: arrays
has comment: http://stackoverflow.com/comment/81170619
has comment: http://stackoverflow.com/comment/81170689
has comment: http://stackoverflow.com/comment/81170815
type: AnsweredQuestion

stack
tags question: http://stackoverflow.com/q/47214183
tags question: http://stackoverflow.com/q/47066033
tags question: http://stackoverflow.com/q/47177795
type: Tag
tag name: stack

http://stackoverflow.com/comment/81280544
comment on: http://stackoverflow.com/q/47165343
type: Comment
score: 0
has text: So, as I understand it, I indent before the 'g' then? I'm sorry, I'm still trying to understand the layout..
type: QuestionComment

http://stackoverflow.com/q/47076606
linked to: http://stackoverflow.com/q/12169839
type: AnsweredQuestion
score: 0
has title: passing two numbers as inputs and joining them together into a single string
has body: I am very new to the coding world and stuck on this issue.I am attempting to pass two numbers as inputs and join them together into a single string. The problem I am encountering is that my code performs an addition function rather than combining the numbers. my code is below with the results after. import sys number1 = int(sys.argv[1]) number2 = int(sys.argv[2]) newnumber = number1 + number2 print(newnumber) Program Failed for Input: 123 456 Expected Output: 123456 Your Program Output: 579 Any suggestions?
has comment: http://stackoverflow.com/comment/81101689
has answer: http://stackoverflow.com/a/47076651
accepted answer: http://stackoverflow.com/a/47076651
type: Question
answer count: 1
tagged with: python

random
tags question: http://stackoverflow.com/q/47164359
tags question: http://stackoverflow.com/q/47106199
tags question: http://stackoverflow.com/q/47203519
tags question: http://stackoverflow.com/q/47179545
tag name: random
tags question: http://stackoverflow.com/q/47213130
tags question: http://stackoverflow.com/q/47146595
tags question: http://stackoverflow.com/q/47123009
tags question: http://stackoverflow.com/q/47114939
tags question: http://stackoverflow.com/q/47074972
type: Tag
tags question: http://stackoverflow.com/q/47168372
tags question: http://stackoverflow.com/q/47143004
tags question: http://stackoverflow.com/q/47184521
tags question: http://stackoverflow.com/q/47136434
tags question: http://stackoverflow.com/q/47158685
tags question: http://stackoverflow.com/q/47067311
tags question: http://stackoverflow.com/q/47120772
tags question: http://stackoverflow.com/q/47097464
tags question: http://stackoverflow.com/q/47109886

http://stackoverflow.com/comment/81338711
type: QuestionComment
score: 0
has text: @AvinashRaj thx ur comments.I wrote ur code like `fil = request.FILES.get('file') if fil: file = fil.temporary_file_path() else None`but always program is in else statement.How should I fix this?
comment on: http://stackoverflow.com/q/47194526
type: Comment

http://stackoverflow.com/a/47209010
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81369886
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81369916
answers question: http://stackoverflow.com/q/47208647
has comment: http://stackoverflow.com/comment/81369959
has comment: http://stackoverflow.com/comment/81370844
has comment: http://stackoverflow.com/comment/81374693
has comment: http://stackoverflow.com/comment/81373410
has comment: http://stackoverflow.com/comment/81374735
type: Answer
has comment: http://stackoverflow.com/comment/81371462
has comment: http://stackoverflow.com/comment/81371134
has body: The solution I provided is overkill ...But still work df1=df.stack().to_frame() m=df1[0].groupby(level=0).apply(lambda x :x.str.isalpha().diff().ne(0).cumsum()) df1.groupby([df1.index.get_level_values(0),m]).sum().unstack().add_prefix('col1_') Out[116]: col1_0 0 col1_1 col1_2 col1_3 col1_4 0 A 1 2 3 1 BC 3 4 5 2 D 6 7 8 3 BE 9 10 11 Just change here m=df1[0].groupby(level=0).apply(lambda x :x.str.isalpha().ne(1).cumsum()) df1.groupby([df1.index.get_level_values(0),m]).sum().unstack().add_prefix('col1_') Out[164]: col1_0 0 col1_0 col1_1 col1_2 col1_3 0 A 1,5 2,5 3,5 1 BC 3,5 4,5 5,5 2 D 6,5 7,5 8,5 3 BE 9,5 10,5 11,5
has comment: http://stackoverflow.com/comment/81370902
accepted answer of: http://stackoverflow.com/q/47208647
has comment: http://stackoverflow.com/comment/81374740
has comment: http://stackoverflow.com/comment/81373010
downvote count: 0
has comment: http://stackoverflow.com/comment/81370148
has comment: http://stackoverflow.com/comment/81370027

http://stackoverflow.com/a/47080614
has comment: http://stackoverflow.com/comment/81113140
answers question: http://stackoverflow.com/q/47080557
type: Answer
accepted answer of: http://stackoverflow.com/q/47080557
has comment: http://stackoverflow.com/comment/81110799
score: 0
type: AcceptedAnswer
has body: You have to use return values like this: punctuations = '''!()-[]{};:'"\,&lt;&gt;./?@#$%^&amp;*_~ ''' def puncrem(x): y = "" for char in str(x): if char not in punctuations: y = y + char return y start = "h%e*l(l&amp;o" finish = puncrem(start) print(finish)

http://stackoverflow.com/q/47132494
score: 0
answer count: 1
tagged with: shift
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47132632
tagged with: python
has body: I have a series (A) with business days as index: index value 1990-01-03 358.76 1990-01-04 355.67 1990-01-05 352.20 1990-01-08 353.79 1990-01-09 349.62 1990-01-10 347.31 1990-01-11 348.53 1990-01-12 339.93 1990-01-15 337.00 1990-01-16 340.75 1990-01-17 337.40 1990-01-18 338.19 1990-01-19 339.15 1990-01-22 330.38 1990-01-23 331.61 1990-01-24 330.26 1990-01-25 326.08 1990-01-26 325.80 1990-01-29 325.20 1990-01-30 322.98 1990-01-31 329.08 1990-02-01 328.79 1990-02-02 330.92 1990-02-05 331.85 1990-02-06 329.66 1990-02-07 333.75 1990-02-08 332.96 1990-02-09 333.62 1990-02-12 330.08 2017-09-22 2502.22 2017-09-25 2496.66 2017-09-26 2496.84 2017-09-27 2507.04 2017-09-28 2510.06 2017-09-29 2519.36 i would like to have a new series with same index and monthly returns new_series= pandas.Series(index=A.index) new_series=A/A.shift(1month)-1 i don't like solutions like .shift(25) because is not accurate: new_series=A/A.shift(25)-1 thanks all for replies EDIT: i would like this output: 22/01/1990 #N/A 23/01/1990 #N/A 24/01/1990 #N/A 25/01/1990 #N/A 26/01/1990 #N/A 29/01/1990 #N/A 30/01/1990 #N/A 31/01/1990 #N/A 01/02/1990 #N/A 02/02/1990 #N/A 05/02/1990 -0.057779671 06/02/1990 -0.063997729 07/02/1990 -0.056643772 08/02/1990 -0.047651736 09/02/1990 -0.039417235 12/02/1990 -0.028976554
has title: Get rolling one month return in a Python series

http://stackoverflow.com/q/47172288
tagged with: lambda
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/81294066
score: 0
has comment: http://stackoverflow.com/comment/81294324
answer count: 1
has title: Failed Gmail authentication through smtplib and AWS Lambda
tagged with: aws-lambda
type: Question
has body: I'm trying to write an AWS Lambda function that periodically sends an email using Python's smtplib. This function works outside of AWS lambda, and I've verified that the environment variables are valid many times. import os import smtplib def lambda_handler(event, context): """Function that runs to send the email.""" otf_email = os.environ.get("OTF_EMAIL") my_email = os.environ.get("MY_EMAIL") pw = os.environ.get("GMAIL_PW") body = 'Subject:\nThis is a test from the AWS lambda function.' smtp_obj = smtplib.SMTP('smtp.gmail.com', 587) smtp_obj.ehlo() smtp_obj.starttls() smtp_obj.login(my_email, pw) smtp_obj.sendmail(my_email, otf_email, body) smtp_obj.sendmail(my_email, my_email, body) smtp_obj.quit() The first part of the error: "errorMessage": "(534, b'5.7.14 &lt;https://accounts.google.com/signin/continue?sarp=1&amp;scc=1&amp;plt=AKgnsbsR\\n5.7.14 vlSLqK014L_ddv0GicpBkQ1o229bk_zYZe8gMUGlddfJLox0EnXFwtUl9GpBygMxCzoATW\\n5.7.14 3UjdqLIvkTcUx6vGO09gE33_CMkdMaVK-F1d8FC4SypPh8n3ft6BaZubjr4b_M7FD2roiN\\n5.7.14 LyTNxCogmPGDqNQP8overGbbDNTZ7rdeEGBYqG9dExVjtqnRda6eEwC9e9Ib8zHfsjASRM\\n5.7.14 Zi8ShH9zxelYTJ-IhALwvPFV0pJIg&gt; Please log in via your web browser and\\n5.7.14 then try again.\\n5.7.14 Learn more at\\n5.7.14 https://support.google.com/mail/answer/78754 u131sm4947518pgc.89 - gsmtp')"
tagged with: smtplib
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47172577
has comment: http://stackoverflow.com/comment/81294948
tagged with: python

http://stackoverflow.com/comment/81198875
comment on: http://stackoverflow.com/q/47124169
type: Comment
type: QuestionComment
has text: I added my code guys, you can look at it if you want
score: 0

http://stackoverflow.com/a/47121484
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47121421
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47121421
has body: You have found a wrong answer; \e is not a valid escape sequence in Python. In some echo implementations, \e is an escape sequence for the ASCII ESC character, but in Python you need to use a different notation. The rest of the answers on that page use correct forms, either \x1b or \033.

http://stackoverflow.com/q/47084987
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/31684448
favorite count: 0
tagged with: matplotlib-3d
type: Question
has title: How to color 3D gridlines
score: 3
has body: I was looking for a way to change the color of a 3D plots gridlines and was unable to find a clean and easy way to do so. The only answer I found was here and it came off as a bit complex. I was wondering if there was an easier way to color the gridlines of a 3D plot in matplotlib using mpl_toolkits.mplot3d simple example found here import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = fig.gca(projection='3d') theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) z = np.linspace(-2, 2, 100) r = z**2 + 1 x = r * np.sin(theta) y = r * np.cos(theta) ax.plot(x, y, z, label='parametric curve') ax.legend() plt.show()
accepted answer: http://stackoverflow.com/a/47086538
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/47086538
type: AnsweredQuestion
tagged with: gridlines
upvote count: 3

http://stackoverflow.com/comment/81303994
type: Comment
type: QuestionComment
has text: e.g. 2018-01-01 00:00:00 as datetime column and another column with strings 0000, 0500, 0610, etc
comment on: http://stackoverflow.com/q/47177148
score: 0

http://stackoverflow.com/a/47215566
type: Answer
answers question: http://stackoverflow.com/q/47215511
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47215511
has body: Generally, the more Pythonic way is not to use map, filter, and reduce, but to use comprehensions. For your code, that would be result = {'{}_fields'.format(model_name): _do_something(model_name) for model_name in list_of_model_names} Comprehensions can also work for lists and sets.

http://stackoverflow.com/q/47183095
score: -1
has comment: http://stackoverflow.com/comment/81315507
has answer: http://stackoverflow.com/a/47183331
has comment: http://stackoverflow.com/comment/81315539
has comment: http://stackoverflow.com/comment/81315364
has comment: http://stackoverflow.com/comment/81315267
has answer: http://stackoverflow.com/a/47183178
upvote count: 3
has comment: http://stackoverflow.com/comment/81315434
has body: Supposing we have two lists, where list1 contains initial values, and list 2 has all the values to update in the first list: list1 = [('a', 0), ('b', 0), ('c', 0)] list2 = [('a', 5), ('c', 3)] The desired result is a merged list3, of list2 values inserted into list1 values, using to the first element as index: list3 = [('a', 5), ('b', 0), ('c', 3)] I tried running the following code without success: list3 = list1 + list2 list3 = list(zip(list1, list2))
favorite count: 0
type: Question
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/81315266
has comment: http://stackoverflow.com/comment/81315153
type: UnansweredQuestion
has title: Merge two lists of tuples into one
tagged with: python

http://stackoverflow.com/a/47205690
type: AcceptedAnswer
has body: Found out that there is a limit for pickling Python objects set by the database's BLOB or BINARY LARGE OBJECT. To get around this you can try using Fileflow dump the file into a temporary folder and push the filepath via the XCOM functionality Handle the entire process within a single task and push certain values via XCOM
type: Answer
answers question: http://stackoverflow.com/q/47188305
score: 2
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47188305

http://stackoverflow.com/comment/81313765
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47178187
has text: You might find it helpful [How do you run a worker with AWS Elastic Beanstalk?](https://stackoverflow.com/questions/14761468/how-do-you-run-a-worker-with-aws-elastic-beanstalk)

http://stackoverflow.com/comment/81211876
comment on: http://stackoverflow.com/q/47130437
type: Comment
type: QuestionComment
has text: This is way too broad. Start with the [documentation](http://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html) and ask any more specific questions you have as you go through the docs.
score: 2

http://stackoverflow.com/q/47121960
has body: I've found some answers regarding displaying text on screen with Python. There's a lot about pop up messages and notifications. However, I'm trying to create an unobtrusive little box (say, on the bottom of the screen maybe?). Something that'll be like a transparent overlay where messages will pop up in different colors while you're working. Like a notification box that is independent. I don't have background in pygtk or tkinter or anything to do with GUI really (I'm a web developer). I don't know how to do this and all my Google searches give me examples of popping alerts on screen or communicating with the system's notifications which isn't relevant (cause I have little control over the appearence of that). How do I do this?
type: AnsweredQuestion
tagged with: windows
has answer: http://stackoverflow.com/a/47123665
has comment: http://stackoverflow.com/comment/81193532
has comment: http://stackoverflow.com/comment/81193756
has comment: http://stackoverflow.com/comment/81194298
has comment: http://stackoverflow.com/comment/81193886
has comment: http://stackoverflow.com/comment/81193616
favorite count: 0
linked to: http://stackoverflow.com/q/4485610
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/81193686
has comment: http://stackoverflow.com/comment/81194818
accepted answer: http://stackoverflow.com/a/47123665
type: Question
linked to: http://stackoverflow.com/q/21840133
has title: python - project text to screen on transparent unobtrusive overlay box
linked to: http://stackoverflow.com/q/45427411
has comment: http://stackoverflow.com/comment/81193545
has comment: http://stackoverflow.com/comment/81196098
downvote count: 0
has comment: http://stackoverflow.com/comment/81193637
tagged with: python
has comment: http://stackoverflow.com/comment/81196074
answer count: 1

http://stackoverflow.com/comment/81099723
has text: Good, but still the *desired* outcome is missing - provide an example of what exactly your desired result is
comment on: http://stackoverflow.com/q/47074909
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47135132
score: 0
has body: I stumbled upon something that seems a bit strange to me. Consider the following piece of code: import numpy as np a = np.random.rand(6,7) print(a.shape) b = np.logical_and([a &lt;= 1], [a &gt;= 0]) print(b.shape) While I can easily get rid of the singleton dimension of b with numpy.squeeze, I wonder why it even appears at all. According the the documentation here it says: Returns: y : ndarray or bool Boolean result with the same shape as x1 and x2 of the logical AND operation on corresponding elements of x1 and x2 But the shape of a and b are not the same. What am I missing?
answer count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81219670
tagged with: arrays
has title: Why does numpy.logical_and create a singleton dimension in this example?
tagged with: python
has comment: http://stackoverflow.com/comment/81235500
has answer: http://stackoverflow.com/a/47135469
accepted answer: http://stackoverflow.com/a/47135469
type: AnsweredQuestion

http://stackoverflow.com/q/47107219
has comment: http://stackoverflow.com/comment/81177290
has comment: http://stackoverflow.com/comment/81172824
has comment: http://stackoverflow.com/comment/81172863
has title: Pass specific 'state' Selection from one object to another - Odoo v8
has comment: http://stackoverflow.com/comment/81172716
has comment: http://stackoverflow.com/comment/81167034
answer count: 0
has comment: http://stackoverflow.com/comment/81237848
tagged with: odoo
score: 1
tagged with: odoo-8
has comment: http://stackoverflow.com/comment/81176459
has comment: http://stackoverflow.com/comment/81237886
favorite count: 0
type: Question
has body: I have these models: class bsi_production_order(models.Model): _name = 'bsi.production.order' @api.model def create(self, vals): if vals.get('name', 'New') == 'New': if vals.get('production_type') == 'budgeted': vals['name'] = self.env['ir.sequence'].next_by_code('bsi.production.budgeted') or '/' elif vals.get('production_type') == 'nonbudgeted': vals['name'] = self.env['ir.sequence'].next_by_code('bsi.production.non_budgeted') or '/' elif vals.get('production_type') == 'direct': vals['name'] = self.env['ir.sequence'].next_by_code('bsi.production.direct') or '/' return super(bsi_production_order, self).create(vals) name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New') date = fields.Date(string="Production Date") production_type = fields.Selection([ ('budgeted','Budgeted'), ('nonbudgeted','Non Budgeted'), ('direct','Direct Order'), ], string='Type of Order', index=True, track_visibility='onchange', copy=False, help=" ") notes = fields.Text(string="Notes") order_lines = fields.One2many('bsi.production.order.lines', 'production_order', states={'finished': [('readonly', True)], 'cancel': [('readonly', True)]}, string="Order lines", copy=True) print_orders = fields.One2many('bsi.print.order', 'production_orders', string="Print Orders") state = fields.Selection([ ('draft','Draft'), ('start','Started'), ('inprogress','In progress'), ('print_order_inprogress','Print Order In Progress'), ('finished','Finished'), ('cancel','Cancel'), ], string='State', index=True, track_visibility='onchange', copy=False, help=" ") class bsi_print_order(models.Model): _name = 'bsi.print.order' @api.model def create(self, vals): if vals.get('name', 'New') == 'New': vals['name'] = self.env['ir.sequence'].next_by_code('bsi.print.order') or '/' return super(bsi_print_order, self).create(vals) name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New') date = fields.Date(string="Print Date") origin = fields.…
has comment: http://stackoverflow.com/comment/81251850
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/a/47071896
has comment: http://stackoverflow.com/comment/81092321
type: Answer
has comment: http://stackoverflow.com/comment/81092804
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/47071416
downvote count: 0
has body: Something makes me think that you don't make use of your sqlalchemy models properly. Why, instead of detaching from session and doing weird stuff with your relation (many tuples with same user?), can't you leverage creating list of photos per user by using mechanism that is intended to that by SQLalchemy? If you have your relation between User and Photo, you can either: change relationship loading strategy to default (delete lazy attribute at all or set it to 'select'), and then query database for Users: users = db.session.query(User).all() ...and access user's photos as a list of db objects. user.photos # photos is a list of all user's photos with lazy='dynamic' you can reach all users the same way, but now photos is also a query (read more on: dynamic relationships): A key feature to enable management of a large collection is the so-called “dynamic” relationship. This is an optional form of relationship() which returns a Query object in place of a collection when accessed ...and like with every query, you can use its API (filter(), first(), or in your case all() for getting all of the photos.
has comment: http://stackoverflow.com/comment/81092498

http://stackoverflow.com/comment/81135104
type: Comment
comment on: http://stackoverflow.com/a/47092330
type: AnswerComment
has text: this is not what the question asks. This just prints the pairs that have a difference of less than the threshold. but he wants to find the closest pairs even if they are not at the same index.
score: 0

http://stackoverflow.com/comment/81118216
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47084128
has text: thanks for the tip - unfortunately, the issue still persists
score: 0

http://stackoverflow.com/q/47167956
has comment: http://stackoverflow.com/comment/81285905
has comment: http://stackoverflow.com/comment/81287391
has comment: http://stackoverflow.com/comment/81286371
type: UnansweredQuestion
has title: Plotting a graph with a picture as a background and another picture as the plot points
tagged with: matplotlib
tagged with: python
score: 0
has body: Here is what I tried to do. It displayed the image as the background but it did not display the x,y plot. I also want to use another picture for my plot points. x=[0,1,2,3,4,5] y=[0,1,2,3,4,5] im = plt.imread('testimage.png') implot = plt.imshow(im) plt.plot(x,y,'o',color='black') plt.show() Thanks.
answer count: 0
linked to: http://stackoverflow.com/q/15160123
has comment: http://stackoverflow.com/comment/81286329
type: Question

http://stackoverflow.com/comment/81189566
type: AnswerComment
score: 1
has text: @DocMagro seems like installing MySQL-Python in a Windows environment can be troublesome; this answer may help: https://stackoverflow.com/a/5685209/253358
type: Comment
comment on: http://stackoverflow.com/a/47114341

http://stackoverflow.com/comment/81278998
type: AnswerComment
has text: If you used (the right) pip, it should already be the right version. But it's not complaining about scrapy, it's complaining about `cryptography.hazmat.bindings._openssl`. Did you install that one using pip? Do you have `_openssl.pyd` somewhere in `C:\Users\dell\Anaconda3\envs\scrapy-env\lib\site-packages`? Try reinstalling the right `cryptography` package.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47164350

http://stackoverflow.com/q/47146886
has body: I have python script like below. In this script, I am collecting stdout and stderr of the script in a file and storing in Linux. In this script, I am running the function path_finder in a loop over input_file In this script, I am using subprocess to move data in Linux to a different location. I want this subprocess call to run after finishing the loop but instead, it runs when the loop runs for the first time and when the second time the loop runs it throws an error which is expected. As the file is present it throws an error. #!/usr/bin/python import os import sys import traceback import subprocess def path_finder( table, mysql_user, user, dir, ): day = datetime.now().strftime('%Y-%m-%d') month = datetime.now().strftime('%Y-%m') Linux_path = '/data/logging/{}'.format(input_file) New_path = '/user/{}/{}/logging/{}/{}/{}'.format(user,dir,mysql_user,month,day) subprocess.call(["rm", Linux_path]) so = se = open('/data/logging/{}'.format(input_file), 'a', 0) #re-open stdout without buffering sys.stdout = os.fdopen(sys.stdout.fileno(), 'a', 0) # redirect stdout and stderr to the log file opened above os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) ### CODE: Do something ### if errors the print traceback ### repeat the same for every table in input file ## Execute below statement after for loop completed subprocess.call(["cp", Linux_path, New_path]) if len(sys.argv) != 5: print 'Invalid number of args......' exit() input_file = sys.argv[1] mysql_user = sys.argv[2] user = sys.argv[3] dir = sys.argv[4] input = open("{}.format(input_file)", "r") for table in input: path_finder( table, mysql_user, user, dir, ) sc.stop() print How can I change my script so that the sub process call will run after the for loop is done?
type: AnsweredQuestion
score: 0
answer count: 1
type: Question
tagged with: for-loop
tagged with: subprocess
has answer: http://stackoverflow.com/a/47147586
accepted answer: http://stackoverflow.com/a/47147586
tagged with: python
has title: Calling a sub process after for loop is completed in python

http://stackoverflow.com/comment/81329233
score: 0
type: AnswerComment
type: Comment
has text: OK, that makes sense, thank you. But I can't work out how to get around it? Do I essentially want to tell it to start seeking at 0 but then end at the end of the document?
comment on: http://stackoverflow.com/a/47189746

http://stackoverflow.com/comment/81308877
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47179912
type: AnswerComment
has text: This is exactly what I mean. Thanks! @COLDSPEED

http://stackoverflow.com/q/47205555
has answer: http://stackoverflow.com/a/47225561
has comment: http://stackoverflow.com/comment/81360829
tagged with: python
answer count: 1
has body: Here is my model: user_map = Table( "user_map", Column('user_id', Integer, ForeignKey('user.id'), primary_key=True), Column('map_id', Integer, ForeignKey('map.id'), primary_key=True), PrimaryKeyConstraint('user_id', 'map_id', name='pk_user_map') ) class Map(Base): id = Column(Integer, primary_key=True) name = Column(String) owner_id = Column(Integer, ForeignKey('user.id')) shared_maps = relationship( 'User', secondary=user_map, backref=backref('maps', lazy='dynamic') ) class User(Base): id = Column(Integer, primary_key=True) name = Column(String) email = Column(String, unique=True) shared_maps = Map.query.filter(Map.shared_maps.any()).all() I want to query the user_map table, using the join condition "Map.id == user_map.map_id", but SQLAlchemy is trying to join using "Map.id == user_map.map_id and Map.owner_id == user_map.user_id". How can I specify my join condition? I tried to use primaryjoin attribute in the relationship and to specify the condition inside the .join() but without success. Thanks in advance!
has comment: http://stackoverflow.com/comment/81397249
tagged with: join
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81360839
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/81402008
has comment: http://stackoverflow.com/comment/81395442
accepted answer: http://stackoverflow.com/a/47225561
type: Question
has title: How to specify the join condition on a many-to-many relationship using SQLAlchemy

http://stackoverflow.com/comment/81135228
type: QuestionComment
comment on: http://stackoverflow.com/q/47090354
has text: ok but my waitkey() is used to stop video after 10 seconds then how can i handle it ? can u please edit my code and share the updated code with me.
score: 0
type: Comment

http://stackoverflow.com/a/47220857
score: 2
has comment: http://stackoverflow.com/comment/81396925
has comment: http://stackoverflow.com/comment/81397231
answers question: http://stackoverflow.com/q/47220744
has comment: http://stackoverflow.com/comment/81394086
has comment: http://stackoverflow.com/comment/81395169
upvote count: 2
downvote count: 0
type: Answer
has body: The figure shown inside the Jupyter notebook is saved using fig.savefig(&lt;some buffer&gt;, bbox_inches="tight"). Hence, in order to obtain the same figure when saving to disc, you would also need to save it using the bbox_inches="tight" argument, fig.savefig("output.png", bbox_inches="tight")
has comment: http://stackoverflow.com/comment/81397150

http://stackoverflow.com/comment/81407976
has text: Sebastian Łącki: Out of curiosity, which of the two techniques worked for you?
type: AnswerComment
comment on: http://stackoverflow.com/a/47214873
score: 0
type: Comment

http://stackoverflow.com/q/47204256
has answer: http://stackoverflow.com/a/47204917
has title: Counting loops/cycles of numbers in Python
has comment: http://stackoverflow.com/comment/81357363
favorite count: 0
type: Question
tagged with: python-3.x
has body: Trying to count machine cycles. I need help populating the ID column with some Python code. Thanks for your help. Every time the Cycle restarts at 1, I would like ID to represent that new cycle from 1 to N. Cycle ID 1 1 2 1 … 1 35 1 1 2 2 2 … 2 457 2 1 3 2 3 … 3 128 3
has comment: http://stackoverflow.com/comment/81357313
tagged with: python
has answer: http://stackoverflow.com/a/47204403
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/47204411
upvote count: 2
score: 0
possible better answer: http://stackoverflow.com/a/47204917
downvote count: 2
has answer: http://stackoverflow.com/a/47204411
tagged with: loops

http://stackoverflow.com/a/62512171
has body: If you are on a linux os, changing file permissions could possibly fix the problem. But beware of what you do with permissions: chmod 755 "/path to chromedriver file" I downloaded the file via python itself, which unfortunately disabled execution permission and this was the quick fix for it.
type: Answer
score: 7
downvote count: 0
upvote count: 7
answers question: http://stackoverflow.com/q/47148872

http://stackoverflow.com/comment/81185221
comment on: http://stackoverflow.com/q/47115600
score: 1
type: Comment
type: QuestionComment
has text: And now I'm seeing from the rect docs that I'm not passing the correct x and y input. This should be coordinates for the rect centers (and mine are unequal length). It seems that making this plot should be trivial though, so I welcome anyone to point out any obvious oversight.

http://stackoverflow.com/a/47208678
upvote count: 1
answers question: http://stackoverflow.com/q/47208633
score: 1
type: Answer
has body: You're using the format function of strings incorrectly. You're trying to use string interpolation, which is an entirely different method of formatting strings. You should try something like this: filename = 'mylog{0}.txt'.format(i) The {0} explicitly states that you should take the first value passed to format. You could leave it as {} if you'd like - it makes no real difference.
downvote count: 0
has comment: http://stackoverflow.com/comment/81366620

http://stackoverflow.com/q/47163749
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81279337
has comment: http://stackoverflow.com/comment/81277380
answer count: 1
accepted answer: http://stackoverflow.com/a/47164296
type: Question
has body: I have run the following code on python in order to retrieve various crypto currency closing prices from their inception. I have run it successfully using the following tickers: tickers = ['USDT_BTC','USDT_BCH','USDT_ETC','USDT_XMR','USDT_ETH','USDT_DASH', 'USDT_XRP','USDT_LTC','USDT_NXT','USDT_STR','USDT_REP','USDT_ZEC'] I now have changed it as follows (full code included) and get a ValueError. [LN1] def CryptoDataCSV(symbol, frequency): #Params: String symbol, int frequency = 300,900,1800,7200,14400,86400 #Returns: df from first available date url ='https://poloniex.com/public?command=returnChartData&amp;currencyPair='+symbol+'&amp;end=9999999999&amp;period='+str(frequency)+'&amp;start=0' df = pd.read_json(url) df.set_index('date',inplace=True) df.to_csv(symbol + '.csv') print('Processed: ' + symbol) [LN2] import pandas as pd import matplotlib.pyplot as plt %matplotlib inline [LN3] tickers = 'ETH_BTC','STR_BTC','XMR_BTC','XRP_BTC','LTC_BTC','DASH_BTC', 'ETC_BTC','POT_BTC','OMG_BTC','FCT_BTC','ZEC_BTC','BTS_BTC','VTC_BTC', 'XEM_BTC','MAID_BTC','DGB_BTC','STRAT_BTC','LSK_BTC','XVC_BTC','SC_BTC', 'DOGE_BTC','XBC_BTC','GNT_BTC','EMC2_BTC','CLAM_BTC','RIC_BTC','SYS_BTC', 'DCR_BTC','STEEM_BTC','ZRX_BTC','GAME_BTC','VIA_BTC','NXC_BTC','NXT_BTC' ,'VRC_BTC','NAV_BTC','PINK_BTC','STORJ_BTC','ARDR_BTC','BCN_BTC','CVC_BTC', 'EXP_BTC','LBC_BTC','GNO_BTC','GAS_BTC','OMNI_BTC','XCP_BTC','NEOS_BTC', 'BURST_BTC','AMP_BTC','FLDC_BTC','FLO_BTC','SBD_BTC','BLK_BTC','BTCD_BTC', 'NOTE_BTC','GRC_BTC','PPC_BTC','BTM_BTC','XPM_BTC','NMC_BTC','PASC_BTC', 'NAUT_BTC','BELA_BTC','SJCX_BTC','HUC_BTC','RADS_BTC'] [LN4] for ticker in tickers: CryptoDataCSV(ticker, 86400) I now get the following error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () 1 for ticker in tickers: ----> 2 CryptoDataCSV(ticker, 86400) in CryptoDataCSV(symbol, frequency) 7 url ='https://poloniex.com/public?command=returnChartData&amp;currencyP…
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47164296
tagged with: python
has title: Received "ValueError: If using all scalar values, you must pass an index" in Python
has comment: http://stackoverflow.com/comment/81277794

http://stackoverflow.com/comment/81357949
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47204356
has text: I like it! it's a plus one :)
type: Comment

http://stackoverflow.com/a/65851049
has body: If you run it on a Windows computer you can also add it to Windows PATH (environment variables) so you don't have to declare executable_path. You can just say: webdriver.Chrome(options=your_options)
score: 0
answers question: http://stackoverflow.com/q/47148872
type: Answer

http://stackoverflow.com/comment/81376813
type: AnswerComment
comment on: http://stackoverflow.com/a/47213638
score: 0
has text: I know this works, but still waiting for me to grab the area and then It will screenshot it
type: Comment

http://stackoverflow.com/q/47173574
tagged with: asynchronous
tagged with: celery
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/49737062
answer count: 1
tagged with: python
has title: Setting a signature of a task as starting task of multipe chain in celery
tagged with: celery-canvas
has comment: http://stackoverflow.com/comment/81422087
has comment: http://stackoverflow.com/comment/81328525
has comment: http://stackoverflow.com/comment/81434945
has comment: http://stackoverflow.com/comment/81493927
score: 2
type: AnsweredQuestion
has body: Suppose A to G are async tasks and we want to implement a task workflow like this canvas /---&gt; B() A() ----&gt; C() -&gt; D() \---&gt; E() -&gt; F() -&gt; G() According to the problem, we need to use the result of A() for starting of multiple chains. In code: from celery import chain # A (params) ????? B.apply_async(params) chain( C.s(params), D.s(params) ).apply_async() chain( E.s(params), F.s(params), G.s(params) ).apply_async() In the Celery Canvas, how can I use the result of A() to first elements of multiple chains asynchronously without run the A() three times? (I'm using the Celery 4.1.0 and RabbitMQ as a broker)
downvote count: 0
tagged with: celery-task
accepted answer: http://stackoverflow.com/a/49737062
has comment: http://stackoverflow.com/comment/81447798
has comment: http://stackoverflow.com/comment/81447741

http://stackoverflow.com/comment/81278918
comment on: http://stackoverflow.com/q/47164554
has text: Do you have pandas? This is a more suited to that. Indeed, it's only one operation.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47160969
has comment: http://stackoverflow.com/comment/81271834
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47160355
type: AcceptedAnswer
downvote count: 0
has body: The easiest but not the safest way is to replace the \" with some string that will not occur elsewhere. Then strip, and replace back. raw_value = r'"Simon said: \"Jump!\""' IMPOSSIBLE_STR = '\\"3' raw_value.replace('\\"', IMPOSSIBLE_STR).strip('"').replace(IMPOSSIBLE_STR,'\\"') Out[102]: 'Simon said: \\"Jump!\\"' I suppose it's very unlikely to have \" followed by a number. Regex will probably solve the problem better, conditioned on that you write the correct regex!
answers question: http://stackoverflow.com/q/47160355
has comment: http://stackoverflow.com/comment/81271619
upvote count: 2

http://stackoverflow.com/comment/81312650
type: Comment
type: QuestionComment
has text: @JohnZwinck Just pointing out, I'm not the downvoter, but there's a [war raging](https://meta.stackoverflow.com/questions/359059/how-well-should-gold-badge-holders-prove-the-correctness-of-their-unhammering?cb=1) so that might explain the collateral damage.
score: 0
comment on: http://stackoverflow.com/q/47181495

http://stackoverflow.com/comment/81315669
has text: I have edited. The sorry Incomplete comment was posted.In case If I have not made anything clear please tell me.
type: Comment
comment on: http://stackoverflow.com/a/47182145
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81123049
comment on: http://stackoverflow.com/q/47086683
type: Comment
has text: Bits or bytes? A slice of the digest will be measured in bytes, not bits; you were pulling `n` bytes there.
score: 0
type: QuestionComment

http://stackoverflow.com/q/47077096
type: AnsweredQuestion
score: 0
has title: Python & Pandas - Using chr(255) as a separator
tagged with: pandas
has comment: http://stackoverflow.com/comment/81115407
has comment: http://stackoverflow.com/comment/81308521
answer count: 1
has comment: http://stackoverflow.com/comment/81115421
has comment: http://stackoverflow.com/comment/81102599
type: Question
has comment: http://stackoverflow.com/comment/81308556
accepted answer: http://stackoverflow.com/a/47202873
has body: I'm trying to parse firewall logs with Python &amp; Pandas but i'm having issues with getting the correct separator to work; In my current log data : num�date�time�orig�type�action�alert�i/f_name�i/f_dir�product�log_sys_message�origin_id�ProductFamily�src�dst�proto�message_info�service�s_port�rule�rule_uid�rule_name�service_id�xlatesrc�xlatedst�NAT_rulenum�NAT_addtnl_rulenum�xlatedport�xlatesport�ICMP�ICMP Type�ICMP Code�rule_guid�hit�policy�first_hit_time�last_hit_time�log_id�description�status�version�comment�update_service�TCP packet out of state�tcp_flags�sys_message:�inzone�outzone�Protection Name�Severity�Confidence Level�protection_id�SmartDefense Profile�Performance Impact�Industry Reference�Protection Type�Update Version�Attack Info�attack�capture_uuid�FollowUp�Total logs�Suppressed logs 0�24Oct2017�23:59:00�10.100.255.190�control� ��daemon�inbound�VPN-1 &amp; FireWall-1�Log file has been switched to: 2017-10-24_235900.log�cteafmfw1�Network�������������������������������������������������� and the code: import pandas as pd file = pd.read_csv('2017-10-25_235900.log-export.csv', sep='\xff', header=0, index_col=False) print(file) when i run this i can see that the separator is not processed; I've tried also assignin it to variable with value chr(255) as was proposed for similiar issue but cannot seem to get this separator prosessed at all. I know that i can process the file and replace separator but as there is tons of data with this separator already would be nice to know is it even possible to get this working?
has answer: http://stackoverflow.com/a/47202873
tagged with: python

http://stackoverflow.com/a/47092372
has body: As per your problem statement, there could be more than 1 way to solve it. One, which you have already stated. Other could be something like internal routing. This would involve a request wrapper . Something like this : from flask import Flask, redirect, request, render_template app = Flask("the_flask_module") @app.route('/', methods=["GET", "POST"]) def post_redirect_get(): if request.method == "GET": return render_template("post_redirect_get.html") else: # Use said data. return redirect("target", code=303) @app.route("/target") def target(): return "I'm the redirected function"
answers question: http://stackoverflow.com/q/47091958
type: Answer
score: 0

http://stackoverflow.com/q/47163518
has title: Begin BigQuery query job without fetching rows on google-cloud-bigquery 0.28.0 python library
upvote count: 1
score: 1
has body: google-cloud-bigquery 0.28.0 python library introduced many breaking changes. By looking at the migration documentation there are some examples on how to run queries. Question is: how can one begin a job and synchronously wait for completion (state="DONE") without fetching the results? This is useful for jobs with big outputs and a configured destination table.
tagged with: google-bigquery
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81282140
tagged with: python
has comment: http://stackoverflow.com/comment/81278156
answer count: 0
downvote count: 0

http://stackoverflow.com/q/47214001
downvote count: 0
has title: Unable to convert model from Keras to Tensorflow
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47225894
answer count: 1
tagged with: keras
tagged with: tensorflow
has body: I get the following binary classification Keras model, which trains not well, but trains: def vgg_stack(self): def func(x): x = layers.Conv2D(64, (3, 3), activation='relu')(x) x = layers.MaxPooling2D((3, 3), strides=(2, 2))(x) x = layers.Conv2D(128, (3, 3), activation='relu')(x) x = layers.MaxPooling2D((2, 2), strides=(2, 2))(x) x = layers.Conv2D(128, (3, 3), activation='relu')(x) x = layers.MaxPooling2D((2, 2), strides=(2, 2))(x) x = layers.Conv2D(64, (3, 3), activation='relu')(x) x = layers.MaxPooling2D((2, 2), strides=(2, 2))(x) x = layers.Flatten()(x) x = layers.Dense(512, activation='relu')(x) x = layers.Dense(256, activation='relu')(x) x = layers.Dense(1, activation='sigmoid')(x) return x return func def implement(self): self.inputs = layers.Input((self.input_width, self.input_height, self.input_depth)) self.outputs = self.vgg_stack()(self.inputs) self.opt = optimizers.Adam(lr=self.learning_rate) self.model = models.Model(inputs=self.inputs, outputs=self.outputs) self.model.compile(loss='binary_crossentropy', optimizer=self.opt) def fit_predict(self): ... self.model.fit(data_train, actuals_train, batch_size=self.batch_size, epochs=10, verbose=1, validation_data=[data_validation, actuals_validation], callbacks=[self]) it's predictions look like following [[ 0.58952832] [ 0.89163774] [ 0.99083483] ..., [ 0.52727282] [ 0.72056866] [ 0.99504411]] I.e. it's something. I tried to convert the model to pure tensroflow and got def conv2drelu(self, x, filters, kernel_size, padding='VALID'): input_depth = int(x.get_shape()[-1]) weights = tf.Variable(tf.truncated_normal([kernel_size[0], kernel_size[0], input_depth, filters], dtype=tf.float32, stddev=self.init_stddev)) self.var_list.append(weights) biases = tf.Variable(tf.constant(0.0, shape=[filters], dtype=tf.float32)) self.var_list.append(biases) y = tf.nn.conv2d(x, weights, [1, 1, 1, 1], padding=padding) y = tf.nn.bias_add(y, biases) y = tf.nn.relu(y) return y def maxpooling(self, x, pool_size, strides, padding='VALID'…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81377681
accepted answer: http://stackoverflow.com/a/47225894
tagged with: python
type: AnsweredQuestion
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/81377611

http://stackoverflow.com/q/47096681
tagged with: openpyxl
has title: how to compare datetime.datetime and pyodbc.row values
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47097853
accepted answer: http://stackoverflow.com/a/47097853
has comment: http://stackoverflow.com/comment/81153445
tagged with: python
tagged with: pyodbc
has body: I am trying to see if values in DateRef row in Access database is equal to datetime.datetime value in Excell cell. Cannot wrap my head around how to convert pyodbc.row to datetime.datetime. In[18]:sheet['BL2'].value Out[18]: datetime.datetime(2017, 12, 15, 0, 0) In[21]type(sheet['BL2'].value) Out[21]: datetime.datetime In [17]: DateRef_aslist[-1] In [17]: (datetime.datetime(2017, 12, 15, 0, 0), ) In [20]: type(DateRef_aslist[-1]) In [20]: Out[20]: pyodbc.Row In [19]: DateRef_aslist[-1] == sheet['BL2'].value Out[19]: False
type: AnsweredQuestion
score: 0
upvote count: 1

http://stackoverflow.com/a/47114894
has body: Your usage of requests.Session() is proper, so I'd reckon that the problem in not with cookies but rather with your login. Websites like Amazon and Facebook sometimes require form metadata along with login web requests that you are currently not passing. If I am right, this answer should be able to help you.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47108802

http://stackoverflow.com/comment/81293170
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ I did so,but same error happens.How should I fix this?
type: Comment
comment on: http://stackoverflow.com/q/47171751
type: QuestionComment

http://stackoverflow.com/a/50292753
has comment: http://stackoverflow.com/comment/110145406
downvote count: 1
answers question: http://stackoverflow.com/q/47142848
type: Answer
has body: As mentioned in other question https://stackoverflow.com/a/36499718/1657819 this error may happen if you're under proxy, so disabling proxy may help unset https_proxy
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/120498933

http://stackoverflow.com/a/47147362
answers question: http://stackoverflow.com/q/47147146
type: Answer
has comment: http://stackoverflow.com/comment/81245066
accepted answer of: http://stackoverflow.com/q/47147146
score: 9
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81245276
has body: I think you want subplots_adjust: fig,ax = plt.subplots(1) fig.subplots_adjust(left=0,right=1,bottom=0,top=1) ax.axis('tight') ax.axis('off') In this case: import matplotlib.pyplot as plt from scipy.io import wavfile import numpy as np def graph_spectrogram(wav_file): rate, data = wavfile.read(wav_file) fig,ax = plt.subplots(1) fig.subplots_adjust(left=0,right=1,bottom=0,top=1) ax.axis('off') pxx, freqs, bins, im = ax.specgram(x=data, Fs=rate, noverlap=384, NFFT=512) ax.axis('off') fig.savefig('sp_xyz.png', dpi=300, frameon='false') if __name__ == '__main__': # Main function graph_spectrogram('...')
upvote count: 9

http://stackoverflow.com/q/47217297
downvote count: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47285577
tagged with: django
favorite count: 0
type: Question
has body: I'm trying to build a messaging app. Here's my model: class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) This is what I tried in the view: data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by('-created_at') In the template: {% for abc in data %} {{ abc.receiver }} &lt;br/&gt; {% endfor %} Here I want to filter the distinct receivers and re-order them based upon the fact that to whom request.user sent new message recently (as we see on social media platforms). How can I do that?
tagged with: python
has title: Fetch distinct receivers from message model while preserving order
score: 2
upvote count: 2

http://stackoverflow.com/comment/81387292
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47218675
has text: your parentheses in `any` are the first problem. The second being the logic. Look at the answers below for the correct use of `any`
score: 0

http://stackoverflow.com/q/47122494
type: AnsweredQuestion
downvote count: 0
answer count: 1
favorite count: 0
has title: Same Y-axis in parallel plot
has body: I have this code: import pandas as pd import matplotlib.pyplot as plt import seaborn as sns;sns.set_style("whitegrid") import seaborn as sns; sns.set(style="ticks") x = pd.read_csv("C:\\Users\dell\\Desktop\\delikatesy_owoce_i_warzywa(wyczyszczone).csv", sep=',') x2 = x[x.grupa.str.contains('RAZEM') == False] del x2['rok'] del x2['miesiac'] del x2['dzien_tygodnia_liczba'] del x2['dzien'] del x2['data2'] del x2['Unnamed: 0'] x2['data'] = pd.to_datetime(x2['data']) x3 = x2[x2["data"].isin(pd.date_range('2017-10-01','2017-10-18'))] x4 = x3.groupby('grupa')['marza_netto'].agg({"marza_netto2": 'size'}).join(x3.groupby('grupa').sum()).reset_index() x4.insert(4,'marza_procent2', x4['marza_procent']/x4['marza_netto2']) del x4['marza_netto2'] del x4['marza_procent'] x4 = x4.set_index('grupa').T.rename_axis('DANE').reset_index().rename_axis(None,1) flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"] fig, ax = plt.subplots(1,3) g1 = sns.barplot(x="DANE", y="OWOCE", palette=sns.color_palette(flatui),data=x4,ci=None, ax=ax[0]) g2 = sns.barplot(x="DANE", y="WARZYWA", palette=sns.color_palette(flatui),data=x4,ci=None, ax=ax[1]) g3 = sns.barplot(x="DANE", y="NASIONA", palette=sns.color_palette(flatui),data=x4,ci=None, ax=ax[2]) sns.despine() g1.figure.set_size_inches(8,6) g2.axes.set_title('Wpływ procentu marży na wielkosć sprzedaży', fontsize=15,color="b",alpha=0.3) g1.set_xlabel("OWOCE",size = 15,color="g",alpha=0.5) g2.set_xlabel("WARZYWA",size = 15,color="g",alpha=0.5) g3.set_xlabel("NASIONA",size = 15,color="g",alpha=0.5) g1.set_ylabel("",size = 20,color="r",alpha=0.5) g2.set_ylabel("",size = 20,color="r",alpha=0.5) g3.set_ylabel("",size = 20,color="r",alpha=0.5) plt.setp(g1.get_xticklabels(), rotation=-45) plt.setp(g2.get_xticklabels(), rotation=-45) plt.setp(g3.get_xticklabels(), rotation=-45) Where I compare three product groups separately. And I don't know how to make the values on the Y axis on each graph are proportional to each other and related t…
type: Question
tagged with: seaborn
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/47122592
tagged with: python
has answer: http://stackoverflow.com/a/47122592
tagged with: pandas
score: 2
upvote count: 2

http://stackoverflow.com/comment/81103435
has text: As other people have already mentioned, your epoch and beaches are inverted most likely. Also, having a heavy loss in the test means overfitting the data. Try using regularization if you are seeing the same issue even after changing the loops.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47069671
score: 0

http://stackoverflow.com/comment/81177926
type: Comment
comment on: http://stackoverflow.com/q/47110454
score: 0
type: QuestionComment
has text: @Iridium I have tried that as well, to no avail :( I'll try a library instead, thanks!

http://stackoverflow.com/comment/81151565
comment on: http://stackoverflow.com/q/47100760
score: 0
has text: please paste your code instead of showing screenshots ...
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81178161
score: 0
type: Comment
has text: Keep in mind that you are not able to re-read the first 3 bytes after calling `file.read(3)`. You need to call `file.seek(0)` if you want to re-read the first 3 bytes. Look at the `KeyError: b'\xe0\x00\x10'`. You don't have that in your file_sigs dict. I bet that's reading bytes 4,5,6 since you've called `file.read(3)` before.
type: QuestionComment
comment on: http://stackoverflow.com/q/47113097

http://stackoverflow.com/comment/81347766
type: Comment
type: QuestionComment
score: 0
has text: How come the 2D plot is black and white?
comment on: http://stackoverflow.com/q/47197748

http://stackoverflow.com/comment/81215485
has text: Basically, the website is telling you: "dont hit me so hard". By setting `CONCURRENT_REQUESTS_PER_DOMAIN=1`, you are limiting the number of connection to 1. You can also try setting the option `DOWNLOAD_DELAY=5` to set a 5 seconds delay between those requests (feel free to increase/decrease this value to find the optimal one).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47093583
type: AnswerComment

http://stackoverflow.com/q/47112929
has comment: http://stackoverflow.com/comment/81176855
has answer: http://stackoverflow.com/a/47113120
has comment: http://stackoverflow.com/comment/81176847
has comment: http://stackoverflow.com/comment/81175851
answer count: 2
score: 1
has body: My data is a nested dicitionary of people in countries. Here's what it looks like with unimportant stuff removed: {'DE': [{'createdTime': '2017-11-03T13:41:01.000Z', 'fields': {'Land': 'DE', 'Teilnehmer': 'James Hunt'}, 'id': 'reccgdSZXZFvAztCT'}, {'createdTime': '2017-11-04T12:50:21.000Z', 'fields': {'Land': 'DE', 'Teilnehmer': 'Susie Mueller'}, 'id': 'recQhmPmTrlZzoI84'}, {'createdTime': '2017-11-04T12:50:33.000Z', 'fields': {'Land': 'DE', 'Teilnehmer': 'Tom Tikky'}, 'id': 'recKCh99xvQwwCmSp'}], 'UK': [{'createdTime': '2017-11-03T13:41:01.000Z', 'fields': {'Land': 'UK', 'Teilnehmer': 'John Doe'}, 'id': 'recFTlSMXNET6e2UX'}, {'createdTime': '2017-11-03T14:16:00.000Z', 'fields': {'Land': 'UK', 'Teilnehmer': 'Jane Smith'}, 'id': 'recLqDHWh14TLm30g'}, {'createdTime': '2017-11-03T18:41:56.000Z', 'fields': {'Land': 'UK', 'Teilnehmer': 'Claire Singer'}, 'id': 'recB8XaFb7va0lT50'}]} It has previously been sorted by country already. I now need to build sender/receiver pairs and everyone needs to be in two pairs - once as the sender, once as the receiver. Both sides need to be from the same country. So with the sample data from above there will be 3 pairs per country at the end. All that matters on the output is the id. Basically I thought a list would work at the output but I'm not sure if those are reliable when it comes to the order of elements within the list. Apart from that this is what the result could look like: [ # DE Pairs ['reccgdSZXZFvAztCT', 'recQhmPmTrlZzoI84'], ['recQhmPmTrlZzoI84', 'recKCh99xvQwwCmSp'], ['recKCh99xvQwwCmSp', 'reccgdSZXZFvAztCT'], # UK Pairs ['recFTlSMXNET6e2UX', 'recLqDHWh14TLm30g'], ['recLqDHWh14TLm30g', 'recB8XaFb7va0lT50'], ['recB8XaFb7va0lT50', 'recFTlSMXNET6e2UX'] ] Everything that came to my mind to solve this involves several levels of for loops but I still didn't manage to get it done. I'm very sure there must be a pythonic way to solve this. Any ideas?
downvote count: 0
has answer: http://stackoverflow.com/a/47114290
upvote count: 1
has comment: http://stackoverflow.com/comment/81177832
favorite count: 0
has comment: http://stackoverflow.com/comment/81176903
type: Question
tagged with: python-3.x
has title: Build pairs from dictionary
type: UnansweredQuestion
tagged with: python

imagedownload
tag name: imagedownload
type: Tag
tags question: http://stackoverflow.com/q/47206788

http://stackoverflow.com/q/47100106
has body: I have seen the Scikit-Learn example of Gaussian mixture for clustering. In this example (and other examples of this model), it looks the data always has two dimensions: plt.scatter(X[:, 0], X[:, 1], s=10, color=colors[y_pred]) I use the following script ( X actully has more than 2 columns), clf = mixture.GaussianMixture(n_components=2, covariance_type='full') clf.fit(X) y_pred = clf.predict(X) colors = np.array(list(islice(cycle(['#377eb8', '#ff7f00', '#4daf4a', '#f781bf', '#a65628', '#984ea3', '#999999', '#e41a1c', '#dede00']), int(max(y_pred) + 1)))) plt.scatter(X[:, 0], X[:, 1], s=10, color=colors[y_pred]) plt.show() How can I visualize the clusters and data points?
has title: How use visualize Gaussian mixture model's clusters for multi dimensional data in Scikit?
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: cluster-analysis
downvote count: 0
tagged with: scikit-learn
tagged with: python
upvote count: 7
score: 7

http://stackoverflow.com/a/51007448
answers question: http://stackoverflow.com/q/47179433
has body: this worked for me from backports.functools_lru_cache import lru_cache
has comment: http://stackoverflow.com/comment/117262644
type: Answer
score: 0

http://stackoverflow.com/comment/81221286
score: 0
type: Comment
type: QuestionComment
has text: The dataframe could have `float64` values, `int32` values, even `numpy.nan` values.
comment on: http://stackoverflow.com/q/47135742

http://stackoverflow.com/comment/81311797
comment on: http://stackoverflow.com/q/47180020
has text: @Miki, I will try that so
score: 0
type: Comment
type: QuestionComment

decimal
tags question: http://stackoverflow.com/q/47113787
tag name: decimal
type: Tag
tags question: http://stackoverflow.com/q/47214856
tags question: http://stackoverflow.com/q/47105893

http://stackoverflow.com/q/47207361
possible better answer: http://stackoverflow.com/a/47217928
has body: I am trying to group customers according to a certain given dataset with attributes like DOB, Gender, State, pincode, transaction_id, promocode etc. Every time I run the algorithm there is a huge difference in the silhouette score of the clustering from the previous one i.e. the result is not consistent. Probably that is because of the random seeds to the datasets. Here is the line which passes attribute to the algorithm. km1 = KMeans(n_clusters=6, n_init=25, max_iter = 600) Is there any method to assign clusters or optimise such that after everytime I run the program, the score is consistent and better? I am using Python 3 with scikit-learn.
has answer: http://stackoverflow.com/a/47217928
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47209277
answer count: 2
tagged with: k-means
tagged with: cluster-analysis
tagged with: machine-learning
tagged with: scikit-learn
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47209277
type: Question
has comment: http://stackoverflow.com/comment/81365162
score: 3
has title: How to put the seed values of K-means algorithm?
tagged with: python
upvote count: 4

http://stackoverflow.com/comment/81174382
type: QuestionComment
type: Comment
has text: Can the things in the array/list be sorted? Is `A < B` a valid operation? Is `A1 == A2` True? Are you asking literally how to randomly assign sequence numbers to groups of letters?
score: 0
comment on: http://stackoverflow.com/q/47112109

http://stackoverflow.com/comment/100869570
type: AnswerComment
has text: The else after the if is unnecessary since you're writing to table in both cases.
comment on: http://stackoverflow.com/a/47839247
type: Comment
score: 2

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/47163065
tags question: http://stackoverflow.com/q/47147532
tags question: http://stackoverflow.com/q/47084834
tags question: http://stackoverflow.com/q/47163664
type: Tag
tags question: http://stackoverflow.com/q/47122561

http://stackoverflow.com/q/47170879
score: 8
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/40628977
tagged with: partition
answer count: 1
downvote count: 0
tagged with: sharding
has title: What is partitioner parameter in Tensorflow variable_scope used for?
accepted answer: http://stackoverflow.com/a/47179468
tagged with: tensorflow
has answer: http://stackoverflow.com/a/47179468
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/38352494
upvote count: 8
has body: tf.variable_scope has a partitioner parameter as mentioned in documentation. As I understand it's used for distributed training. Can anyone explain it in more details what is the correct use of it?
tagged with: python

http://stackoverflow.com/q/47209441
downvote count: 2
tagged with: cluster-analysis
tagged with: scikit-learn
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81378630
answer count: 1
has answer: http://stackoverflow.com/a/47217797
type: Question
has title: Why does sklearn require the true labels when implementing the rand index ?
has comment: http://stackoverflow.com/comment/81378574
has body: I have been looking into evaluating the accuracy of my clusters and Rand Index appears to be one that is hugely popular in the literature. It is calculated by making a pairwise comparison of each item in each cluster and assigning a score to them based on four criteria: True positive , true negative , false positive and false negative or a , b , c , d. The Rand score is calculated by taking the sum of the true positive and true negatives and dividing them by the sum of all the above mentioned classes. My question is , why does sklearn then require the correct labels to calculate the Rand Index Score ?
score: -2
favorite count: 0
upvote count: 0

http://stackoverflow.com/comment/81333091
type: QuestionComment
comment on: http://stackoverflow.com/q/47191791
score: 0
type: Comment
has text: I expect `Columns: [A, B]` to be in the output. I know I can do `df.A == 4` in this particular case, but not all apply calls can be replaced like that, so that's not providing an answer.

http://stackoverflow.com/comment/81317721
has text: Sorry just a quick question. If I wanted the diamond to have a width no more than 30 and the user inputted 35. How would I stop it from even printing thanks
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47183342

http://stackoverflow.com/comment/81266746
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47158491
score: 1
has text: `a.hot` is a function, so you need to call it if you want its `return`ed value. `a.i` is an integer whose value you can access just as is. `__init__` has nothing to do with the second case at all, except that it gets called automatically when `MyClass2` is instantiated.

http://stackoverflow.com/q/47171974
has comment: http://stackoverflow.com/comment/81293734
answer count: 1
tagged with: selenium
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47172217
accepted answer: http://stackoverflow.com/a/47172217
score: 0
has title: How to get a value of a class?
has body: Can someone please advise how I can tell Selenium to keep clicking on the "Next Page" button until it finds specific month? I can use it to get to a specific page, where I can find this title id, but I can't figure out how to tell if I'm on "December 2017" page? And if not, click the "Next" button again. You can see in the line below that I'm on November 2017 page: November 2017 Here is my Python code up to a point where I'm stuck... next_page_button = browser.find_element_by_id("ctl00_cphBody_rdc_NN") # This click takes me to a calendar page next_page_button.click() # Now I'm on a calendar page, I have the class name, but how to tell for what month??? my_month = browser.find_element_by_class_name("rcTitle") Can someone please advise? Thank you!
tagged with: python
tagged with: selenium-webdriver
type: Question

http://stackoverflow.com/comment/81079354
comment on: http://stackoverflow.com/q/47065548
type: Comment
score: 0
has text: What is your desired output?
type: QuestionComment

http://stackoverflow.com/comment/81116745
type: Comment
comment on: http://stackoverflow.com/q/47083667
score: 1
type: QuestionComment
has text: Are the two foos in `set_a` and `set_b` really equal (`==`) or do they just have the same hash?

http://stackoverflow.com/comment/81327844
type: QuestionComment
has text: Why do you need the `while True:` loop at all?
comment on: http://stackoverflow.com/q/47189194
score: 1
type: Comment

memoization
type: Tag
tag name: memoization
tags question: http://stackoverflow.com/q/47188706

http://stackoverflow.com/comment/81285958
comment on: http://stackoverflow.com/q/47167972
has text: I am new. I am not sure I understand the question. They're both the same kind of information, a sentence, three dots and a link at the end. The only difference is that I can extract the element from things_on_queue using el.text, and I can extract the same exact text element from things_to_tweet using "el" alone. Not sure if that helps
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47188727
downvote count: 0
upvote count: 1
tagged with: python
has title: Operation error when trying to delete a document
favorite count: 0
has comment: http://stackoverflow.com/comment/81360984
score: 1
tagged with: pymongo
has body: I'm trying to delete a document; when I do so, I get the following error: OperationError: Could not delete document (unrecognized write concern field: write_concern) Here's how I am deleting my document: appointmentInformation = appointment.objects.get(booking_id=str(request.args.get('booking_id'))) appointmentInformation.delete() I'm tying to delete the appointment object based on its booking_id; it throws me that error. I'm using Mongo: mongoengine==0.8.7 pymongo==2.8.1 I am looking for a solution for the Mongo version I'm using and do not plan on updating.
tagged with: mongoengine
has comment: http://stackoverflow.com/comment/81368907
type: Question
has comment: http://stackoverflow.com/comment/81360247
tagged with: mongodb
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/81148713
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47099196
type: Comment
has text: I definitely will keep this in mind now. So many time spent for such simple mistake.

http://stackoverflow.com/comment/81356226
score: 0
comment on: http://stackoverflow.com/a/47200367
type: Comment
has text: @HakariDo: hi again, try this one! ... will check duplicates in a directory.
type: AnswerComment

http://stackoverflow.com/q/47092416
answer count: 2
downvote count: 0
tagged with: python
tagged with: virtualenv
has answer: http://stackoverflow.com/a/76746419
possible better answer: http://stackoverflow.com/a/76746419
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: anaconda
has body: I want to use multiple conda environments together. I have a huge conda environment containing a lot of packages (lets call it the monolith) which I use in all my projects and don't want to create again. I want to create a separate smaller conda environments for each project and work use it along with my huge monolith. So that I can keep the monolith clean and use for multiple projects safely. Following are a few things I think should be taken care of, Update PATH, PYTHONPATH and LD_LIBRARY_PATH variables. When installing a new package run a try dry run on all the environments in the stack and only then install it to the top environment. So that any version conflicts can be caught. While executing the dry runs keep track of all the packages conda lists for installation. And when running the final install on top environment install only the intersection of packages listed in each of the dry run with --no-deps flag. This way we can avoid reinstallation of packages. Would this approach work?
has answer: http://stackoverflow.com/a/47094340
accepted answer: http://stackoverflow.com/a/47094340
favorite count: 0
type: Question
has title: Using stacked conda environments

http://stackoverflow.com/q/47102736
has body: I've put together this Forward Kinematics function for Baxter arm robot based on its hardware specs and the following joints axis: The joint positions for the following forward kinematics are not matching the corresponding Cartesian coordinates, what am I doing wrong here? def FK_function_2(joints): def yaw(theta): #(rotation around z) y = np.array([[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1] ]) return y R01 = yaw(joints[0]).dot(np.array([[-1, 0, 0], [0, 0, 1], [0, 1, 0]])) R12 = yaw(joints[1]).dot(np.array([[0, 0, -1], [-1, 0, 0], [0, 1, 0]])) R23 = yaw(joints[2]).dot(np.array([[-1, 0, 0], [0, 0, 1], [0, 1, 0]])) R34 = yaw(joints[3]).dot(np.array([[-1, 0, 0], [0, 0, 1], [0, 1, 0]])) R45 = yaw(joints[4]).dot(np.array([[-1, 0, 0], [0, 0, 1], [0, 1, 0]])) R56 = yaw(joints[5]).dot(np.array([[-1, 0, 0], [0, 0, 1], [0, 1, 0]])) R67 = yaw(joints[6]).dot(np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])) d = np.array([0.27035, 0, 0.36435, 0, 0.37429, 0, 0.229525]) a = np.array([0.069, 0, 0.069, 0, 0.010, 0, 0]) l1 = np.array([a[0]*np.cos(joints[0]), a[0]*np.sin(joints[0]), d[0]]); l2 = np.array([a[1]*np.cos(joints[1]), a[1]*np.sin(joints[1]), d[1]]); l3 = np.array([a[2]*np.cos(joints[2]), a[2]*np.sin(joints[2]), d[2]]); l4 = np.array([a[3]*np.cos(joints[3]), a[3]*np.sin(joints[3]), d[3]]); l5 = np.array([a[4]*np.cos(joints[4]), a[4]*np.sin(joints[4]), d[4]]); l6 = np.array([a[5]*np.cos(joints[5]), a[5]*np.sin(joints[5]), d[5]]); l7 = np.array([a[6]*np.cos(joints[6]), a[6]*np.sin(joints[6]), d[6]]); unit = np.array([0, 0, 0, 1]) H0 = np.concatenate((np.concatenate((R01, l1.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0) H1 = np.concatenate((np.concatenate((R12, l2.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0) H2 = np.concatenate((np.concatenate((R23, l3.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0) H3 = np.concatenate((np.concatenate((R34, l4.reshape(3, 1)), axis=1), unit.reshape(1,4)), axis=0) H4 = np.concatenate((np.concat…
score: 7
answer count: 1
upvote count: 7
has comment: http://stackoverflow.com/comment/81410343
favorite count: 0
type: Question
tagged with: robotics
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81667984
downvote count: 0
has title: Forward Kinematics for Baxter
tagged with: python
tagged with: kinematics
has answer: http://stackoverflow.com/a/47298942

http://stackoverflow.com/a/47084195
has comment: http://stackoverflow.com/comment/81117980
score: 3
has body: You're telling it to return to /alerts, where the actual URL defined for it is investigations/alerts A better way for you to do this would use reverse and do it like so: return HttpResponseRedirect(reverse('alerts')) This would let you use the name kwarg you've already defined, so if you decide to change the URL, it won't matter if the name stays the same.
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81117776
has comment: http://stackoverflow.com/comment/81118300
answers question: http://stackoverflow.com/q/47084128
type: Answer

http://stackoverflow.com/comment/81081579
has text: Can you cite the documentation you are using? Is it effbot? The function seems to be returning an empty tuple. Perhaps this is a change between py2 and py3. The comparison to `'()'` wont work, as that's a string, not a tuple. Instead try `if name == ():` (without the quotes) or more idiomatically `if not name:`. Those both work for me.
score: 0
comment on: http://stackoverflow.com/q/47066606
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47122459
tagged with: datetime
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/47122672
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47122525
tagged with: python
has title: Create a new column based on Grouping of similar values in another column in pandas
has answer: http://stackoverflow.com/a/47122672
accepted answer: http://stackoverflow.com/a/47122525
type: AnsweredQuestion
score: 0
tagged with: pandas
has body: Hi I have an event data frame with datetimes and event ids and sensor ids. I would like to group events that happen within one hour per sensor and if possible tag them with the group count. Original Data Frame sensor_id event_id time 0 A e1 2017-02-14 05:30:00 1 A e2 2017-02-14 05:45:00 2 A e3 2017-02-14 08:30:00 3 B e3 2017-02-14 05:20:00 4 B e4 2017-02-14 05:30:00 5 B e6 2017-02-14 05:45:00 6 C e1 2017-02-14 05:30:00 7 C e3 2017-02-14 07:30:00 8 C e7 2017-02-14 09:35:00 Desired Result: sensor_id event_id time group 0 A e1 2017-02-14 05:30:00 1 1 A e2 2017-02-14 05:45:00 1 2 A e3 2017-02-14 08:30:00 2 3 B e3 2017-02-14 05:20:00 1 4 B e4 2017-02-14 05:30:00 1 5 B e6 2017-02-14 05:45:00 1 6 C e1 2017-02-14 05:30:00 1 7 C e3 2017-02-14 07:30:00 2 8 C e7 2017-02-14 09:35:00 3 I understand that I should group by user, event and then, time using timdelta of 1 hour but I have no clue how to do the rest. Any tips will be appreciated.

http://stackoverflow.com/a/47190545
score: 3
downvote count: 0
has body: The problem is that your processor instantiates the form on each render. Each time you call render, your processor is called, which instantiates a new form and displays THAT form, not the form instance that you created in the view. Therefore, the form being rendered is a blank instance but the form that contains the input and errors was destroyed by garbage collection after finishing your view. A way I would do this, is passing the form you create in the view back to context before rendering. Pass it in to a context key such as "name_form_filled". Then if that variable is present in the context, don't render "name_form", instead render "name_form_filled". views.py def user_profile(request): ctx = {} if request.method == 'POST': name_form = NewNameForm(request.POST) if name_form.is_valid(): name_form.save() # you named this named_form, not form. # If you want to redirect to another view when the form is saved successfuly, do it here. else: ctx["name_form_filled"] = form else: ctx.update({'title': 'Profile', 'active_tab': 'Profile'}) return render (request, 'user_profile.html', ctx) user_profile.html &lt;div id="form_container"&gt; {% if name_form_filled %} &lt;!-- Render form that has input and errors from previous POST. --&gt; {{ name_form_filled }} {% else %} &lt;!-- render empty initial form. User has not attempted to submit yet. --&gt; {{ name_form }} {% endif %} &lt;/div&gt; =========================================================================== Another way you could do this is turn this view into a class based view and inherit a base class based view. This base class will override the get_context_data method and add your three forms. Note that you won't be using the context processor with this methodology so you could get rid of it if wanted in this case. All views that use your form will extend the base view class. Then, after evaluating your form, if it is invalid, overwrite your name_form context key with the invalid form instance, which will be in your …
answers question: http://stackoverflow.com/q/47188555
type: Answer
upvote count: 3

http://stackoverflow.com/comment/81112211
type: Comment
type: QuestionComment
score: 0
has text: @JacobBarnes Yes, I have tried printing budget_query after it is assigned a value. It appears to be identical to the desired query.
comment on: http://stackoverflow.com/q/47081291

http://stackoverflow.com/comment/81329998
type: Comment
has text: @AlMashudShishir The thing is, your code as it is might work in some cases, and fail in others. For example, the check for `data` you use could fail if the API doesn't return data, see the edit.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47190177

http://stackoverflow.com/comment/81177679
comment on: http://stackoverflow.com/a/47113501
score: 0
type: AnswerComment
has text: Thanks @MartijnPieters for the explanation and the patch - it works. Does it makes sense to try to get this into requests itself?
type: Comment

http://stackoverflow.com/comment/81209817
score: 0
has text: How are you making that call to your application?
comment on: http://stackoverflow.com/q/47122561
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81257347
type: Comment
comment on: http://stackoverflow.com/q/47153905
score: 0
has text: Strings are immutable. `var` will not change until you reassign the name.
type: QuestionComment

http://stackoverflow.com/q/47129819
answer count: 1
linked to: http://stackoverflow.com/q/11309739
has title: Cannot pick columns dtype after numpy hstack
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81212888
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81209593
tagged with: python
has answer: http://stackoverflow.com/a/47129922
favorite count: 0
has body: I want to choose column based on dtype. Examples: a = np.random.randn(10, 10).astype('float') b = np.random.randn(10, 10).astype('uint8') t=np.hstack((a,b)) t=pd.DataFrame(t) uints = t.select_dtypes(include=['uint8']).columns.tolist() The expected output from uints is: [10,11,12,13,14,15,16,17,18,19] The problem is when i join my original numpy data (a and b) together using hstack, dtype cannot be detected correctly as the code above returning [].
tagged with: pandas
score: 1

http://stackoverflow.com/comment/81342790
type: QuestionComment
score: 0
has text: What? Can you elaborate in the question itself?
type: Comment
comment on: http://stackoverflow.com/q/47196329

http://stackoverflow.com/q/47169712
has title: Feeding Samples to SVM in OpenCV
tagged with: python
tagged with: object-detection
tagged with: svm
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: I'm trying to train an SVM in opencv with a list of numpy images, but I keep getting the error TypeError: samples is not a numpy array, neither a scalar for the last line of code. The error is most likely from the way I setup my data in the samplePrep function. Here is my code. import os import glob import pandas as pd import xml.etree.ElementTree as ET import numpy as np import cv2 Preparing the Data class dataPrep: def import_from_XML(self, path): xml_list = [] for xml_file in glob.glob(path + '/*.xml'): tree = ET.parse(xml_file) root = tree.getroot() for member in root.findall('object'): value = (root.find('filename').text, int(root.find('size')[0].text), int(root.find('size')[1].text), member[0].text, int(member[4][0].text), int(member[4][1].text), int(member[4][2].text), int(member[4][3].text) ) xml_list.append(value) column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax'] xml_df = pd.DataFrame(xml_list, columns=column_name) return xml_df def samplePrep(self, xml_df, path, yscaling = 36, xscaling = 81): sample_list = [] label_list = [] with open(xml_df) as xml_df: i = 0 for xml in xml_df: if i == 0: i =+ 1 continue else: xml = list(xml.split(',')) filename = xml[0] width = int(xml[1]) height = int(xml[2]) if xml[3] == "Red_TL": label = 1 elif xml[3] == "Orange_TL": label = 2 elif xml[3] == "Green_TL": label = 3 label_list.append(np.array(label)) xmin = int(xml[4]) ymin = int(xml[5]) xmax = int(xml[6]) ymax = int(xml[7]) image = cv2.imread(path + "/" +filename) image = image[ymin:ymax, xmin:xmax] gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray_image = cv2.resize(gray_image, None,fx=xscaling/(xmax-xmin),fy=yscaling/(ymax-ymin), interpolation = cv2.INTER_NEAREST) np_image = np.array(gray_image) flat_image = np_image.ravel() sample_list.append(flat_image) i =+ 1 return sample_list, label_list SVM Wrapper class Learn: def __init__(self): self.est = cv2.ml.SVM_create() def train(self, X, y, params = dict(kernel_type=cv2.ml.SVM…
downvote count: 0
tagged with: opencv3.3
favorite count: 0
type: Question
tagged with: opencv

http://stackoverflow.com/comment/81255053
comment on: http://stackoverflow.com/a/47152531
score: 0
type: AnswerComment
has text: @timgeb No you are right, there is an access-class in everey line vty block.
type: Comment

http://stackoverflow.com/a/47114375
accepted answer of: http://stackoverflow.com/q/47114208
has comment: http://stackoverflow.com/comment/81179228
score: 3
has comment: http://stackoverflow.com/comment/81179777
answers question: http://stackoverflow.com/q/47114208
has body: You don't create a new matrix, but just give np.matrix another name matriz1. For numpy, you don't need loops, just use index slicing: v1 = np.matrix('1,2;3,4;2,6;4,5') distancia = len(v1) * 2 // 3 matriz1 = v1[:distancia].copy()
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81232888
type: Comment
comment on: http://stackoverflow.com/a/47132508
score: 0
type: AnswerComment
has text: Updated the Answer. Update the status please.

http://stackoverflow.com/comment/81132913
type: Comment
type: AnswerComment
has text: Thanks for taking your time to reply my question, I tried your first method and it returned ['axx', 'xaa', 'xzz', 'bbb', 'ccc'], while I want the result to be ['xaa', 'xzz', 'axx', 'bbb', 'ccc'] , which means that i want to sort them out by "x" but it should sort the second char normally as the sorted() func does
comment on: http://stackoverflow.com/a/47086283
score: 0

http://stackoverflow.com/comment/81239239
type: Comment
score: 0
type: AnswerComment
has text: yes but its about running the window or not via a command line Option like python my_app.py --console
comment on: http://stackoverflow.com/a/47126260

http://stackoverflow.com/q/47118233
has comment: http://stackoverflow.com/comment/81186627
upvote count: 1
has comment: http://stackoverflow.com/comment/81186532
downvote count: 1
tagged with: integer
favorite count: 0
tagged with: tuples
has comment: http://stackoverflow.com/comment/81186547
type: Question
tagged with: http://stackoverflow.com/tag/csv
has title: generator object result when converting tuple of string to tuple of int
tagged with: python
accepted answer: http://stackoverflow.com/a/47118324
answer count: 1
has body: I have a .csv file which contains x/y coordinates amongst other information. I need to extract the x/y coordinate information to feed into another package. That package accepts a list of tuples, of which the tuples contains integers) Eg. [(1,2), (3,4)] rdpList = [] with open ('test.csv', 'rb') as fp_in reader = csv.reader(fp_in, delimiter = ',') for row in reader: del row[0:4] #trimmming to column with x coordinates del row[2:] #trimming to column with y coordinate rdpList.append(tuple(row)) This get me close the result I need, however the data type inside the tuples are string. Eg [('1','2'),('3','4')] Trying rdpList = [] with open ('test.csv', 'rb') as fp_in reader = csv.reader(fp_in, delimiter = ',') for row in reader: del row[0:4] del row[2:] rdpList.append(tuple(int(x) for x in tup) for tup in row) gives me [&lt;generator object &lt;genexpr&gt; at 0x7f36452e1a00&gt;, &lt;generator object &lt;genexpr&gt; at 0x7f36452e1a50&gt;] Trying rdpList = [] with open ('test.csv', 'rb') as fp_in reader = csv.reader(fp_in, delimiter = ',') for row in reader: del row[0:4] del row[2:] for y in row: int(y) rdpList.append(tuple(row)) gives me ValueError: invalid literal for int() with base 10: 'x' Trying rdpList = [] with open ('test.csv', 'rb') as fp_in reader = csv.reader(fp_in, delimiter = ',') for row in reader: del row[0:4] del row[2:] rdpList.append(tuple(map(int, row.split(',')))) gives me AttributeError: 'list' object has no attribute 'split' How could I get to the result I want? The state of the .csv file is unimportant, only rdpList[] is important,
has answer: http://stackoverflow.com/a/47118324
has comment: http://stackoverflow.com/comment/81186668
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/47197982
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/47197960
type: Answer
has body: num = print("input no. :") print simply prints, it has no return value. You are looking for input: num = input("input no. :") As a side note, sum is a built-in function and it is not a good idea to overwrite it, so pick another name for sum.
upvote count: 2

http://stackoverflow.com/comment/81125597
comment on: http://stackoverflow.com/q/47087510
score: 0
type: Comment
has text: @DebanjanB All the values highlighted green/under the win tab (win odds) https://ibb.co/nQMOyG
type: QuestionComment

http://stackoverflow.com/a/47199216
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47198703
has body: There might be a way to solve this problem with itertools, but I think it can be done quick enough with a self-made permutation function: example_bases = [ "GAT", # options for first position "A", # options for second position "C", # ... "TC", "G", "CGA" ] def permutate(bases, results, depth=0, current_result=""): """Create permutations of a list of strings All resulting strings have the length len(bases), and there will be a total of mult([len(options) for option in bases]) total results, e.g.: ["abc", "de", "fghi"] -&gt; 3 * 2 * 4 -&gt; 24 :param bases: List of possible options for a base :param results: The object which will contain all valid results :param depth: Internal counter for current recursive depth :param current_result: Internal variable to keep track of progress """ if depth == len(bases): results.append(current_result) else: for base in bases[depth]: permutate(bases, results, depth+1, current_result+base) example_results = [] permutate(example_bases, example_results) for sequence in example_results: print(sequence) prints the 18 possible combinations for this particular example: GACTGC GACTGG GACTGA GACCGC GACCGG GACCGA AACTGC AACTGG AACTGA AACCGC AACCGG AACCGA TACTGC TACTGG TACTGA TACCGC TACCGG TACCGA If recursion is not your thing or you have a question about the code, please feel free to ask.
score: 1
has comment: http://stackoverflow.com/comment/81348867
type: Answer
has comment: http://stackoverflow.com/comment/81348474
has comment: http://stackoverflow.com/comment/81348463
has comment: http://stackoverflow.com/comment/81348393
answers question: http://stackoverflow.com/q/47198703
type: AcceptedAnswer

http://stackoverflow.com/q/47203746
answer count: 2
has comment: http://stackoverflow.com/comment/81359228
has answer: http://stackoverflow.com/a/50831645
score: 1
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/81360277
downvote count: 0
has comment: http://stackoverflow.com/comment/81367982
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81362818
has body: For some reason Openpyxl won't save the the xlsx file at the end of the program. I am trying to read measurments from a file, each line is a different measurement. I want to take them and write them to excel as to make using this data later on easier. Everything seems to work, but in the end the data isn't saved, if i create new file where the changes should be saved it will not be created. from openpyxl import load_workbook from openpyxl import Workbook wb = load_workbook(filename='Data_Base.xlsx') sheet = wb.worksheets[0] BS = [] Signal = [] with open('WifiData2.txt') as f: for line in f: y = int(line.split('|')[0].split(';')[3]) x = int(line.split('|')[0].split(';')[2]) floor = int(x = line.split('|')[0].split(';')[1]) data = line.split("|")[1].strip() measurements = data.split(";") for l in measurements: raw = l.split(" ") BSSID = raw[0] signal_strength = raw[1] print(signal_strength) BS.append(BSSID) Signal.append(signal_strength) for row_num in range(sheet.max_row): num = row_num if row_num &gt; 1: test_X = int(sheet.cell(row=row_num, column=4).value) test_Y = int(sheet.cell(row=row_num, column=3).value) test_floor = int(sheet.cell(row=row_num, column=2).value) if (test_X == x and test_Y == y and test_floor == floor): nr = nr + 1 if (nr &gt; 3): q = 1 if (q == 0): sheet.cell(row=sheet.max_row+1, column = 2, value = floor) sheet.cell(row=sheet.max_row + 1, column=3, value=x) sheet.cell(row=sheet.max_row + 1, column=4, value=y) sheet.cell(row=sheet.max_row + 1, column=2, value=sheet.max_row) for element in BS: nr = 0 for col in sheet.max_column: if BS[element] == sheet.cell(row=1, column=col).value: sheet.cell(row=sheet.max_row + 1, column=col, value=Signal[element]) nr = 1 if (nr == 0): sheet.cell(row=1, column=sheet.max_column+1, value=BS[element]) sheet.cell(row=sheet.max_row+1, column=sheet.max_column + 1, value=BS[element]) Signal.clear() BS.clear() wb.save('Data_Base1.xlsx') What is weird that if i save the workbook earlier it will create the file. Of cour…
has answer: http://stackoverflow.com/a/54835195
type: UnansweredQuestion
tagged with: python
has title: Openpyxl won't save file
tagged with: excel
has comment: http://stackoverflow.com/comment/81358206

http://stackoverflow.com/comment/81241955
score: 0
has text: During installation you can check option "Add Python to PATH". If for some reason you didn't checked it you have to add it manually. Check python in one of default installation dirs listed here: https://docs.python.org/3/using/windows.html
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47112902

http://stackoverflow.com/comment/81101610
type: QuestionComment
has text: OK, so your network is notwork. We cannot help you:(
type: Comment
comment on: http://stackoverflow.com/q/47069278
score: 0

http://stackoverflow.com/comment/81092554
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47072004
type: Comment
has text: I made a "collectstatic" and all my files are in the /static/ directory but in local there are not accessible :/

ta-lib
tags question: http://stackoverflow.com/q/47150440
tag name: ta-lib
tags question: http://stackoverflow.com/q/47150399
type: Tag

http://stackoverflow.com/q/47109980
tagged with: python
accepted answer: http://stackoverflow.com/a/47110033
has comment: http://stackoverflow.com/comment/81170221
has answer: http://stackoverflow.com/a/47110033
has comment: http://stackoverflow.com/comment/81170201
type: AnsweredQuestion
has title: How can i replace image masking in for-loop with logical indexing in python?
score: 1
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81170230
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy
tagged with: opencv
tagged with: indexing
has body: I am trying to track an object in a video by its color. Can i simplify this code: while True: ret, frame = cap.read() if not ret: break height, width, channel = frame.shape hue = cv2.cvtColor(frame, cv2.COLOR_RGB2HSV) for i in range(width): for j in range(height): if (hue[j, i, 0] &lt; 110 or hue[j, i, 0] &gt; 140): hue[j, i, 0] = 0 hue[j, i, 1] = 0 hue[j, i, 2] = 0
has comment: http://stackoverflow.com/comment/81170179

http://stackoverflow.com/a/47168932
downvote count: 0
has body: &lt;State:Alabama&gt; is just the string representation of the State. The list item itself is not a string, but of type us.states.State, as you saw two lines earlier. I did not try it, but according to the documentation of that package, to get a list of all the state names, a list comprehension like the following should work: state_names = [state.name for state in us.states.STATES_AND_TERRITORIES]
has comment: http://stackoverflow.com/comment/81287787
score: 5
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/47168881
answers question: http://stackoverflow.com/q/47168881
type: AcceptedAnswer

http://stackoverflow.com/q/47174683
tagged with: python
type: UnansweredQuestion
tagged with: qpushbutton
has comment: http://stackoverflow.com/comment/81299060
has title: pyqt5 QpushButton not working
tagged with: pyqt
score: 0
tagged with: user-interface
upvote count: 1
has comment: http://stackoverflow.com/comment/81299389
has body: I have this GUI written in python and utilizing PYQT5. I have a functioning version, but I now want to add a QpushButton that executes a method called add_Bladebox. This method adds a doublespinbox to the gui. The method works fine when I call it as part of the code, but when I try to execute it via the QpushButton, nothing happens. I know that without a loop, I could only ever do it once anyway(no position change implemented), but I can add that feature later. So any suggestion as to why it's not working is well appreciated. import sys from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QSizePolicy, QDoubleSpinBox, QLabel, QCheckBox, QMainWindow, QGridLayout) from PyQt5.QtCore import QCoreApplication import matplotlib from matplotlib.figure import Figure import numpy as np # Mark: QGridlayout importoitu, muttei käytetty from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as F igureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar class MainWindow(QWidget): def __init__(self): super().__init__() self.initUI() # Geometry of main window: self.setGeometry(200, 200, 1000, 1000) self.setWindowTitle('Simulation') # Set canvas: self.m = PlotCanvas(self, width=5, height=10) self.m.move(0,0) # Simulate button: sim = QPushButton('Simulate', self) sim.clicked.connect(self.simulate) sim.resize(sim.sizeHint()) sim.move(550, 700) # Quit button: qbtn = QPushButton('Quit', self) qbtn.clicked.connect(QCoreApplication.instance().quit) qbtn.resize(qbtn.sizeHint()) qbtn.move(800, 700) # Input box for x1: self.x1 = self.inputBox(800,80,10.0,0.01,0.2,2) self.x1_label = self.label(800,60,"x1") # Checkbox for sending data via email: self.send_box = QCheckBox('Send data’, self) self.send_box.move(550, 600) self.send_box.toggle() # Button for adding input boxes blade_button = QPushButton('Add', self) # THE PROBLEM IS THE NEXT LINE AS FAR AS I UNDERSTAND blade_button.clicked.connect(self.add_Bladebox) self.show() # Method…
downvote count: 1
favorite count: 0
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/81299447

http://stackoverflow.com/q/47209452
has title: Dictionary matching with wilcard word?
has answer: http://stackoverflow.com/a/47209513
score: 1
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47209515
answer count: 3
upvote count: 2
has answer: http://stackoverflow.com/a/47209515
has answer: http://stackoverflow.com/a/47209535
downvote count: 1
favorite count: 0
type: Question
has body: Suppose I have a python dictionary as follows: myDict = {"I need you to call the doctor please.": "I'm sorry, Dave. I'm afraid I can't do that."} However, if I have a variable called myName that is set equal to "XYZ" I want it to just output: "I'm sorry, XYZ. I'm afraid I can't do that." I am curious how to set up the dictionary values then?
possible better answer: http://stackoverflow.com/a/47209513

http://stackoverflow.com/comment/81079622
score: 0
type: Comment
type: AnswerComment
has text: Any loop you need to make it work :) probably a `while`.
comment on: http://stackoverflow.com/a/47065493

http://stackoverflow.com/comment/81191866
type: Comment
type: AnswerComment
has text: @ericj they do, but integers are immutable. And your second example is explicit slice assignment, of course `l` gets changed.
comment on: http://stackoverflow.com/a/47121071
score: 1

http://stackoverflow.com/comment/81161489
has text: looks like the return of `warning` should be `return category_warning(storm_category(speed))`
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47105391
type: Comment

http://stackoverflow.com/q/47217891
favorite count: 0
has comment: http://stackoverflow.com/comment/81651683
type: Question
downvote count: 2
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81390569
answer count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81389405
type: UnansweredQuestion
upvote count: 4
linked to: http://stackoverflow.com/q/13784201
score: 2
has comment: http://stackoverflow.com/comment/81400128
has title: How does matplotlib 1.5.3's tight_layout() interact with subplots_adjust()?
has comment: http://stackoverflow.com/comment/81387421
has body: I am using Matplotlib 1.5.3 in Python 3. I have a 3x3 subplot structure, or more generically an unspecified subplot structure that I'm trying to add a color bar to. As per this thread, an apparently good way to do this is to distort the subplots with subplots_adjust(), and add the colorbar as a new axes. Except, I have tight_layout() enabled, and that totally messes with things. Here is the function that, based on what I have read about subplots_adjust(), should work: import matplotlib.pyplot as plt def add_colorbar(last_im): SPACE = 0.2 # portion of final width reserved for colorbar and its padding PADDING = 0.5 # portion of reserved space reserved for padding fig = plt.gcf() # expand image to make room for colorbar w,h = fig.get_size_inches() fig.set_size_inches((w/(1-SPACE), h)) # shrink right side of subplot to create empty space on # right hand side fig.subplots_adjust(right=0.9*(1-SPACE)) # 0.9 being the original value # create colorbar axes, place in empty space with padding cbax = fig.add_axes([1-SPACE*(1-PADDING/2), 0.15, SPACE*(1-PADDING), 0.7]) fig.colorbar(last_im, cax=cbax) But the subplot configuration is kept centered, so this creates basically no space, and the color bar is drawn straight over the subplots. I have also tried using plt.tight_layout(rect=[0, 0, 1-SPACE, 1]) instead of subplots_adjust(), but this seems to do even less than the subplots_adjust() statement, and messes with basically just the sizes of the individual subplots. It seems neither of these functions work as advertised for me. What am I missing? Faulty plot shown below, with plot titles censored to be on the safe side. Alternatively, I'd be fine with a solution for adding a colorbar that will generically work for a figure with any subplot configuration, but I'd prefer to understand the baffling behavior of subplots_adjust() and the tight_layout() rect. EDIT: Problem ended up being that I made tight_layout() calls erroneously after running add_colorbar(). Correct behavior is obse…

http://stackoverflow.com/comment/81162769
has text: No, you _don't_ want to mount the disk image in order to get to the bytes you want. BTW, you can do this sort of thing in Python 2 or Python 3, but IMHO it's less confusing in Python 3, since it makes a clear distinction between text and bytes; also, the Python 3 `bytes` type has several useful methods that are more convenient than using `binascii`.
type: QuestionComment
comment on: http://stackoverflow.com/q/47105363
type: Comment
score: 0

http://stackoverflow.com/a/47094136
score: 1
has body: np.where is quicke and simple solution. In [47]: df['A'] = np.where(np.isnan(df['A']) &amp; df['B'] == 0, 3, df['A']) In [48]: df Out[48]: A B 0 3.0 0 1 3.0 0 2 3.0 0 3 NaN 1 4 NaN 1
answers question: http://stackoverflow.com/q/47092567
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47147951
score: 1
upvote count: 1
has body: Is there an easy way to read hdf5 file remotely (through ssh) within the Python. As far as I know default h5py module does not allow this. What's the easiest way of doing this? PS. Copying is not an option, I have terabytes of data.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81251195
tagged with: h5py
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47149150
has title: hdf5 over ssh in Python
has comment: http://stackoverflow.com/comment/81246195
tagged with: ssh
tagged with: python
has comment: http://stackoverflow.com/comment/81271772
answer count: 1
downvote count: 0
tagged with: hdf5

http://stackoverflow.com/q/47168312
score: 2
tagged with: arrays
has comment: http://stackoverflow.com/comment/81288893
downvote count: 0
tagged with: sorting
tagged with: eigenvalue
favorite count: 0
possible better answer: http://stackoverflow.com/a/61621472
type: Question
has title: Sorting eigenvalues and eigenvectors
accepted answer: http://stackoverflow.com/a/47171243
tagged with: python
has comment: http://stackoverflow.com/comment/81286796
has answer: http://stackoverflow.com/a/47171243
has comment: http://stackoverflow.com/comment/81294976
has answer: http://stackoverflow.com/a/73771721
linked to: http://stackoverflow.com/q/43194671
has comment: http://stackoverflow.com/comment/81286685
tagged with: numpy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/61621472
answer count: 3
upvote count: 2
has body: The function numpy.linalg.eig supports calculating the eigenvalues and eigenvectors of a stack of matrices at once. In my case, I have 500000 2x2 matrices, organised in a 1000x500x2x2 numpy array, and calling numpy.linalg.eig on this returns 1000x500x2 eigenvalues and 1000x500x2 (2-component) eigenvectors. Just what I need. However, I need the eigenvalues and eigenvectors to be sorted. I tried to sort the eigenvalues with vals, vecs = np.linalg.eig(array) vals = vals[np.argsort(vals, axis = -1)] yet this returns an array of shape 1000x500x2x500x2, instead of 1000x500x2, which I would expect. Is there a simple way to fix this, without resorting to looping over the array? And is there a similarly simple way to sort the eigenvectors according to the eigenvalues? This question has sort of been answered here: Sorted eigenvalues and eigenvectors on a grid but the answer is tailored to a (another) special case, and not very well explained, and I haven't been successful in adapting it to my case. I considered posting a comment to that answer, asking for details, but I am currently at 49 reputation points, and you need 50 to comment.

http://stackoverflow.com/q/47087096
has comment: http://stackoverflow.com/comment/81125295
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81124041
score: 0
has comment: http://stackoverflow.com/comment/81125376
answer count: 0
has comment: http://stackoverflow.com/comment/81125449
has body: On running the following code: plt.fill_between(df.index.unique(), min_vals, max_vals) I get the error: *** TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' df.index.unique() is DatetimeIndex(['2005-01-01', '2005-01-02', '2005-01-03', '2005-01-04', '2005-01-05', '2005-01-06', '2005-01-07', '2005-01-08', '2005-01-09', '2005-01-10', ... '2005-07-05', '2005-07-06', '2005-07-07', '2005-07-08', '2005-07-09', '2005-07-10', '2005-07-11', '2005-07-12', '2005-07-13', '2005-07-14'], dtype='datetime64[ns]', name='datetime', length=195, freq=None) and min_vals and max_vals are numpy arrays of same length as df.index.unique(). Sample: array([ 118.15219205, 118.09140844, 118.05368241, 118.01825058, 117.9923672 , 117.97512 , 117.98164725, 117.96102018, 117.93014226, 117.89721839]) I do not get this error with pandas version 0.20.3 but I do get this error with pandas version 0.21. How to fix this?
type: Question
tagged with: pandas
has title: Plotting bug with pandas 0.21

http://stackoverflow.com/a/47211183
score: 3
type: Answer
upvote count: 3
downvote count: 0
has body: To explain what happens here: QuerySet methods like filter(), exclude(), order_by() etc. return a QuerySet, that is why they can be chained. What you tried first is trying to patch the methods as if they would be in a package hierarchy. What you ended up doing is not patching the method but mocking the return value for each chained method, which is how it is done. Unfortunately there is not much documentation on this. When I ran into this problem I had some stackoverflow answers that helped me, but I can't seem to find them again. Similar questions (where the answers don't really provide an explaination): Django ORM - mock values().filter() chain Mocking a Django Queryset in order to test a function that takes a queryset There are libraries out there that might help you: mock-django provides an ORM mocking class. Their approach to mocking QuerySet methods is quite interesting. What I personally found very useful for testing Django models is Model Mommy, because it helps you to create easy mocks of models.
answers question: http://stackoverflow.com/q/47097803

http://stackoverflow.com/a/47208229
type: Answer
answers question: http://stackoverflow.com/q/47208095
score: -1
has body: for g in group: exec(g + ' = []') That would create lists named by the values in group. Be very cautious using 'exec`. Make sure it is YOUR code in the exec.
upvote count: 0
has comment: http://stackoverflow.com/comment/81376939
downvote count: 1

http://stackoverflow.com/comment/81172873
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47111471
has text: Thank you! The turtle functionality is there now!!!!!! BUT....it always draws a square, and doesn't recognise the input parameters.
type: Comment

http://stackoverflow.com/q/47080219
has answer: http://stackoverflow.com/a/47080395
tagged with: http://stackoverflow.com/tag/json
downvote count: 2
answer count: 1
upvote count: 1
has title: Python script for create multiple JSON files with predefined data
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: ios
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81109506
tagged with: macos-sierra
accepted answer: http://stackoverflow.com/a/47080395
type: AnsweredQuestion
has body: I'm new to Python, I have simple requirement in my iOS project. I want to create multiple JSON files with some fix data in each file. I googled some articles but didn't found exactly what I wish to do. So how do I achieve this? Following things I'm able to do this but not giving expected output: I have txt file which has list of 100 names, This text file I have kept in folder which has script file also, Now I want to create txt file for each name in the list in the same folder for that I have did something like this: titles = open("title.txt",'r') for lines in titles: output = open((lines.strip())+'.json','w') output.write(lines.strip('\n')) output.close() titles.close() This script creating files of mentioned names successfully. Now I want to write predefined some fix data in each file. This is my sample json data, I want to copy this data into each file. How do I achieve this. { "product": "Live JSON generator", "version": 3.1, "releaseDate": "2014-06-25T00:00:00.000Z", "demo": true, "person": { "id": 12345, "name": "John Doe", "phones": { "home": "800-123-4567", "mobile": "877-123-1234" }, "email": [ "jd@example.com", "jd@example.org" ], "dateOfBirth": "1980-01-02T00:00:00.000Z", "registered": true, "emergencyContacts": [ { "name": "Jane Doe", "phone": "888-555-1212", "relationship": "spouse" }, { "name": "Justin Doe", "phone": "877-123-1212", "relationship": "parent" } ] } }

http://stackoverflow.com/q/47154508
type: Question
tagged with: cx-freeze
accepted answer: http://stackoverflow.com/a/47155561
score: 1
has title: cx_freeze executable not working when I run through cmd in python
tagged with: python
tagged with: cmd
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/81260059
tagged with: exe
has comment: http://stackoverflow.com/comment/81260444
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/47155561
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81260477
has body: Hi I have converted my script to exe using cx_freeze but when I am running its not working as expected My script:cmd.py import sys import pandas as pd import numpy as np for arg in sys.argv: print (arg) print ("Hello World!") my setup.py having both the scripts in same folder import sys,os from cx_Freeze import setup, Executable os.environ['TCL_LIBRARY'] = r'C:\ProgramData\Anaconda3\tcl\tcl8.6' os.environ['TK_LIBRARY'] = r'C:\ProgramData\Anaconda3\tcl\tk8.6' setup( name = "On Dijkstra's Algorithm", version = "3.1", description = "A Dijkstra's Algorithm help tool.", executables = [Executable("cmd.py", base = "Win32GUI")]) A folder named build is created with cmd.exe but when I am running the below line in cmd cmd one two nothing is happening, Please help
favorite count: 0

http://stackoverflow.com/comment/81380058
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47215275
type: QuestionComment
has text: Posting an image is bad juju. Are we supposed to retype it to try it??? cut-n-paste!

http://stackoverflow.com/comment/81254167
type: Comment
type: QuestionComment
score: 0
has text: Thanks! Now, either by adding `print` calls or by using a debugger, figure out what the arguments are to `savgol_filter()`. That is, what are the values of `x`, `scale`, `PO` and `dy[0]` that trigger the error?
comment on: http://stackoverflow.com/q/47151464

http://stackoverflow.com/a/47067965
answers question: http://stackoverflow.com/q/47067601
score: 0
has body: I believe your trouble is on line 6: now = datetime.date It looks like you're trying to create a datetime object with the current time, but that's not what you're doing with that line. I believe you want now = datetime.datetime.now() there instead.
type: Answer

http://stackoverflow.com/q/47142496
score: 2
has comment: http://stackoverflow.com/comment/81240087
has answer: http://stackoverflow.com/a/47143789
answer count: 1
has body: I would like to define a bounded version of a continuous random variable distribution (say, an exponential, but I might want to use others as well). The bounds are 0 and 1. I would like to draw random variates (as done by scipy.stats.rv_continuous.rvs), use the ppf (percentage point function) (as done by scipy.stats.rv_continuous.ppf), and possibly use the cdf (cumulative density function) (as done by scipy.stats.rv_continuous.cdf) Possible approaches I can think of: Getting random variates in an ad hoc way is not difficult import scipy.stats d = scipy.stats.expon(0, 3/10.) # an exponential distribution as an example rv = d.rvs(size=target_number_of_rv) rv = rv[0=&lt;rv] rv = rv[rv&lt;=1] while len(rv) &lt; target_number_of_rv: rv += d.rvs(1) rv = rv[0=&lt;rv] rv = rv[rv&lt;=1] but 1) this is non-generic and potentially error-prone and 2) it does not help with the ppf or cdf. Subclassing scipy.stats.rv_continuous, as is done here and here. Thereby, the ppf of scipy.stats.rv_continuous can be used. The drawback is that it requires the pdf (not just a pre-defined rv_continuous object or the pdf of the unbounded distribution and the bounds), and if this is wrong, cdf and ppf and everything else will be wrong as well. Designing a class that cares for applying the bounds to the rv generation and for correcting the value of the ppf obtained from the unbounded object in scipy.stats. A drawback is that this is non-generic and error-prone as well and that it may be difficult to correct the ppf. My feeling is that the value of the cdf of the unbounded distribution could be scaled by what share of probability mass is out of the bounds (in total, lower and upper), but I may be wrong. That would be for lower and upper bounds l and u and any valid quantile x (with l&lt;=x&lt;=u): (cdf(x)-cdf(l))/(cdf(u)-cdf(l)). Obtaining the ppf would, however, require to invert the resulting function. My feeling is that there might be a better and more generic way to do this. Is there? Maybe wi…
tagged with: scipy
has title: How to obtain a python scipy-type continuous rv distribution object that is bounded?
favorite count: 0
type: Question
tagged with: distribution
upvote count: 2
accepted answer: http://stackoverflow.com/a/47143789
downvote count: 0
linked to: http://stackoverflow.com/q/17093318
tagged with: python
tagged with: statistics
type: AnsweredQuestion

http://stackoverflow.com/comment/81554355
has text: Oh and I get the `exec format error` on the `armf/python` no matter what command it should execute. Try to start a container with bash running? Nope, `exec format error`. Basically that image is broken lol
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47280363
score: 0

http://stackoverflow.com/comment/81171334
comment on: http://stackoverflow.com/q/47110540
has text: Before scraping the page have a look at its source code. Here you would notice that the table is generated dynamically from a JSON object stored in a ` ` block at the end of the HTML document.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81267063
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47140338
type: QuestionComment
has text: No the issue was in the Content-Type.

sctp
tags question: http://stackoverflow.com/q/47152301
tag name: sctp
type: Tag

http://stackoverflow.com/q/47142870
has title: Is it a good practice to pass db connection as parameter to methods?
has comment: http://stackoverflow.com/comment/81237667
tagged with: python
has comment: http://stackoverflow.com/comment/81238432
tagged with: sqlalchemy
favorite count: 0
score: 2
upvote count: 2
tagged with: database-connection
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81238279
answer count: 1
has comment: http://stackoverflow.com/comment/81237296
has comment: http://stackoverflow.com/comment/81237716
type: Question
has answer: http://stackoverflow.com/a/47144880
has comment: http://stackoverflow.com/comment/81235971
tagged with: postgresql
has comment: http://stackoverflow.com/comment/81236023
has comment: http://stackoverflow.com/comment/81237001
has comment: http://stackoverflow.com/comment/81238208
has comment: http://stackoverflow.com/comment/81236049
has body: I am writing Python application to operate on Postgres database with SQLAlchemy. Specified the database information in a settings.py DATABASE = { 'drivername': 'postgres', 'host': 'xyz.com', 'port': '5432', 'username': 'user', 'password': 'pass', 'database': 'db_dev' } Then I created a db_connection.py with a method to create a connection. from sqlalchemy import * from sqlalchemy.engine.url import URL from . import settings def get_engine(): return create_engine(URL(**settings.DATABASE)) I want to have another module db_ops.py that has all the database operation func1, func2 methods and call them in the main application module engine = db.connection.get_engine() db_ops.func1() db_ops.func2() And that means I will need to pass engine as a parameter to these methods. func1(engine) func2(engine) Somehow I don't like the idea of making db connection as method parameter. Is there a better way to do it?
has comment: http://stackoverflow.com/comment/81237324

http://stackoverflow.com/a/47110082
answers question: http://stackoverflow.com/q/47109931
type: Answer
upvote count: 13
has comment: http://stackoverflow.com/comment/81354181
has comment: http://stackoverflow.com/comment/81171331
type: AcceptedAnswer
downvote count: 0
score: 13
has comment: http://stackoverflow.com/comment/81170385
has comment: http://stackoverflow.com/comment/81171230
has comment: http://stackoverflow.com/comment/81354263
accepted answer of: http://stackoverflow.com/q/47109931
has body: I think the best is create dictionary of DataFrames: d = {} for i in range(12,0,-1): d['t' + str(i)] = df.shift(i).add_suffix('_t' + str(i)) If need specify columns first: d = {} cols = ['column1','column2'] for i in range(12,0,-1): d['t' + str(i)] = df[cols].shift(i).add_suffix('_t' + str(i)) dict comprehension solution: d = {'t' + str(i): df.shift(i).add_suffix('_t' + str(i)) for i in range(12,0,-1)} print (d['t10']) column1_t10 column2_t10 0 NaN NaN 1 NaN NaN 2 NaN NaN 3 NaN NaN 4 NaN NaN 5 NaN NaN 6 NaN NaN 7 NaN NaN 8 NaN NaN 9 NaN NaN 10 0.0 19.0 11 1.0 18.0 12 2.0 17.0 13 3.0 16.0 14 4.0 15.0 15 5.0 14.0 16 6.0 13.0 17 7.0 12.0 18 8.0 11.0 19 9.0 10.0 EDIT: Is it possible by globals, but much better is dictionary: d = {} cols = ['column1','column2'] for i in range(12,0,-1): globals()['df' + str(i)] = df[cols].shift(i).add_suffix('_t' + str(i)) print (df10) column1_t10 column2_t10 0 NaN NaN 1 NaN NaN 2 NaN NaN 3 NaN NaN 4 NaN NaN 5 NaN NaN 6 NaN NaN 7 NaN NaN 8 NaN NaN 9 NaN NaN 10 0.0 19.0 11 1.0 18.0 12 2.0 17.0 13 3.0 16.0 14 4.0 15.0 15 5.0 14.0 16 6.0 13.0 17 7.0 12.0 18 8.0 11.0 19 9.0 10.0
has comment: http://stackoverflow.com/comment/81170367

http://stackoverflow.com/a/47205851
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47205740
type: Answer
upvote count: 4
has body: You can use heapq.nsmallest, and specify the second element in the tuple as the comparison key: from heapq import nsmallest lst = [('p1',12.5),('p2',3),('p4',1),('p5',16),('p6',15)] nsmallest(3, lst, key=lambda x: x[1]) # [('p4', 1), ('p2', 3), ('p1', 12.5)]
score: 4
downvote count: 0
answers question: http://stackoverflow.com/q/47205740

http://stackoverflow.com/comment/81261996
has text: @JimFasarakisHilliard its a good practice to comment for improvement. Who said people dont' comment. its just your perception I think.
type: AnswerComment
comment on: http://stackoverflow.com/a/47156307
score: 1
type: Comment

http://stackoverflow.com/q/47105228
answer count: 1
score: 6
has body: I've read the blank line section in pep8. It says that we should surround top level functions with blank lines, but it doesn't say anything about if statements. I've done some digging on what a top level is in Python and it seems to be anything that's not indented. Does this mean that if statements should be surrounded by blank lines? Are if statements considered functions? I can't find anything on stack overflow about this.
has title: Should if statements be surrounded by blank lines to follow PEP8?
has comment: http://stackoverflow.com/comment/91152677
favorite count: 0
has comment: http://stackoverflow.com/comment/81161038
has comment: http://stackoverflow.com/comment/81161089
type: Question
has comment: http://stackoverflow.com/comment/81161208
tagged with: python
accepted answer: http://stackoverflow.com/a/47105335
upvote count: 16
has answer: http://stackoverflow.com/a/47105335
downvote count: 10
has comment: http://stackoverflow.com/comment/85411203
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85422074
has comment: http://stackoverflow.com/comment/81161295
tagged with: pep8

http://stackoverflow.com/a/47102751
answers question: http://stackoverflow.com/q/47102613
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: First, you do not have a lit, that is a dict, so you can access z by using coordinates as key: my_dict = {(x,y): z, (x,y):z...} my_dict[(x, y)] In a for loop: for probability in my_dict.values(): print(probability) I recommend you do not use the name list for this cause it is a built-in

http://stackoverflow.com/comment/81195649
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47121919
has text: That's not me. Appreciate the example. Upvoted for the addition.
score: 0

cntk
tags question: http://stackoverflow.com/q/47210102
tag name: cntk
tags question: http://stackoverflow.com/q/47118723
type: Tag

http://stackoverflow.com/comment/81273547
has text: Hello @Ctx, I have inserted 'fflush(stdout)' after printf() in C program and also, changed the mydll.printFunc.restype to None. Unfortunately, I still see the output as an integer i.e. 26. Any other suggestions please ?
type: AnswerComment
comment on: http://stackoverflow.com/a/47161318
type: Comment
score: 0

http://stackoverflow.com/q/47214029
possible better answer: http://stackoverflow.com/a/47214272
downvote count: 0
has answer: http://stackoverflow.com/a/47214767
has comment: http://stackoverflow.com/comment/81377678
has answer: http://stackoverflow.com/a/47214272
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/47233906
has comment: http://stackoverflow.com/comment/81378073
has comment: http://stackoverflow.com/comment/81377650
has comment: http://stackoverflow.com/comment/81377689
accepted answer: http://stackoverflow.com/a/47214574
tagged with: python
has body: I have a movie script, "The Departed", and I want to parse out the data by names of the character. The format of the text file has no delimiters, but it will have the characters name BILLY in all caps. The only identifier I have are the names that are in all caps. I read through regex and other threads, but I am unsure where to start..... file = open("Departed.txt","r") data = file.read() pattern = re.compile(r'BILLY') matches = pattern.finditer(data) for match in matches: print(match) This returns the whole script still... https://pastebin.com/226VzLWu
has answer: http://stackoverflow.com/a/47214574
has title: Parsing Text File with no Delimiters in Python
type: AnsweredQuestion
score: 2
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/81377513

http://stackoverflow.com/a/47160202
answers question: http://stackoverflow.com/q/47160158
downvote count: 0
upvote count: 1
has body: Make sure you initialize both vars before creating the client from coinbase.wallet.client import Client api_key = 'my api key here' api_secret = 'my api secret' client = Client(api_key, api_secret) The error specifically tells you that api_key is not defined
score: 1
type: Answer

pip
tags question: http://stackoverflow.com/q/47118488
tags question: http://stackoverflow.com/q/47149607
tags question: http://stackoverflow.com/q/47118100
tags question: http://stackoverflow.com/q/47197766
tags question: http://stackoverflow.com/q/47179822
tags question: http://stackoverflow.com/q/47222422
tags question: http://stackoverflow.com/q/47193441
tags question: http://stackoverflow.com/q/47194257
tags question: http://stackoverflow.com/q/47197083
tags question: http://stackoverflow.com/q/47128653
tags question: http://stackoverflow.com/q/47140445
tags question: http://stackoverflow.com/q/47201417
tags question: http://stackoverflow.com/q/47071256
tags question: http://stackoverflow.com/q/47110762
tags question: http://stackoverflow.com/q/47210058
tags question: http://stackoverflow.com/q/47169404
type: Tag
tags question: http://stackoverflow.com/q/47127178
tags question: http://stackoverflow.com/q/47175638
tags question: http://stackoverflow.com/q/47212197
tags question: http://stackoverflow.com/q/47081168
tags question: http://stackoverflow.com/q/47208409
tags question: http://stackoverflow.com/q/47215381
tags question: http://stackoverflow.com/q/47175857
tags question: http://stackoverflow.com/q/47098185
tags question: http://stackoverflow.com/q/47140166
tags question: http://stackoverflow.com/q/47124348
tags question: http://stackoverflow.com/q/47087357
tags question: http://stackoverflow.com/q/47086702
tags question: http://stackoverflow.com/q/47180075
tags question: http://stackoverflow.com/q/47155596
tags question: http://stackoverflow.com/q/47223151
tags question: http://stackoverflow.com/q/47164979
tag name: pip
tags question: http://stackoverflow.com/q/47203530
tags question: http://stackoverflow.com/q/47185393
tags question: http://stackoverflow.com/q/47114190
tags question: http://stackoverflow.com/q/47091061
tags question: http://stackoverflow.com/q/47119885
tags question: http://stackoverflow.com/q/47079385
tags question: http://stackoverflow.com/q/47086999
tags question: http://stackoverflow.com/q/47141625
tags question: http://stackoverflow.com/q/47143286

http://stackoverflow.com/comment/81121677
score: 0
type: Comment
type: QuestionComment
has text: what have you tried so far and why isn't that working?
comment on: http://stackoverflow.com/q/47086002

http://stackoverflow.com/comment/81166932
comment on: http://stackoverflow.com/q/47108076
score: 1
has text: The property you use in the path to normalize isn't included in the result, it's used to find the records to normalize.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81233770
score: 3
has text: `melt` is now a first class method. So, your question really has no answer except for, in your version of pandas, they hadn't got around to implementing it yet.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47141916

http://stackoverflow.com/comment/81379546
has text: in time order, the 3 assignments will be at bottom or at the top.So it's esay to copy them all at a single operation.
type: Comment
comment on: http://stackoverflow.com/q/47215035
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81509754
comment on: http://stackoverflow.com/a/47202999
type: Comment
score: 0
type: AnswerComment
has text: Do you get the error with `docker build` or `docker run`? With `docker run` it depends on where the script is in the container, not the host. With `docker build` you need to execute the command inside the directory your script lies in.

http://stackoverflow.com/q/47106490
has title: Removing quotes from elements in python list
has answer: http://stackoverflow.com/a/47106544
possible better answer: http://stackoverflow.com/a/47106606
type: Question
has answer: http://stackoverflow.com/a/47106606
type: AnsweredQuestion
score: 0
tagged with: list
tagged with: python
has comment: http://stackoverflow.com/comment/81163577
has comment: http://stackoverflow.com/comment/81163575
accepted answer: http://stackoverflow.com/a/47106544
has body: I have a python list that looks like alist = ['4', '1.6', 'na', '2e-6', '42']. If i want to remove the quotes from this and make it look like [4, 1.6, na, 2e-6, 42], normally i use the following code : alist = [float(x) if type(x) is str else None for x in alist] But this time, as I have the string 'na' as one of the elements in the list, this line of code will not work. Is there an elegant way to do this in python?
answer count: 2
has comment: http://stackoverflow.com/comment/81163519
has comment: http://stackoverflow.com/comment/81163580
has comment: http://stackoverflow.com/comment/81163535

http://stackoverflow.com/a/47105739
answers question: http://stackoverflow.com/q/47105694
downvote count: 0
upvote count: 1
has body: If you want to include 100, in the range, you need an upper limit just above: import random for count in range(5): price = float(random.randrange(1, 101)) print (price) Output: 6.0 10.0 6.0 10.0 3.0
type: AcceptedAnswer
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47105694

http://stackoverflow.com/q/47204715
has answer: http://stackoverflow.com/a/47273983
downvote count: 0
answer count: 1
has body: This question pertains to Python 3 statsmodels and its general linear model class. Whenever I have an array of values for my endogenous variable such that the values are more than an order of magnitude apart, the GLM does not converge and it throws an exception. Here is a coded example of what I mean. import pandas as pd import pyarrow.parquet as pq import numpy as np import statsmodels.api as sm import matplotlib.pyplot as plt import math col = ["a", \ "b", \ "c", \ "d", \ "e", \ "f", \ "g", \ "h"] df = pd.DataFrame(np.random.randint(low=1, high=100, size=(20, 8)), columns=col) df["a"] = [0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01] df2 = pd.DataFrame(np.random.randint(low=1, high=100, size=(20, 8)), columns=col) df2["a"] = np.random.randint(low=10000, high=99999, size=(20, 1)) df3 = pd.DataFrame(np.random.randint(low=1, high=100, size=(20, 8)), columns=col) df3["a"] = [0.01, \ 0.01, \ 0.01, \ 0.01, \ 0.01, \ 0.01, \ np.random.randint(low=10000, high=99999), \ 0.01, \ 0.01, \ 0.01, \ 0.01, \ 0.01, \ np.random.randint(low=10000, high=99999), \ 0.01, \ 0.01, \ 0.01, \ 0.01, \ 0.01, \ 0.01, \ 0.01] try: actual = df"a" fml1 = "a ~ log(b) + c + d + e + f + g" data1 = df"b", "c", "d", "e", "f", "g" model = sm.GLM(actual, data1, formula=fml1, family=sm.families.Tweedie(link_power=1.1)).fit() model_pred = model.predict() print("SUCCESS") except: print("FAILURE") try: actual = df2"a" fml1 = "a ~ log(b) + c + d + e + f + g" data1 = df2"b", "c", "d", "e", "f", "g" model = sm.GLM(actual, data1, formula=fml1, family=sm.families.Tweedie(link_power=1.1)).fit() model_pred = model.predict() print("SUCCESS") except: print("FAILURE") try: actual = df3"a" fml1 = "a ~ log(b) + c + d + e + f + g" data1 = df3"b", "c", "d", "e", "f", "g" model = sm.GLM(actual, data1, formula=fml1, family=sm.families.Tweedie(link_power=1.1)).fit() model_pred = model.predict() print("SUCCESS") except: print("F…
favorite count: 0
type: AnsweredQuestion
tagged with: statsmodels
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/47273983
tagged with: pandas
tagged with: matplotlib
tagged with: python
has title: How do I fix this convergence error? Python 3 statsmodels
type: Question
tagged with: numpy

http://stackoverflow.com/a/47220565
downvote count: 0
has body: Here's a slightly modified data format. With it, it becomes easier to show moves and display the whole grid: chessBoard = [["_"] * 8 for i in range(8)] moves = [(1, 2),(1, 4),(5, 2),(5, 4),(2, 1),(2, 5),(4, 1),(4, 5)] # Add a symbol on the grid for every move for i, j in moves: chessBoard[i][j] = "X" index_to_letter = 'abcdefgh' # Display board with row numbers for i, row in enumerate(chessBoard): print(' | '.join(row) + ' ' + index_to_letter[i]) It outputs: _ | _ | _ | _ | _ | _ | _ | _ a _ | _ | X | _ | X | _ | _ | _ b _ | X | _ | _ | _ | X | _ | _ c _ | _ | _ | _ | _ | _ | _ | _ d _ | X | _ | _ | _ | X | _ | _ e _ | _ | X | _ | X | _ | _ | _ f _ | _ | _ | _ | _ | _ | _ | _ g _ | _ | _ | _ | _ | _ | _ | _ h
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47220380
answers question: http://stackoverflow.com/q/47220380
score: 1
type: AcceptedAnswer

generator
type: Tag
tags question: http://stackoverflow.com/q/47166701
tags question: http://stackoverflow.com/q/47142467
tags question: http://stackoverflow.com/q/47162981
tag name: generator
tags question: http://stackoverflow.com/q/47087060
tags question: http://stackoverflow.com/q/47146905
tags question: http://stackoverflow.com/q/47080479
tags question: http://stackoverflow.com/q/47084046
tags question: http://stackoverflow.com/q/47075370
tags question: http://stackoverflow.com/q/47070119

http://stackoverflow.com/comment/81225834
has text: What do you want it to look like?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47138276
type: QuestionComment

http://stackoverflow.com/comment/81258305
has text: As I said, reassign. `df = obj.df` or `df = obj.edit()` if you make `obj.edit` `return` the dataframe.
comment on: http://stackoverflow.com/a/47154351
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47126859
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81210612
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/47207817
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81203951
has body: I have a pandas.dataframe column, where my first four values should be filled into other cells upto 200 lines below in the same order in the same column. I can do it via loop (for) but it does not fit for purpose, since i will do lots of this loops and will take significant CPU time. I am looking for something much more efficient (may be like append or concat?). Hope my question is clear! This is my input: index y 0 0 1 5 2 5 3 0 4 NaN 5 NaN 6 NaN 7 NaN 8 NaN ... 1456 NaN This is what i want to get: index y 0 0 1 5 2 5 3 0 4 0 5 5 6 5 7 0 8 0 ... 1456 NaN Thank You for help! P.S. Thanks for comments on updating question!!!
downvote count: 2
answer count: 1
has title: Fill pandas dataframe cells with specific values
accepted answer: http://stackoverflow.com/a/47207817
favorite count: 0

http://stackoverflow.com/q/47195184
linked to: http://stackoverflow.com/q/47186590
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 1
has body: I've written a script in python in combination with selenium to parse some information from a webpage. There are few store names along with their links on that webpage. If I click on any of the links, a card-like box pops up containing information. My intention is to click on each link and parse information from that card. However, when I execute my script, it does click on each link and a box-like container pops up with each click but I can't parse information from it. Looks like i have defined the correct selectors but still no luck. This is the follow up question of this thread: Click Here Link to be used in the below script: The link This is the full code: from selenium import webdriver ; import time from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() wait = WebDriverWait(driver, 10) driver.get("use above link") wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "#store-locator-iframe"))) while True: try: for item in wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "#addresses_list li a:not(.directions-link)"))): driver.execute_script('arguments[0].scrollIntoView();', item) item.click() time.sleep(4) except: break for elem in wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".gm-style-iw .gm_popup"))): name = elem.find_element_by_class_name("gm_name").text phone = elem.find_element_by_class_name("gm_phone").text print(name,phone) driver.quit() Elements within the selector exist: Adel Outfitters 1221 W 4th St Adel, Georgia 31620 United States P: 229-896-7105 adeloutfitters@yahoo.com https://www.facebook.com/pages/Adel-Outfitters/132735763434461 Directions➲ View on Google Maps
tagged with: selenium
tagged with: web-scraping
has answer: http://stackoverflow.com/a/47195362
accepted answer: http://stackoverflow.com/a/47195362
tagged with: selenium-webdriver
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
has title: Unable to parse information from a box like container activated upon each click
tagged with: python

http://stackoverflow.com/q/47125591
score: 4
tagged with: design-patterns
has comment: http://stackoverflow.com/comment/81201520
tagged with: proxy
has answer: http://stackoverflow.com/a/47126104
has title: How does the `super` class implement the proxy design pattern?
linked to: http://stackoverflow.com/q/46517113
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81201560
has comment: http://stackoverflow.com/comment/81201453
has comment: http://stackoverflow.com/comment/81201544
has comment: http://stackoverflow.com/comment/81201423
has comment: http://stackoverflow.com/comment/81201505
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/44991579
upvote count: 5
type: UnansweredQuestion
has body: From Python in a Nutshell super(cls,obj) returns a super-object of object obj (which must be an instance of class cls or of any subclass of cls), suitable for calling superclass methods. From https://docs.python.org/3.6/library/functions.html#super super([type[, object-or-type]]) returns a proxy object that delegates method calls to a parent or sibling class of type. A comment by Martijn Pieters says that the return object of super(cls,obj) is an example of the proxy design pattern. In Design Pattern by Gamma et al, the proxy design pattern is implemented by inheriting the class of the subject of proxy. But I found that super class is inherited only from object, and not from the subject of proxy, which is "a parent or sibling class of type". So I wonder how the super class implement the proxy design pattern? By duck typing? Thanks.
tagged with: python

http://stackoverflow.com/a/47159543
upvote count: 2
answers question: http://stackoverflow.com/q/47153868
downvote count: 0
type: Answer
has body: Your problem is here: “a Cython script which calculates all pairwise distances…” Essentially every floating-point operation (add, subtract, multiply, divide, using any “elementary” function such as square root, cosine, logarithm, and so on), some rounding error may be added. For the basic arithmetic operations, the result is calculated as if the exact mathematical result were calculated and then rounded to the nearest representable floating-point value. Ideally, the elementary functions would behave this way too, but most implementations have some additional error, because calculating these functions precisely is difficult. As an example, consider calculating 1/3*18 using decimal floating-point with four digits. 1 and 3 in decimal floating-point have no error; they are representable as 1.000 and 3.000. But their quotient, ⅓, is not representable. When you do the division, the result is .3333. Then, when you multiply .3333 by 18, the exact result is 5.9994. Because our floating-point format has only four digits, we have to round this to some number we can represent. The nearest representable value is 5.999, so that is returned. When you compare a calculated value to a constant such as 161.08, you are comparing a value with several accumulated rounding errors to a value with only one rounding error (when the decimal numeral “161.08” in the source is converted to binary floating-point, there is a rounding error). So the values are different. You often will not see this difference when numbers are printed with default precision because only a few digits are shown. This means the full internal value is rounded to a few digits for display, and that rounding conceals the differences. If you print the numbers with more precision, you will see the differences.
score: 2
has comment: http://stackoverflow.com/comment/81307961
has comment: http://stackoverflow.com/comment/81318144

http://stackoverflow.com/a/47088803
accepted answer of: http://stackoverflow.com/q/47071771
score: 1
type: Answer
has body: After some more checks, I seemed to figure out the issue was with the following lines, files needs mandatory filetype which can be obtained from MimeTypes().guess_type(path)[0] and the request_data should have been json.dumps(request_data) files = {'file': (temp_file_path, open(temp_file_path, 'rb'), filetype)} # .... Other code r = requests.post(url, files=files, data={'request': json.dumps(request_data)}, headers=headers)
answers question: http://stackoverflow.com/q/47071771
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81105204
type: QuestionComment
comment on: http://stackoverflow.com/q/47074208
type: Comment
score: 0
has text: I saw the "--no-sandbox" tips when I debug and before posting here. Haven't thought of putting this as chrome_options for chromedriver. It works! May you please post it as an answer? Thank you very much!

http://stackoverflow.com/comment/81155060
type: AnswerComment
has text: regex will do what ??? find the user input from the file content !! fantastic.... then how will that solve getting my age of that user input ?? Idea is nowhere close to what i expected but thank you for trying.
type: Comment
comment on: http://stackoverflow.com/a/47102306
score: 0

http://stackoverflow.com/comment/108319009
comment on: http://stackoverflow.com/q/47178402
score: 0
type: Comment
has text: @jtlz2 The library and its documentations quite a while over the past 2 years.
type: QuestionComment

http://stackoverflow.com/comment/81380910
type: AnswerComment
comment on: http://stackoverflow.com/a/47215546
has text: Appending a list is *completely* unnecessary. Your `max(i)` call does nothing.
type: Comment
score: 0

http://stackoverflow.com/q/47103249
downvote count: 0
accepted answer: http://stackoverflow.com/a/47145116
tagged with: tensorflow
favorite count: 0
type: Question
has body: I am building a dataset with two tensors of shape [batch,width,heigh,3] and [batch,class] for each element. For simplicity lets say class = 5. What shape do you feed to dataset.padded_batch(1000,shape) such that image is padded along the width/height/3 axis? I have tried the following: tf.TensorShape([[None,None,None,3],[None,5]]) [tf.TensorShape([None,None,None,3]),tf.TensorShape([None,5])] [[None,None,None,3],[None,5]] ([None,None,None,3],[None,5]) (tf.TensorShape([None,None,None,3]),tf.TensorShape([None,5])‌​) Each raising TypeError The docs state: padded_shapes: A nested structure of tf.TensorShape or tf.int64 vector tensor-like objects representing the shape to which the respective component of each input element should be padded prior to batching. Any unknown dimensions (e.g. tf.Dimension(None) in a tf.TensorShape or -1 in a tensor-like object) will be padded to the maximum size of that dimension in each batch. The relevant code: dataset = tf.data.Dataset.from_generator(generator,tf.float32) shapes = (tf.TensorShape([None,None,None,3]),tf.TensorShape([None,5])) batch = dataset.padded_batch(1,shapes)
answer count: 2
score: 6
upvote count: 6
tagged with: python
possible better answer: http://stackoverflow.com/a/47108003
has answer: http://stackoverflow.com/a/47145116
tagged with: tensorflow-datasets
has answer: http://stackoverflow.com/a/47108003
has title: How to use tf.data.Dataset.padded_batch with a nested shape?
has comment: http://stackoverflow.com/comment/81228304
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81239303
has comment: http://stackoverflow.com/comment/81180734
has comment: http://stackoverflow.com/comment/81229417

http://stackoverflow.com/comment/81305765
has text: Since you posted no code, I assume the documentation might suffice: http://pythonhosted.org/python-bioformats/_modules/bioformats/formatreader.html Theres the method `openBytes`
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47178242

http://stackoverflow.com/comment/81322646
type: QuestionComment
score: 0
has text: Take a look at [`pickle`](https://docs.python.org/3.6/library/pickle.html)
comment on: http://stackoverflow.com/q/47186746
type: Comment

http://stackoverflow.com/q/47085048
type: Question
has body: I have a data frame with a column that has numbers in format x.x or x.xx randomly embedded in a string. I can separately extract such numbers using pd[colName].str.extract('(\d\.\d)') or pd[colName].str.extract('(\d\d\.\d)') And then merging the two results. But how would I combines these two conditions together using some sort of 'or' condition to achieve the same in one go.
has comment: http://stackoverflow.com/comment/81119473
has answer: http://stackoverflow.com/a/47085075
accepted answer: http://stackoverflow.com/a/47085075
tagged with: python
type: AnsweredQuestion
has title: pandas extract using multiple conditions
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/q/47202846
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I am doing a project for medical data mining ,and using a python api call Aqua.io ,the goal is to search for ICD code by their description. The tutorial is not so clear for me,especially the parameters call 'client_options' and 'option'. Tutorial The description of client option are below: Client Options The following options are available while instantiating a client: base: Base url for the api user_agent: Default user-agent for all requests headers: Default headers for all requests request_type: Default format of the request body client = aqua_io.Client({ 'client_id': '09a8b7', 'client_secret': '1a2b3' }, client_options) I am not sure how to set this four parameters , are they all necessary? I have try this way and came out an error: TypeError: request() got an unexpected keyword argument 'request_type' client = aqua_io.Client({ 'client_id': '****','client_secret': '***' }, {'base':'https://aqua.io','user_agent': '**', 'headers': 'XHTML', 'request_type': 'JSON'}) And if I only put parameter 'base' , it works. client = aqua_io.Client({ 'client_id': '****','client_secret': '***' },{'base':'https://aqua.io'}) Similar question on parameter call method option,description is below: Method Options The following options are available while calling a method of an api: headers: Headers for the request query: Query parameters for the url body: Body of the request request_type: Format of the request body When I run code like this, it came out an error: TypeError: request() got an unexpected keyword argument 'request_type' icd9 = client.icd9() response = icd9.single_code("066-4",{'request_type':'json'}) Did anyone have experience of using this api ? Thanks !
tagged with: python
has comment: http://stackoverflow.com/comment/81356738
tagged with: medical
has title: How to use aqua.io API (for ICD-10 description to code)
has comment: http://stackoverflow.com/comment/81354151
answer count: 0
type: UnansweredQuestion
tagged with: icd
score: 1
has comment: http://stackoverflow.com/comment/96005809

http://stackoverflow.com/q/47155654
has comment: http://stackoverflow.com/comment/81261424
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81262418
has answer: http://stackoverflow.com/a/47161237
tagged with: python
has comment: http://stackoverflow.com/comment/81268255
score: -1
has comment: http://stackoverflow.com/comment/81263958
has comment: http://stackoverflow.com/comment/81262713
has comment: http://stackoverflow.com/comment/81262050
has comment: http://stackoverflow.com/comment/81263709
tagged with: tkinter
has comment: http://stackoverflow.com/comment/81261608
has body: i am new at python.I have 3 Accelerometer Values.X axis Y axis and Z axis. I can monitoring them via these codes below: from liblo import * from tkinter import* import sys import time @make_method('/muse/acc', 'fff') def acc_callback(self, path, args): acc_x, acc_y, acc_z = args print "%s %f %f %f" % (path, acc_x, acc_y, acc_z) def Record(): ....... ....... However,i want to record them via tkinter/record button R = Tkinter.Button(top, text ="Record", command = Record) R.pack() How can i record these datas via button?Thanks.
upvote count: 0
has comment: http://stackoverflow.com/comment/81261275
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81263723
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81269834
has title: Python Tkinter Record Strings

http://stackoverflow.com/a/47080981
accepted answer of: http://stackoverflow.com/q/47077433
type: AcceptedAnswer
has body: download the msi version of graphviz from >http://www.graphviz.org/Download_windows.php add C:\Program Files (x86)\Graphviz2.38\bin to my system variables in PATH
answers question: http://stackoverflow.com/q/47077433
score: 1
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/47134887
has comment: http://stackoverflow.com/comment/81261906
has body: Your cart model has no field or method Title, but you've included it in your fields list. You can only serialize fields or methods that exist on the model, or that you create explicit links to. You get the product titles in your template because you're passing back orders = Order.objects.filter(cart=cart). Your Order object string method, which is what you're displaying in the template is return self.product.title - so you're going from the order object, to the corresponding product (a join) and fetching the title attribute of that object. To do the same in the serializer, you need to define a serializer for each object, and then nest them. class CartSerializer(ModelSerializer): class Meta: model = Cart fields = [ 'title', 'cover_image', 'summary', 'price', ] class ProductSerializer(ModelSerializer): class Meta: model = Product ...etc... class OrderSerializer(ModelSerializer): class Meta: model = Order product = ProductSerializer ...etc...
score: 0
answers question: http://stackoverflow.com/q/47134646
has comment: http://stackoverflow.com/comment/81222561
has comment: http://stackoverflow.com/comment/81220798
has comment: http://stackoverflow.com/comment/81222281
type: Answer

http://stackoverflow.com/comment/81269986
has text: @POLOSTutorials: if you see a declaration of cross-posting in a question, please do not remove it. Cross-posting may be seen as somewhat impatient, but undeclared cross-posting is much worse, and the OP may receive downvotes for that, even though the first version correctly owned up to the cross-posting.
score: 0
comment on: http://stackoverflow.com/q/47157092
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47107167
has comment: http://stackoverflow.com/comment/81164831
has comment: http://stackoverflow.com/comment/81165119
has comment: http://stackoverflow.com/comment/81164786
has comment: http://stackoverflow.com/comment/81164740
score: 1
has body: You are almost correct . Using range you are not taking the number. Just add n+1 instead of n. That should work. Also you are not stroing the divident in the list. I added that too. def problem(n): myList = [] for i in range(2, n+1): if n % i == 0 and [int(n/i),i] not in myList: myList.append([i,int(n/i)]) return myList
downvote count: 0
has comment: http://stackoverflow.com/comment/81164743
upvote count: 1
has comment: http://stackoverflow.com/comment/81164757
type: Answer
answers question: http://stackoverflow.com/q/47107127

http://stackoverflow.com/a/47163055
has body: I'll try and provide an optimised solution for 0.9. IIUC ix should work here. m = df["max"] &gt; df["min"].abs() i = df.ix[m, 'idCaseMax'] j = df.ix[~m, 'idCaseMin'] df['idMax'] = i.append(j) df idCaseMax idCaseMin max min idMax lineId 1 5 10 120 -110 5 2 27 23 150 -205 23 3 15 40 110 -80 15 4 11 8 90 -150 8
score: 3
type: Answer
answers question: http://stackoverflow.com/q/47162944
upvote count: 3
has comment: http://stackoverflow.com/comment/81275928
downvote count: 0

http://stackoverflow.com/a/47101663
score: 0
has comment: http://stackoverflow.com/comment/81154169
has comment: http://stackoverflow.com/comment/81153612
has comment: http://stackoverflow.com/comment/81154332
has body: Yes, there are ways to do this, but you're complicating the situation. First of all, simplify your program even more: pull the remote code into your program file, and solve the access problem there. After that works, then you split it into a second file. Second, if you want those items to be in a form you can easily search, do that. At the moment, you went out of your way to separate them into distinct variables, when you obviously want to keep them together. Do this in one of two ways: (1) simple list: people = [ {'fullname':'John Wick', 'Age': 35 , 'job':'Hitman'}, {'fullname':'Mark Zuckerberg', 'Age': 30, 'job': 'Developer'}, {'fullname':'Will smith', 'Age': 45, 'job': 'Actor'}, {'fullname':'Messi' , 'Age': 28, 'job' : 'Player'} ] Now, use your normal list search methods to find the matching item. (2) Dictionary, indexed the way you want to use it: people = { 'John Wick': {'Age': 35 , 'job':'Hitman'}, 'Mark Zuckerberg': {'Age': 30, 'job': 'Developer'}, 'Will smith': {'Age': 45, 'job': 'Actor'}, 'Messi': {'Age': 28, 'job' : 'Player'} } This way, you get the person's record with a direct reference, people[user_input]. Does that get you moving?
has comment: http://stackoverflow.com/comment/81154681
answers question: http://stackoverflow.com/q/47101333
has comment: http://stackoverflow.com/comment/81154811
has comment: http://stackoverflow.com/comment/81153985
has comment: http://stackoverflow.com/comment/81154602
has comment: http://stackoverflow.com/comment/81153653
has comment: http://stackoverflow.com/comment/81153745
type: Answer
has comment: http://stackoverflow.com/comment/81154708
has comment: http://stackoverflow.com/comment/81154459
has comment: http://stackoverflow.com/comment/81154638

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/47085828
tags question: http://stackoverflow.com/q/47076949
tags question: http://stackoverflow.com/q/47077278
tags question: http://stackoverflow.com/q/47090882
tags question: http://stackoverflow.com/q/47088828
tags question: http://stackoverflow.com/q/47153543
tags question: http://stackoverflow.com/q/47170169
tags question: http://stackoverflow.com/q/47187066
tags question: http://stackoverflow.com/q/47160822
tags question: http://stackoverflow.com/q/47148262
tags question: http://stackoverflow.com/q/47187250
tags question: http://stackoverflow.com/q/47068395
tags question: http://stackoverflow.com/q/47092512
tags question: http://stackoverflow.com/q/47216630
tags question: http://stackoverflow.com/q/47162900
tags question: http://stackoverflow.com/q/47213797
tags question: http://stackoverflow.com/q/47090508
tags question: http://stackoverflow.com/q/47112249
tags question: http://stackoverflow.com/q/47179463
tags question: http://stackoverflow.com/q/47129690
tags question: http://stackoverflow.com/q/47181946
tags question: http://stackoverflow.com/q/47156673
tag name: json
tags question: http://stackoverflow.com/q/47198889
tags question: http://stackoverflow.com/q/47153242
tags question: http://stackoverflow.com/q/47111058
tags question: http://stackoverflow.com/q/47190008
tags question: http://stackoverflow.com/q/47212887
tags question: http://stackoverflow.com/q/47141595
tags question: http://stackoverflow.com/q/47108076
tags question: http://stackoverflow.com/q/47102104
tags question: http://stackoverflow.com/q/47096008
tags question: http://stackoverflow.com/q/47192724
tags question: http://stackoverflow.com/q/47080219
tags question: http://stackoverflow.com/q/47090465
tags question: http://stackoverflow.com/q/47186148
tags question: http://stackoverflow.com/q/47218038
tags question: http://stackoverflow.com/q/47202065
tags question: http://stackoverflow.com/q/47126947
tags question: http://stackoverflow.com/q/47066449
tags question: http://stackoverflow.com/q/47149820
tags question: http://stackoverflow.com/q/47069348
tags question: http://stackoverflow.com/q/47071339
tags question: http://stackoverflow.com/q/47067601
tags question: http://stackoverflow.com/q/47080608
tags question: http://stackoverflow.com/q/47200845
tags question: http://stackoverflow.com/q/47213930
tags question: http://stackoverflow.com/q/47220781
tags question: http://stackoverflow.com/q/47156864
tags question: http://stackoverflow.com/q/47184906
tags question: http://stackoverflow.com/q/47081807
tags question: http://stackoverflow.com/q/47168531
tags question: http://stackoverflow.com/q/47203330
tags question: http://stackoverflow.com/q/47105560
tags question: http://stackoverflow.com/q/47103079
type: Tag
tags question: http://stackoverflow.com/q/47085679
tags question: http://stackoverflow.com/q/47145002
tags question: http://stackoverflow.com/q/47072757
tags question: http://stackoverflow.com/q/47139674
tags question: http://stackoverflow.com/q/47078447
tags question: http://stackoverflow.com/q/47186614
tags question: http://stackoverflow.com/q/47125466
tags question: http://stackoverflow.com/q/47085842
tags question: http://stackoverflow.com/q/47163749
tags question: http://stackoverflow.com/q/47125028
tags question: http://stackoverflow.com/q/47205238
tags question: http://stackoverflow.com/q/47144474
tags question: http://stackoverflow.com/q/47140793
tags question: http://stackoverflow.com/q/47142290
tags question: http://stackoverflow.com/q/47073591
tags question: http://stackoverflow.com/q/47146910
tags question: http://stackoverflow.com/q/47202802
tags question: http://stackoverflow.com/q/47158862
tags question: http://stackoverflow.com/q/47091629
tags question: http://stackoverflow.com/q/47222467
tags question: http://stackoverflow.com/q/47135852
tags question: http://stackoverflow.com/q/47178618

http://stackoverflow.com/comment/81146152
type: QuestionComment
comment on: http://stackoverflow.com/q/47098198
score: 1
has text: and urlconfig ?
type: Comment

http://stackoverflow.com/comment/81312220
type: Comment
type: QuestionComment
has text: Which the loss?
score: 1
comment on: http://stackoverflow.com/q/47179307

http://stackoverflow.com/comment/81309154
score: 0
type: AnswerComment
has text: I did the same for the following IP and port UDP_IP = '192.168.x.xx' UDP_PORT = 5555 and I get the following error OSError: [WinError 10049] The requested address is not valid in its context
comment on: http://stackoverflow.com/a/47179813
type: Comment

http://stackoverflow.com/comment/81533576
has text: Yes: https://msdn.microsoft.com/en-gb/library/ff650441.aspx
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47184906
type: QuestionComment

min
type: Tag
tags question: http://stackoverflow.com/q/47211965
tags question: http://stackoverflow.com/q/47102446
tags question: http://stackoverflow.com/q/47083962
tags question: http://stackoverflow.com/q/47082378
tag name: min

http://stackoverflow.com/q/47195778
downvote count: 0
tagged with: python
tagged with: python-requests
tagged with: zeep
score: 3
has answer: http://stackoverflow.com/a/47195850
tagged with: http-proxy
answer count: 1
has body: I'm using requests and zeep library to connect to a server using SOAP API. If I manually set the internet proxy, I can connect. However, I intend to use proxy setting in my script to automate the process. I'm using the following block of code to do that, but I'm getting the error below. Can anyone pls help me where am I making the mistake? ConnectionError: HTTPSConnectionPool(host='xxxl.com', port=443): Max retries exceeded with url: /webservice.php?wsdl (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)) from requests import Session from requests.auth import HTTPBasicAuth from zeep import Client from zeep.transports import Transport session = Session() session.proxies = {'http': 'http://abcdef.com:80'} session.auth = HTTPBasicAuth('username', 'passwd') client = Client('https://abcxyz.com/webservice.php?wsdl', transport=Transport(session=session))
has comment: http://stackoverflow.com/comment/113565637
favorite count: 0
has title: Unable to connect to SOAP API with proxy setting
type: Question
upvote count: 3
type: UnansweredQuestion

dpkg
tag name: dpkg
type: Tag
tags question: http://stackoverflow.com/q/47124398

http://stackoverflow.com/comment/81302356
score: 0
comment on: http://stackoverflow.com/a/47176507
type: Comment
type: AnswerComment
has text: Nice one with where.

http://stackoverflow.com/q/47177696
has title: NoReverseMatch with keyword argument uidb64 with Django 2.0
tagged with: python
has comment: http://stackoverflow.com/comment/81305274
has answer: http://stackoverflow.com/a/63258776
answer count: 4
has answer: http://stackoverflow.com/a/47178385
type: AnsweredQuestion
tagged with: django-templates
downvote count: 0
has comment: http://stackoverflow.com/comment/81305432
has answer: http://stackoverflow.com/a/64854085
upvote count: 23
possible better answer: http://stackoverflow.com/a/63258776
score: 23
accepted answer: http://stackoverflow.com/a/47178385
favorite count: 0
type: Question
has body: I can't understand why my code doesn't work. Before it worked, but now, when I run the server and test, the code does not work. When the user is registering, I send him activation email, like this: def send_activation_email(serializer, request, user): current_site = get_current_site(request) message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) mail_subject = 'Activate your blog account.' to_email = serializer.data['email'] email = EmailMessage(mail_subject, message, to=[to_email]) email.send() acc_active_email.html {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} and my url file . . url(r'^activate/(?P&lt;uidb64&gt;[0-9A-Za-z_\-]+)/(?P&lt;token&gt;[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate_account, name='activate'), . . but I have this error: Exception Type: NoReverseMatch Exception Value: Reverse for 'activate' with keyword arguments '{'uidb64': b'NDM', 'token': '4qz-8f770502bd8b02786da9'}' not found. 1 pattern(s) tried: ['activate/(?P&lt;uidb64&gt;[0-9A-Za-z_\\-]+)/(?P&lt;token&gt;[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] highlights this line http://{{ domain }}{% url 'activate' uidb64=uid token=token %}
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81305587
has answer: http://stackoverflow.com/a/73562927
tagged with: django-2.0
tagged with: django

http://stackoverflow.com/a/47127757
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47119234
upvote count: 1
has body: Looks like it had to do with my mongoengine version. I installed these modules and it started working as expected: flask-mongoengine==0.7 mongoengine==0.8.7 pymongo==2.8.1
type: Answer

http://stackoverflow.com/a/47091924
type: AcceptedAnswer
has body: From the Dictionary displays documentation: If a comma-separated sequence of key/datum pairs is given, they are evaluated from left to right to define the entries of the dictionary: each key object is used as a key into the dictionary to store the corresponding datum. This means that you can specify the same key multiple times in the key/datum list, and the final dictionary’s value for that key will be the last one given. (Bold emphasis mine). So yes, that is guaranteed. All Python implementations must adhere to this, deviation from the above specification would be a bug. Older Python version documentation have not always included that last sentence, but the order of evaluation has always been explicit.
downvote count: 1
has comment: http://stackoverflow.com/comment/81133417
has comment: http://stackoverflow.com/comment/81133441
accepted answer of: http://stackoverflow.com/q/47091884
upvote count: 9
type: Answer
score: 8
answers question: http://stackoverflow.com/q/47091884
has comment: http://stackoverflow.com/comment/81133499

http://stackoverflow.com/comment/81190171
type: QuestionComment
comment on: http://stackoverflow.com/q/47120159
score: 0
has text: @UpmostScarab Yeah it was a typing error.I just changed the variable name.
type: Comment

http://stackoverflow.com/q/47178577
has title: Python: SSHTunnel and Socks5 server
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81324302
tagged with: ssh
tagged with: python
has comment: http://stackoverflow.com/comment/81342169
has body: I'm trying for the last couple of hours to find a solution of tunneling a SSH connection and create a Socks5 server on that SSH tunnel, so I can browse a webpage with Selenium. For connecting to remote SSH, I've been using sshtunnel. I managed to connect to the remote SSH server. Now I'm trying to create a SOCKS5 server on that connection so I can use it with FireFox. I'm exhausted, have been searching for at least 4 hours and no result. What should I look for? Did anyone create a Socks5 server from a SSH Tunnel?
tagged with: proxy
score: 0
answer count: 0
tagged with: selenium
tagged with: ssh-tunnel
type: Question

http://stackoverflow.com/q/47214505
answer count: 1
accepted answer: http://stackoverflow.com/a/47223811
type: Question
score: 0
has comment: http://stackoverflow.com/comment/81378571
has comment: http://stackoverflow.com/comment/81378790
tagged with: dataframe
tagged with: python
tagged with: where-clause
has body: I am trying to implement the following logic on a python dataframe. If the string value in Column A is in a list that I pre-designated, then replace Column B with the value in Column A. Otherwise, leave the value in column B as is. The closest I can get right now is a wonky np.where statement that isn't quite what I want and errors out. Please see below. Any help is greatly appreciated
has title: Dataframe: if value in first column is in a list of strings, replace second column with value
tagged with: replace
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/98581773
has answer: http://stackoverflow.com/a/47223811

datetime
tags question: http://stackoverflow.com/q/47211664
tags question: http://stackoverflow.com/q/47196719
tags question: http://stackoverflow.com/q/47117769
tags question: http://stackoverflow.com/q/47198276
tags question: http://stackoverflow.com/q/47209407
tags question: http://stackoverflow.com/q/47201783
tags question: http://stackoverflow.com/q/47098112
tags question: http://stackoverflow.com/q/47180036
tag name: datetime
tags question: http://stackoverflow.com/q/47199701
tags question: http://stackoverflow.com/q/47200805
tags question: http://stackoverflow.com/q/47195258
tags question: http://stackoverflow.com/q/47192568
tags question: http://stackoverflow.com/q/47164814
tags question: http://stackoverflow.com/q/47173925
tags question: http://stackoverflow.com/q/47192577
tags question: http://stackoverflow.com/q/47084766
tags question: http://stackoverflow.com/q/47087883
tags question: http://stackoverflow.com/q/47178086
tags question: http://stackoverflow.com/q/47132548
tags question: http://stackoverflow.com/q/47076050
tags question: http://stackoverflow.com/q/47186807
tags question: http://stackoverflow.com/q/47122459
tags question: http://stackoverflow.com/q/47135190
tags question: http://stackoverflow.com/q/47177238
tags question: http://stackoverflow.com/q/47206742
tags question: http://stackoverflow.com/q/47087176
tags question: http://stackoverflow.com/q/47121926
tags question: http://stackoverflow.com/q/47167369
type: Tag
tags question: http://stackoverflow.com/q/47222436
tags question: http://stackoverflow.com/q/47207023
tags question: http://stackoverflow.com/q/47161480
tags question: http://stackoverflow.com/q/47177148
tags question: http://stackoverflow.com/q/47145703
tags question: http://stackoverflow.com/q/47209612
tags question: http://stackoverflow.com/q/47097949
tags question: http://stackoverflow.com/q/47102258
tags question: http://stackoverflow.com/q/47132702
tags question: http://stackoverflow.com/q/47101076
tags question: http://stackoverflow.com/q/47148516
tags question: http://stackoverflow.com/q/47106322
tags question: http://stackoverflow.com/q/47097447
tags question: http://stackoverflow.com/q/47133250
tags question: http://stackoverflow.com/q/47131431
tags question: http://stackoverflow.com/q/47143592
tags question: http://stackoverflow.com/q/47148171

http://stackoverflow.com/q/47143655
has comment: http://stackoverflow.com/comment/81238565
downvote count: 3
tagged with: web-scraping
favorite count: 0
type: Question
has body: I want to extract the columns of a .txt file and put them into a pandas DataFrame or csv. I also need to extract some information from the header of the .txt file and add them as columns in the dataframe/csv. Here is the link of the file http://meteosearch.meteo.gr/data/askyfou/2017-01.txt Partial screenshot of the file Thank you in advance for your help.!
has answer: http://stackoverflow.com/a/47144821
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
score: -3
tagged with: python
has title: .txt file to Pandas dataframe
has answer: http://stackoverflow.com/a/47145310
tagged with: text
answer count: 2
tagged with: pandas
upvote count: 0

http://stackoverflow.com/comment/81209896
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47129876
has text: Factually, there is no such item as `Phone Numbers` on the Webpage. Either it's a `Mobile` or `Office` + `Ext`

http://stackoverflow.com/comment/81194393
has text: This works if I want them in lexigraphical order, but I'd like to maintain the original (non-lexigraphical) order
score: 0
comment on: http://stackoverflow.com/q/47122232
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81283073
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47165138
score: 0
has text: I have updated my code with the surface.If I want to make a sausage link,which part should I fixed?

http://stackoverflow.com/q/47142311
has comment: http://stackoverflow.com/comment/81242118
has title: unknown error: chrome failed to start
tagged with: python
has answer: http://stackoverflow.com/a/47166290
tagged with: selenium-chromedriver
type: AnsweredQuestion
score: 1
upvote count: 1
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/81241844
accepted answer: http://stackoverflow.com/a/47166290
has answer: http://stackoverflow.com/a/47150467
possible better answer: http://stackoverflow.com/a/47150467
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81243964
answer count: 2
linked to: http://stackoverflow.com/q/25311593
has comment: http://stackoverflow.com/comment/81241625
linked to: http://stackoverflow.com/q/36133894
has body: I've been stuck for days because of this issue and can't seem to find a solution. I can't get the chromedriver to work on my machine, no matter what I do. I've tried pretty much every setup I could possibly imagine. To list a few: Chrome 64 bits, Python 64 bits Chrome 32 bits, Python 32 bits Chrome 64 bits, Python 32 bits Chrome 32 bits, Python 64 bits I've also tried different versions of Chrome with their corresponding chromedriver versions. I've tried different prior versions of selenium, and that is, on every previously mentioned setups. For an actual context, here's my current setup: Windows 10 Professional x64 Python 3.6.3 64 bits Selenium 3.7.0 Google Chrome 62.0.3202.75 64 bits Chromedriver 2.33 I will not post my code as no matter which code I use, it fails. Even the simplest most basic code that launches a chromedriver will not work. Also, it works on my colleague's machine. So to give some context, here's a code snippet I've tried that doesn't work: from selenium import webdriver webdriver.Chrome(executable_path="bin/chromedriver.exe") I've also tried to add the chromedriver to my PATH and launching the chromedriver with no arguments but this doesn't work either. The error I'm getting is this one: selenium.common.exceptions.WebDriverException: Message: unknown error: chrome failed to start (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64) And here's the log that gets generated if I launch the driver with the verbose/logging parameters: [1.979][INFO]: COMMAND InitSession { "capabilities": { "alwaysMatch": { "browserName": "chrome", "goog:chromeOptions": { "args": [ ], "extensions": [ ] }, "platformName": "any" }, "firstMatch": [ { } ] }, "desiredCapabilities": { "browserName": "chrome", "goog:chromeOptions": { "args": [ ], "extensions": [ ] }, "platform": "ANY", "version": "" } } [1.985][INFO]: Populating Preferences file: { "alternate_error_pages": { "enabled": false }, "autofill": { "…

http://stackoverflow.com/comment/81207810
has text: Just run `scrapy runspider yourspider.py ` with the code I posted to see the results.
comment on: http://stackoverflow.com/a/47128208
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47184312
has body: def remove_entries(d, k): if k in d: del d[k] for value in d.values(): if isinstance(value, dict): remove_entries(value, k) Here's a pretty basic recursive function for doing it Edit: If you also want to handle lists nested in dicts, nested in lists, etc, something like the below will owrk. def remove_from_dict_in_list(l, k): for i in l: if isinstance(i, list): remove_from_dict_in_list(i, k) elif isinstance(i, dict): remove_entries(i, k) def remove_entries(d, k): if k in d: del d[k] for value in d.values(): if isinstance(value, dict): remove_entries(value, k) elif isinstance(value, list): remove_from_dict_in_list(value, k)
type: Answer
answers question: http://stackoverflow.com/q/47184175
score: 1
has comment: http://stackoverflow.com/comment/81317764
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81371486
type: AnswerComment
comment on: http://stackoverflow.com/a/47210268
type: Comment
has text: I think this would work for Nvidia GPUs. We need the code to run on AMD GPUs as well, which do not work with CUDA.
score: 0

http://stackoverflow.com/a/47108244
accepted answer of: http://stackoverflow.com/q/47108165
score: 0
has comment: http://stackoverflow.com/comment/81167247
type: Answer
has body: 1 - you dont. Scope of methods and variables is most of the time handled by programming conventions. In this case you would add a underline in the beggining of the checker to identify it as a private method that should only be called by the other methods inside the class. 2 - to synchronize multiple threads you need to work with the the threads using threading specific commands, trying to use the "carry_on" like you did will make you end in some weird alleys. Ps: if I recall there is the @Async and @Sync annotations, you could look further into it.
answers question: http://stackoverflow.com/q/47108165
has comment: http://stackoverflow.com/comment/81167560
has comment: http://stackoverflow.com/comment/81167001
type: AcceptedAnswer

http://stackoverflow.com/q/47162944
accepted answer: http://stackoverflow.com/a/47163041
has body: I'm working under python 2.5 (I'm restricted to that version due to external api) and would like to get same results as below code I wrote under python 2.7 import pandas as pd df = pd.DataFrame({"lineId":[1,2,3,4], "idCaseMin": [10, 23, 40, 8], "min": [-110, -205, -80, -150], "idCaseMax": [5, 27, 15, 11], "max": [120, 150, 110, 90]}) df = df.set_index("lineId") df["idMax"] = df["idCaseMax"].where(df["max"]&gt;abs(df["min"]),df["idCaseMin"]) The DataFrame results in: &gt;&gt;&gt; df idCaseMax max idCaseMin min idMax lineId 1 5 10 120 -110 5 2 27 23 150 -205 23 3 15 40 110 -80 15 4 11 8 90 -150 8 The idMax column is defined based on the id which gets the greatest value, in absolute module, within max and min columns. I can't use where function as it's not available under pandas 0.9.0 (latest version available for python 2.5) and numpy 1.7.1. So, which options do I have to get same results for idMax column without using pandas where function?
answer count: 4
has answer: http://stackoverflow.com/a/47163041
possible better answer: http://stackoverflow.com/a/47163055
has answer: http://stackoverflow.com/a/47163055
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47163195
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47162945
has title: How to conditionally select column based on other columns under pandas DataFrame without using where function?
tagged with: python-2.5
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: python

http://stackoverflow.com/comment/116740632
type: Comment
has text: quick question: how can use something like greater than or less than in this approach?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47182568

annotate
tags question: http://stackoverflow.com/q/47122340
tag name: annotate
type: Tag

http://stackoverflow.com/a/47174448
answers question: http://stackoverflow.com/q/47171602
has body: The error says it all : File "&lt;stdin&gt;", line 1, in &lt;module&gt; Seems the error occurs on the very first line which is as : driver=webdriver.Chrome() This is because here in this code block unless you import webdriver, the driver object is unable to properly initiate/handle the instance of WebBrowser i.e. Chrome Browser. Solution : While working with Selenium 3.x, ChromeDriver 2.33.x you need Chrome Browser v60-62 with Python 3.x bindings, and you have to do the following: Download the chromedriver binary from this link. Import the necessary modules Provide the absolute path of the chromedriver binary in your system. Below is the minimal code : //The Linux Example from selenium import webdriver driver = webdriver.Chrome(executable_path=r'/usr/bin/chromedriver') driver.get('https://www.google.co.in') print("Page Title is : %s" %driver.title) driver.quit() //The Windows Example from selenium import webdriver driver = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe') driver.get('https://www.google.co.in') print("Page Title is : %s" %driver.title) driver.quit() Update : On a separate note as you are seeing WebDriverException: Message: unknown error: Chrome failed to start: crashed perform the following additional steps : Uninstall Google Chrome from your system through Revo Uninstaller. Run CCleaner to wipe out all the unwanted OS chores. Take a system Reboot Install latest official build of Google Chrome Execute your Test.
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/81125376
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47087096
type: Comment
has text: good point @SethMMorton, I am not sure if it is a bug or just behavior that is changed and I need to adapt code

http://stackoverflow.com/q/47191002
type: Question
has comment: http://stackoverflow.com/comment/81409414
has comment: http://stackoverflow.com/comment/81334609
answer count: 0
type: UnansweredQuestion
has title: No Sniff activated with phantomjs scraping; workaround?
tagged with: selenium
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/81409444
tagged with: phantomjs
score: 0
tagged with: python
has body: I am trying to access the match history site for a match on matchhistory.na.leaugeoflegends.com using Phantomjs. I was able to run the program successfully when I first wrote it but now I get a modified version of the page. The full version I first had included data from the site tables, which is what I am interested in. In the version I receive now I noticed this snippet at the top: http-equiv="X-Content-Type-Options" content="nosniff which I understand prevents repeated scraping of the site. Is there any way to work around this issue? For reference, I need data from about 200 matches from this site The code I am using is: import selenium.webdriver driver = selenium.webdriver.PhantomJS() driver.get('http://matchhistory.na.leagueoflegends.com/en/#match-details/TRLH3/1002320097?gameHash=ce10e47aa8e2d965&amp;tab=stats') html=driver.page_source Thank you for any help
has comment: http://stackoverflow.com/comment/81331628
tagged with: sniffing

dataframe
tags question: http://stackoverflow.com/q/47112388
tags question: http://stackoverflow.com/q/47115448
tags question: http://stackoverflow.com/q/47165083
tags question: http://stackoverflow.com/q/47096797
tags question: http://stackoverflow.com/q/47130691
tags question: http://stackoverflow.com/q/47208391
tags question: http://stackoverflow.com/q/47157223
tags question: http://stackoverflow.com/q/47170100
tags question: http://stackoverflow.com/q/47117421
tags question: http://stackoverflow.com/q/47112607
tags question: http://stackoverflow.com/q/47203332
tags question: http://stackoverflow.com/q/47101613
tags question: http://stackoverflow.com/q/47207023
tags question: http://stackoverflow.com/q/47074884
tags question: http://stackoverflow.com/q/47116484
tags question: http://stackoverflow.com/q/47214500
tags question: http://stackoverflow.com/q/47118756
tags question: http://stackoverflow.com/q/47087907
tags question: http://stackoverflow.com/q/47122613
tags question: http://stackoverflow.com/q/47104285
tags question: http://stackoverflow.com/q/47114833
tags question: http://stackoverflow.com/q/47089597
tags question: http://stackoverflow.com/q/47106855
tags question: http://stackoverflow.com/q/47150440
tags question: http://stackoverflow.com/q/47079393
tags question: http://stackoverflow.com/q/47211837
tags question: http://stackoverflow.com/q/47121675
tags question: http://stackoverflow.com/q/47122232
tags question: http://stackoverflow.com/q/47156739
tags question: http://stackoverflow.com/q/47128960
tags question: http://stackoverflow.com/q/47138136
tags question: http://stackoverflow.com/q/47091273
tags question: http://stackoverflow.com/q/47163975
tags question: http://stackoverflow.com/q/47119259
tags question: http://stackoverflow.com/q/47157613
tags question: http://stackoverflow.com/q/47187712
tags question: http://stackoverflow.com/q/47148170
tags question: http://stackoverflow.com/q/47113882
tags question: http://stackoverflow.com/q/47173057
tags question: http://stackoverflow.com/q/47068178
tags question: http://stackoverflow.com/q/47088267
tags question: http://stackoverflow.com/q/47098571
tags question: http://stackoverflow.com/q/47159554
tags question: http://stackoverflow.com/q/47159415
tags question: http://stackoverflow.com/q/47101815
tags question: http://stackoverflow.com/q/47154691
tags question: http://stackoverflow.com/q/47144979
tags question: http://stackoverflow.com/q/47191732
tags question: http://stackoverflow.com/q/47186724
tags question: http://stackoverflow.com/q/47128570
tags question: http://stackoverflow.com/q/47126706
tags question: http://stackoverflow.com/q/47065228
tags question: http://stackoverflow.com/q/47209847
tags question: http://stackoverflow.com/q/47191956
tags question: http://stackoverflow.com/q/47149317
tags question: http://stackoverflow.com/q/47136436
tags question: http://stackoverflow.com/q/47189166
tags question: http://stackoverflow.com/q/47111737
tags question: http://stackoverflow.com/q/47090309
tags question: http://stackoverflow.com/q/47214505
tags question: http://stackoverflow.com/q/47170169
tags question: http://stackoverflow.com/q/47132838
tags question: http://stackoverflow.com/q/47204234
tags question: http://stackoverflow.com/q/47111829
tags question: http://stackoverflow.com/q/47067228
tags question: http://stackoverflow.com/q/47119525
tags question: http://stackoverflow.com/q/47113370
tags question: http://stackoverflow.com/q/47128009
tags question: http://stackoverflow.com/q/47125791
tags question: http://stackoverflow.com/q/47126285
tags question: http://stackoverflow.com/q/47121397
tags question: http://stackoverflow.com/q/47086468
tags question: http://stackoverflow.com/q/47176420
tags question: http://stackoverflow.com/q/47147830
tags question: http://stackoverflow.com/q/47118820
tags question: http://stackoverflow.com/q/47067418
tags question: http://stackoverflow.com/q/47220773
tags question: http://stackoverflow.com/q/47123666
tags question: http://stackoverflow.com/q/47126567
tags question: http://stackoverflow.com/q/47148381

http://stackoverflow.com/comment/81349031
type: QuestionComment
has text: The mentioned response downloads the file automatically at client's machine. they are not saved on server.
score: 0
comment on: http://stackoverflow.com/q/47199321
type: Comment

http://stackoverflow.com/a/47189850
type: Answer
has comment: http://stackoverflow.com/comment/81329553
has comment: http://stackoverflow.com/comment/81330338
has body: I fixed your code: answer_1 = "america" answer_2 = "italy" getin_1 = input("Enter your Username: ") getin_2 = input("Enter your password: ") while getin_1 != answer_1 or getin_2 != answer_2: print("Incorrect") print("Please proceed") getin_1 = input("Enter your Username: ") getin_2 = input("Enter your password: ") print("Your username and password are OK.") To ask user again and again, you have to put question in a loop - if command is not sufficient. There is no need to use break or continue commands as all required conditions are already in the while loop.
has comment: http://stackoverflow.com/comment/81329159
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81329170
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47189414
has comment: http://stackoverflow.com/comment/81329497
answers question: http://stackoverflow.com/q/47189414
score: 1

http://stackoverflow.com/comment/81244762
comment on: http://stackoverflow.com/q/47147146
has text: I've just seen you can give a negative value to `pad_inches` in [this](https://stackoverflow.com/questions/11837979/removing-white-space-around-a-saved-image-in-matplotlib) answer comment, have you tried that?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81213558
type: Comment
type: QuestionComment
score: 5
has text: How would python decide which key-word arguments belong to `**kw_ent` and which belong to `**kw_but`? Just pass two separate `dict` objects as normal parameters: `kw_ent, kw_but`.
comment on: http://stackoverflow.com/q/47132049

http://stackoverflow.com/a/47113720
type: Answer
has comment: http://stackoverflow.com/comment/81177550
accepted answer of: http://stackoverflow.com/q/47113666
upvote count: 2
type: AcceptedAnswer
downvote count: 1
has body: You can build dicts containing only the required keys in a list comprehension, generating the corresponding indices in the comprehension using enumerate like so: keys = ('Name', 'Surname') lst = [(i, {k: d[k] for k in keys}) for i, d in enumerate(contact_book)]
score: 1
answers question: http://stackoverflow.com/q/47113666

http://stackoverflow.com/comment/81203965
comment on: http://stackoverflow.com/a/47126578
type: AnswerComment
score: 0
has text: Thank you so much. It is very helpful. Anyway, I thought I will manage to add also: Il_result = -(xp-xa)*(yb-ya) + (yp-ya)*(xb-xa) and Roz_result = (Wy_result) - (Il_result), but I have an error: AttributeError: Calculator instance has no attribute 'Ilo_set'. My question is: how to implement properly the other formulae into my code?
type: Comment

http://stackoverflow.com/q/47128960
accepted answer: http://stackoverflow.com/a/47154093
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47154093
has title: Finding the averages within a multi-column dataframe?
has body: Here is my dataframe:, yes it is quite large. bigdataframe Out[2]: movie id movietitle releasedate \ 0 1 Toy Story (1995) 01-Jan-1995 1 4 Get Shorty (1995) 01-Jan-1995 2 5 Copycat (1995) 01-Jan-1995 3 7 Twelve Monkeys (1995) 01-Jan-1995 4 8 Babe (1995) 01-Jan-1995 5 9 Dead Man Walking (1995) 01-Jan-1995 6 11 Seven (Se7en) (1995) 01-Jan-1995 7 12 Usual Suspects, The (1995) 14-Aug-1995 8 15 Mr. Holland's Opus (1995) 29-Jan-1996 9 17 From Dusk Till Dawn (1996) 05-Feb-1996 10 19 Antonia's Line (1995) 01-Jan-1995 11 21 Muppet Treasure Island (1996) 16-Feb-1996 12 22 Braveheart (1995) 16-Feb-1996 13 23 Taxi Driver (1976) 16-Feb-1996 14 24 Rumble in the Bronx (1995) 23-Feb-1996 15 25 Birdcage, The (1996) 08-Mar-1996 16 28 Apollo 13 (1995) 01-Jan-1995 17 30 Belle de jour (1967) 01-Jan-1967 18 31 Crimson Tide (1995) 01-Jan-1995 19 32 Crumb (1994) 01-Jan-1994 20 42 Clerks (1994) 01-Jan-1994 21 44 Dolores Claiborne (1994) 01-Jan-1994 22 45 Eat Drink Man Woman (1994) 01-Jan-1994 23 47 Ed Wood (1994) 01-Jan-1994 24 48 Hoop Dreams (1994) 01-Jan-1994 25 49 I.Q. (1994) 01-Jan-1994 26 50 Star Wars (1977) 01-Jan-1977 27 54 Outbreak (1995) 01-Jan-1995 28 55 Professional, The (1994) 01-Jan-1994 29 56 Pulp Fiction (1994) 01-Jan-1994 ... ... ... 99970 332 Kiss the Girls (1997) 01-Jan-1997 99971 334 U Turn (1997) 01-Jan-1997 99972 338 Bean (1997) 01-Jan-1997 99973 346 Jackie Brown (1997) 01-Jan-1997 99974 682 I Know What You Did Last Summer (1997) 17-Oct-1997 99975 873 Picture Perfect (1997) 01-Aug-1997 99976 877 Excess Baggage (1997) 01-Jan-1997 99977 886 Life Less Ordinary, A (1997) 01-Jan-1997 99978 1527 Senseless (1998) 09-Jan-1998 99979 272 Good Will Hunting (1997) 01-Jan-1997 99980 288 Scream (1996) 20-Dec-1996 99981 294 Liar Liar (1997) 21-Mar-1997 99982 300 Air Force One (1997) 01-Jan-1997 99983 310 Rainmaker, The (1997) 01-Jan-1997 99984 313 Titanic (1997) 01-Jan-1997 99985 322 Murder at 1600 (1997) 18-Apr-1997 99986 328 Conspiracy Theory (1997) 08-Aug-1997 99987 333 Game, The (1…
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81225141
tagged with: pandas
has comment: http://stackoverflow.com/comment/81208173
answer count: 1
has comment: http://stackoverflow.com/comment/81208479
has comment: http://stackoverflow.com/comment/81208853
type: Question
tagged with: average

http://stackoverflow.com/a/47179813
answers question: http://stackoverflow.com/q/47179707
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/81309154
has body: the easy way is using socket import socket import socket UDP_IP = "127.0.0.1" UDP_PORT = 5005 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 "received message:", data
has comment: http://stackoverflow.com/comment/81310077
has comment: http://stackoverflow.com/comment/81309831

http://stackoverflow.com/comment/81394996
type: QuestionComment
has text: See [`setattr`](https://docs.python.org/3/library/functions.html#setattr)
comment on: http://stackoverflow.com/q/47222655
score: 0
type: Comment

http://stackoverflow.com/q/47207819
answer count: 1
has title: Python: String to Regex Pattern
has comment: http://stackoverflow.com/comment/81364977
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81364892
has comment: http://stackoverflow.com/comment/81364721
accepted answer: http://stackoverflow.com/a/47208892
tagged with: python
tagged with: regex
type: AnsweredQuestion
has body: Suppose I have a string of characters. charstr = "SZR" Suppose that the character Z is a loaded character and can represent S, P, Q, W, or R I want to write a function get_regex(charstr) which takes charstr as an input and returns a regular expression string. Which can then be used to find patterns in other strings. The following code should not results in answer = 'None', since SZR matches SRR and SWR, which are in SQSRRSWR. charstr = "SZR" answer = re.search(get_regex(charstr), 'SQSRRSWR') I have tried the following but it won't work. Any suggestions? import re def get_regex(charstr): charstr = re.sub("Z", "[SPQWR]{1}", charstr) # Z: can be S,P,Q,W, or R #The line directly below this was in my original post. I have commmented it out and the function now works properly. #charstr = "\'\'\'^ " + charstr + "\'\'\'" # Results in '''^ S[SPQWR]{1}R''' return charstr charstr = "SZR" answer = re.search(get_regex(charstr), 'SQSRRSWR') print(answer) # Results in None
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47208892
downvote count: 1

http://stackoverflow.com/comment/81122823
type: AnswerComment
has text: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html have a look here this might help you
type: Comment
comment on: http://stackoverflow.com/a/47086418
score: 0

http://stackoverflow.com/q/47086510
answer count: 2
tagged with: visual-studio-code
downvote count: 0
has body: Problem: I have dozens of jupyter notebooks that all have some text that I need to replace. Example Each notebook contains a reference to an external file in directory foo. ./ |- foo | |- image.jpg | |- ... |- notebooks |- file1.ipynb |- file2.ipynb |- file3.ipynb |- ... However, the foo directory will soon be renamed to bar, thereby orphaning the associated links in the notebooks. Thus, I will need to rename all the links in each notebook from the old foo directory name to the new bar name, e.g. foo/image.jpg to bar/image.jpg. Question: Opening each one by one will take a lot of time. Is there an efficient and safe solution for batch editing text for multiple jupyter notebooks? Approach Since notebooks are essentially json files, I am considering a simple search and replace in VSCode. I've tried this on a test notebook and it seems to work, but I am not sure if this method will somehow corrupt the files. I appreciate any safe suggestions.
has answer: http://stackoverflow.com/a/47086639
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/78301535
upvote count: 1
score: 1
tagged with: windows
tagged with: python
tagged with: jupyter
has title: How to batch edit text in jupyter notebooks?
favorite count: 0
tagged with: jupyter-notebook
type: Question

http://stackoverflow.com/comment/81338614
has text: Quite lengthy and messy. @Jerrybibo
comment on: http://stackoverflow.com/q/47194629
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47097616
has title: How to correctly implement lazy loading in tensorflow?
score: 0
has body: The following code (while trying to replicate code structure in https://danijar.com/structuring-your-tensorflow-models/ ) import tensorflow as tf class Model: def __init__(self, x): self.x = x self._output = None @property def output(self): if not self._output: weight = tf.Variable(tf.constant(4.0)) bias = tf.Variable(tf.constant(2.0)) self._output = tf.multiply(self.x, weight) + bias return self._output def main(): x = tf.placeholder(tf.float32) model = Model(x) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) output = sess.run(model.output, {x: 4.0}) print(output) if __name__ == '__main__': main() gives an error. A part of it is as follows: Caused by op 'Variable_1/read', defined at: File "example.py", line 27, in &lt;module&gt; main() File "example.py", line 23, in main output = sess.run(model.output, {x: 4.0}) File "example.py", line 12, in output weight = tf.Variable(tf.Variable(tf.constant(4.0))) FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Variable_1 How do I resolve the issue?
has answer: http://stackoverflow.com/a/47099161
answer count: 1
upvote count: 1
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81146383
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81147820
tagged with: python

http://stackoverflow.com/comment/81104397
score: 1
comment on: http://stackoverflow.com/q/47077891
type: Comment
type: QuestionComment
has text: Due to GIL, threads are not good for paralleling computationally expensive tasks. Use the multiprocessing module instead.

http://stackoverflow.com/comment/81250605
has text: @smundlay So the default worked! Thank you! How would I change it after though?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47150390
type: QuestionComment

http://stackoverflow.com/q/47203240
has body: I have a piece of code which when run through the terminal works fine when it is provided with all the arguments, however I would like one argument to be optional, and to only run the IF statement if this argument is provided, here is my code: import argparse import sys import csv parser= argparse.ArgumentParser() parser.add_argument('-r', '--range', help= 'Enter range of two m/z values in format of x,y', default= '1000,1500') parser.add_argument('files', nargs= '*') parser.add_argument('-a', '--amino_acid', help= 'Enter one letter code of amino acid you wish to search for (optional)') args=parser.parse_args() if aa in sequence: amino_acids.append(str(sequence)) So I would like the "if aa in sequence" part to only execute if the -a arg is given, however when this argument isn't given it tries to run it anyway and fails. Any help is appreciated, thanks. Error: Traceback (most recent call last): File "project2.py", line 32, in &lt;module&gt; if aa in sequence: TypeError: 'in &lt;string&gt;' requires string as left operand, not NoneType
has comment: http://stackoverflow.com/comment/81355058
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81355411
has comment: http://stackoverflow.com/comment/81355421
has title: How to only execute IF statement if given an argument
has comment: http://stackoverflow.com/comment/81355264
downvote count: 1
has comment: http://stackoverflow.com/comment/81355355
has comment: http://stackoverflow.com/comment/81366655
has comment: http://stackoverflow.com/comment/81354974
answer count: 1
tagged with: if-statement
tagged with: argparse
tagged with: python
score: -1
tagged with: python-3.6
has answer: http://stackoverflow.com/a/47203476
favorite count: 0
type: Question

http://stackoverflow.com/comment/81127922
score: 0
has text: @solarissmoke am still new to python django
type: QuestionComment
comment on: http://stackoverflow.com/q/47089049
type: Comment

http://stackoverflow.com/q/47121163
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/81192257
answer count: 2
has comment: http://stackoverflow.com/comment/81192539
tagged with: sqlite
has answer: http://stackoverflow.com/a/47121831
has comment: http://stackoverflow.com/comment/81192661
type: Question
has comment: http://stackoverflow.com/comment/81192750
accepted answer: http://stackoverflow.com/a/47122195
possible better answer: http://stackoverflow.com/a/47121831
has answer: http://stackoverflow.com/a/47122195
tagged with: python
has comment: http://stackoverflow.com/comment/81192330
has comment: http://stackoverflow.com/comment/81192761
has comment: http://stackoverflow.com/comment/81192150
has body: After upgrading to sqlitebck ver. 1.3: Traceback (most recent call last): File "/opt/rh/python27/root/usr/lib64/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/opt/rh/python27/root/usr/lib64/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/opt/IBM/InformationServer/Server/DSEngine/bin/ISMD-emeaprd.py/__main__.py", line 38, in &lt;module&gt; AttributeError: 'module' object has no attribute 'Connection' /var/tmp/sclPqKpVb: line 8: 2032 Segmentation fault (core dumped) python /opt/IBM/InformationServer/Server/DSEngine/bin/ISMD-emeaprd.py And line 38 is: import sqlitebck I've compiled it on a RHEL 6.9 - no errors: [05.11.2017] [11:13:05 GMT] root@ $ scl enable python27 bash [root@prod-eur-isbi01 sqlitebck-1.3]# python setup.py build running build running build_ext building 'sqlitebck' extension creating build creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/src gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/local/include -I/opt/rh/python27/root/usr/include/python2.7 -c src/sqlitebck.c -o build/temp.linux-x86_64-2.7/src/sqlitebck.o In file included from /opt/rh/python27/root/usr/include/python2.7/pyconfig.h:6, from /opt/rh/python27/root/usr/include/python2.7/Python.h:8, from src/sqlitebck.c:33: /opt/rh/python27/root/usr/include/python2.7/pyconfig-64.h:1199:1: warning: "_POSIX_C_SOURCE" redefined In file included from /usr/include/string.h:27, from src/sqlitebck.c:31: /usr/include/features.h:162:1: warning: this is the location of the previous definition In file included from /opt/rh/python27/root/usr/include/python2.7/pyconfig.h:6, from /opt/rh/python27/root/usr/include/py…
has title: "import sqlitebck" Leads to "'module' object has no attribute 'Connection'"

http://stackoverflow.com/comment/81240814
comment on: http://stackoverflow.com/q/47145175
type: Comment
score: 0
has text: I cannot reproduce what you are seeing, but then, I can't really try out what you are doing since you don't provide `c`
type: QuestionComment

http://stackoverflow.com/a/47072155
has body: you can try this one.you can't assign value to variable in template engine {% for user in users %} {% endfor %}
answers question: http://stackoverflow.com/q/47065726
upvote count: 0
downvote count: 2
score: -2
type: Answer

http://stackoverflow.com/a/47218760
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47217846
has comment: http://stackoverflow.com/comment/81387745
type: Answer
has comment: http://stackoverflow.com/comment/81410447
has comment: http://stackoverflow.com/comment/81408420
has body: When you call re.match() if the string supplied doesn't match the regex pattern, it will equal None. What I'm assuming the problem is, is that you are coming across a filename that doesn't match the regex pattern you have supplied. Even if the regex matches your files correctly, the first time re.match() returns None it will break unless you explicitly catch it. Otherwise, when you call re.match().group(), it doesn't exist and it raises an error. This worked for me when I made files with the name format specified: import os import re def rename_num(path): # Create a pattern to match filenames to match_pattern = r"Vertragshandbuch_Beitrag_(\d+)_(\w+(\W\w+)*)\.docx" pattern = re.compile(match_pattern) # For each file in the path supplied above for filename in os.listdir(path): # Use the re module to match the regex pattern to the filename. # If the filename doesn't match the regex found will be equal to None. found = pattern.match(filename) # If found is not equal to None, print the filename, groups and rename the file if found: os.rename(os.path.join(path, filename), os.path.join(path, found.group(1) + ".docx")) print("{} renamed to {}".format(filename, found.group(1) + ".docx")) # To run the above method in the directory the script is in: p = os.path.abspath(os.path.dirname(__file__)) rename_num(p) I created files with names like you supplied (numbers 001 - 007) and this was my output: Vertragshandbuch_Beitrag_001_Term Sheet.docx renamed to 001.docx Vertragshandbuch_Beitrag_002_Term Sheet.docx renamed to 002.docx Vertragshandbuch_Beitrag_003_Term Sheet.docx renamed to 003.docx Vertragshandbuch_Beitrag_004_Term Sheet.docx renamed to 004.docx Vertragshandbuch_Beitrag_005_Term Sheet.docx renamed to 005.docx Vertragshandbuch_Beitrag_006_Term Sheet.docx renamed to 006.docx Vertragshandbuch_Beitrag_007_Term Sheet.docx renamed to 007.docx I hope this helps.
has comment: http://stackoverflow.com/comment/81469900
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81387535
accepted answer of: http://stackoverflow.com/q/47217846
downvote count: 0
has comment: http://stackoverflow.com/comment/81410242

http://stackoverflow.com/q/47166453
tagged with: gnome-terminal
duplicate of: http://stackoverflow.com/q/30010939
tagged with: python
possible better answer: http://stackoverflow.com/a/51840705
has body: I am trying to write a program that opens a gnome-terminal window and executes a python file in it. When I call the gnome-terminal subprocess with the subprocess module like this: import subprocess subprocess.call(['gnome-terminal', '-x', 'python3 '+filename]) I get the following error: Failed to execute child process "python3 /home/user/Documents/test.py” (No such file or directory) I have tried to cd to the directory /home/user/Documents/test.py first and then run the file, but it didn't work.
answer count: 4
has answer: http://stackoverflow.com/a/51840705
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47181938
linked to: http://stackoverflow.com/q/30010939
tagged with: subprocess
upvote count: 3
accepted answer: http://stackoverflow.com/a/47188779
downvote count: 0
tagged with: child-process
has answer: http://stackoverflow.com/a/47188779
favorite count: 0
type: Question
has title: "Failed to execute child process (No such file or directory)" when calling gnome-terminal subprocess in Python 3
score: 3
has answer: http://stackoverflow.com/a/50889702

http://stackoverflow.com/comment/81159278
type: QuestionComment
has text: @Rish OK, so your for loop works too with `string = string.replace(a, b)`, but `strings.index` is clearer and probably faster.
comment on: http://stackoverflow.com/q/47103246
score: 1
type: Comment

http://stackoverflow.com/comment/81095627
comment on: http://stackoverflow.com/a/47073112
score: 1
type: Comment
type: AnswerComment
has text: You can't extend a Django template with a Jinja template or vice versa. I would try to avoid having base templates for Jinja and Django, it sounds like needless duplication. You might have problems if you try to override the `registration/` templates with Jinja templates, since they are also used by the Django admin which uses Django templates. You could probably customize `django-registration` and the built in authentication views to point to Jinja2 templates.

http://stackoverflow.com/a/47091426
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47091227
accepted answer of: http://stackoverflow.com/q/47091227
has comment: http://stackoverflow.com/comment/81134488
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81133633
has body: What do you mean by "the for loop stopped working" ? it blocks at a given iteration or you get a runtime exception or you stop seeing improvement in the gradient? If it blocks at an iteration is certainly because your inner loop never ends while P_new &lt; P: since your P_new is constantly decreasing However, the problem I see is that when you do P = P_new and then you ask P_new &lt; P the last statement is always False. If you could show the code contained in the forward and backward functions we may be able to help you as Jeremy says, you should also avoid using global variables

http://stackoverflow.com/q/47163694
score: 0
has title: How to prepare 'hashed' text data for classifier
has body: sequence = 'I am Bob' The sequence has been altered in some way, like e.g. letters have been replaced with the subsequent letter (a->b), and spaces with 'ss': hashed_seq = 'JssbnssCpc' #for lack of a better word I'm using 'hashed' In my experience, for text classification, you tokenize the sentence/words with some dictionary, e.g.: vocab = {'&lt;PAD&gt;': 0, 'I': 1, 'Bob': 2, 'am': 3} tokenized_seq = [1,3,2] How would I prepare (tokenize etc) the data for text classification in my case without decoding them? I only have the data after the algorithm has altered them. Language: Python
has comment: http://stackoverflow.com/comment/81277435
tagged with: nlp
has comment: http://stackoverflow.com/comment/81277622
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81278608
answer count: 0
has comment: http://stackoverflow.com/comment/81278094
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81278052
has comment: http://stackoverflow.com/comment/81278186
has comment: http://stackoverflow.com/comment/81278149
upvote count: 1
tagged with: scikit-learn
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/81278627

http://stackoverflow.com/a/47211651
has comment: http://stackoverflow.com/comment/81372716
type: Answer
answers question: http://stackoverflow.com/q/47211132
has body: I found one way that works. Use PyDict_Merge() to merge the module dictionaries. https://docs.python.org/2/c-api/dict.html#c.PyDict_Merge PyObject *mod = PyImport_ImportModule("mod"); PyDict_Merge(PyModule_GetDict(other_mod), PyModule_GetDict(mod), true); Should merge the symbols from one module into another. But, I ended up merging these into the global namespace instead. So, PyObject *global = PyEval_GetGlobals(); PyObject *mod = PyImport_ImportModule("mod"); PyDict_Merge(global, PyModule_GetDict(mod), true); will merge the symbols from the import of "mod" into the global namespace.
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81372741

http://stackoverflow.com/comment/81359086
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47203887
type: AnswerComment
has text: I see that this is probably written as multiple lines for better commentability, but this might be even more elegant with a list comprehension.

http://stackoverflow.com/comment/81217067
comment on: http://stackoverflow.com/q/47133498
type: Comment
type: QuestionComment
has text: It's not very clear to me what you're going after. Could you maybe show the expected output from the above example input?
score: 0

http://stackoverflow.com/a/47131944
upvote count: 0
answers question: http://stackoverflow.com/q/47131857
downvote count: 1
has body: Have you check pip is really pip for python3 and python's version? You could using pip for python2. Like this link
type: Answer
score: -1

http://stackoverflow.com/comment/81181227
type: Comment
score: 0
type: AnswerComment
has text: @jojo There's no tuple anywhere.
comment on: http://stackoverflow.com/a/47115578

http://stackoverflow.com/a/47208428
score: 1
has body: You do not need to open the file first if you need with! Also you need to specify what the character used for splitting needs to be, otherwise it splits on every whitespace and not on ',' as you want it to. This code works (assuming your file is called 'file.txt'): dict = {} with open('file.txt', 'r') as f: for line in f: items = line.split(',') print(items) key, values = items[0], items[1:] dict[key] = values englishWord = dict.keys() spanishWord = dict.values()
type: Answer
answers question: http://stackoverflow.com/q/47208285
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81291597
has text: It makes a huge difference :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47170642
type: Comment

http://stackoverflow.com/comment/81094233
score: 0
type: Comment
type: QuestionComment
has text: could you share the link of the webpage?
comment on: http://stackoverflow.com/q/47072836

http://stackoverflow.com/q/47192771
tagged with: machine-learning
tagged with: keras
has body: I am anovice in keras. I amhaving some input dimension issues can you please tell me how should I solve this error. I would be really grateful to you. This is code the data set has 15 columns. Predictors are from column index [2:14] and 14th column has four classification labels. # load dataset dataframe = pandas.read_csv("tesp_attack.csv",header=None) dataframe = dataframe.values predictors = dataframe[:,2:14].astype(int) response = dataframe[:,14] n_cols=predictors.shape[1] print(n_cols) encoder = LabelEncoder() encoder.fit(response) encoded_response = encoder.transform(response) dummy_response = np_utils.to_categorical(encoded_response) model = Sequential() model.add(Dense(50,activation='relu',input_shape=(n_cols,))) model.add(Dense(50,activation='relu')) model.add(Dense(12,activation='softmax')) model.compile(optimizer='adam',loss='categorical_crossentropy', metrics = ['accuracy']) model.fit(predictors,dummy_response) This is the error -- --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-209-442bc37e349e&gt; in &lt;module&gt;() ----&gt; 1 model.fit(predictors,dummy_response) ~\Anaconda3\lib\site-packages\keras\models.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, **kwargs) 865 class_weight=class_weight, 866 sample_weight=sample_weight, --&gt; 867 initial_epoch=initial_epoch) 868 869 def evaluate(self, x, y, batch_size=32, verbose=1, ~\Anaconda3\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs) 1520 class_weight=class_weight, 1521 check_batch_axis=False, -&gt; 1522 batch_size=batch_size) 1523 # Prepare validation data. 1524 do_validation = False ~\Anaconda3\lib\site-packages\keras\engine\train…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81339994
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47197543
score: -2
tagged with: neural-network
has title: Keras input dimension error
tagged with: python
has comment: http://stackoverflow.com/comment/81343413
has comment: http://stackoverflow.com/comment/81350584
has comment: http://stackoverflow.com/comment/81334865
has comment: http://stackoverflow.com/comment/81335121
tagged with: deep-learning
upvote count: 0
downvote count: 2
answer count: 1

http://stackoverflow.com/comment/81293232
type: AnswerComment
has text: `return float(format((float(allRes)/(allRes + (5*70))),'.2f'))` will do
type: Comment
comment on: http://stackoverflow.com/a/47171774
score: 0

http://stackoverflow.com/comment/81255656
type: Comment
type: QuestionComment
has text: Actually it is in a list of names, and the problem raises when variable arrives to special german characters, but here to make an example I wrote it directly as string.
comment on: http://stackoverflow.com/q/47153004
score: 0

http://stackoverflow.com/a/47145188
has comment: http://stackoverflow.com/comment/81241390
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81240561
has comment: http://stackoverflow.com/comment/81248681
answers question: http://stackoverflow.com/q/47145070
type: Answer
has body: Looks like you're on Python 3? I'm guessing the error stems from this line: m = (l+(r-1))/2 In Python 3, this division will create a float (as opposed to just regular ints -- the behavior in Python 2). If you want to create ints still, you can use: m = (l+(r-1)) // 2 This is a floor division and will give you an int, which should work for your use case.
accepted answer of: http://stackoverflow.com/q/47145070
has comment: http://stackoverflow.com/comment/81241090
score: 2
upvote count: 2

http://stackoverflow.com/comment/81291468
comment on: http://stackoverflow.com/q/47170698
score: 0
type: Comment
type: QuestionComment
has text: { '0_0': ['a'], '0_1': ['b', 'c'], '1': ['d'], '2': ['e', 'f'], } should be the output right?

http://stackoverflow.com/q/47122445
has comment: http://stackoverflow.com/comment/81194600
has title: Capture stderr exception in python logging module
has body: How can I set the python logging module to write an exception to a file handler? In the console I naturally see the system exception, but how can I configure logging to send it also to a file handler when I not explicitly surround it with a try block? import logging import logging.config logging.config.fileConfig('logging.conf') log = logging.getLogger('my_file_logger') log.info('writes to logfile') print('prints to console') not_a_command # force exception And logging.conf [loggers] keys=root,console,my_file_logger [handlers] keys=consoleHandler,fileHandler [formatters] keys=simpleFormatter [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s [handler_consoleHandler] class=StreamHandler formatter=simpleFormatter level=DEBUG args=(sys.stdout,) stream=sys.stdout [handler_fileHandler] class=FileHandler formatter=simpleFormatter level=DEBUG args=('logfile_'+time.strftime('%%Y%%m%%d', time.localtime())+'.log', 'a') [logger_root] level=ERROR handlers=consoleHandler [logger_console] level=DEBUG propagate=0 qualname=console handlers=consoleHandler [logger_my_file_logger] level=DEBUG propagate=0 qualname=my_file_logger handlers=consoleHandler,fileHandler Thanks!
score: 3
linked to: http://stackoverflow.com/q/6234405
answer count: 0
upvote count: 3
downvote count: 0
favorite count: 0
type: Question
tagged with: exception
type: UnansweredQuestion
tagged with: python
tagged with: logging

http://stackoverflow.com/comment/81108360
type: Comment
has text: Well, [there is a `.zip` file in PyPI](https://pypi.python.org/pypi/tia), have tried that one?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47078456

http://stackoverflow.com/q/47199314
has comment: http://stackoverflow.com/comment/81347822
has answer: http://stackoverflow.com/a/47199749
tagged with: string
has comment: http://stackoverflow.com/comment/81347737
downvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47199749
tagged with: python
accepted answer: http://stackoverflow.com/a/47199786
tagged with: regex
has answer: http://stackoverflow.com/a/47199786
has body: I have a following String (from BeautifulSoup) [[["RE 3364",1140509724,714348396,"84/149614/18/19/80","6",8,"","Eberswalde Hbf",[[-35,-27,-1064,"4","82",null,null],[711,639,2823,"5","81",null,null],[1151,1043,5155,"5","83",null,null],[2383,2230,11893,"5","83",null,null],[4019,3731,20530,"5","82",null,null],[5637,5232,29168,"5","83",null,null],[7273,6733,37806,"","0",null,null]],"Berlin-Lichtenberg","8010036","Bernau(b Berlin)","8013470","09.11.17","-1",null,"1:37","1:18",null,null,"4",null,null],["RB 18642",354496333,422441800,"84/147727/18/19/80","14",8,"","Nauen",[[6329,-1007,-4763,"14","66",null,null],[4962,-791,403,"14","66",null,null],[3686,-594,5192,"14","66",null,null],[3227,-522,6914,"14","66",null,null],[1942,-324,11757,"14","66",null,null],[872,-144,15793,"14","66",null,null],[-1932,314,26394,"20","62",null,null],[-2076,224,27147,"13","126",null,null],[-3425,593,30000,"","0",null,null],[-3425,593,31389,"14","121",null,null],[-4099,710,32779,"14","121",null,null],[-6939,1168,38664,"","0",null,null]],"Berlin-Spandau","8010404","Albrechtshof","8080040","09.11.17","-1",null,"1:32","1:29",null,null,"4",null,null],["01:29:30",2,35000,5000,"guiV=4.1.3&amp;","20171109","69869174432dcbb13e038c953c9a7cc9","09.11.17","11:06:30",0]],[]] How can I split this string by this regex? \[\"+[A-Z] (its not completly correct) and write the splitted string in to new line? [[["RE 3364",1140509724,714348396,"84/149614/18/19/80","6",8,"","Eberswalde Hbf",[[-35,-27,-1064,"4","82",null,null],[711,639,2823,"5","81",null,null],[1151,1043,5155,"5","83",null,null],[2383,2230,11893,"5","83",null,null],[4019,3731,20530,"5","82",null,null],[5637,5232,29168,"5","83",null,null],[7273,6733,37806,"","0",null,null]],"Berlin-Lichtenberg","8010036","Bernau(b Berlin)","8013470","09.11.17","-1",null,"1:37","1:18",null,null,"4",null,null] ["RB 18642",354496333,422441800,"84/147727/18/19/80","14",8,"","Nauen",[[6329,-1007,-4763,"14","66",null,null],[4962,-791,403,"14","66",null,null],[3686,-594,5192,…
type: AnsweredQuestion
score: 0
answer count: 2
has title: Split String by a regex and write to new line
upvote count: 1
linked to: http://stackoverflow.com/q/956867

http://stackoverflow.com/comment/81116280
type: Comment
type: QuestionComment
has text: what about `\s\&[^&]*$`
score: 0
comment on: http://stackoverflow.com/q/47083451

http://stackoverflow.com/a/47128961
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81208171
answers question: http://stackoverflow.com/q/47128907
type: Answer
accepted answer of: http://stackoverflow.com/q/47128907
has body: Your question is a bit unclear, but I think you are trying to get a list of all of the result_str values. In that case, you can create a list before any of your for loops, and append the result to that list. result_list = [] for row in row2: for cell in row: if cell.value == 'a': result_list.append(cell.column) print(result_list)

django-generic-views
type: Tag
tag name: django-generic-views
tags question: http://stackoverflow.com/q/47074632
tags question: http://stackoverflow.com/q/47185334

http://stackoverflow.com/q/47182113
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has body: I have problem including a shared object file in my python script, running ubuntu 16.04. The files to this script are supplied to me and I have no possibility to recompile them. It is a file using old boost libraries (1.34.1) thread and serialization. The error I get is: ImportError: ./libsubs_reg.so: undefined symbol: _ZN5boost21recursive_timed_mutexC1Ev Checking dependent libraries for libsus_reg: # readelf -d libsubs_reg.so Dynamic section at offset 0x27118 contains 28 entries: Tag Type Name/Value 0x00000001 (NEEDED) Shared library: [libboost_serialization-gcc42-mt-1_34_1.so.1.34.1] 0x00000001 (NEEDED) Shared library: [libboost_thread-gcc42-mt-1_34_1.so.1.34.1] 0x00000001 (NEEDED) Shared library: [libstdc++.so.6] 0x00000001 (NEEDED) Shared library: [libm.so.6] 0x00000001 (NEEDED) Shared library: [libgcc_s.so.1] 0x00000001 (NEEDED) Shared library: [libc.so.6] I have created links from the 1.34.1 boost versions to the currently installed, 1.58.0. # ldd libsub_reg.so linux-gate.so.1 =&gt; (0xb7762000) libboost_serialization-gcc42-mt-1_34_1.so.1.34.1 =&gt; /usr/lib/i386-linux-gnu/libboost_serialization-gcc42-mt-1_34_1.so.1.34.1 (0xb76ba000) libboost_thread-gcc42-mt-1_34_1.so.1.34.1 =&gt; /usr/lib/i386-linux-gnu/libboost_thread-gcc42-mt-1_34_1.so.1.34.1 (0xb7695000) libstdc++.so.6 =&gt; /usr/lib/i386-linux-gnu/libstdc++.so.6 (0xb751d000) libm.so.6 =&gt; /lib/i386-linux-gnu/libm.so.6 (0xb74c8000) libgcc_s.so.1 =&gt; /lib/i386-linux-gnu/libgcc_s.so.1 (0xb74ab000) libc.so.6 =&gt; /lib/i386-linux-gnu/libc.so.6 (0xb72f5000) libpthread.so.0 =&gt; /lib/i386-linux-gnu/libpthread.so.0 (0xb72d8000) libboost_system.so.1.58.0 =&gt; /usr/lib/i386-linux-gnu/libboost_system.so.1.58.0 (0xb72d2000) librt.so.1 =&gt; /lib/i386-linux-gnu/librt.so.1 (0xb72c9000) /lib/ld-linux.so.2 (0x80027000) Checking the links... # ls -la libboost* | grep "\-&gt;" lrwxrwxrwx 1 root root 24 jun 14 2016 libboost_regex.so -&gt; libboost_regex.so.1.58.0 lrwxrwxrwx 1 root root 32 nov 8 14:53 libboost_seriali…
tagged with: boost-thread
type: UnansweredQuestion
tagged with: python
has title: undefined symbol: _ZN5boost21recursive_timed_mutexC1Ev when importing .so file in python
tagged with: c++
answer count: 0
score: 1
tagged with: boost

http://stackoverflow.com/comment/81495526
comment on: http://stackoverflow.com/a/47270814
type: Comment
has text: Glad you got this working - what was the exact problem in the end? (PS: did you know you have the upvoting privilege? Please feel free to test it out on my answer :)
type: AnswerComment
score: 0

http://stackoverflow.com/a/47127847
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/47124800
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47124800
upvote count: 4
has body: In the end I converted my float32 arrays to javascript Buffer objects and used 'binary' mode. Also I needed to switch from pyshell.on to pyshell.stdout.on which is in the python-shell test scripts for binary mode but not in the readme... In Node: var options = {mode: 'binary'}; var pyshell = new PythonShell('test.py', options); var data = Buffer.from(myFloat32TypedArray.buffer, 'float32'); pyshell.send(data).end((err) =&gt; { if (err){ console.log(err); }else{ console.log('data sent'); }; }); pyshell.stdout.on('data', function (data) { console.log(data); }); In Python: input_data = np.frombuffer(sys.stdin.read(), dtype=np.float32) sys.stdout.write(input_data)

http://stackoverflow.com/a/47136872
type: Answer
has comment: http://stackoverflow.com/comment/81225031
has comment: http://stackoverflow.com/comment/81224829
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81223943
answers question: http://stackoverflow.com/q/47135742
has body: Following the example provided by @uuazed, a faster way would be using numexpr import pandas as pd import numpy as np import numexpr as ne df = pd.DataFrame(np.random.randn(int(1e6), 2), columns=['A', 'B']) eq = "A + B + sqrt(B + 4)" timeit df.eval(eq) # 15.9 ms ± 177 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) timeit A=df.A; B=df.B; ne.evaluate(eq) # 6.24 ms ± 396 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) numexpr may also have more supported operations

http://stackoverflow.com/a/47091597
has body: First convert to strings and then apply lambda function: df = df.set_index('Test') a = df'A','B','C'.astype(str).apply(lambda x: int(''.join(x),2), 1) b = df'D','E'.astype(str).apply(lambda x: int(''.join(x),2), 1) df = pd.DataFrame({'X':a, 'Y':b}).reset_index() print (df) Test X Y 0 t1 0 2 1 t2 5 1 2 t3 7 2 3 t4 0 1 Another faster solutions, inpired by answers: df = df.set_index('Test') #define columns in dictionary cols = {'X':['A','B','C'],'Y':['D','E']} #dictionary of Series d = {k:df[v].dot((1 &lt;&lt; np.arange(len(v) - 1, -1, -1))) for k, v in cols.items()} #alternative, inspired by divakar answer #d ={k:pd.Series((2**np.arange(len(v)-1,-1,-1)).dot(df[v].values.T)) for k,v in cols.items()} df = pd.concat(d, 1).reset_index() print (df) Test X Y 0 t1 0 2 1 t2 5 1 2 t3 7 2 3 t4 0 1 Dynamic solution - create dict of columns names by groupby by floor divide helper array create by arange: df = df.set_index('Test') cols = pd.Series(df.columns).groupby(np.arange(len(df.columns)) // 3).apply(list).to_dict() {0: ['A', 'B', 'C'], 1: ['D', 'E']} d = {k:df[v].dot((1 &lt;&lt; np.arange(len(v) - 1, -1, -1))) for k, v in cols.items()} df = pd.concat(d, 1).reset_index() print (df) Test 0 1 0 t1 0 2 1 t2 5 1 2 t3 7 2 3 t4 0 1
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47091273
has comment: http://stackoverflow.com/comment/81133009
score: 1
answers question: http://stackoverflow.com/q/47091273
type: Answer
has comment: http://stackoverflow.com/comment/81133428
has comment: http://stackoverflow.com/comment/81132989

http://stackoverflow.com/a/47188881
type: Answer
has body: you can create a custom template filter that check if the user is editing his own profile or not. create custom tag: first send context called pk that equal the profile pk then.. create a directory called templatetags in the app directory and add a python file in it called __init__.py -two under scores- now create another file called profile_extras.py type this in: from django.template.loader_tags import register @register.filter(name="ownPro") def ownPro(user, id): if Profile.objects.get(id=id).user == user: return True else: return False now in the edit profile template add this {% load profile_extras %} {% if user|ownPro:pk %} .... allow to edit {% else %} you are not allowed {% endif %} don't forget to restart the server
answers question: http://stackoverflow.com/q/47188250
upvote count: 0
score: -2
downvote count: 2

http://stackoverflow.com/q/47115063
has title: Porting cython files from python2 to python3 with 2to3
has answer: http://stackoverflow.com/a/47115237
tagged with: python
tagged with: cython
favorite count: 0
score: 4
upvote count: 4
tagged with: python-2to3
has body: I have a python package which was developed under python2.7, but I need to port it to python3.6 . I use cython in some parts of the code, hence the package has both .py and .pyx files. I tried the 2to3 command, but I got an error that I couldn't neither understand nor solve. Example: I have the following test.pyx file # cython: profile=False cimport cython @cython.boundscheck(False) @cython.wraparound(False) @cython.profile(False) cpdef sillyfunction(): print 'Thank you for your kind help' return and I run 2to3 test.pyx. What I obtain is: user@machine:~$ 2to3 test.pyx RefactoringTool: Skipping optional fixer: buffer RefactoringTool: Skipping optional fixer: idioms RefactoringTool: Skipping optional fixer: set_literal RefactoringTool: Skipping optional fixer: ws_comma RefactoringTool: Can't parse test.pyx: ParseError: bad input: type=1, value=u'cython', context=(u' ', (2, 8)) RefactoringTool: No files need to be modified. RefactoringTool: There was 1 error: RefactoringTool: Can't parse test.pyx: ParseError: bad input: type=1, value=u'cython', context=(u' ', (2, 8))
type: UnansweredQuestion
answer count: 1
downvote count: 0
type: Question

http://stackoverflow.com/comment/81150799
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47087539
score: 0
has text: It sounds like you have the Cloud SDK installed, if you run `gcloud components install app-engine-python` does the module not found error go away? (assuming you haven't mapped a local lib folder)

http://stackoverflow.com/a/47135432
type: Answer
has body: Voicing the comment of @PM 2Ring. You can join the input into one list, and one function, and place it respectively. import csv import os from tkinter import * import time with open("TP.csv", "w") as db: writer = csv.writer(db) writer.writerow(["DATE", "INPUT"])# Create the file with this as heading def save_print_data(): global e3 data = e3.get() display = time.strftime('%d/%m/%y %I:%M:%S%p', time.localtime()) totalinput = [display, data] with open("TP.csv", "a") as savedb: w = csv.writer(savedb) w.writerow(totalinput) root = Tk() root.geometry("400x400") profile = StringVar() e3 = Entry(width=50, textvariable=profile) label1 = Label(root) b1 = Button(root, text="Print &amp; save", command=lambda: [save_print_data()]) e3.pack() label1.pack() b1.pack() root.mainloop() This will make a csv file which will look like: DATE INPUT 06/11/17 10:58:17AM test I am not familiar with csv module, so i am not sure about resizing the columns, but i am checking for you now. This code however does remove the ####### you were having and at least displays the date
has comment: http://stackoverflow.com/comment/81314375
has comment: http://stackoverflow.com/comment/81316418
score: 0
answers question: http://stackoverflow.com/q/47134833
has comment: http://stackoverflow.com/comment/81220698
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81220648
accepted answer of: http://stackoverflow.com/q/47134833
has comment: http://stackoverflow.com/comment/81316657

http://stackoverflow.com/comment/90205529
type: Comment
comment on: http://stackoverflow.com/a/47159136
score: 0
type: AnswerComment
has text: @freakish That doesn't count the number of lines, that just counts the size. You'd have to for loop over the buffer and count '\n'. I'd edit your answer but it has a benchmark so I can't (As it'll affect the output). It's probably better benchmarking to include a final printf so it's actually input/output identical to the python, and so you would've noticed the logic error.

http://stackoverflow.com/comment/81290356
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47170354
type: Comment
has text: and the `or` part with backticks?

http://stackoverflow.com/comment/81274673
type: QuestionComment
score: 0
has text: Please show the code that you've tried, and where you have problem that you're unable to solve.
comment on: http://stackoverflow.com/q/47162310
type: Comment

http://stackoverflow.com/comment/81271286
comment on: http://stackoverflow.com/a/47151660
type: AnswerComment
score: 0
type: Comment
has text: Wow! That's a beautiful error page! Thanks! I'll go look for a template!

http://stackoverflow.com/a/47165456
has comment: http://stackoverflow.com/comment/81346283
has body: Use level order traversal and store the contents of each level in a string. After each level is complete, print the string. This is the basics. If you now want fancier output like the one you have above, you can look into better ways to space out the elements and maybe use a graphics library to display the nodes.
answers question: http://stackoverflow.com/q/47164748
has comment: http://stackoverflow.com/comment/81299429
score: 1
upvote count: 1
type: Answer
downvote count: 0

gradient-descent
tags question: http://stackoverflow.com/q/47156113
tag name: gradient-descent
tags question: http://stackoverflow.com/q/47178371
tags question: http://stackoverflow.com/q/47165079
tags question: http://stackoverflow.com/q/47211478
type: Tag
tags question: http://stackoverflow.com/q/47103581

http://stackoverflow.com/comment/81300372
has text: @CuriousStudent I am going to credit @jezrael with providing you the solution to that, and I didn't want to _copy_ that. Basically see `df['Text'].apply(lambda x: ' '.join(x.split(' ')[:-1]))` in his answer where he uses `x.foo` and not `x.str.foo`.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47175387
type: AnswerComment

http://stackoverflow.com/comment/81366099
comment on: http://stackoverflow.com/q/47208391
score: 0
type: Comment
has text: That did it. If it's a duplicate question, please show me where. I was surprised I couldn't find it. Maybe I wasn't asking the most correct way.
type: QuestionComment

http://stackoverflow.com/a/47121063
type: AcceptedAnswer
downvote count: 0
has body: You cannot modify immutable objects in python, no. Any reassignment does not modify the original object, but simply changes the reference that the variable points to. With mutable objects, you can modify it contents, and the changes will be seen when accessing the object via any variables/references that point to it. Understanding the difference between objects and references is the key to understanding this. Since you're curious to know if this is possible... it is! But only if you wrap your string inside something else, say, a dict. def get_new_name(d): d['name'] = 'new_name' name = 'name' d = {'name' : name} get_new_name(d) name = d['name'] print(name) 'new_name' You'd also need to decide on some protocol that you and the function agree upon for smooth communication between each other. Sure, you could also use a global variable, but your question wasn't really about that... and I wouldn't recommend doing it either - it's bad practice to create impure functions.
has comment: http://stackoverflow.com/comment/81191890
accepted answer of: http://stackoverflow.com/q/47121021
has comment: http://stackoverflow.com/comment/81191882
type: Answer
has comment: http://stackoverflow.com/comment/81191923
score: 4
answers question: http://stackoverflow.com/q/47121021
upvote count: 4

http://stackoverflow.com/comment/81298874
type: Comment
score: 0
type: QuestionComment
has text: @ElliottBrossard - I'll do so. A quick point to note though, I had ruled out streaming the data in as its seems that this prevents DML on the table, you get a message about there being a streaming buffer. But if there's a way to stop the streaming buffer enabling further DML then this may prove to be the best option. Is there any such way of turning off the buffer after the data has been loaded?
comment on: http://stackoverflow.com/q/47168595

http://stackoverflow.com/comment/81373238
type: AnswerComment
has text: You're welcome! Things like this are frustrating for all of us when we first start programming.
type: Comment
comment on: http://stackoverflow.com/a/47211865
score: 0

http://stackoverflow.com/a/47108463
score: -1
has comment: http://stackoverflow.com/comment/81167367
upvote count: 0
has body: It is not awry code, you want to add two informations, therefore you must either pass two parameters to format or concatenate the string more "manually" You could go with Logging.info("initial data " + hash_value + " " + data) Or you could change the "data" object so its "str" or the repr method adds the hash by itself (preferably the repr in this case) Class Data(): .... def __repr__(self): Return self.hash() + " " self.data Which in this case will print the hash and the string version of the parameter data( or simply whatever you want to show as string) passing only one parameter in the string format. Anyway, you could make the formating string prettier with.... Logging.info("Initial data {hash} {data}".format(hash=hash_value, data=data)) By the way, in C++ and Java you would also need to declare two "entries" for those two atributes. In java would be something like this: LOGGING.info("Initial data {} {}", hash, data);
downvote count: 1
answers question: http://stackoverflow.com/q/47108372
has comment: http://stackoverflow.com/comment/81173726
type: Answer

http://stackoverflow.com/comment/93496981
type: AnswerComment
has text: This worked! thanks a lot! I am trying to figure out the problem for more than an hour. Reinstalling my python, messing with the files on the lib/site-packages folder.
type: Comment
comment on: http://stackoverflow.com/a/49335954
score: 0

http://stackoverflow.com/q/47088969
has comment: http://stackoverflow.com/comment/81129354
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47089497
upvote count: 0
type: UnansweredQuestion
has title: Can't figure out small errors in my code?
answer count: 1
has comment: http://stackoverflow.com/comment/81127297
downvote count: 1
favorite count: 0
has body: MY CODES PROBLEMS 3 and 4: def avg_weight(diet, data): acc = [] grams = data.items() for (name , food , weights) in grams: if diet == food: acc.append([weights]) total = sum(acc) avg = total / len(acc) return avg up above I get a syntax error with the acc.append([weights]) line for some reason 3: def word_positions(phrase): str.split(phrase) for num in phrase: return (num + ":" + str(phrase[num]) I get a random EOF error for some reason. Thanks guys!
type: Question

http://stackoverflow.com/a/47169865
accepted answer of: http://stackoverflow.com/q/47169035
has comment: http://stackoverflow.com/comment/81289858
answers question: http://stackoverflow.com/q/47169035
has body: Try this: def createDir(path): if not os.path.exists(path): os.mkdir(path) import os cwd = os.getcwd() config = { 'g7': {}, 'd5': {}, 'a9': {}, } config['g7']['append_dir_to_filename'] = 1 config['g7']['device_name'] = 'Canon-G7' config['g7']['raw_file'] = ('cr2', 'jpg', 'mp4') config['d5']['append_dir_to_filename'] = 1 config['d5']['device_name'] = 'Nikon-D5' config['d5']['raw_file'] = ('nef', 'jpg', 'avi') config['a9']['append_dir_to_filename'] = 1 config['a9']['device_name'] = 'Sony-alpha-a9' config['a9']['raw_file'] = ('mp4', 'jpg', 'avi') dirs_name = os.listdir(cwd) for dir_name in dirs_name: for key_word in config: if dir_name.endswith(key_word): _raw_files = os.path.join(cwd, dir_name, r'_raw_files') _sup_files = os.path.join(cwd, dir_name, r'_sup_files') createDir(_raw_files) createDir(_sup_files)
type: Answer
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81289762

http://stackoverflow.com/q/47081291
has comment: http://stackoverflow.com/comment/81112406
has comment: http://stackoverflow.com/comment/81112071
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81113039
has comment: http://stackoverflow.com/comment/81112211
has comment: http://stackoverflow.com/comment/81112178
tagged with: sql
accepted answer: http://stackoverflow.com/a/47082064
has comment: http://stackoverflow.com/comment/81112476
has comment: http://stackoverflow.com/comment/81111962
answer count: 1
tagged with: mysql
has answer: http://stackoverflow.com/a/47082064
has title: Python-generated MySQL SELECT query not returning full list of results
type: Question
has comment: http://stackoverflow.com/comment/81112106
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81112297
score: 0
has body: I am writing a Python3 script that takes a number inputted by a user and assigns it to a variable called "set_budget", which is then used to construct a MySQL SELECT query. I'm using the MySQLdb database connector library. The relevant section of my code looks like this: set_budget = '' set_budget = sys.argv[1] budget = '' if set_budget == '0': budget = '10.00' elif set_budget == '1': budget = '25.00' elif set_budget == '2': budget = '50.00' else: print('Enter "0" for $10.00, "1" for $25.00, and "2" for $50.00') budget_query = ("SELECT park_name FROM parks WHERE admission_price &lt;= " + budget) cursor = connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute (budget_query) result_set = cursor.fetchall() This should theoretically create a MySQL query like SELECT park_name FROM parks WHERE admission_price &lt;= 10.00 if the user inputs the number "0". The admission_price column is a decimal(5,2) field in the database. When I query SELECT park_name FROM parks WHERE admission_price &lt;= 10.00 directly in MySQL it properly returns all of the parks where the admission_price is between 0.00 and 10.00. However, when I run my Python script, only the parks with an admission price between 0.00 and 9.99 are returned. Moreover, if I select the $25.00 option by typing "1" in the script it inexplicably excludes some parks priced between 10.00 and 25.00 in addition to excluding parks where the admission_price is exactly 25.00. Am I doing something wrong in the execution of this code or should I be using a different method to construct MySQL queries with Python?
tagged with: python
has comment: http://stackoverflow.com/comment/81112127

matplotlib
tags question: http://stackoverflow.com/q/47104220
tags question: http://stackoverflow.com/q/47217891
tags question: http://stackoverflow.com/q/47109960
tags question: http://stackoverflow.com/q/47167490
tags question: http://stackoverflow.com/q/47097985
tags question: http://stackoverflow.com/q/47211866
tags question: http://stackoverflow.com/q/47065228
tags question: http://stackoverflow.com/q/47204715
tags question: http://stackoverflow.com/q/47091592
tags question: http://stackoverflow.com/q/47087407
tags question: http://stackoverflow.com/q/47152353
tags question: http://stackoverflow.com/q/47072014
tags question: http://stackoverflow.com/q/47189276
tags question: http://stackoverflow.com/q/47196669
tags question: http://stackoverflow.com/q/47104101
tags question: http://stackoverflow.com/q/47118563
tags question: http://stackoverflow.com/q/47167496
tags question: http://stackoverflow.com/q/47212474
tags question: http://stackoverflow.com/q/47081343
tags question: http://stackoverflow.com/q/47170230
tags question: http://stackoverflow.com/q/47155569
tags question: http://stackoverflow.com/q/47098063
tags question: http://stackoverflow.com/q/47123681
tags question: http://stackoverflow.com/q/47074423
tags question: http://stackoverflow.com/q/47102873
tags question: http://stackoverflow.com/q/47122494
tags question: http://stackoverflow.com/q/47141827
tags question: http://stackoverflow.com/q/47148585
tags question: http://stackoverflow.com/q/47126186
tags question: http://stackoverflow.com/q/47142840
tags question: http://stackoverflow.com/q/47076428
tags question: http://stackoverflow.com/q/47220786
tags question: http://stackoverflow.com/q/47084879
tags question: http://stackoverflow.com/q/47084641
tags question: http://stackoverflow.com/q/47117354
tags question: http://stackoverflow.com/q/47161832
tags question: http://stackoverflow.com/q/47083648
tags question: http://stackoverflow.com/q/47199527
tags question: http://stackoverflow.com/q/47186962
tags question: http://stackoverflow.com/q/47212868
tags question: http://stackoverflow.com/q/47146855
tags question: http://stackoverflow.com/q/47207620
tags question: http://stackoverflow.com/q/47101046
tags question: http://stackoverflow.com/q/47084987
tags question: http://stackoverflow.com/q/47127554
tags question: http://stackoverflow.com/q/47155550
tags question: http://stackoverflow.com/q/47124683
tags question: http://stackoverflow.com/q/47148803
tags question: http://stackoverflow.com/q/47112381
tags question: http://stackoverflow.com/q/47223288
tags question: http://stackoverflow.com/q/47118267
tags question: http://stackoverflow.com/q/47165138
tags question: http://stackoverflow.com/q/47170051
tag name: matplotlib
tags question: http://stackoverflow.com/q/47203332
tags question: http://stackoverflow.com/q/47197949
tags question: http://stackoverflow.com/q/47112522
tags question: http://stackoverflow.com/q/47194496
tags question: http://stackoverflow.com/q/47187153
tags question: http://stackoverflow.com/q/47129625
tags question: http://stackoverflow.com/q/47083979
tags question: http://stackoverflow.com/q/47079385
tags question: http://stackoverflow.com/q/47185277
tags question: http://stackoverflow.com/q/47120191
tags question: http://stackoverflow.com/q/47151484
tags question: http://stackoverflow.com/q/47158443
tags question: http://stackoverflow.com/q/47105021
tags question: http://stackoverflow.com/q/47086205
tags question: http://stackoverflow.com/q/47101836
tags question: http://stackoverflow.com/q/47136578
tags question: http://stackoverflow.com/q/47163614
tags question: http://stackoverflow.com/q/47111159
tags question: http://stackoverflow.com/q/47144724
tags question: http://stackoverflow.com/q/47200326
tags question: http://stackoverflow.com/q/47128570
tags question: http://stackoverflow.com/q/47121997
tags question: http://stackoverflow.com/q/47212554
tags question: http://stackoverflow.com/q/47179961
tags question: http://stackoverflow.com/q/47147748
tags question: http://stackoverflow.com/q/47083947

http://stackoverflow.com/comment/81288429
type: QuestionComment
comment on: http://stackoverflow.com/q/47169221
score: 1
has text: Correct, I only want it available on the computer running it.
type: Comment

http://stackoverflow.com/q/47185226
has body: I create a new Process from django app. Can i create new record in database from this process? My code throws exception: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. UPD_1 def post(self, request): v = Value('b', True) proc = Process(target=start, args=(v, request.user, request.data['stock'], request.data['pair'], '1111')) proc.start() def start(v, user, stock_exchange, pair, msg): MyModel.objects.create(user=user, stock_exchange=stock_exchange, pair=pair, date=datetime.now(), message=msg)
tagged with: database
tagged with: python
has answer: http://stackoverflow.com/a/54352549
answer count: 2
upvote count: 3
type: UnansweredQuestion
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/47185644
favorite count: 0
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/81319554
score: 3
has title: Django access to database from another process
linked to: http://stackoverflow.com/q/8242837
has comment: http://stackoverflow.com/comment/81319786

http://stackoverflow.com/comment/81327305
has text: Thanks for the explanation. Seems like the opposite of java, in which == is the memory location while str.is() is the content of the string.
comment on: http://stackoverflow.com/q/47188706
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81265408
has text: This doesn't answer your question, but why not use `wc` instead of Python? `cat huge.csv | wc -l`, or `wc -l huge.csv`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47158071

http://stackoverflow.com/comment/81262759
comment on: http://stackoverflow.com/a/47153241
score: 0
type: Comment
has text: I am new here , and i think we can not chat , for chat we need REPUTATION100
type: AnswerComment

http://stackoverflow.com/q/47161699
tagged with: python
has title: Open image after BytesIO
has body: I would like to get a photo from my url. Trying to create it ,then use .get() and convert it into :BytesIO() img = Image.fromarray(srcData) fp = 'https://telegram.org/new.png' response = requests.get(fp) f = BytesIO(response.content) f.seek(0) f=Image.open(f) Why do I get an error, which is: cannot identify image file _io.bytesio Then try to send it: bot.send_photo(chat_id=chat_id, photo=f)
score: 0
answer count: 0
linked to: http://stackoverflow.com/q/13137817
has comment: http://stackoverflow.com/comment/81273242
type: Question
has comment: http://stackoverflow.com/comment/81273706
has comment: http://stackoverflow.com/comment/81275066
has comment: http://stackoverflow.com/comment/81274361
type: UnansweredQuestion

http://stackoverflow.com/a/47215200
type: Answer
answers question: http://stackoverflow.com/q/47215094
has body: It seems that you don't understand the iterator very clearly, or something else. for mileINk in miles: In each iteration of the above statement, Python assess one element in miles to mileINk. Thus, mileINk not equals to 1.609344 anymore, but equals to 0,1,2,3,4 in each iteration. Changing the statement to for mile in miles: conV = mileINk * mile kilo.append(str(conV)) is ok.
score: 0

http://stackoverflow.com/a/47071220
has body: Instance and class attributes can be kind of confusing to understand at first. The best way of thinking about it is to pay attention to the name. Instance attributes are owned by the specific instance of the class, meaning that these attributes can vary from instance to instance of a specific class. On the other hand, Class attributes are owned by the class itself, so the attribute has the same value for each instance of a particular class. In your example, var would be a class attribute to every instance of MyClass. However, once var is set to a different value for any given instance, say this_obj.var = 69, then this_obj.var is now an instance attribute to the this_obj instance. Meaning, instance attribute are created upon changing the class attribute of any instance. Hope that helps! EDIT: You can also change the class attribute value itself, meaning it'll change for all instances without an instance attribute for that specific variable. For example MyClass.var = 34 would change the value for all instances of MyClass that hasn't created an instance attribute yet.
answers question: http://stackoverflow.com/q/47070899
upvote count: 3
score: 3
type: Answer
downvote count: 0

http://stackoverflow.com/comment/81207148
has text: so the desired output is ... `[1,0,1,1]`?
comment on: http://stackoverflow.com/q/47128539
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81374894
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47212686
has text: You want `self.assertIsInstance` instead of `isInstance`.
score: 2

http://stackoverflow.com/q/47168026
tagged with: python
has body: For learning purposes, I wrote a test.py which simply will print out "Hello World". Now the problem is that I want to have like an installer for Windows so the program installs and executes after being installed. test.py hello() def hello(): print('HELLO WORLD') So do I have to change the code in the program a little bit or something else?
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81286019
tagged with: installation
downvote count: 0
linked to: http://stackoverflow.com/q/49146
answer count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81286034
has comment: http://stackoverflow.com/comment/81286015
tagged with: windows
has title: How to make a windows standalone installer for my test.py
has answer: http://stackoverflow.com/a/47168348
accepted answer: http://stackoverflow.com/a/47168348

http://stackoverflow.com/comment/81082872
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47066728
has text: If it works, what exactly does it return?
score: 0

http://stackoverflow.com/a/47160904
accepted answer of: http://stackoverflow.com/q/47160708
type: Answer
has comment: http://stackoverflow.com/comment/81315043
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47160708
has body: You can try this: new_final_data = [[b for a, b in i.items()][0][0][0] for i in a] output = [{"Name":i["Name"], 'Value':i['ResourceRecords'][0]["Value"]} for i in new_final_data] Output: [{'Name': 'xyz.net.', 'Value': '1.1.1.1'}]
has comment: http://stackoverflow.com/comment/81314560
score: 0

http://stackoverflow.com/comment/81339373
has text: I got this message now
comment on: http://stackoverflow.com/a/47195101
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81205832
type: QuestionComment
comment on: http://stackoverflow.com/q/47127734
score: 0
has text: If that other script is just a main function (or has no function), you'll need to make one that accepts the ip as a parameter
type: Comment

http://stackoverflow.com/comment/81204188
type: QuestionComment
has text: yes, you define form fields fields = ('title', 'id', 'description', 'url', 'active') and you don't have parents in it, what is equal to exclude = ('parents'). do you make it specially because you cannot save parents or there is another reason for that?
score: 0
comment on: http://stackoverflow.com/q/47126208
type: Comment

http://stackoverflow.com/a/47157509
has body: The reason your code doesn't work is you are trying to use split on a list, but it is meant to be used on a string. Therefore in your example you would use row2[0] to access the first element of the list. my_list = row2[0].split(" ") Alternatively, if you have access to the numpy library you can use loadtxt. import numpy as np f = np.loadtxt("data.txt", dtype=str, skiprows=1) print (f) # ['second_row_1' 'second_row_2' 'second_row_3'] The result of this is an array as opposed to a list. You could simply cast the array to a list if you require a list print (list(f)) #['second_row_1', 'second_row_2', 'second_row_3']
accepted answer of: http://stackoverflow.com/q/47157240
type: Answer
has comment: http://stackoverflow.com/comment/81265055
upvote count: 4
score: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47157240
downvote count: 0
has comment: http://stackoverflow.com/comment/81264411

http://stackoverflow.com/q/47104306
type: Question
has body: I want to do in a for loop something like this: for i in range(n): x = vector() np.savetxt('t.txt', x, newline=" ") but I want to save each array x as a new line in my file, but this doesn't happen with the code above, can anybody help? Thanks!
has answer: http://stackoverflow.com/a/47104494
score: 1
has comment: http://stackoverflow.com/comment/81159439
tagged with: python
linked to: http://stackoverflow.com/q/45222878
has title: How to save array iteratively to file in python?
tagged with: numpy
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81159232
has answer: http://stackoverflow.com/a/47104361
upvote count: 1
type: UnansweredQuestion
tagged with: file
favorite count: 0

http://stackoverflow.com/comment/81159268
type: Comment
has text: what have you tried? I would assume maybe something with zip or defining your own function??
comment on: http://stackoverflow.com/q/47104354
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81365721
type: Comment
comment on: http://stackoverflow.com/a/47207396
score: 0
type: AnswerComment
has text: Please see further question update. Apologies about not providing such detail initially. Perhaps i should accept your answer and open a new question.

http://stackoverflow.com/q/47190486
tagged with: spyder
has answer: http://stackoverflow.com/a/47190551
tagged with: python
favorite count: 0
type: Question
tagged with: numpy
downvote count: 0
type: UnansweredQuestion
has title: spyder (python) variable explorer different view
answer count: 1
upvote count: 1
score: 1
has body: i am looking at a tutorial video, and i copied and paste the code. somehow the way spyder shows some variables is different from the way in the tutorial video. this is the way it shows on my pc, i need to double click total_reward to see the value 2178. and this is the way it is shown in the video how can i make spyder show me the value without clicking "class 'numpy.int64'"? it is exactly the same code.

http://stackoverflow.com/comment/81380494
type: Comment
comment on: http://stackoverflow.com/a/47211729
score: 0
type: AnswerComment
has text: Have you been able to get this command to work on the command line and in a Python script by calling it with subprocess? command: 'java -cp "/usr/local/lib/stanford-corenlp-full-2017-06-09/*" -Xmx2g edu.stanford.nlp.pipeline.StanfordCoreNLP -annotators tokenize,ssplit,pos,lemma,ner,parse,dcoref -file nlp.txt 2>parse.out'

http://stackoverflow.com/q/47186322
has body: I'm trying to make a window with wxPython, but trying to install it into the project interpreter in my Pycharm project doesn't work. I then tried installing it onto my computer, but that didn't work either. I've read that wxPython is not very compatible with Linux, so I'm drawing a blank. How do I get wxPython onto Ubuntu 16.04 and then allow me to use Pycharm in order to make the window?
has answer: http://stackoverflow.com/a/53649056
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81322988
has answer: http://stackoverflow.com/a/47208282
favorite count: 0
answer count: 2
tagged with: pycharm
type: UnansweredQuestion
tagged with: wxpython
has title: Getting wxPython with Ubuntu 16.04 and using it with Pycharm
tagged with: python
tagged with: ubuntu
type: Question
has comment: http://stackoverflow.com/comment/81322662
downvote count: 0

http://stackoverflow.com/comment/81364498
has text: Pro tips: homework questions are welcome here. However, it is best to ask confidently. Don't be chatty or beg, it's like asking for downvotes. "Please halp me", "Be nice to me", "Thanks in advance" are all best refrained from. We like succinct questions here anyway.
score: 0
comment on: http://stackoverflow.com/q/47193691
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47263399
type: AcceptedAnswer
downvote count: 0
has body: As @pvg mentioned in the comments, overriding load_resource function with your base64 functionality does the trick. import base64,io def load_resource(self, reason, filename): if reason == "image": if filename.startswith("http://") or filename.startswith("https://"): f = BytesIO(urlopen(filename).read()) elif filename.startswith("data"): f = filename.split('base64,')[1] f = base64.b64decode(f) f = io.BytesIO(f) else: f = open(filename, "rb") return f else: self.error("Unknown resource loading reason \"%s\"" % reason) EDIT : This is a sample code to insert images into pdf. I commented some instructions in code. from fpdf import FPDF import os import io import base64 class PDF(FPDF): def load_resource(self, reason, filename): if reason == "image": if filename.startswith("http://") or filename.startswith("https://"): f = BytesIO(urlopen(filename).read()) elif filename.startswith("data"): f = filename.split('base64,')[1] f = base64.b64decode(f) f = io.BytesIO(f) else: f = open(filename, "rb") return f else: self.error("Unknown resource loading reason \"%s\"" % reason) def sample_pdf(self,img,path): self.image(img,h=70,w=150,x=30,y=100,type="jpg") #make sure you use appropriate image format here jpg/png pdf.output(path, 'F') if __name__ == '__main__': img = # pass your base64 image # you can find sample base64 here : https://pastebin.com/CaZJ7n6s pdf = PDF() pdf.add_page() pdf_path = # give path to where you want to save pdf pdf.sample_pdf(img,pdf_path)
answers question: http://stackoverflow.com/q/47195075
has comment: http://stackoverflow.com/comment/105204846
accepted answer of: http://stackoverflow.com/q/47195075
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/114955860
upvote count: 3

http://stackoverflow.com/q/47205568
upvote count: 3
type: UnansweredQuestion
answer count: 1
tagged with: mitmproxy
downvote count: 0
tagged with: websocket
has title: Mitmproxy, push own WebSocket message
favorite count: 0
score: 3
has body: I inspect a HTTPS WebSocket traffic with Mitmproxy. Currently I can read/edit WS messages with: class Intercept: def websocket_message(self, flow): print(flow.messages[-1]) def start(): return Intercept() .. as attached script to Mitmproxy. How do I push/inject my own message to the client? Not edit existing one, but add a new message.
tagged with: python
has answer: http://stackoverflow.com/a/70210105
type: Question

http://stackoverflow.com/a/47200163
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47199246
upvote count: 1
has body: A regex is just a string which may or may not contain wildcard or special characters. So the best way to "make elements of a list part of a regex" is to 'write' the regex : my_list = ['hope', 'faith', 'help'] for regex_el in my_list: regex = "{0:s}".format(regex_el) print regex Of course that is over simplistic. That's just using a plain string as a regex. You could have small regular expressions to bolt into the larger regex or you could surround the element from the list with other parts of a regex : regex = "^ *{0:s} ".format(regex_el) Would construct a regex to find your word only if it were the first word in a string, preceded by none or more spaces and followed by a space. Then in your code, replace the 'word' in your call to findall with the 'regex' constructed above. You will need to replace the line_list in your call to findall as well as findall expects a pattern (be that a simple string or a genuine regex) and a string in which to search (that could be word in your loop or line from the loop over lines in the file. Also note print match will print an empty list if no match was found. You may wish to replace that with if match: print(match) To only print words from the line which match your constructed regex. Could I recommend you check out this website : https://regex101.com/ to experiment with regexs and the strings you're aplying them to.
type: Answer

http://stackoverflow.com/comment/81089514
has text: Can you say your tensorflow version and python release?
type: AnswerComment
comment on: http://stackoverflow.com/a/47070464
score: 0
type: Comment

http://stackoverflow.com/q/47087451
tagged with: python
tagged with: pandas
type: AnsweredQuestion
score: 0
has title: Refer to next index in pandas
answer count: 1
has body: If I had a simple pandas DataFrame like this: frame = pd.DataFrame(np.arange(12).reshape((3,4)), columns=list('abcd'), index=list('123')) I want find the max value from each row, and use this to find the next value in the column and add this value to a new column. So the above DataFrame looks like this (with d2 changed to 3): a b c d 1 1 2 3 4 2 5 6 7 3 3 9 10 11 12 So, conceptually the first row should be scanned, 4 is identified as the largest number, then 3 is found as the number within the same column but in the next index. Similarly for the row 2, 7 is the largest number, and 11 is the next number in that column. So 3 and 11 should get added to a new column like this: a b c d Next 1 1 2 3 4 NaN 2 5 6 7 3 3 3 9 10 11 12 11 I started by making a function like this, but it only finds the max values. f = lambda x: x.max() max = frame.apply(f, axis='columns') frame['Next'] = max
accepted answer: http://stackoverflow.com/a/47087520
type: Question
has answer: http://stackoverflow.com/a/47087520

http://stackoverflow.com/q/47189215
accepted answer: http://stackoverflow.com/a/47189439
type: AnsweredQuestion
answer count: 3
tagged with: pandas
downvote count: 0
upvote count: 1
score: 1
possible better answer: http://stackoverflow.com/a/47189464
has body: I am having dataframe df. I need to subtract only non-zero values in dataframe and if its 0 then keep its as 0. difference = df[value] - 10 Help me in doing conditional subtracting efficiently as possible, subtract only if value greater than zero in dataframe. Dataframe df value 1 0 2 0 3 0 4 0 5 51.134 6 52.4833 7 53.7698 8 5 Expected output: 0 0 0 0 41.134 42.4833 43.7698 -5
has answer: http://stackoverflow.com/a/47189464
has answer: http://stackoverflow.com/a/47189301
has answer: http://stackoverflow.com/a/47189439
favorite count: 0
type: Question
has title: Need to subtract only the non-zero values in pandas - python
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/81343505
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47196843
score: 0
has text: @user110244: Because what comes after `for` is used for an assignment. It can be a variable, an element in a sequence. `for x in A:; A[-1] = x` is really equivalent to `for A[-1] in A`.

http://stackoverflow.com/comment/81156684
comment on: http://stackoverflow.com/a/47091242
has text: A static code analyzer like rubocop will tell you not to use DateTime and favor Date or Time if one of the simpler classes will do. Unless a DateTime method is being called with a start argument such as Date::ENGLAND, Date::GREGORIAN, Date::ITALY or Date::JULIAN, it will be less performant. TLDR: You can almost always use Time instead of DateTime.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47067050
type: Question
has answer: http://stackoverflow.com/a/47067553
has comment: http://stackoverflow.com/comment/81082762
has title: Is there any way to call synchronously the method 'toHtml' which is QWebEnginePage's object?
has comment: http://stackoverflow.com/comment/81083247
has answer: http://stackoverflow.com/a/51955678
has body: I'm trying to get html code from the QWebEnginePage object. According to Qt reference, QWebEnginePage object's 'toHtml' is asynchronous method as below. Asynchronous method to retrieve the page's content as HTML, enclosed in HTML and BODY tags. Upon successful completion, resultCallback is called with the page's content. so I tried to find out how call this method synchronously. the result what i want to get is below. class MainWindow(QWidget): html = None ... ... def store_html(self, data): self.html = data def get_html(self): current_page = self.web_view.page() current_page.toHtml(self.store_html) # I want to wait until the 'store_html' method is finished # but the 'toHtml' is called asynchronously, return None when try to return self.html value like below. return self.html ... ...
tagged with: qwebengineview
tagged with: python
score: 4
possible better answer: http://stackoverflow.com/a/70919697
upvote count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/70919697
answer count: 3
tagged with: pyqt
tagged with: qwebenginepage
downvote count: 0
tagged with: pyqt5
favorite count: 0
accepted answer: http://stackoverflow.com/a/47067553

http://stackoverflow.com/q/47071450
tagged with: python
possible better answer: http://stackoverflow.com/a/47071610
answer count: 4
has body: I have a number of lists called: index_1, index_2, index_3, ...., index_n. What I want is to concatenate them all in a new list. My code so far: index_all=[] for i in range(1,n+1): index_all = index_all + globals()["index_"+str(i)] However, I get an error: KeyError: index_1 Any ideas as to how to solve this?
favorite count: 0
has comment: http://stackoverflow.com/comment/81091098
has answer: http://stackoverflow.com/a/47071831
type: Question
tagged with: concatenation
has comment: http://stackoverflow.com/comment/81091538
upvote count: 1
has comment: http://stackoverflow.com/comment/81091133
has answer: http://stackoverflow.com/a/47072085
has comment: http://stackoverflow.com/comment/81091516
accepted answer: http://stackoverflow.com/a/47072085
has answer: http://stackoverflow.com/a/47071610
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81091023
tagged with: list
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/47071700
has comment: http://stackoverflow.com/comment/81091578
has title: Concatenate a variable number of lists in Python

http://stackoverflow.com/comment/81176444
score: 0
has text: You may need elevated privileges.
comment on: http://stackoverflow.com/q/47113240
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47128095
answer count: 2
has title: How to run for loop in pandas
tagged with: pandas
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81206685
favorite count: 0
type: Question
has body: I am doing a coursera course and want to create various dataframe using for loop, the idea is to create a list and then add each df into the list. However, below come back with error: File "&lt;ipython-input-10-2863e455a5c5&gt;", line 7 array.append(county_df.where(county_df['STNAME']=state)) ^ SyntaxError: keyword can't be an expression census_df = pd.read_csv('census.csv') county_df=census_df[census_df['SUMLEV'] == 50] county_df.head() county_df['STNAME'].unique() list = [] print type(list) for state in county_df['STNAME'].unique(): array.append(county_df.where(county_df['STNAME']=state)) print (list)
has answer: http://stackoverflow.com/a/47128910
has answer: http://stackoverflow.com/a/47128435
has comment: http://stackoverflow.com/comment/81206583
has comment: http://stackoverflow.com/comment/81206998
tagged with: python
linked to: http://stackoverflow.com/q/11633421

http://stackoverflow.com/comment/81105391
score: 1
type: Comment
type: QuestionComment
has text: no, not a stupid question. I think this answer can explain it better than I can: https://stackoverflow.com/questions/40741282/cannot-use-requests-module-on-aws-lambda
comment on: http://stackoverflow.com/q/47077829

http://stackoverflow.com/comment/81109711
type: QuestionComment
has text: Since django-admin works, you can do `django-admin runserver`. I don't know what's wrong with your environment. You can try `python -c 'import django'` to confirm that the virtualenv is indeed activated as expected. What is the contents of your `manage.py` file?
comment on: http://stackoverflow.com/q/47078101
score: 0
type: Comment

http://stackoverflow.com/a/47122273
score: 1
type: Answer
has body: You could try dict comprehension : population_dict = {" ".join(str(x) for x in item[0]): int(item[1][0]) for item in population} this dict comprehension is same as: population_dict={} for item in population: population_dict[" ".join(str(x) for x in item[0])] = int(item[1][0]) print(population_dict) output: {'0 0 1 1 1 0 0 1 1 0 1 1 0 0 0 1': 3, '0 0 1 0 1 1 0 1 1 1 1 0 0 0 0 1': 1, '1 0 0 1 1 1 0 0 1 1 0 1 1 0 0 0': 3, '0 1 1 0 1 1 0 0 1 1 1 0 0 1 0 0': 4}
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47120859

http://stackoverflow.com/comment/81202671
comment on: http://stackoverflow.com/q/47126172
type: Comment
type: QuestionComment
has text: Do the slices of C not reference the original? I was under the impression that numpy slices were views. How does one modify the initial matrix?
score: 0

http://stackoverflow.com/q/47110317
has comment: http://stackoverflow.com/comment/81171695
has comment: http://stackoverflow.com/comment/81171650
has body: I want to load pre-trained word embedding from glove, and there are some errors of encoding, I have tried encoding, but no work, how to fix this? def load_word_embedding_glove(glovefile): print ("loading golve word embddings...") f = open(glovefile, 'r', encoding='utf-8') model = {} for line in f: splitLine = line.split() word = splitLine[0] embdding = [float(val) for val in splitLine[1:]] model[word] = embdding print ("glove word embedding is loaded") return model I then print (model), the error occurs: filepath = "../Pretrained/glove/glove.6B.100d.txt" model = load_word_embedding_glove(filepath) print (model) the error: UnicodeEncodeError: 'ascii' codec can't encode character '\u2013' in position 208465: ordinal not in range(128) by the way, I used python 3.
has comment: http://stackoverflow.com/comment/81171682
type: Question
tagged with: encoding
has comment: http://stackoverflow.com/comment/81171265
answer count: 0
has comment: http://stackoverflow.com/comment/81171170
type: UnansweredQuestion
tagged with: word-embedding
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/81171386
has comment: http://stackoverflow.com/comment/81171699
has title: loading glove word embedding has encoding error

http://stackoverflow.com/a/47393161
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47210058
has comment: http://stackoverflow.com/comment/135377560
score: 3
has body: After digging through the source code, I can answer this now. The setup.py file: from numpy.distutils.command.install import install as _install from numpy.distutils.core import Extension from numpy.distutils.core import setup extF = Extension(name="test_module.fortran_module", sources=["test_module/fortran_module.f90"]) compile_args_parallel = "-fopenmp" link_args_parallel = "-lgomp" class install(_install): user_options = _install.user_options + [('build=', None, None)] def initialize_options(self): _install.initialize_options(self) self.build = None def finalize_options(self): _install.finalize_options(self) if(self.build == "parallel"): for ext in self.distribution.ext_modules: if(ext.name == "test_module.fortran_module"): ext.extra_f90_compile_args = compile_args_parallel ext.extra_link_args = link_args_parallel def run(self): _install.run(self) setup( name="test_module", packages=["test_module"], ext_modules=[extF], cmdclass={"install": install} ) Installing this with pip install . installs the serial version and pip install . --install-option="--build=parallel" installs the parallel version of the Fortran module.
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/92299961
answers question: http://stackoverflow.com/q/47210058

http://stackoverflow.com/comment/81404375
type: Comment
comment on: http://stackoverflow.com/a/47212796
has text: No problem. That's not anger; more of "Sorry, bro, that's the end of our leash." When the question gets to coding basic skills that are in many tutorials, we expect you to find it on your own -- and probably learn the next five things while you're looking.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81174841
comment on: http://stackoverflow.com/q/47111897
has text: Can you explain why they don't `seem to run simultaniously` or interact? How do you know?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47163141
answers question: http://stackoverflow.com/q/47162981
has comment: http://stackoverflow.com/comment/81399910
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47162981
has body: A simple solution for this specific problem is to return a new list, rather than the foo object. def list_gen(): foo = [1,2,3,4] for i in range(5, 9): foo[1] = i yield list(foo) Disclaimer: I don't use generators a lot, so this could be against best practice. But it solves the problem.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81275937

http://stackoverflow.com/q/47161060
has comment: http://stackoverflow.com/comment/81272116
has comment: http://stackoverflow.com/comment/81271731
answer count: 1
accepted answer: http://stackoverflow.com/a/47161121
duplicate of: http://stackoverflow.com/q/18665873
has answer: http://stackoverflow.com/a/47161121
type: Question
has comment: http://stackoverflow.com/comment/81271729
has comment: http://stackoverflow.com/comment/81271678
has title: Keep specific columns of list based on boolean Array
tagged with: arrays
has body: In Python I have a list with column names that has the following form: columns_names = ['example1', 'example2', 'example3', 'example4', 'example5'] and an array which describes which columns should be used and has the following form: columns_used = [False False True False True] I want to create a new list that contains only the columns that I would like to use (the array value is True). columns_names_used = ['example3', 'example5']
tagged with: python
linked to: http://stackoverflow.com/q/18665873
type: AnsweredQuestion
score: 0
tagged with: list

http://stackoverflow.com/comment/81559960
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47285131
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/159045/discussion-between-rebecca21-and-bharath).

http://stackoverflow.com/comment/81276163
type: Comment
has text: It seems that you are just using an example. You need that in <TOKEN> you use an actual token. It looks like: "Each bot is given a unique authentication token when it is created. The token looks something like 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11, but we'll use simply <token> in this document instead. You can learn about obtaining tokens and generating new ones in this document. "
type: QuestionComment
comment on: http://stackoverflow.com/q/47163157
score: 0

http://stackoverflow.com/a/47171038
has comment: http://stackoverflow.com/comment/81294818
has comment: http://stackoverflow.com/comment/81293208
accepted answer of: http://stackoverflow.com/q/47170398
has comment: http://stackoverflow.com/comment/81293282
has comment: http://stackoverflow.com/comment/81293474
has body: You haven't actually showed the part where you use your look-up table in code, however you can begin by restructuring your loop-up table to simplify your problem. Something like this: config = { 'append_dir_to_filename' : ('d5', 'a9'), 'd5': ('nef', 'jpg', 'avi'), 'a9': ('mp4', 'jpg', 'avi') } These modifications assume that you don't need information for the directories that you don't want to append to the file name. With this in place, the rest of the code is pretty straightforward: prefix = os.path.basename(root) if (prefix[-2:] in config['append_dir_to_filename']): for f in files: for extension in config[prefix[-2:]]: if (f.endswith('.' + extension)): #Do the appending business here Haven't really tested the code, but this should work for you. EDIT: In case you follow in the suggestion in my comment, use the below code: prefix = os.path.basename(root) if (prefix[-2:] in config['append_dir_to_filename']): for f in files: cameraObj = config[prefix[-2:]] for extension in cameraObj.supported_extensions: if (f.endswith('.' + extension)): #Do the appending business here and the look-up table will be like so: config = { 'append_dir_to_filename' : ('d5', 'a9'), 'd5': Camera(...list of properties...), 'a9': Camera(...list of properties...) } EDIT: Ok, I essentially had to write the entire code from scratch. This version definitely works. import os cwd = os.getcwd() config = { 'append_dir_to_filename' : ('d5', 'a9'), 'd5': ('nef', 'jpg', 'avi'), 'a9': ('mp4', 'jpg', 'avi') } cameraDirs = [os.path.join(cwd, x) for x in next(os.walk(cwd))[1] if x[-2:] in config['append_dir_to_filename']] for cameraDir in cameraDirs: cameraShortName = cameraDir[-2:] for rootDir, _, files in os.walk(cameraDir): prefix = os.path.basename(rootDir) for file in files: if (any(x for x in config[cameraShortName] if file.endswith(x))): os.rename(os.path.join(rootDir, file), os.path.join(rootDir, "{}_{}".format(prefix, file)))
has comment: http://stackoverflow.com/comment/81292461
has comment: http://stackoverflow.com/comment/81293834
answers question: http://stackoverflow.com/q/47170398
type: Answer
has comment: http://stackoverflow.com/comment/81296557
has comment: http://stackoverflow.com/comment/81291997
has comment: http://stackoverflow.com/comment/81293710
has comment: http://stackoverflow.com/comment/81291804
has comment: http://stackoverflow.com/comment/81292335
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81292834
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81126341
comment on: http://stackoverflow.com/a/47088370
score: 1
type: Comment
type: AnswerComment
has text: Your reasoning amazes me. Thanks again.

http://stackoverflow.com/comment/81373986
has text: Also not working. The Documentation tells me about this `-E Ignore all PYTHON* environment variables, e.g. PYTHONPATH and PYTHONHOME, that might be set.` Weirdly enough `PYTHONUNBUFFERED=1 python [...]` is working now... I triple checked the spelling of the environment variable. I can't explain this and feel really dumb that I took your time. Thanks for your efforts @Elias Byberi.
type: AnswerComment
comment on: http://stackoverflow.com/a/47160440
score: 1
type: Comment

http://stackoverflow.com/q/47145117
tagged with: python
accepted answer: http://stackoverflow.com/a/47160793
answer count: 1
has body: I am writing an application in which I want to be able to move rectangles by clicking and dragging them. The code below does this correctly so far from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Memory(QWidget): grid = None scene = None def __init__(self, geometry, parent=None): super(Memory, self).__init__(parent=parent) self.layout = QGridLayout(self) self.scene = QGraphicsScene(self) self.scene.setSceneRect(geometry.x(), geometry.y(), geometry.width(), geometry.height()) self.scene.setBackgroundBrush(Qt.white) self.view = QGraphicsView() self.view.setScene(self.scene) self.layout.addWidget(self.view) rect = QRectF(40, 40, 220, 110) self.make_proxy(rect) rect2 = QRectF(300, 40, 220, 110) self.make_proxy(rect2) def make_proxy(self, rect): label = QLabel('World') label.setAlignment(Qt.AlignCenter | Qt.AlignCenter) # create proxy proxy = QGraphicsProxyWidget() proxy.setWidget(label) proxy.setGeometry(rect) self.scene.addItem(proxy) # create parent item rectangle = QGraphicsRectItem(rect) rectangle.setFlag(QGraphicsItem.ItemIsMovable, True) self.scene.addItem(rectangle) # set parent proxy.setParentItem(rectangle) def main(): app = QApplication(sys.argv) form = Memory(QRect(10, 10, 550, 180)) form.show() app.exec_() if __name__ == '__main__': main() However, the first rectangle is always on the bottom of the scene since it was added at first to it. But when I click on it it should go to the top of the scene so that it appears above the second rectangle. This is why I want to subclass QGraphicsRectItem and add new features to it. But when I implement it as below class RectItem(QGraphicsRectItem): def __init__(self, rect): QGraphicsRectItem.__init__(self) self.rectangle = rect def boundingRect(self): super(RectItem, self).boundingRect() return self.rectangle and define the rectangle variable as rectangle = RectItem(rect) the items are not movable anymore, i.e. the QGraphicsItem.ItemIsMovable flag has no effect. Is there…
has comment: http://stackoverflow.com/comment/81241036
has answer: http://stackoverflow.com/a/47160793
tagged with: pyqt
type: AnsweredQuestion
tagged with: pyqt5
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81249060
has comment: http://stackoverflow.com/comment/81245610
type: Question
has title: Subclassing QGraphicsRectItem in PyQt
has comment: http://stackoverflow.com/comment/81270316
downvote count: 0

http://stackoverflow.com/comment/81316994
type: Comment
type: AnswerComment
has text: thank you, this extracts all data but separated into all all material items, all can and all category - not in a list each x each.
score: 0
comment on: http://stackoverflow.com/a/47183380

http://stackoverflow.com/comment/81268297
type: Comment
has text: Show the HTML please
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47159417

http://stackoverflow.com/comment/81278156
type: QuestionComment
comment on: http://stackoverflow.com/q/47163518
score: 1
has text: Not sure what you mean by fetching results but when you run a query job (`query_job = bqclient.query(query, config)`) the job starts automatically but it does not fetch any results. If you want to wait for results and fetch them then you could run `results = list(query_job.result())` but other than that the operation is done asynchronously already.
type: Comment

http://stackoverflow.com/q/47214979
tagged with: matrix
score: 1
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has title: concatenate two matrices with interleaved columns
linked to: http://stackoverflow.com/q/47030661
has body: I have two 2-D arrays and I would like to concatenate them interleaving the columns Initial arrays (with shape (3, 8) each): array([[ 107, 115, 132, 138, 128, 117, 121,135], [ 149, 152, 151, 143, 146, 149, 149,148], [ 152, 142, 146 , 141, 143, 148, 149, 153]]) array([[ 25, 28, 28, 25, 23, 21, 20, 18], [ 3, 3, 2, 2, 10, 12, 12, 1], [ 1, 0, 2, 0, 0, 0, 0, 1]]) Result (with shape 6x8): array([[ 107, 115, 132, 138, 128, 117, 121, 135], [ 25, 28, 28, 25, 23, 21, 20, 18], [ 149, 152, 151, 143, 146, 149, 149, 148], [ 3, 3, 2, 2, 10, 12, 12, 13], [ 152, 142, 146 , 141, 143, 148, 149, 153] [ 1, 0, 2, 0, 0, 0, 0, 1]]) I know it should be possible to do it with a series of reshapes, but I couldn't figure out how!
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/41776579
duplicate of: http://stackoverflow.com/q/47030661
has answer: http://stackoverflow.com/a/47215013

http://stackoverflow.com/a/47164965
downvote count: 0
score: 3
upvote count: 3
has body: The problem is that Python needs to serialize the foo object and resurrect it in the new process. __init__ isn't called during resurrection, so your foo object won't have a ._bar attribute early enough. The solution is to let the serialize/resurrect methods through specially, ie. change your __getattr__ to: def __getattr__(self, attr): if attr in {'__getstate__', '__setstate__'}: return object.__getattr__(self, attr) return getattr(self._bar, attr) and it should work.
type: Answer
answers question: http://stackoverflow.com/q/47164697

http://stackoverflow.com/a/47066209
downvote count: 1
upvote count: 9
type: Answer
accepted answer of: http://stackoverflow.com/q/47066197
score: 8
answers question: http://stackoverflow.com/q/47066197
has body: Try this: np.arange(len(a))[a==b] It creates a new array from 0 to length a representing the indices. Then use a==b to slice the array, returning the indices where a and b are the same. Additionally from @Reblochon-Masque: You can use numpy.where to extract the indices where two values meet a specified condition: import numpy a = numpy.array([0, 1, 2, 3, 4, 5, 6]) b = numpy.array([6, 5, 4, 3, 2, 1, 6]) numpy.where(a==b) output: (array([3, 6]),)
type: AcceptedAnswer

enumeration
tag name: enumeration
tags question: http://stackoverflow.com/q/47196406
type: Tag
tags question: http://stackoverflow.com/q/47196262

http://stackoverflow.com/q/47098898
has comment: http://stackoverflow.com/comment/81148520
has title: Pandas DataFrame: Calculate metrics between specific index elements/positions
type: Question
has answer: http://stackoverflow.com/a/47099267
score: 0
has body: I have a DataFrame of length N and certain indices/positions ni in arbitrary distances. Now I want to calculate metrics between two consecutive index elements ni and ni+1. Example: import numpy as np import pandas as pd df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD')) df['id'] = ['W', 'W', 'W', 'Z', 'Z', 'Y', 'Y', 'Y', 'Z', 'Z'] print(df) A B C D id 0 0.347501 -1.152416 1.441144 -0.144545 w 1 0.775828 -1.176764 0.203049 -0.305332 w 2 1.036246 -0.467927 0.088138 -0.438207 w 3 -0.737092 -0.231706 0.268403 0.464026 x 4 -1.857346 -1.420284 -0.515517 -0.231774 x 5 -0.970731 0.217890 0.193814 -0.078838 y 6 -0.318314 -0.244348 0.162103 1.204386 y 7 0.340199 1.074977 1.201068 -0.431473 y 8 0.202050 0.790434 0.643458 -0.068620 z 9 -0.882865 0.687325 -0.008771 -0.066912 z Now let's say I have n1=0, n2=4, n3=5, n4=9 and want to calculate the arithmentic mean between these for columns A and B e.g. mean(n1,n2), mean(n2,n3), mean(n3,n4), mean(n4,n5). The expected output would be a DataFrame with 4 rows (means) and two colums (A and B). Any hints are welcome! Thanks in advance!
answer count: 3
has comment: http://stackoverflow.com/comment/81148079
tagged with: pandas
possible better answer: http://stackoverflow.com/a/47099111
has comment: http://stackoverflow.com/comment/81148218
has answer: http://stackoverflow.com/a/47099642
has answer: http://stackoverflow.com/a/47099111
accepted answer: http://stackoverflow.com/a/47099267
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81148056
has comment: http://stackoverflow.com/comment/81147923
tagged with: python

http://stackoverflow.com/comment/81275918
comment on: http://stackoverflow.com/a/47124123
has text: Also, I ended up adding the ```iso8601.parse``` to the expected time: ```expected_time = iso8601.parse_date('2017-09-18 23:09:33')``` - I updated my question with the changes
type: Comment
score: 0
type: AnswerComment

drf-queryset
type: Tag
tags question: http://stackoverflow.com/q/47222697
tag name: drf-queryset

http://stackoverflow.com/a/47070272
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47070119
has body: Your generator is not iterating over the dictionary. It is iterating over a new list object that sorted() returned: &gt;&gt;&gt; d = {1:'a', 2:'x', 4:'m', 8:'d', 16:'f'} &gt;&gt;&gt; l = sorted(d.items()) &gt;&gt;&gt; d {1: 'a', 2: 'x', 4: 'm', 8: 'd', 16: 'f'} &gt;&gt;&gt; l [(1, 'a'), (2, 'x'), (4, 'm'), (8, 'd'), (16, 'f')] &gt;&gt;&gt; d.pop(2) 'x' &gt;&gt;&gt; l [(1, 'a'), (2, 'x'), (4, 'm'), (8, 'd'), (16, 'f')] Removing items from the dictionary can't update the new list; that structure is not a live view on the dictionary. For that to work, you'd have to re-sort the dictionary each and every iteration, and keep track of an iteration position: def sorted_view(d): pos = 0 while pos &lt; len(d): yield sorted(d.items())[pos] pos += 1 This is hugely inefficient; sorting is a relatively expensive operation. A more efficient method would be to store just the keys in sorted order, and then test if the key is still available: def min_key_order(adict:dict): for key in sorted(adict): if key in adict: yield (key, adict[key]) This will however not detect if you added more keys.
type: Answer

http://stackoverflow.com/comment/81344424
score: 0
has text: Instead add order by b.pid at the end of the query after where a.domid=? Order by b.pid
comment on: http://stackoverflow.com/a/47196606
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47216177
has body: Each row of a data frame column is a list of dictionaries. I want to convert the list of dictionaries to a new data frame with each dictionary as a new cell in my data frame. The keys of the dictionaries as the columns. Each dictionary has 44 keys, so I have 44 columns. I need to do this for all the rows (lists) of the data frame column and append each newly transformed data frame cell to the existing data frame. My problem is, not all the dictionaries from my list are transformed to a cell in a new data frame. Many of the dictionaries are missed. My data frame column df[‘data’] looks like this: 0 [ { "name": "Tom", "age": 10 }, { "name": "Mark", "age": 5 }, { "name": "Pam", "age": 7 }, { "name": "Dick", "age": 12 } ] 1 [ { "name": “Ash", "age": 20 }, { "name": “Jim", "age": 54 }, { "name": “Sam", "age": 29 }, { "name": “Poo", "age": 15 } ] len(df) = 2 Output should be like this: df_all Name Age Tom 10 Mark 5 Pam 7 Dick 12 Ash 20 Jim 54 Sam 29 Poo 15 len(df_all) =8 My code is below: #Reading all the rows of the column ‘data’ from the df data = df['data'].iloc[:1500] len(data) #1500 #Creating an empty data frame df_append = pd.DataFrame([]) #Iterating over all rows(lists of dictionaries) of a data frame and converting #each list to a data frame and keep appending to it. for each_item in data: df_each_row = pd.DataFrame(each_item) df_all = df_append.append(df_each_row) df_all len(df_all) #501 If each row(list) in 'data' has 10 dictionaries, then there should be 1500*10(15000) rows present in the final dataframe. Instead I get only 501 rows. However, I get 44 columns correctly.
favorite count: 0
type: Question
has title: How to iterate each cell of data column,convert and append each cell?
answer count: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81382654
tagged with: python
has comment: http://stackoverflow.com/comment/81381906
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81382474
has comment: http://stackoverflow.com/comment/81382556
possible better answer: http://stackoverflow.com/a/47216938
accepted answer: http://stackoverflow.com/a/47216661
has comment: http://stackoverflow.com/comment/81381730
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47216938
has comment: http://stackoverflow.com/comment/81382534
has answer: http://stackoverflow.com/a/47216661
tagged with: pandas
has comment: http://stackoverflow.com/comment/81382822
tagged with: loops
has comment: http://stackoverflow.com/comment/81382488

http://stackoverflow.com/comment/81278706
type: QuestionComment
has text: Any suggestions on how to do the substitution for missing values?
comment on: http://stackoverflow.com/q/47164436
type: Comment
score: 0

http://stackoverflow.com/comment/81106613
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47078310
has text: Tried that, still no data points.

http://stackoverflow.com/a/47088821
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/81127862
accepted answer of: http://stackoverflow.com/q/47088661
has body: In the case of df.index.values[4][1] * 2, where the value is a string (honeyhoney), it's fine to assign that to a column: df['col1'] = df.index.values[4][1] * 2 df.col1 when food month 2011-04-04 honey feb honeyhoney jan honeyhoney milk feb honeyhoney jan honeyhoney In your second example, though, the one with the error, you're not actually performing an operation on a single value: df.index.values[2]*2 (Timestamp('2011-04-04 00:00:00'), 'milk', 'feb', Timestamp('2011-04-04 00:00:00'), 'milk', 'feb') You could still smush all that into a string, or into some other format, depending on your needs: df['col2'] = ''.join([str(x) for x in df.index.values[2]*2]) But the main issue is that the output of df.index.values[2]*2 gives you a multi-dimensional structure, which doesn't map to the existing structure of df. New columns in df can either be a single value (in which case it's replicated automatically to fit the number of rows in df), or they can have the same number of entries as len(df). UPDATE per comments IIUC, you can use get_level_values() to apply an operation to an entire level of a MultiIndex: df.index.get_level_values(1).values*2 array(['honeyhoney', 'honeyhoney', 'milkmilk', 'milkmilk', 'honeyhoney', 'honeyhoney', 'milkmilk', 'milkmilk', 'honeyhoney', 'honeyhoney', 'milkmilk', 'milkmilk', 'honeyhoney', 'honeyhoney', 'milkmilk', 'milkmilk'], dtype=object)
has comment: http://stackoverflow.com/comment/81162412
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47088661

http://stackoverflow.com/comment/81205839
comment on: http://stackoverflow.com/q/47100903
has text: @GPhilo - yes seems there is no straightforward way of doing this for a tensor - however a way using the tf.data API would also be interesting. The analogous of np.delete in tensorflow would be the ideal solution.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47166428
has comment: http://stackoverflow.com/comment/81283169
has comment: http://stackoverflow.com/comment/81283216
has comment: http://stackoverflow.com/comment/81283618
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/81283415
has title: Comparing all elements of a list to each other
tagged with: python
type: Question
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81285097
has body: I am trying to write a program that can index the reads of a FASTQ file and run a QC on the barcodes attached to each read. I am using a dictionary to store the indices using the barcode as key - the corresponding value is a list of lists where the indices are kept. A barcode is an 8 character string containing the letters A, T, G, and C. A read looks like this with a header, sequence, +, and another sequence: @ST-K00127:119:HF2FVBBXX:8:1101:31253:1595 1:N:0:TCTTCACA TTTTTCATTGATCTGTCGCAAGGCTTCCTCCGCTGTACCGTTTAACTTGAATTCCATTACGTAAATAAATCTGTCTGTC + AAAFFJJFJJJJJFJJJ And a dictionary element could look like this: key: TCTTCACA value: [[0,350], [351,500]] Now I am trying to run a function that measures edit distance between two barcodes and I want to do this for each barcode against all other barcodes in the dictionary. I am creating an upper triangle matrix storing all the edit distances and then I am finding the number of positions where the edit distance is equal to 1 or 2. The problem is that I keep getting differing numbers of positions unless I sort the list of keys beforehand, which in my humble opinion should not make a difference as all elements are still being compared to each other no matter the order of the list. Can someone help me? I am wondering whether it is my code or if there is soomething going on behind the scenes that I don't know of. Code example: key_list = list(barcode_index.keys()) N = len(key_list) barcode_matrix = np.zeros((N, N)) for i in range(N)): for j in range(i+1,N): barcode_matrix[i,j] = calculate_distance(key_list[i], key_list[j]) error_barcodes1 = np.where(barcode_matrix==1) error_barcodes2 = np.where(barcode_matrix==2) def calculate_distance(barcode1, barcode2): distance = 0 for i in range(0,8): if barcode1[i] != barcode2[i]: distance += 1 return distance
has comment: http://stackoverflow.com/comment/81369085

http://stackoverflow.com/q/47167148
tagged with: math
has answer: http://stackoverflow.com/a/57910640
has title: Long run time for automorphic program
has comment: http://stackoverflow.com/comment/81284806
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81286221
answer count: 2
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81284404
has comment: http://stackoverflow.com/comment/81285039
has answer: http://stackoverflow.com/a/47168455
tagged with: python
has comment: http://stackoverflow.com/comment/81284677
has body: I wrote a program to solve for the nth automorphic number (numbers that, when squared, end in the original number (ex. 6252 = 390625, 390625 % 1000 = 625). import time def green(n): start_time = time.time() f = 3 if n==1: return 1 elif n==2: return 5 elif n==3: return 6 n1 = "5" n2 = "6" tempn2 = "0" tempn1 = "0" x = 1 while f!=n+1: if int(n1) &gt; int(n2): tempn2 = str(x) + n2 while int(pow(int(tempn2), 2, 10**(len(tempn2)))) != int(tempn2): tempn2 = str(x) + n2 x+=1 x=1 f+=1 n2 = tempn2 if f==n+1: break else: tempn1 = str(x) + n1 while int(pow(int(tempn1), 2, 10**len(tempn1))) != int(tempn1): tempn1 = str(x) + n1 x+=1 x=1 f+=1 n1 = tempn1 print("--- %s seconds ---" % (time.time() - start_time)) return min(int(n1), int(n2)) Sorry for the poor code, first year Comp Sci. Program Runtime vs. Input I need the 5000th input to be less than a 12-second run-time. The current code takes about 45 seconds.
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/81285361
tagged with: algorithm
tagged with: time-complexity

http://stackoverflow.com/comment/81333658
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47191956
score: 0
has text: I've added it to th question

http://stackoverflow.com/comment/81319821
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47184031
type: QuestionComment
has text: @cdarke No, I haven't done that. Also, `my_func` uses other bash functions in its definition. Does this affect anything?

http://stackoverflow.com/comment/81530386
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47278404
has text: I see you submitted the commit 10 hours ago and it still hasn't been updated. Have commits you submitted before taken this long as well?
type: AnswerComment

http://stackoverflow.com/q/47075812
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47075953
tagged with: graphene-python
has title: How to hit external graphql URL using gql
type: Question
upvote count: 2
downvote count: 0
answer count: 1
tagged with: graphql
has body: How to hit external graphql URL using gql? As per github repo: from gql import gql, Client client = Client(schema=schema) query = gql(''' { hello } ''' ) client.execute(query) Even though, the author say it is inspired by apollo client ,I didn't see any way of providing URL while executing the graphql.
tagged with: python
has answer: http://stackoverflow.com/a/47075953
favorite count: 0
score: 2

http://stackoverflow.com/q/47205097
has answer: http://stackoverflow.com/a/47205265
tagged with: database
tagged with: python
has comment: http://stackoverflow.com/comment/83654952
score: 0
has body: I have a database in MS SQL where we populated our data in this database. I am trying to write a web-based app in order to read that data and present it on a webpage. I know the data structure and model so don't want to migrate them since they already exist. Is this possible? Also, is it possible for Django to write the necessary tables it needs in a separate database?
type: UnansweredQuestion
answer count: 1
type: Question
has title: how to read a preexisting database into to django

http://stackoverflow.com/q/47112687
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81175424
downvote count: 0
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/47112721
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47112721
tagged with: split
has comment: http://stackoverflow.com/comment/81175228
has body: import sys for line in sys.stdin.read() : numbers = line.split() print numbers I have been trying to figure out what is going on when I am using split() in python. Based on what I've read, with no arguments, it splits on white space, and it splits the line into a list of strings. When I run this (tiny) snippet of code (using this to try to figure out what is going wrong in a larger program) with input similar to 1 100 2 32 3 76 I get : ['1'] [] ['1'] ['0'] ['0'] [] ['2'] [] ['3'] ['2'] [] ['3'] [] ['7'] ['6'] [] I have tried a couple of arguments in split(), including (' '), and no argument as well as ('\n') to see if I can figure out why it is splitting each element into individual characters. I also tried using input of two separate words per line, and got similar output. So, my question is : why is this splitting after each character rather than on white space?
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/81175251
has title: Trying to use split() on stdin in python

http://stackoverflow.com/q/47110381
type: Question
tagged with: numpy
score: 2
answer count: 3
upvote count: 2
type: UnansweredQuestion
tagged with: arrays
downvote count: 0
favorite count: 0
has title: how to store my iterations into arrays in python?
has answer: http://stackoverflow.com/a/47110499
tagged with: python
has answer: http://stackoverflow.com/a/47110423
has answer: http://stackoverflow.com/a/47111100
has body: I've defined the following function which takes x and n as arguments, using Taylor series summation to approximate arctan. I also embedded a conditional statement inside so the function works for all x. import math import math for x in range(1,10,1): def arctan(x, n): arctang=0 inv_x=1/x for i in range(n): sign=(-1)**i arctang = arctang + ((inv_x**(2.0*i+1))/(2.0*i+1))*sign if x&gt;0: arc_tan=(math.pi/2)-arctang else: arc_tan=-(math.pi/2)-arctang return arc_tan print(arctan(x,100)) this code prints the iterations: 0.7878981009052581 1.1071487177940906 1.2490457723982544 1.3258176636680326 1.3734007669450157 1.4056476493802696 1.4288992721907325 1.446441332248135 1.460139105621001 however I want to be able to store the x values into an array, and these iterations into another so I can generate a graph out of the arrays, ie: something along the lines x=[1,2,3,4,5,6,7,8,9] y=[iterations as listed] How should I go about doing this? thanks!

http://stackoverflow.com/q/47074778
has title: Python: convert CSV columns into arrays, except 1st and last row
tagged with: python
type: AnsweredQuestion
score: 0
has body: I have a CSV file, called results_date.csv which looks like this: Header1 ; Header2 ; Header3 string1=0,1 ; string2=0,2 ; string3=0,3 string4=0,4 ; string5=0,5 ; string6=0,6 .............................. stringX=0,x ; stringY=0,y ; stringZ=0,z some other big string at the end I want to parse through this file, and save the text into 2 arrays, for columns 1 and 2, but without the equal and the number after it, header and the other big string at the end. Ex: array_for_column1 = ["string1", "string4", ..., "stringX"] array_for_column2 = ["string2", "string5", ..., "stringY"] These arrays will be used for a confusion matrix. I tried to do it this way: #!/usr/bin/python3 import csv data = csv.reader(open('results_date.csv', 'r'), delimiter=";", quotechar='|') column1 = [] column2 = [] for row in data: column1.append(row[0]) column2.append(row[1]) print (column1) print (column2) But it doesn't work. This code only prints the 1st column, and throws an error for the 2nd column. Thanks for help in advance!
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81097890
has answer: http://stackoverflow.com/a/47075045
accepted answer: http://stackoverflow.com/a/47075045
tagged with: arrays

http://stackoverflow.com/a/47216411
answers question: http://stackoverflow.com/q/47198551
downvote count: 0
upvote count: 1
has body: I don't think there's a way to make the contents of %{...%} be preprocessed, but not wrapped - for most of what the preprocessor does it relies on a typemap to actually be instantiated to populate the substitution information (although $descriptor could still work and I've wished for it in the past). My usual solution is to pass the SWIG type info as an argument into functions like that, for example: %{ //COPY THIS BLOCK AS IS #include &lt;headers.h&gt; static CppClass* get_CppClass_from_swig_object(PyObject* obj, swig_type_info *ty) { //... use ty instead of $descriptor here Which means that when you use get_CppClass_from_swig_object in a typemap all you need to do is use $1_descriptor or $descriptor to get the correct value for the second argument.
score: 1
type: Answer

http://stackoverflow.com/a/47370825
accepted answer of: http://stackoverflow.com/q/47219565
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47219565
downvote count: 0
type: AcceptedAnswer
has body: I guess you want to be able to: 1) Add a vertical line that the user can drag. For that, try vline = p1.addLine(x=0, movable=True) 2) Draw markers wherever the vertical line intersects your plot curves. You can do this manually by connecting to a signal that is emitted whenever the line moves: def update(line): x = line.value() # find and plot intersection points vline.sigPositionChanged.connect(update)
type: Answer

http://stackoverflow.com/q/47085467
has comment: http://stackoverflow.com/comment/81120712
has answer: http://stackoverflow.com/a/47085673
answer count: 4
has title: How would I remove all duplicates in Python List?
favorite count: 0
has comment: http://stackoverflow.com/comment/81120789
type: Question
has answer: http://stackoverflow.com/a/47085606
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81120723
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/47085649
has comment: http://stackoverflow.com/comment/81120929
has answer: http://stackoverflow.com/a/47085677
has comment: http://stackoverflow.com/comment/81120845
has comment: http://stackoverflow.com/comment/81120813
has body: For example: newList = [1, 1, 2, 2, 2, 2, 3, 4, 4, 4, 4, 5, 5] I need the list to be: newList = [3] Another example: tempList = [["cheese", "ham"], ["spinach", "dressing"], ["cheese", "ham"]] The list would be: tempList = "spinach", "dressing" It can't use anything that won't work on unhashable items - the real list will have list stored in it. I also will have over 100,000 objects so speed is the biggest factor. I don't need the list to be in any sort of order. Here is what I have come up with so far: newList.sort() i = 0 while i &lt; newList.__len__()-1: x = 1 while newList[i].__eq__(newList[i + x]): x += 1 if not (i + x &lt;= newList.__len__()- 1): break if x != 1: for j in range(i, i + x): del newList[i] i-=1 i+=1 This works but I'm wondering if there is amore efficient way.
downvote count: 0

http://stackoverflow.com/q/47123960
has comment: http://stackoverflow.com/comment/81201271
has title: TensorFlow use CPU and GPU independently
has answer: http://stackoverflow.com/a/47126459
tagged with: gpu
tagged with: python
has body: I have a simple issue: I have two small processes in Tensorflow 1.3.0 (GPU) with python 3 on windows 10 with CUDA 8. I want to run one on the GPU and the other one on CPU segregated from each other (they should NOT cooperate!). Here is a small nonsense example-code: import tensorflow as tf import time import os import sys dim = 6096 try: device = sys.argv[1] except: device = "gpu" print("Running for "+device) cur_graph = tf.Graph() with cur_graph.as_default(): with tf.device("/"+device+":0"): x = tf.Variable(tf.random_normal([dim, dim]), dtype=tf.float32) y = tf.Variable(tf.random_normal([dim, dim]), dtype=tf.float32) z = tf.Variable(tf.random_normal([dim, dim]), dtype=tf.float32) a = tf.matmul(x, y) b = tf.matmul(a, z) training_start = time.time() with tf.Session() as sess: init_op = tf.global_variables_initializer() sess.run(init_op) sess.run(a) training_time = (time.time() - training_start) print("Time: %5.3f" % training_time) If I start it on CLI with my_prog.py cpu it takes ~10 seconds to finish and utilizes the CPU while GPU is idling If I start it on CLI with my_prog.py gpu it takes ~1 seconds to finish and utilizes the GPU while GPU is idling So far so good. Now I want to start it in different CMD's in parallel and I expect both processes work independently and utilizing CPU and GPU. But I always get an Exception from my GPU process: G:\Workspace\Python>device_test.py gpu Running for gpu 2017-11-05 17:27:52.940625: W C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations. 2017-11-05 17:27:52.940879: W C:\tf_jenkins\home\workspace\rel-win\M\windows-gpu\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations. 2017-11-05 17:27:53.3731…
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81224196
has comment: http://stackoverflow.com/comment/81202327

http://stackoverflow.com/a/47168478
type: Answer
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81287039
has body: You can use regex: import re my_string = ''.join(mylist) # 'A[BC]D[EFG]' # Replace '[' or ']' with ',' in my_string pattern = '[\[\]]' my_string = re.sub(pattern, ',', my_string) # 'A,BC,D,EFG,' my_list = my_string.split(',') # ['A', 'BC', 'D', 'EFG', ''] new_list = [letter for letter in my_list if letter] # ['A', 'BC', 'D', 'EFG']
answers question: http://stackoverflow.com/q/47168383
has comment: http://stackoverflow.com/comment/81287016

http://stackoverflow.com/comment/81352315
type: QuestionComment
score: 0
has text: you mean testing like this: `int(arr[j]) > int(key)`
comment on: http://stackoverflow.com/q/47201984
type: Comment

qwidget
tag name: qwidget
tags question: http://stackoverflow.com/q/47139958
type: Tag
tags question: http://stackoverflow.com/q/47110432
tags question: http://stackoverflow.com/q/47071384

http://stackoverflow.com/comment/81113293
has text: You really only need to paste the one line. And yes but remove the `.replace(...)`. What effect do you think that has on a `Request` object?
type: AnswerComment
comment on: http://stackoverflow.com/a/47080397
score: 0
type: Comment

http://stackoverflow.com/a/47077330
has comment: http://stackoverflow.com/comment/81105971
has comment: http://stackoverflow.com/comment/81111018
upvote count: 4
has body: Your long-lasting zero-activity network connection might get dropped by intermediate proxies, firewalls, routers, NATs, etc. And the requests.get() never finds out about it because it's passively waiting for the response. One way to prevent this, on a TCP layer, is to use the TCP keep-alive (which is usually off by default). In Python, you can configure the TCP keep-alive directly via low-level socket.setsockopt, but since you're already using requests, the easier way is via TCPKeepAliveAdapter available from the requests_toolbelt package: import requests from requests_toolbelt.adapters.socket_options import TCPKeepAliveAdapter url = '...' session = requests.Session() keep_alive = TCPKeepAliveAdapter(idle=120, count=20, interval=30) session.mount(url, keep_alive) session.get(url)
has comment: http://stackoverflow.com/comment/81110987
has comment: http://stackoverflow.com/comment/81105193
downvote count: 0
answers question: http://stackoverflow.com/q/47076402
score: 4
has comment: http://stackoverflow.com/comment/82614286
has comment: http://stackoverflow.com/comment/81111101
has comment: http://stackoverflow.com/comment/81106885
has comment: http://stackoverflow.com/comment/81111083
type: Answer

http://stackoverflow.com/comment/81181384
type: QuestionComment
comment on: http://stackoverflow.com/q/47115745
has text: import matplotlib.style; import pyplot as plt there should be new line or ;
score: 1
type: Comment

http://stackoverflow.com/comment/81256795
type: AnswerComment
has text: Thanks. Works now. I never worked with the assign method. And I was missing the sort call.
type: Comment
comment on: http://stackoverflow.com/a/47146469
score: 0

http://stackoverflow.com/q/47154519
answer count: 2
has comment: http://stackoverflow.com/comment/81259537
tagged with: sum
has body: I have a large list with numbers n1 in listn1. I want to add all multiples of each number, if the multiplicand is not in another list listn2 (prime numbers with specific characteristics) and the product is below a maximum max_n. The multiplicand is in most cases below 10, but can go up to 100,000. My code so far looks like: s = 0 for n1 in listn1: s += sum(n1 * i for i in range(1, 1 + max_n // n1) if i not in listn2) The problem: this approach is sloooow. It takes seconds to calculate listn1 and listn2, so I know that there are more than a million numbers to add. But I started the summation yesterday evening and it is still running this morning. Is there a Pythonic way to speed up this summation?
downvote count: 0
has title: Speeding up summation in Python
has answer: http://stackoverflow.com/a/48732288
tagged with: python
has comment: http://stackoverflow.com/comment/81258819
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47156710
linked to: http://stackoverflow.com/q/10922231
has comment: http://stackoverflow.com/comment/81261460
possible better answer: http://stackoverflow.com/a/48732288
has answer: http://stackoverflow.com/a/47156710
has comment: http://stackoverflow.com/comment/81288570
score: 1
has comment: http://stackoverflow.com/comment/81261473
upvote count: 1
has comment: http://stackoverflow.com/comment/81262364
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81265939
tagged with: python-3.x

http://stackoverflow.com/comment/81161575
has text: That looks like a dictionary. Try temp_in_celsius['temp'] (assuming the return from pyowm is in temp_in_celsius).
comment on: http://stackoverflow.com/q/47105311
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47126706
type: Question
has title: Subtract each row from first row in dataframe
has body: I have a dataframe (called df) with three variables, the head of which shown below. There are 600 rows of data. X1 X2 X3 0 0.049150 0.270032 0.577858 1 0.602387 0.065492 0.555747 2 0.598355 0.235002 0.482744 3 0.522151 0.253991 0.402630 4 0.402601 0.206630 0.553987 I am trying to subtract each row from the first. That is, I'm looking for row1 - row2, then row1 - row3, and so on. I am new to using for loops (and Python in general), and my current attempts aren't getting very far: for i in range(len(df)): diff[i] = df.iloc[0,:] - df.iloc[i,:] diff2 = math.sqrt((diff[0])**2 + (diff[1])**2 + (diff[2])**2) print(diff2) for context on the final three lines, I am trying to take the square root of the differences between each row item. So, sqrt((row1col1-row2col1)^2 + (row1col2 - row2col2)^2 + (row1col3 - row2col3)^2) and then I want to store the results of this for all the row differences up to row 600 in a new vector. If you would like further context, I am trying to implement the second step of a "Subtractive Clustering" algorithm, the formula for which is as follows: where ra=1
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81203604
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/47127112
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47127112
favorite count: 0

http://stackoverflow.com/comment/81386140
type: Comment
type: AnswerComment
has text: lets make simpler: 1. get only the size for all files. 2. compare size. 3. eliminate all unique size files. 4. on the remaining set of files (the ones whose size occurs more than once = possible dups) do an md5 or byte-by-bytes comparison. 5. print out the dup paths as a new line each. i think that would be very handy.
score: 0
comment on: http://stackoverflow.com/a/47200367

http://stackoverflow.com/q/47170425
tagged with: webdriver
has answer: http://stackoverflow.com/a/47170494
type: Question
accepted answer: http://stackoverflow.com/a/47171604
tagged with: selenium-chromedriver
upvote count: 0
has title: Login to Gmail with Selenium Webdriver
duplicate of: http://stackoverflow.com/q/44856887
downvote count: 1
tagged with: python
has body: I'm trying to automatically log into Gmail via a Python script. I'm using the selenium webdriver. I've managed to get my email entered but I don't know how to get my password entered as well. I've already checked past questions on here but the selectors mentioned in the answers don't seem to work. I keep getting an "Unable to locate element" error. The code I tried: driver.find_element_by_name("password").send_keys(pw)
favorite count: 0
has answer: http://stackoverflow.com/a/47171604
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/44856887
answer count: 3
possible better answer: http://stackoverflow.com/a/47170464
tagged with: selenium
score: -1
has answer: http://stackoverflow.com/a/47170464

http://stackoverflow.com/a/47158762
has comment: http://stackoverflow.com/comment/81267780
has body: After your first if block, you can use an additional if block to append to your lists when rank==1. x = [] y = [] rank = None with open(file, "r") as f: for lines in f: line = lines.strip().split() if(line[0] == "segment"): rank = int(line[3]) points = int(line[5]) continue if rank==1: x.append(float(line[0])) y.append(float(line[1]))
answers question: http://stackoverflow.com/q/47158559
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81269738
type: Answer
accepted answer of: http://stackoverflow.com/q/47158559

http://stackoverflow.com/q/47076428
has answer: http://stackoverflow.com/a/47077097
has answer: http://stackoverflow.com/a/47077617
has comment: http://stackoverflow.com/comment/81102175
downvote count: 0
has comment: http://stackoverflow.com/comment/81101823
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81105390
has body: I have a bit of Python code written by a previous engineer and I am trying to add to it. The script records the value of a serial string input, and logs the value in the string in a CSV file against time. The CSV file appears like this 12h35m15s,0.01t 12h35m16s,0.02t 12h35m17s,0.05t 12h35m18s,0.15t 12h35m19s,0.21t 12h35m20s,0.23t 12h35m21s,0.20t 12h35m22s,0.21t 12h35m23s,0.22t 12h35m24s,0.26t and so on... What I have done is added a section in the code so that when you press a button it uses matplotlib to generate a graph of the data in the CSV file. The problem I have is that matplotlib cannot plot the time in the format 12h25m15s as it isn't a float. I have changed the code to remove the h, m and s from the CSV file, but the problem is the seconds value. The seconds at 1 second is 1s, not 01s, therefore my graphed values would be for example: 12358 (at 12h25m8s) 12359 (at 12h25m9s) 123510 (at 12h25m10s) 123511 (at 12h25m11s) 123512 (at 12h25m12s) 123513 (at 12h25m13s) then when it goes to 12h36m 12361 (at 12h36m1s) 12362 (at 12h36m2s) and so on... this means that when my graph is plotted it sees 12h36m1s as a lower value than 12h35m10s and mixes up where the data should be in the graph. I need to find one of two solutions: 1) Correct the time format so that matplotlib correctly plots the time 2) Set my x axis value to be the number of data records being plotted. I.e. if I have 50 data records for y, my x axis is simply 1-50 and not time. Can anyone help on this? My graph code is: import matplotlib.pyplot as plt import matplotlib.dates as mdates import datetime as dt import numpy as np s = open('log0.csv','r').read() CSVunits = ('kN', 'T', 'lb', 'kg', 't') for c in CSVunits: s = ''.join( s.split(c) ) out_file = open('graph.csv','w') out_file.write(s) out_file.close() data = [['13h10m5s'],['13h20m5s'],['13h30m5s'],['13h40m5s'],['13h50m5s'],['14h0m5s']] #data = np.loadtxt('graph.csv', delimiter=',', skiprows=4,usecols=[0]) x = [mdates.date2num(dt.datetime.strptime(x[…
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has title: Matplotlib x Axis time error
has comment: http://stackoverflow.com/comment/81144612
has comment: http://stackoverflow.com/comment/81106060
score: 2
linked to: http://stackoverflow.com/q/1574088
answer count: 2
upvote count: 2

http://stackoverflow.com/a/47100089
type: Answer
score: 0
has body: In Python, if you do not explicitly return a value it will return a default of None type. You can fix this by adding a returning the function call choosing(): def choosing(): p = int(input("Rock: 0; Paper: 1; scissor: 2:")) if p &lt; 0 or p &gt; 2: print("\nPlease enter valid value") return choosing() else: return int(p) Also, I agree with @Kindall, recursion here seems like an overkill for simply asking for input.
answers question: http://stackoverflow.com/q/47100024

http://stackoverflow.com/q/47213727
favorite count: 0
type: Question
tagged with: enums
has comment: http://stackoverflow.com/comment/81408066
has body: New Python convert here. Simply, trying to loop through a list in Python using openpyxl. Of course, my list has about 100 items and my code has more conditions. lst = ['1','2','a','a12'] for value in enumerate(lst): row = ws1.iter_rows(min_row=value,max_row=value) When I try without enumerate I get error "must be str, not int" and when I try with enumerate I get error "Can only concatenate tuple (not "int") to tuple". I believe it has something to do with min_row and max_row requiring an int, but even then I get "'int' object is not iterable". Also, tried making value str() and int() Any advice much appreciated, thank you.
tagged with: python
has title: Loop through a list in Python using enumerate and openpyxl
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47214075
accepted answer: http://stackoverflow.com/a/47214075
upvote count: 1
tagged with: openpyxl
answer count: 1
downvote count: 1
tagged with: loops

http://stackoverflow.com/comment/81233188
has text: I got `ImportError: No module named site` It seems the QGIS python executable isn't loading properly, even if it does work fine when launched from a batch file.. Probably has to do with specifying environment paths, which was what I was trying to avoid. Unless you see other explanations?
type: Comment
comment on: http://stackoverflow.com/q/47140927
type: QuestionComment
score: 0

http://stackoverflow.com/a/47215093
has comment: http://stackoverflow.com/comment/81380576
type: Answer
has body: To enable error checking for unresolved references, go to "Preferences." Preferences Menu Then, select "Editor"... Editor Then "Inspections"... Inspections Then search for "unresolved reference." Search Bar Error checking for unresolved references should be enabled by default. Image
answers question: http://stackoverflow.com/q/47214763
score: 0

ivr
tags question: http://stackoverflow.com/q/47163664
tag name: ivr
type: Tag

http://stackoverflow.com/comment/81181130
comment on: http://stackoverflow.com/q/47115583
type: QuestionComment
has text: @charlietfl Is there some way, maybe without Javascript to do this?
type: Comment
score: 0

http://stackoverflow.com/comment/81278724
type: Comment
type: QuestionComment
score: 0
has text: You don't even know what you already have.
comment on: http://stackoverflow.com/q/47164436

http://stackoverflow.com/q/47104415
tagged with: tensorflow
favorite count: 0
has answer: http://stackoverflow.com/a/47105546
type: Question
answer count: 2
has body: Well, I am working on a GPU server. All other users are using keras with Theano backend. I have installed TensorFlow using virtualenv and later I installed keras using usual pip command. When I try to run keras in this virtual environment, it is using Theano backend because of the /home/user/.keras/keras.json file. I know I can use TensorFlow by making changes in the json file but for some reason other users are not allowing this. I would like to know if there is a way to use keras with TensorFlow installed in my virtual environment other than the globally installed "Theano". NOTE: The other users still should be able to use Theano OS: Ubuntu 16.04
downvote count: 0
tagged with: python
has title: How do I use TensorFlow backend in keras without changing keras.json?
tagged with: keras
possible better answer: http://stackoverflow.com/a/47104915
has answer: http://stackoverflow.com/a/47104915
type: AnsweredQuestion
tagged with: ubuntu-16.04
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/47105546

http://stackoverflow.com/comment/81355695
type: AnswerComment
comment on: http://stackoverflow.com/a/47164296
has text: i have another query though, which I have posted as well. your assistance would be appreciated.
score: 0
type: Comment

http://stackoverflow.com/q/47081576
type: Question
has answer: http://stackoverflow.com/a/75341715
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81307018
has comment: http://stackoverflow.com/comment/81171931
answer count: 1
downvote count: 0
tagged with: caesar-cipher
upvote count: 1
has comment: http://stackoverflow.com/comment/81169247
favorite count: 0
has title: Cryptography with Python 3.6
tagged with: python-3.x
has body: I have been working on Cryptography Question. What I tried to write first code with OrderedDict is this. from collections import OrderedDict alphabet = OrderedDict( [(u'a', u'ç'), (u'b', u'd'), (u'c', u'e'), (u'ç', u'f'), (u'd', u'g'), (u'e', u'g'), (u'f', u'h'), (u'g', u'i'), (u'g', u'i'), (u'h', u'j'), (u'i', u'k'), (u'i', u'l'), (u'j', u'm'), (u'k', u'n'), (u'l', u'o'), (u'm', u'ö'), (u'n', u'p'), (u'o', u'r'), (u'ö', u's'), (u'p', u'ş'), (u'r', u't'), (u's', u'u'), (u'ş', u'ü'), (u't', u'v'), (u'u', u'y'), (u'ü', u'z'), (u'v', u'a'), (u'y', u'b'), (u'z',u'c'), (9, '')]) text = 'öğtjçdç9dğp9grnvrt9jyuğbkp9içokoğr9pyp9nçtkbğt9iypoğtk9gycğpoğgkikpk9gybgyö9ağ9uğpkp9kekp9drboğ9dkt9urty9\ jçcktoçgkö9içokoğr9gç9uvçmç9dçuoçöçn9kekp9vğn9bçşöçp9iğtğnğp9\ çpçjvçtk9dyogyiyp9ağ9dy9öğvkp9grubçukpk9rnybçdkogkikp9\ çoirtkvöçoçtk9kuvğgkikp9gkogğ9nrgoçöçp9ağ9dçuoçtkpç9çpçjvçt9\ ağ9ngvççmnçç9bçcçtçn9nrgoçtkpk9uktnğvkp9kphr9çgğtğukpğ9öçko9çvöçpgkt9\jçgk9irtğbkö9uğpk' out = [] for k, v in alphabet.items(): for i in list(text): if i == v: out.append(alphabet[v]) outlast = (''.join(out)) print(outlast) I can't compare list of 'text' and alphabet values. I want to "text's every element(i) compare values and if it be 'i==values' Append i to 'out' list but as keys!" I'm using PyCharm 2017.2.2 Can you Help Me? Actually Cryptyography Key is 3. "3 times go up on Turkish alphabet" This is WRONG Output: ffffffffffffffffffffffffffffffffffffffffffffgggggggggggiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiijllllllllllmmmmmmööpppppppppppprrrrrrrrrrrrrrrrrrsssssssssssşşşşşşşşşşşşşşşşşşşşşşşşşşşştttttttttttttüvvvvvvvvvvvvvvvvvvvvyyyyyyyyyyyyaaaaaaaaaaabbbbbbbbbbbbççççdddddddddeee Expected Output: merhaba ben doktor huseyin galileo nun kariyer gunleri duzenledigini duydum ve senin icin boyle bir soru hazirladim galileo da staja baslamak icin tek yapman gereken anahtari buldugun ve bu metin dosyasini okuyabildigin algoritmalari istedigin dilde kodlaman ve baslarina anahtar ve kdtaajkaa yazarak kodlarini sirke…
tagged with: ordereddictionary
score: 1
tagged with: python
tagged with: cryptography

http://stackoverflow.com/comment/81325784
comment on: http://stackoverflow.com/q/47188143
score: 0
type: Comment
has text: what have you tried that isn't working? also your expected inputs and outputs aren't 100% consistent with the wording of what you ask.
type: QuestionComment

http://stackoverflow.com/comment/81330667
type: Comment
type: AnswerComment
has text: What's the point of `'{}'.format(x)` vs. `str(x)`? You could also probably handle other numbers if you just remove all `.`'s and `lstrip('0')`
comment on: http://stackoverflow.com/a/47189921
score: 0

http://stackoverflow.com/q/47219302
type: Question
has comment: http://stackoverflow.com/comment/81388003
has body: I have a column in a dataframe as such: x 0 0 0 1 1 1 1 0 0 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 What I would like to do is create a new column that sums up the groups of 1s that follow one another, only when there are more than 3 adjacent 1s.So the output I want is x y 0 0 0 0 0 0 1 4 1 4 1 4 1 4 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 8 1 8 1 8 1 8 1 8 1 8 1 8 1 8 0 0 0 0 0 0 So in the first set of 1s, there are four of them, so I show a count of 4 in column y. In the second set of 1s, there are three of them, but I do not show a count in column y. In the third set of 1s, there are eight of them, so I should a count of 8 in column y. Thank you very much!
type: UnansweredQuestion
answer count: 1
tagged with: count
upvote count: 1
tagged with: python
downvote count: 1
tagged with: sequential
tagged with: series
score: 0
has title: Count sequentially matching values in column python
has answer: http://stackoverflow.com/a/47219528
favorite count: 0

http://stackoverflow.com/comment/81290737
type: Comment
comment on: http://stackoverflow.com/q/47170280
score: 0
type: QuestionComment
has text: Yeah iterate over keys is what I am thinking about. But how to execute var1 = squeeze(var1) with var1 being a string of the variable name?

macos
tags question: http://stackoverflow.com/q/47124312
tags question: http://stackoverflow.com/q/47124128
tags question: http://stackoverflow.com/q/47149607
tags question: http://stackoverflow.com/q/47124348
tags question: http://stackoverflow.com/q/47110834
tags question: http://stackoverflow.com/q/47127195
tags question: http://stackoverflow.com/q/47149021
tags question: http://stackoverflow.com/q/47120507
tags question: http://stackoverflow.com/q/47184031
tags question: http://stackoverflow.com/q/47082736
tags question: http://stackoverflow.com/q/47138248
type: Tag
tags question: http://stackoverflow.com/q/47139176
tags question: http://stackoverflow.com/q/47136471
tags question: http://stackoverflow.com/q/47203965
tags question: http://stackoverflow.com/q/47221562
tags question: http://stackoverflow.com/q/47217105
tags question: http://stackoverflow.com/q/47176450
tags question: http://stackoverflow.com/q/47199225
tags question: http://stackoverflow.com/q/47191290
tags question: http://stackoverflow.com/q/47207631
tags question: http://stackoverflow.com/q/47079131
tag name: macos
tags question: http://stackoverflow.com/q/47081080
tags question: http://stackoverflow.com/q/47205334
tags question: http://stackoverflow.com/q/47191345

http://stackoverflow.com/comment/81226946
comment on: http://stackoverflow.com/q/47137981
score: 0
type: Comment
type: QuestionComment
has text: The only thing that's changed since then is [jyni](https://jyni.org/). There's no indication that it does support lxml, but it's possible that it might. Otherwise you're out of luck I think.

http://stackoverflow.com/comment/81297538
has text: convert the time to seconds
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47173925

http://stackoverflow.com/comment/81205524
type: Comment
type: AnswerComment
score: 1
has text: This is a different problem. Please.ask a new question. Especially when you accepted an answer here. You will want to accept a different answer in the new question. Also, please search a bit around. You need to link the libgfortran library. I don't know why it is not being linked here automatically. There are similar questions on this site.
comment on: http://stackoverflow.com/a/47109940

http://stackoverflow.com/comment/81349472
score: 2
type: Comment
has text: Right, although I would suggest using `type(B_obj)` over `B_obj.__class__` in python3 and new-style classes in Python2.
comment on: http://stackoverflow.com/a/47200448
type: AnswerComment

http://stackoverflow.com/q/47164494
favorite count: 0
type: Question
tagged with: for-loop
accepted answer: http://stackoverflow.com/a/47164569
has comment: http://stackoverflow.com/comment/81279170
upvote count: 0
has body: I am having trouble understanding an error I received when I tried to use a for loop in Python. Here is the loop that caused the issue: list = ["1", "2", "3"] numList = [int(i) for i in list] product = 1 for i in numList: product = product * numList[i] The error was: IndexError: list index out of range I was able to fix the problem by using the following while loop: list = ["1", "2", "3"] numList = [int(i) for i in list] product = 1 i = 0 while i &lt; len(numList): product = product * numList[i] i += 1 What is wrong with the for loop, that causes the error?
answer count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81278712
has comment: http://stackoverflow.com/comment/81278659
has comment: http://stackoverflow.com/comment/81278688
type: AnsweredQuestion
has title: For Loop Throws Error but While Loop Doesnt
tagged with: while-loop
tagged with: syntax
has answer: http://stackoverflow.com/a/47164569
has comment: http://stackoverflow.com/comment/81278654
downvote count: 1

http://stackoverflow.com/comment/81259882
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47152108
has text: Yes I am able to install.But the problem is there are lot many users which were using this script with python 32.So I can not ask all of them port to 64 bit

http://stackoverflow.com/q/47221517
type: Question
upvote count: 3
type: UnansweredQuestion
has body: I have a custom django queryset class, which I use together with custom manager to easly filter objects with chaining. I wanted to add custom method to this class to save its result as a file. However, I am not sure if I am doing it right. How can I get list of objects inside as_file method? class EntryQuerySet(models.QuerySet): def as_file(self, filename='export.xls'): # data = ??? how can I get results here??? print('exporting as {}'.format(filename)) def active(self): return self.filter(status__in=[1, 4, 5]) def with_email(self): return self.filter(contact__email__isnull=False) def by_city(self, city): return self.filter(address__city__icontains=city) def in_next_days(self, days=7): now = datetime.datetime.today() delta = now + relativedelta.relativedelta(days=days) return self.filter(start_date__gte=now, start_date__lte=delta) def in_last_days(self, days=7): now = datetime.datetime.today() delta = now - relativedelta.relativedelta(days=days) return self.filter(start_date__gte=delta, start_date__lte=now) class EntryManager(models.Manager): def get_queryset(self): return EntryQuerySet(self.model, using=self._db) def active(self): return self.get_queryset().active() def by_city(self, city): return self.get_queryset().by_city(city) def with_email(self): return self.get_queryset().with_email() def in_next_days(self, days): return self.get_queryset().in_next_days(days) def in_last_days(self, days): return self.get_queryset().in_last_days(days) I use this as follows: entries = Entry.objects.active().by_city('My city').in_next_days(5) And I want something like: entries = Entry.objects.active().by_city('My city').in_next_days(5).as_file('myfilename.xls') How can I achieve this?
answer count: 1
downvote count: 0
tagged with: django
favorite count: 0
score: 3
has answer: http://stackoverflow.com/a/47221667
has title: Django custom queryset and export
tagged with: django-models
tagged with: python

http://stackoverflow.com/a/49182388
answers question: http://stackoverflow.com/q/47108726
type: Answer
score: 0
has body: You're trying to read an analog signal from the Pi - as another use said: this is not possible without an ADC. I recommend using an Arduino board and reading the values from the Arduino via the serial port. Arduino has a vast database for analog signal processing, so I always recommend it first. I wrote a blog article on how to do this, check it out (if you're interested): Datalogging with Arduino and pySerial on a Raspberry Pi

http://stackoverflow.com/q/47156149
favorite count: 0
type: Question
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/94684091
accepted answer: http://stackoverflow.com/a/47157180
tagged with: python
type: AnsweredQuestion
has title: Unable to use proxies in Scrapy project
tagged with: proxy
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47157180
tagged with: web-scraping
tagged with: web-crawler
tagged with: scrapy
has body: I have been trying to crawl a website that has seemingly identified and blocked my IP and is throwing a 429 Too many requests response. I installed scrapy-proxies from this link: https://github.com/aivarsk/scrapy-proxies and followed the given instructions. I got a list of proxies from here: http://www.gatherproxy.com/ and now here is how my settings.py and proxylist.txt look like: Settings.py BOT_NAME = 'project' SPIDER_MODULES = ['project.spiders'] NEWSPIDER_MODULE = 'project.spiders' # Retry many times since proxies often fail RETRY_TIMES = 10 # Retry on most error codes since proxies fail for different reasons RETRY_HTTP_CODES = [429, 500, 503, 504, 400, 403, 404, 408] DOWNLOADER_MIDDLEWARES = { 'scrapy.downloadermiddlewares.retry.RetryMiddleware': 90, 'scrapy_proxies.RandomProxy': 100, 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 110, } PROXY_LIST = "filepath\proxylist.txt" USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36' CONCURRENT_REQUESTS = 1 DOWNLOAD_DELAY = 2 PROXY_MODE = 0 DOWNLOAD_HANDLERS = {'s3': None} EXTENSIONS = { 'scrapy.telnet.TelnetConsole': None } proxylist.txt http://195.208.172.20:8080 http://154.119.56.179:9999 http://124.12.50.43:8088 http://61.7.168.232:52136 http://122.193.188.236:8118 Yet when I run my crawler, I get the following error: [scrapy.proxies] DEBUG: Proxy user pass not found I tried to search for the specific error on google but could not find any solutions. Help will be highly appreciated. Thanks a lot in advance.

http://stackoverflow.com/a/47131574
has comment: http://stackoverflow.com/comment/81212658
upvote count: 1
has comment: http://stackoverflow.com/comment/81212890
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47131525
has body: No. JavaScript does not support operator overloading. However, you can implement a method yourself that supports Python's index handling. Edit: I suppose you can recreate that effect using Proxy (in ES6+), but I would not recommend it: https://jsfiddle.net/DerekL/Lfjznnbb/ class PythonArray { constructor() { return new Proxy([], { get: function(target, name) { var index = parseInt(name, 10); if (name === NaN) { if (name in target) return target[name]; else throw "Not a number"; } // simple implementation if(index &lt; 0) return target[target.length + index]; else return target[index]; } }); } static from(arr){ var pythonArray = new PythonArray(); for(var i = 0; i &lt; arr.length; i++){ pythonArray[i] = arr[i]; } return pythonArray; } } var arr = PythonArray.from([1, 2, 3]); console.log(arr[0]); // 1 console.log(arr[-1]); // 3 console.log(arr.join("|")); // still works

http://stackoverflow.com/comment/81353916
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47202621
has text: Can you post an example?
score: 0

http://stackoverflow.com/comment/81502973
comment on: http://stackoverflow.com/a/47232117
has text: if you run it like `scrapy crawl matchstat -o out.csv` all the items extracted will be appended to the output csv file :)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47157176
accepted answer of: http://stackoverflow.com/q/47156673
upvote count: 2
has body: You need to convert the numpy array to a list object, which can be easily done using .tolist() method on the numpy array object. Example: pred_list = pred.tolist() return JsonResponse(pred_list, safe=False)
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47156673
type: AcceptedAnswer

http://stackoverflow.com/a/48276627
type: Answer
has body: revert fly tiger resolve this issue
answers question: http://stackoverflow.com/q/47217743
score: 1
downvote count: 1
upvote count: 2

http://stackoverflow.com/q/47223066
possible better answer: http://stackoverflow.com/a/47223185
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/47223185
has comment: http://stackoverflow.com/comment/81396218
has body: I just came across lambda function in python, so just tried to play with it. Here I tried a="ABCD" b=map(lambda x:a[int(x)],a) print(list(b)) And this gives error ValueError: invalid literal for int() with base 10: 'A' but was expecting O/P like this [A,B,C,D] Any explanation on this . Thanks
has comment: http://stackoverflow.com/comment/81396399
has comment: http://stackoverflow.com/comment/81396088
has comment: http://stackoverflow.com/comment/81396246
has comment: http://stackoverflow.com/comment/81395908
tagged with: python
tagged with: dictionary
tagged with: lambda
accepted answer: http://stackoverflow.com/a/47223130
downvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81396047
has answer: http://stackoverflow.com/a/47223130
has comment: http://stackoverflow.com/comment/81395997
has comment: http://stackoverflow.com/comment/81396364
has title: Using lambda function in python
has comment: http://stackoverflow.com/comment/81395907
score: -6
favorite count: 0
type: Question

http://stackoverflow.com/comment/81120407
type: Comment
type: QuestionComment
has text: @0TTT0: Those are attached to the `for` statements. They're syntactically valid (though they may not be *correct*).
comment on: http://stackoverflow.com/q/47085392
score: 0

http://stackoverflow.com/a/47135320
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81221119
answers question: http://stackoverflow.com/q/47135205
type: Answer
has body: This? dic={} while True: am, name=input('ΑΜ, Name: ').split(',') if am =='q': print('End') break else: AM = int(am) dic[AM]=name print(dic)
score: 0
has comment: http://stackoverflow.com/comment/81220531
accepted answer of: http://stackoverflow.com/q/47135205

http://stackoverflow.com/q/47066119
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/47066440
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has body: input: Choc 5 Vani 10 Stra 7 Choc 3 Stra 4 END def process_input(lst): result = [] for string in lines: A=string.split() result.append([A[0],int(A[1])]) return result def merge_products(invent): # your code here # DON’T modify the code below str = input() lines = [] while str != 'END': lines.append(str) str = input() inventory1 = process_input(lines) merge_products(inventory1) print(inventory1) from this output [['Choc', 5], ['Vani', 10], ['Stra', 7], ['Choc', 3], ['Stra', 4]] I need to get this output [['Choc', 8], ['Vani', 10], ['Stra', 11]] How do I combine the integers under same string?
has answer: http://stackoverflow.com/a/47066216
has comment: http://stackoverflow.com/comment/81080604
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47066738
answer count: 3
has title: (Python 3) How do I combine products of a list?
score: 1

strip
tags question: http://stackoverflow.com/q/47160355
type: Tag
tags question: http://stackoverflow.com/q/47104159
tag name: strip

http://stackoverflow.com/comment/81115929
type: QuestionComment
comment on: http://stackoverflow.com/q/47083191
score: 1
has text: Not an answer, but you may want to note that `pd.cut(df['row0'], [0, 250, 500, 1000])` simplifies your binning a great deal.
type: Comment

http://stackoverflow.com/comment/81201651
type: QuestionComment
has text: @Divark - not necessarily, it might be a random list of indices, ex: arr[[5,100, 31, 123]]. You are correct though, they are jagged. My current method: sparse_rows = np.concatenate([np.arange(x1, x2) for x1,x2 in arr[idxs]]) is pretty slow
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47125697

http://stackoverflow.com/q/47091296
has comment: http://stackoverflow.com/comment/81132287
accepted answer: http://stackoverflow.com/a/47091553
answer count: 1
tagged with: django
has answer: http://stackoverflow.com/a/47091553
tagged with: python
has title: A for loop in forms.py fails to load data immediately after it's sent | Python Django
has body: In the forms.py I have a short piece of code which loads the data, but only after I edit print("hello") in it. The code as follows: models.py: class CreateAssignment(models.Model): user = models.ForeignKey(User, editable=False, blank=True, null=True) progress = models.CharField(max_length=254, editable=False, blank=True, null=True) class SetAssignment(models.Model): mechanic = models.ForeignKey(User, editable=False, blank=True, null=True) assignment = models.IntegerField(blank=True, null=True) The mechanic is a permission, plus this mechanic's ID will show in the url of the website, when you will try to set an assignment for this mechanic. forms.py: class SetAssignmentForm(forms.ModelForm): ASSIGNMENT_CHOICES = () for item in CreateAssignment.objects.all(): if item.progress == 'Scheduling': user = User.objects.get(id=item.user_id).username ASSIGNMENT_CHOICES += ( (item.id, user + ' - ' + str(item.id)), ) assignment = forms.ChoiceField(choices=ASSIGNMENT_CHOICES, help_text='This is the assignment that you want to apply to this mechanic.') class Meta: model = SetAssignment fields = ('assignment', ) The user_id in this situation is the user that has been set in the CreateAssignment model. Now the issue is: The for loop in the SetAssignmentForm works, but it loads data after I put a print in it or when I remove the print from it. Which of course shouldn't really affect the code. Is there something I'm overlooking? I've been programming in Python Django for 8 weeks now, so if this is a basic program failure, please refer me to a page, because I haven't been able to find any information on this issue. Thanks for the help. For the ones that want to know: views.py: @login_required def set_assignment(request): form = SetAssignmentForm() id = request.GET.get('id') user_results = User.objects.filter(pk=id).values() return render(request, 'pages/set_assignment.html', {'form': form, 'user_results': user_results}) Gif so you can visually see what's happening: https://drive.google…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81132292
type: Question
score: 0

http://stackoverflow.com/comment/81267376
has text: One question If I dont know my number of functions as it can grow over time. so will this loation be helpful? cant't it be automatically appended to next row ? As I see u have defined the location of cell
type: AnswerComment
comment on: http://stackoverflow.com/a/47152987
score: 0
type: Comment

http://stackoverflow.com/comment/81314242
comment on: http://stackoverflow.com/q/47182458
score: 0
type: Comment
has text: Quick question before I try to answer this: How much do you know about classes/object oriented programming?
type: QuestionComment

http://stackoverflow.com/a/47132832
upvote count: 2
downvote count: 0
score: 2
type: Answer
has body: Not 100% sure I got your question, but you can use an astype(int) conversion. df = df.set_index('DANE').astype(int).reset_index() df DANE BAKALIE NASIONA OWOCE WARZYWA 0 ilosc 5 94 61 623 1 marza_netto 7 120 69 668 2 marza_procent2 32 34 29 27 If you're dealing with rows that have NaNs, either drop those rows and convert, or convert to astype(object). The latter is not recommended because you lose performance.
answers question: http://stackoverflow.com/q/47132749

http://stackoverflow.com/comment/81320517
comment on: http://stackoverflow.com/q/47185334
type: Comment
type: QuestionComment
has text: Did you dig about djangorest custom permission?
score: 0

http://stackoverflow.com/comment/81437187
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47234185
has text: Thanks. Solve also works, that's basically it for a good workflow. However, nonlinsolve and the new solvers don't accept Functions as target variables :/
type: AnswerComment

http://stackoverflow.com/q/47072520
has title: search for a partial string from list and add column with that parital str
accepted answer: http://stackoverflow.com/a/47072615
answer count: 1
has answer: http://stackoverflow.com/a/47072615
favorite count: 0
type: Question
upvote count: 2
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/26577516
has body: I wont to search a df.column for a partial strings that I saved in a series and wont to create a new column with the str that I found in each row. A part of my question was solved by pandas: test if string contains one of the substrings in a list: For example, say I have the series s = pd.Series(['cat','hat','dog','fog','pet']), and I want to find all places where s contains any of ['og', 'at'], I would want to get everything but pet. The solution is: &gt;&gt;&gt; searchfor = ['og', 'at'] &gt;&gt;&gt; s[s.str.contains('|'.join(searchfor))] 0 cat 1 hat 2 dog 3 fog dtype: object but I would like to get pet contains 0 cat at 1 hat at 2 dog og 3 fog og dtype: object
score: 2
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/comment/81131098
comment on: http://stackoverflow.com/q/47090886
score: 0
type: Comment
has text: I mean that class `Line` uses `Point` and vice-versa.
type: QuestionComment

http://stackoverflow.com/comment/81276205
score: 0
has text: I have a python class file which I want to use inside my Robot Framework.The above example contains one python file having two classes and i m trying to implement these classes in robot framework.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47163056

http://stackoverflow.com/a/47170769
type: Answer
has comment: http://stackoverflow.com/comment/81316908
has comment: http://stackoverflow.com/comment/81306395
has comment: http://stackoverflow.com/comment/81291101
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47170441
answers question: http://stackoverflow.com/q/47170441
has body: Perhaps you want to decode it directly from bytes: In [11]: b = b'\xae\xc9\x91\xff\x9d\x12\xac\xbf\xeasz\xfal\t\xba\xbf\xa18x\xf1\x1bF' In [12]: np.fromstring(b, dtype=np.uint8) Out[12]: array([174, 201, 145, 255, 157, 18, 172, 191, 234, 115, 122, 250, 108, 9, 186, 191, 161, 56, 120, 241, 27, 70], dtype=uint8)
score: 1

http://stackoverflow.com/q/47112884
has answer: http://stackoverflow.com/a/47354243
possible better answer: http://stackoverflow.com/a/47354243
has comment: http://stackoverflow.com/comment/81660514
tagged with: python
has answer: http://stackoverflow.com/a/47354647
has title: How to make new decorators available within a class without explicitly importing them?
tagged with: python-decorators
type: AnsweredQuestion
tagged with: metaclass
answer count: 3
has answer: http://stackoverflow.com/a/47354131
accepted answer: http://stackoverflow.com/a/47354131
score: 6
upvote count: 7
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: Is it possible to modify a class so as to make available a certain method decorator, without having to explicitly import it and without having to prefix it (@something.some_decorator): class SomeClass: @some_decorator def some_method(self): pass I don't think this is possible with a class decorator, because that is applied too late. The option that seems more promising is using a metaclass, but I am unsure how, my guess is that I would have to have some_decorator be introduced into the namespace of SomeClass. Thanks to @MartijnPieters for pointing out that staticmethod and classmethod are built-ins. I had expected them to be part of the type machinery. To be clear, I don't have any explicit use-case for this, I am just curious as to whether this is at all possible. ADDENDUM, now that the question has been answered. The original reason why I was looking beyond simply importing or defining a decorator locally, was that I had defined a decorator that would only work if a certain container attribute was initialised on an object, and I was looking for a way to tie enforcing this to the availability of the decorator. I ended up checking whether the attribute existed and if not initialising it within the decorator, which may very well be the lesser evil here.

http://stackoverflow.com/a/47220136
has body: serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Account def update(self, instance, validated_data): instance.branch = validated_data.get('branch', instance.branch) instance.year = validated_data.get('year', instance.year) instance.save() return instance views.py class ProfileView(APIView): api_view = ['PUT'] def put(self, request, format=None): data = request.DATA user_details = Account.objects.get(id=request.query_params.get("id")) serializer = ProfileSerializer(user_details, data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py from django.conf.urls import patterns from django.conf.urls import url from . import views urlpatterns = patterns('', url(r'^user_details/', views.ProfileView), ) Access your PUT using this path: /api/userdetails/?id=1 Now, update user information(branch, year) based on their id.
type: Answer
answers question: http://stackoverflow.com/q/47134307
score: 0

http://stackoverflow.com/comment/81326618
type: AnswerComment
comment on: http://stackoverflow.com/a/47188632
has text: In truth, "my way" is intended to show that this method is pointless. You could just as easily do (in python3, at least...) `fun2 = print`.
type: Comment
score: 0

http://stackoverflow.com/a/47202686
accepted answer of: http://stackoverflow.com/q/47202203
answers question: http://stackoverflow.com/q/47202203
type: AcceptedAnswer
type: Answer
score: 0
has body: Here is a working version for now: import pygame import sys size=(0,0) WHITE=(255,255,255) BLACK=(0,0,0) rectX=(0) rectY=(0) rectSizeX=(100) rectSizeY=(100) screen=pygame.display.set_mode(size) screen.fill(WHITE) pygame.draw.rect(screen, BLACK, [rectX, rectY, rectSizeX, rectSizeY]) pygame.display.flip() mouse_pos = pygame.mouse.get_pos() while True: for event in pygame.event.get(): if event.type == pygame.MOUSEMOTION: mouse_pos = pygame.mouse.get_pos() if mouse_pos[0] &gt;= (rectX) and mouse_pos[1] &gt;= (rectY) and mouse_pos[0] &lt;= (rectX+rectSizeX) and mouse_pos[1] &lt;= (rectY+rectSizeY): print("meme") else: print (mouse_pos) if event.type == pygame.QUIT: pygame.quit() sys.exit() Also note your window is not "not responding" but you cant close it because you need to handle the QUIT type event too.

http://stackoverflow.com/comment/81351666
score: 0
has text: @DRPK I am not talking about the py files - they are quite small. I am talking about the text files that are created by doing "model.save(filename)". These files are huge.
comment on: http://stackoverflow.com/q/47183503
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81149587
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47099741
type: QuestionComment
has text: Please could you give an example of a URL that you'd like to scrape without any Python code/formatting applied?

http://stackoverflow.com/comment/81161003
type: QuestionComment
comment on: http://stackoverflow.com/q/47105185
has text: looks like your pip is installing it for 3.6, not 3.5 (which is the version you are using). Could be that you have 2 different instances of python installed?
score: 0
type: Comment

http://stackoverflow.com/q/47196329
has comment: http://stackoverflow.com/comment/81342790
has comment: http://stackoverflow.com/comment/81344069
has comment: http://stackoverflow.com/comment/81343813
type: AnsweredQuestion
score: 0
tagged with: metaclass
has comment: http://stackoverflow.com/comment/81341909
has body: So there is object.__new__(cls) and super().__new__(cls) functions could be used to create instance, but could I use type(name, bases, dict)(*args, **kwargs) to create instance? class Singleton(object): instance = None def __init__(self, *args, **kwargs): pass def __new__(cls, *args, **kwargs): if isinstance(cls.instance, type(None)): mcls = cls.__class__ cls.instance = type(mcls.__name__, mcls.__bases__, dict(cls.__dict__))(*args, *kwargs) return cls.instance s = Singleton() print(s)
has comment: http://stackoverflow.com/comment/81342025
has comment: http://stackoverflow.com/comment/81343778
has comment: http://stackoverflow.com/comment/81342214
has comment: http://stackoverflow.com/comment/81344133
has title: Is type(name, bases, dict) could be used to create instance(object of class), for example inside Singleton
answer count: 1
has comment: http://stackoverflow.com/comment/81343187
has comment: http://stackoverflow.com/comment/81342344
has comment: http://stackoverflow.com/comment/81342065
has comment: http://stackoverflow.com/comment/81343559
has comment: http://stackoverflow.com/comment/81342212
has comment: http://stackoverflow.com/comment/81343918
linked to: http://stackoverflow.com/q/32720492
has comment: http://stackoverflow.com/comment/81344101
has comment: http://stackoverflow.com/comment/81344211
has comment: http://stackoverflow.com/comment/81343862
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81342702
has comment: http://stackoverflow.com/comment/81343441
has answer: http://stackoverflow.com/a/47197865
accepted answer: http://stackoverflow.com/a/47197865
has comment: http://stackoverflow.com/comment/81342115
has comment: http://stackoverflow.com/comment/81343339
has comment: http://stackoverflow.com/comment/81341540
tagged with: python
has comment: http://stackoverflow.com/comment/81343378
has comment: http://stackoverflow.com/comment/81341723
has comment: http://stackoverflow.com/comment/81342365
has comment: http://stackoverflow.com/comment/81343127
has comment: http://stackoverflow.com/comment/81343517
has comment: http://stackoverflow.com/comment/81344383

http://stackoverflow.com/comment/81149300
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47099642
type: Comment
has text: Mean of only ['A','B'] and I dont think its a different one than what @Andy posted. Its better to use loc than iloc

http://stackoverflow.com/a/47119746
answers question: http://stackoverflow.com/q/47119306
has body: If you're using the SQLAlchemy ORM, you can use Python's itertools.product to simplify the assignment: from itertools import product # assuming teacher_obj, student_obj, and db is already created here teacher_ids = [1, 2] # just as an example student_ids = [1, 2, 3, 4, 5, 6] # ditto for tid, sid in product(teacher_ids, student_ids): teacher_obj.id = tid student_obj.id = sid db.session.commit() If you're on SQLAlchemy Core, you can use the connection's execute method: conn = engine.connect() ins = users.insert() conn.execute( users.insert(), [{"teacher_id": 1, "student_id": 2}, {"teacher_id": 1, "student_id": 3}]) Of course, that assumes you have done the necessary setup, for example: from sqlalchemy import create_engine, Column, Integer, Table, MetaData engine = create_engine('sqlite:///:memory:', echo=True) metadata = MetaData() users = Table('users', metadata, Column('teacher_id', Integer), Column('student_id', Integer)) metadata.create_all(engine) conn = engine.connect()
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/47119306
type: AcceptedAnswer

http://stackoverflow.com/comment/81104067
type: Comment
type: QuestionComment
has text: 35000*200ms is 2 hours. you need probably to refactor your problem.
score: 0
comment on: http://stackoverflow.com/q/47072916

http://stackoverflow.com/comment/106714972
comment on: http://stackoverflow.com/a/53230700
has text: HTTPError 403: 'SSL is required'
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47117780
has comment: http://stackoverflow.com/comment/81185557
possible better answer: http://stackoverflow.com/a/47117838
has comment: http://stackoverflow.com/comment/81185887
favorite count: 0
has comment: http://stackoverflow.com/comment/81185601
type: Question
has body: I am trying to remove files from multiple directories. While: os.remove("C:/WWWWWWW.csv") os.remove("C:/AAAAAAA.CSV”) Tends to work, the code tends to break assuming that one of these directories is not found. The below also tends to work. However, if it can’t find WWWWWWW, then it tends not remove other directory .csv files try: os.remove("C:/WWWWWWW.csv") os.remove("C:/AAAAAAA.CSV”) except OSError: pass I have about 18+ files so I am just wondering if there is a cleaner way than having to: try: os.remove("C:/WWWWWWW.csv") except OSError: pass try: os.remove("C:/WWWWWWW.csv") except OSError: pass The below tends not to address the issue: try: colors = ["C:/d.csv", "C:/a.csv"] for color in colors: os.remove(color) except OSError: pass
has answer: http://stackoverflow.com/a/47117838
has comment: http://stackoverflow.com/comment/81185899
tagged with: python-3.x
has title: Error handling with multiple directories
answer count: 2
has comment: http://stackoverflow.com/comment/81185846
upvote count: 2
has comment: http://stackoverflow.com/comment/81185613
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47117993
has comment: http://stackoverflow.com/comment/81185605
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47117993
tagged with: subprocess
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81186323
tagged with: file

http://stackoverflow.com/comment/81240316
type: AnswerComment
comment on: http://stackoverflow.com/a/47144761
score: 0
type: Comment
has text: ive added that and nothings changed

http://stackoverflow.com/q/47101290
has comment: http://stackoverflow.com/comment/81171527
has title: asyncio: unable to create new event loop
tagged with: python-asyncio
type: UnansweredQuestion
tagged with: autobahn
tagged with: python
has body: I am using Python 3.6.2, on Fedora 26 Workstation. Below is some scrapbook code which demonstrates my issue: EDIT: added Sam Hartman's suggestion to code. import asyncio, json from autobahn.asyncio.websocket import WebSocketClientProtocol, WebSocketClientFactory class MyClientProtocol(WebSocketClientProtocol): def onConnect(self, response): print(response.peer) def onOpen(self): print("open") self.sendMessage(json.dumps({'command': 'subscribe', 'channel': "1010"}).encode("utf8")) def onMessage(self, payload, isBinary): print("message") print(json.loads(payload)) factory1 = WebSocketClientFactory("wss://api2.poloniex.com:443") factory1.protocol = MyClientProtocol loop1 = asyncio.get_event_loop() loop1.run_until_complete(loop1.create_connection(factory1, "api2.poloniex.com", 443, ssl=True)) try: loop1.run_forever() except KeyboardInterrupt: pass loop1.close() asyncio.set_event_loop(asyncio.new_event_loop()) factory2 = WebSocketClientFactory("wss://api2.poloniex.com:443") factory2.protocol = MyClientProtocol loop2 = asyncio.get_event_loop() loop2.run_until_complete(loop2.create_connection(factory2, "api2.poloniex.com", 443, ssl=True)) try: loop2.run_forever() except KeyboardInterrupt: pass loop2.close() After having closed an initial asyncio event loop, creating another and setting it as the global event loop, attempting to use the new event loop yields the following errors: Fatal write error on socket transport protocol: &lt;asyncio.sslproto.SSLProtocol object at 0x7f8a84ed4748&gt; transport: &lt;_SelectorSocketTransport fd=6&gt; Traceback (most recent call last): File "/usr/lib64/python3.6/asyncio/selector_events.py", line 762, in write n = self._sock.send(data) OSError: [Errno 9] Bad file descriptor Fatal error on SSL transport protocol: &lt;asyncio.sslproto.SSLProtocol object at 0x7f8a84ed4748&gt; transport: &lt;_SelectorSocketTransport closing fd=6&gt; Traceback (most recent call last): File "/usr/lib64/python3.6/asyncio/selector_events.py", line 762, in write n =…
score: 2
has comment: http://stackoverflow.com/comment/81172004
upvote count: 2
has answer: http://stackoverflow.com/a/47110931
downvote count: 0
answer count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/45600579

http://stackoverflow.com/q/47197083
has comment: http://stackoverflow.com/comment/81343425
has comment: http://stackoverflow.com/comment/81342757
favorite count: 0
score: 2
type: AnsweredQuestion
upvote count: 2
has title: Python-pip error just after fresh install
tagged with: python
type: Question
tagged with: openssl
answer count: 2
has answer: http://stackoverflow.com/a/53194522
has answer: http://stackoverflow.com/a/47197127
possible better answer: http://stackoverflow.com/a/53194522
accepted answer: http://stackoverflow.com/a/47197127
linked to: http://stackoverflow.com/q/45188413
has comment: http://stackoverflow.com/comment/81342840
downvote count: 0
tagged with: pip
has body: After a fresh install of python3 and python-pip I get this when I try to do anything with pip. fran@fran:~$ pip -v Traceback (most recent call last): File "/usr/bin/pip", line 9, in &lt;module&gt; from pip import main File "/usr/lib/python2.7/dist-packages/pip/__init__.py", line 13, in &lt;module&gt; from pip.exceptions import InstallationError, CommandError, PipError File "/usr/lib/python2.7/dist-packages/pip/exceptions.py", line 6, in &lt;module&gt; from pip._vendor.six import iteritems File "/usr/lib/python2.7/dist-packages/pip/_vendor/__init__.py", line 64, in &lt;module&gt; vendored("cachecontrol") File "/usr/lib/python2.7/dist-packages/pip/_vendor/__init__.py", line 36, in vendored __import__(modulename, globals(), locals(), level=0) File "/usr/share/python-wheels/CacheControl-0.11.5-py2.py3-none-any.whl/cachecontrol/__init__.py", line 9, in &lt;module&gt; File "/usr/share/python-wheels/CacheControl-0.11.5-py2.py3-none-any.whl/cachecontrol/wrapper.py", line 1, in &lt;module&gt; File "/usr/share/python-wheels/CacheControl-0.11.5-py2.py3-none-any.whl/cachecontrol/adapter.py", line 3, in &lt;module&gt; File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/__init__.py", line 53, in &lt;module&gt; File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3-none-any.whl/urllib3/contrib/pyopenssl.py", line 54, in &lt;module&gt; File "/usr/lib/python2.7/dist-packages/OpenSSL/__init__.py", line 8, in &lt;module&gt; from OpenSSL import rand, crypto, SSL File "/usr/lib/python2.7/dist-packages/OpenSSL/SSL.py", line 118, in &lt;module&gt; SSL_ST_INIT = _lib.SSL_ST_INIT AttributeError: 'module' object has no attribute 'SSL_ST_INIT' I'm new with python and I'm totally lost. Any idea?
tagged with: pyopenssl

http://stackoverflow.com/comment/81351483
type: AnswerComment
comment on: http://stackoverflow.com/a/47199474
score: 0
type: Comment
has text: Great, this seems to be less complex. Thanks.

http://stackoverflow.com/q/47209301
upvote count: 2
accepted answer: http://stackoverflow.com/a/47210943
has body: I was working on scraping data using Beautiful soup on multiple pages for the following given website and was able to do it. Can I scrape data for multiple pages using Pandas. Following is the code to scrape a single page and the URL has link to other pages as http://www.example.org/whats-on/calendar?page=3 . import pandas as pd url = 'http://www.example.org/whats-on/calendar?page=3' dframe = pd.read_html(url,header=0) dframe[0] dframe[0].to_csv('out.csv')
downvote count: 0
tagged with: web-scraping
has answer: http://stackoverflow.com/a/47210943
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: pandas
tagged with: python
has title: PANDAS Web Scraping Multiple Pages
possible better answer: http://stackoverflow.com/a/59716869
score: 2
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/59716869

http://stackoverflow.com/comment/81520857
type: Comment
has text: when I try to use dask.array.concatenate(series,axis=0) i get not implemented error... how did it work for you?
type: AnswerComment
comment on: http://stackoverflow.com/a/47218018
score: 0

http://stackoverflow.com/comment/81077968
type: AnswerComment
comment on: http://stackoverflow.com/a/47064881
has text: Awesome thx! Its a real same there is no documentation or example in the docs on timegrouper
score: 1
type: Comment

http://stackoverflow.com/comment/81108150
comment on: http://stackoverflow.com/q/47079559
score: 0
has text: are you running windows & unix/linux?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47101700
tagged with: return
has title: How to return a new object of a defined subclass in return statement
has comment: http://stackoverflow.com/comment/81153541
type: UnansweredQuestion
tagged with: python
tagged with: class
has answer: http://stackoverflow.com/a/47101807
score: 0
has body: I'm trying to get in return statement a new object of a defined class, but I am having difficulties while using the return statement. What I should get is a new object by calling the constructor in the same return statement passing as arguments those that require the constructor. Considering that the constructor of each class is the name of the class. THis is what I have so far: def complementary(self): complementary = ''.join([DNA.bases_complementary[base] for base in self.get_sequence()]) return complementary But it just return a string which is something obvious, but it is possible to return this string as a new object of the subclass DNA (The superclass is SEQUENCE). My SuperClass is this: class SEQUENCE: def __init__(self, sequence): self.__sequence = sequence length = len(sequence) def __str__(self): st = 'The introduced sequence is: {0}\n'.format(self.__sequence) st = st + 'The length of the sequence is: {0}\n'.format(len(self.__sequence)) return st def get_sequence(self): return self.__sequence My DNA subclass is this: class DNA(SEQUENCE): bases = {'A','T', 'C','G'} complementary_bases = {'A':'T', 'T':'A', 'C':'G','G':'C'} transcription = {'A':'U', 'T':'A', 'C':'G','G':'C'} def __init__(self, sequence): super().__init__(sequence) self.__length = len(sequence) bases = {'A','T','C','G'} sequence_set = set(sequence) if sequence_set &lt;= bases: print('The introduced sequence is', sequence, 'with the following length',len(sequence)) else: print('INCORRECT DNA SEQUENCE') raise NameError('SequenceError')
answer count: 1
type: Question

http://stackoverflow.com/a/47074425
has comment: http://stackoverflow.com/comment/81099968
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81099998
score: 1
type: Answer
has body: You can just use broadcasted numpy operations: v = df.val.values[:, None] * df.val.values v array([[ 4, 6, 10, 14], [ 6, 9, 15, 21], [10, 15, 25, 35], [14, 21, 35, 49]]) x = df.foo.values[:, None] + df.foo.values x array([['f1f1', 'f1f2', 'f1f3', 'f1f4'], ['f2f1', 'f2f2', 'f2f3', 'f2f4'], ['f3f1', 'f3f2', 'f3f3', 'f3f4'], ['f4f1', 'f4f2', 'f4f3', 'f4f4']], dtype=object) Conversion to a dataframe is super simple, just call the constructor: pd.DataFrame(x, df.index, df.index) n1 n2 n3 n4 n1 f1f1 f1f2 f1f3 f1f4 n2 f2f1 f2f2 f2f3 f2f4 n3 f3f1 f3f2 f3f3 f3f4 n4 f4f1 f4f2 f4f3 f4f4
has comment: http://stackoverflow.com/comment/81099776
accepted answer of: http://stackoverflow.com/q/47073936
answers question: http://stackoverflow.com/q/47073936
has comment: http://stackoverflow.com/comment/81099797
type: AcceptedAnswer

http://stackoverflow.com/q/47069688
has comment: http://stackoverflow.com/comment/81087220
has comment: http://stackoverflow.com/comment/81087314
type: Question
has answer: http://stackoverflow.com/a/47069837
type: UnansweredQuestion
tagged with: signals
tagged with: python
has title: try/except does not raise error
has comment: http://stackoverflow.com/comment/81087457
tagged with: python-2.7
score: 0
has body: In the following code, import platform import signal import threading import time class TimeoutListener(object): def __init__(self, timeout_seconds, error_message="Timeout executing."): self.timeout_seconds = timeout_seconds self.error_message = error_message self.alarm = None def __enter__(self): signal.signal(signal.SIGALRM, self._handle_timeout) signal.alarm(int(self.timeout_seconds)) def __exit__(self, listener_type, value, traceback): # Disable the alarm. if self.alarm: self.alarm = None else: signal.alarm(0) def _handle_timeout(self, signum, frame): print ("Got the signum %s with frame: %s" % (signum, frame)) raise ValueError(self.error_message) class TimedExecutor(object): @staticmethod def execute(timeout_secs, functor, *args, **kwargs): msg = "Timeout executing method - %s." % functor.__name__ timeout_signal = TimeoutListener(timeout_secs, error_message=msg) try: with timeout_signal: output = functor(*args, **kwargs) except Exception as ex: print("%s did not complete in %s: %s." % (functor.__name__, timeout_secs, repr(ex))) raise return output def foo(): for _ in range(10): try: time.sleep(1) print("SLEEPING") except Exception as ex: print ex ob = TimedExecutor.execute(1, foo) I have TimedExecutor class, which raises error when a function does not complete execution within the given timeout period. The code works fine (i.e. raises error at timeout) when foo is defined as follow: def foo(): try: for _ in range(10): time.sleep(1) print("SLEEPING") except Exception as ex: print ex whereas, if the same code of foo is written inside try/except, it does not raise any error (continues with execution). How could I make it raise the error, without making any changes to foo?
has comment: http://stackoverflow.com/comment/81087344
answer count: 1

http://stackoverflow.com/comment/81152010
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47100970
type: Comment
has text: @Jean-FrançoisFabre yes, I would probably use the `csv` module.

http://stackoverflow.com/q/47190822
has comment: http://stackoverflow.com/comment/81331170
tagged with: python
possible better answer: http://stackoverflow.com/a/47190931
downvote count: 4
has title: Using recursion to find which number is bigger
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81331552
answer count: 2
accepted answer: http://stackoverflow.com/a/47190944
has comment: http://stackoverflow.com/comment/81331179
upvote count: 1
has comment: http://stackoverflow.com/comment/81331173
favorite count: 0
has comment: http://stackoverflow.com/comment/81331184
type: Question
has body: Hello all I am trying to find out which of two numbers is bigger using recursion and without using the > or the &lt; symbols. Is this even possible? I am only allowed to use + or - thanks in advance
has answer: http://stackoverflow.com/a/47190931
has comment: http://stackoverflow.com/comment/81331246
has answer: http://stackoverflow.com/a/47190944
has comment: http://stackoverflow.com/comment/81331108
score: -3

http://stackoverflow.com/q/47206744
favorite count: 0
has title: Convert column float64/int64 to column with float/int as type in pandas dataframe
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81362581
answer count: 1
tagged with: stata
has comment: http://stackoverflow.com/comment/81362778
tagged with: pandas
has comment: http://stackoverflow.com/comment/81362814
has comment: http://stackoverflow.com/comment/81362732
has answer: http://stackoverflow.com/a/47207214
tagged with: types
downvote count: 0
has body: I wanted to save my pandas dataframe as a Stata file and there seems to be a problem with having columns with int64 or float64 types and thus need to be converted to standard Python types int and float. I have searched a lot but not found a solution to my problem as no solution has worked for me. I have tried using something like: import numpy as np def conversion(obj): if isinstance(obj, np.generic): return np.asscalar(obj) mergeddfnew["speech_main_wordspersentcount_wc"]=mergeddfnew["speech_main_wordspersentcount_wc"].apply(conversion) I also tried astype. The type of the column always stays the same.
score: 1
upvote count: 1

http://stackoverflow.com/comment/81300773
score: 0
comment on: http://stackoverflow.com/q/47151484
has text: If you want to ask on an algorithm to determine the ticks the way you imagine, please make that clear in the question. But then it would require to show some attempt. [This could be a good start](http://vis.stanford.edu/papers/tick-labels).
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47179545
score: 1
answer count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/47179725
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47179725
has body: I am building a graph where I want the initial weight to have changeable standard deviation. I tried to use the following command but it yielded an error: import tensorflow as tf import numpy as np stddev = tf.placeholder(dtype=tf.float32) a = tf.placeholder(dtype=tf.float32, shape=[1,50]) weight1 = tf.Variable(tf.truncated_normal(shape=[50, 30],stddev=stddev)) result = tf.reduce_sum(tf.matmul(a, weight1)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(result , {a: np.random.randn(1, 50), stddev: 0.01})) Can anyone help me with this issue? I know that I can set stddev when define it, but the task that I am facing is to use a variant stddev during the process of training.
downvote count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: random
has title: Dynamically change stddev of tf.truncated_normal in tensorflow

http://stackoverflow.com/comment/81213447
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47131758
has text: Modifying native prototypes is generally a bad practice. Just look at the mess Prototype.js has created.
type: Comment

http://stackoverflow.com/comment/81358047
has text: i am creating a game in python using turtle but i am able to control the speed of the turtle in the loop
type: Comment
comment on: http://stackoverflow.com/q/47204447
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81104391
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47077563
score: 0
has text: I want to use matplotlib only..i am trying the Iguananaut's answer..

http://stackoverflow.com/comment/81102691
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47066033
has text: You can also use `np.fromiter`', I've benchmarked it in an answer here. https://stackoverflow.com/questions/46860970/why-use-numpy-over-list-based-on-speed/46868693#46868693. It compares well to using numpy lists.

http://stackoverflow.com/a/47168523
has comment: http://stackoverflow.com/comment/81287422
has comment: http://stackoverflow.com/comment/81480998
upvote count: 3
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47167193
has body: Try to use cron. You just need to store new chat ids somewhere (file, database ect.) and read it from your script. for example to run send_messages.py everyday at 9pm (21:00): 0 21 * * * python send_messages.py
score: 2

http://stackoverflow.com/q/47163992
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/47164181
tagged with: bioinformatics
type: UnansweredQuestion
downvote count: 0
has body: I´m trying to fix this code below. from pylab import * protein = '' amino_acids = ['P', 'G', 'L', 'A'] while ________: protein += choice(amino_acids) if len(protein) == 1000: print(protein) The result I want to get is a random protein of length 1000 comprising of the four given amino acids (P,G,L and A). What is wrong?
favorite count: 0
has answer: http://stackoverflow.com/a/48892877
answer count: 3
tagged with: while-loop
has answer: http://stackoverflow.com/a/51825970
has title: Fixing the code in python / Bioinformatics
tagged with: python
has comment: http://stackoverflow.com/comment/81277949
type: Question
tagged with: python-3.x
tagged with: for-loop

http://stackoverflow.com/a/47185882
score: 5
has body: There really is no question in this question - mypy indeed behaves this way at the moment. The enum support is baked in, and is preliminary and somewhat ad-hoc. The kind of checking you are looking for might be implemented in the future. However, this code is fragile; if Color will change, it will silently break. Remember that Python is not a compiled language - the typechecker pass is optional, and someone else might not use it. The right way IMO is to add assert False at the end. This will also silence mypy.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47149154
answers question: http://stackoverflow.com/q/47149154
upvote count: 5
type: Answer

http://stackoverflow.com/comment/81358941
comment on: http://stackoverflow.com/a/47205091
type: Comment
score: 0
has text: :O gasps Not what I expected, thanks for the speedy answer. I'll try it out
type: AnswerComment

http://stackoverflow.com/a/47082639
answers question: http://stackoverflow.com/q/47082237
has comment: http://stackoverflow.com/comment/81114801
has comment: http://stackoverflow.com/comment/81115073
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47082237
has comment: http://stackoverflow.com/comment/81114732
has body: Build a dictionary of mappings: m = {'MAA' : 'MADRAS', 'BOM': 'BOMBAY', 'MAD' : 'MADRID'} Now, call str.replace on your column: df['Col'] = df['Col'].str.replace(r'.*?(?=[/*-])', lambda x: m.get(x.group(), None))

http://stackoverflow.com/q/47106071
type: UnansweredQuestion
has body: So I have a lot of tables with a general stucture of Base = declarative_base() class Thing(Base): __tablename__ = 'thing' uid = Column(Integer, Sequence('Thing_id_seq'), primary_key=True) name = Column(String) def __repr__(self): return "something" class ThingEntry(Base): __tablename__ = 'thingentry' uid = Column(Integer, Sequence('ThingEntry_id_seq'), primary_key=True) foo = Column(Integer, ForeignKey('foo.uid')) entity = Column(Integer, ForeignKey('thing')) class Quu(Base): __tablename__ = 'quu' uid = Column(Integer, Sequence('Quu_id_seq'), primary_key=True) name = Column(String) description = Column(String) def __repr__(self): return "something" class QuuEntry(Base): __tablename__ = 'quuentry' uid = Column(Integer, Sequence('QuuEntry_id_seq'), primary_key=True) foo = Column(Integer, ForeignKey('foo.uid')) entity = Column(Integer, ForeignKey('quu')) What are some more concise ways of defining all these classes/tables? This method has a lot of code duplication/self-repeating. I was thinking of some kind of inheritance so that I could bring that code down to class Thing(Base): pass class ThingEntry(Base): pass class Quu(Base): description = Column(String) class QuuEntry(Base): pass With some magic auto-assigning the other values (__tablename__, uid, foo, etc), but I'm not sure if that's possible or optimal.
tagged with: database
tagged with: python
has title: SQLAlchemy, concise ways of defining many similar classes/tables
has answer: http://stackoverflow.com/a/47107073
score: 0
tagged with: oop
tagged with: sqlalchemy
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47124385

http://stackoverflow.com/comment/81157470
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47103483
type: QuestionComment
has text: I want to make a very ugly and stupid tic tac toe program so I want to store the board ( idk how else to call that) in one list instead of 9 different variables

http://stackoverflow.com/comment/81244973
has text: One question, if i add [:7,:] to for row in a: it will cut down everything even if matrix is 8x8, how can i manage to show whole matrix, but calculate negative numbers till 7th ?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47147150

http://stackoverflow.com/comment/81174307
comment on: http://stackoverflow.com/a/47112110
type: Comment
score: 0
type: AnswerComment
has text: Much Thanks. The error is fixed but a new one popped up ]now. I'm fairly new, and I've gone to tutorialspoint for dictionaries, but was wondering if you had any other recommendations to look at?

http://stackoverflow.com/q/47154903
has comment: http://stackoverflow.com/comment/81481482
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81259569
has comment: http://stackoverflow.com/comment/81259551
tagged with: optimization
has body: The objective is to get the 3 highest values under each id and assign "primary","secondary", "tertiary" in that order. For example d_id = 1 has values of 100, 200 , 300 for x1 , x2, x3 ( which are store groups). So for d_id = 1 , x3 will be the primary store and so on. Below is the code for the process. cols = ["d_id", "primary", "secondary","tertiary"] scoring_results = pd.DataFrame(columns = cols, index = scoreperseg.index) zz = len(scoreperseg) d_count = 0 for index, row in scoreperseg.iterrows(): d_count += 1 row_sorted = row.sort_values(ascending=False) scoring_results.ix[index]['d_id'] = index scoring_results.ix[index]['primary'] = segment_map[row_sorted[0:3].idxmax()][1][0] scoring_results.ix[index]['secondary'] = segment_map[row_sorted[1:3].idxmax()][1][0] scoring_results.ix[index]['tertiary'] = segment_map[row_sorted[2:3].idxmax()][1][0] Segment_Map Key ['A', 'B', 'C', 'D' s14 ['Premiums'] s14 ['Movies'] s14 Score_Per_Seg d_id s2 s41 s47 s14 3 0 0 0 0.002507676 225 0 0 0 0 Scoring_Result d_id segment segment_genre 3 Premium Movies @COLDSPEED is this helpful? So , for the above example, I need to sort each row in score_per_seg , get the 3 highest values of segments and then find the indexes of those segments in segment map and then store the values in those indexes from segment map in scoring results as primary , secondary, tertiary. I hope this is clear enough to understand. There are more than 5 million d_id's and this process currently take more than 2 hours to complete. Is there any way to optimize these operations. I have tried searching for parallel operations but that won't work here I think. Can someone please guide me on this? Segment_Map contains how many times on an average a household has shopped from a particular store in a year.
has title: Optimizing python dict
has comment: http://stackoverflow.com/comment/81259825
score: 0
answer count: 0
tagged with: pandas

http://stackoverflow.com/comment/81399959
has text: While I appreciate the help of those who helped me get the concept, I also would like to express how rude some community members are. I wonder why there is an abusive and rude Flag option. Again, thank you to all who helped me out.
score: 0
comment on: http://stackoverflow.com/q/47215692
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47217556
type: Question
tagged with: azure
has title: Azure Python SDK Error
tagged with: python
upvote count: 4
score: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47257650
accepted answer: http://stackoverflow.com/a/47257650
answer count: 2
downvote count: 0
tagged with: api
possible better answer: http://stackoverflow.com/a/47217701
has answer: http://stackoverflow.com/a/47217701
has body: I have written python code to get azure resources for a subscription using azure-python sdk, the function to list all the resources inside a resource group is not working, this was working fine a week before, may be the microsoft have changed their api?? I am getting an attribute error, AttributeError: 'ResourceGroupsOperations' object has no attribute 'list_resources' Please Find the code below, from azure.common.credentials import ServicePrincipalCredentials from azure.mgmt.resource.resources import ResourceManagementClient from azure.mgmt.compute import ComputeManagementClient from azure.mgmt.network import NetworkManagementClient subscription_id = '' credentials = ServicePrincipalCredentials( client_id = '', secret = '', tenant = '', ) resource_client = ResourceManagementClient(credentials,subscription_id) resource_client.providers.register('Microsoft.Batch') def get_resources(): for rg in resource_client.resource_groups.list(): for item in resource_client.resource_groups.list_resources(rg.name): print "%s,%s,%s,%s,"%(item.name,item.type,item.location,rg.name) get_resources() Plz do help on this! thanks in advance !
favorite count: 0

http://stackoverflow.com/comment/90206684
has text: @NicholasPipitone why would I want to count number of lines? OP's code doesn't do that.
comment on: http://stackoverflow.com/a/47159136
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47085842
tagged with: python
tagged with: dictionary
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47085979
accepted answer: http://stackoverflow.com/a/47085979
favorite count: 0
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/47085897
has body: I'm working with a Rest Api for finding address details. I pass it an address and it passes back details for that address: lat/long, suburb etc. I'm using the requests library with the json() method on the response and adding the json response to a list to analyse later. What I'm finding is that when there is a single match for an address the 'FoundAddress' key in the json response contains a dictionary but when more than one match is found the 'FoundAddress' key contains a list of dictionaries. The returned json looks something like: For a single match: { 'FoundAddress': {AddressDetails...} } For multiple matches: { 'FoundAddress': [{Address1Details...}, {Address2Details...}] } I don't want to write code to handle a single match and then multiple matches. How can I modify the 'FoundAddress' so that when there is a single match it changes it to a list with a single dictionary entry? Such that I get something like this: { 'FoundAddress': [{AddressDetails...}] }
has title: json change dictionary item to a list with one dictionary
has answer: http://stackoverflow.com/a/47085897

http://stackoverflow.com/q/47216564
downvote count: 0
has comment: http://stackoverflow.com/comment/81383122
has comment: http://stackoverflow.com/comment/81383707
favorite count: 0
has body: I am using dask dataframe.groupby().apply() and get a dask series as a return value. I am each group to a list triplets such as (a,b,1) and wish then to turn all the triplets into a single dask data frame I am using this code in the end of the mapping function to return the triplets as a dask df #assume here that trips is a generator for tripletes such as you would produce from itertools.product([l1,l2,l3]) trip = list(itertools.chain.from_iterable(trip)) df = pd.DataFrame.from_records(trip) return dd.from_pandas(df,npartitions=1) then when I try to use something similar to pandas concat with dask concatenate Assume the result of the apply function is the variable result. I am trying to use import dask.dataframe as dd dd.concat(result, axis=0 and get the error raise TypeError("dfs must be a list of DataFrames/Series objects") TypeError: dfs must be a list of DataFrames/Series objects But when I check for the type of result using print type(result) I get output: class 'dask.dataframe.core.Series' What is the proper way to apply a function over groups of dask groupby object and get all the results into one dataframe? Thanks edit:-------------------------------------------------------------- in order to produce the use case, assume this fake data generation import random import pandas as pd import dask.dataframe as dd people = [[random.randint(1,3), random.randint(1,3), random.randint(1,3)] for i in range(1000)] ddf = dd.from_pandas(pd.DataFrame.from_records(people, columns=["first name", "last name", "cars"]), npartitions=1) Now my mission is to group people by first and last name (e.g all the people with same first name &amp; first last name) and than I need to get a new dask data frame which will contain how many cars each group had. Assume that the apply function can return either a series of lists of tuples e.g [(name,name,cars count),(name,name,cars count)] or a data frame with the same columns - name, name, car count. Yes, I know that particular use case can be …
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81383174
has answer: http://stackoverflow.com/a/47290091
tagged with: dask
tagged with: pandas
has comment: http://stackoverflow.com/comment/81383485
has comment: http://stackoverflow.com/comment/81382676
tagged with: dataframe
tagged with: python
tagged with: apply
has title: python dask dataframes - concatenate groupby.apply output to a single data frame
accepted answer: http://stackoverflow.com/a/47218018
possible better answer: http://stackoverflow.com/a/47290091
type: Question
score: 2
has comment: http://stackoverflow.com/comment/81382765
has answer: http://stackoverflow.com/a/47218018
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81382732

http://stackoverflow.com/q/47080079
linked to: http://stackoverflow.com/q/36939063
tagged with: matplotlib
answer count: 1
downvote count: 0
has body: I'm looking to add a label to a colorbar in Matplotlib, but more importantly, I'm trying to place the label where I want it. I found set_label: cb = plt.colorbar() cb.set_label(units) and I found a question where someone had rotated the text of the label: cb.set_label(units, rotation = 270) and I found a reference to the existence of set_label having kwargs: link for API But WHERE can I find what kwargs are available to me? What I want to do is either locate the label above the colorbar or at the end of the colorbar.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81109752
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/81110433
has title: How to find kwargs for colorbar matplotlib
score: 2
accepted answer: http://stackoverflow.com/a/47083733
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47083733

http://stackoverflow.com/q/47139025
type: Question
tagged with: debugging
has comment: http://stackoverflow.com/comment/81227526
has body: I have a programme with a lot of if else conditions. A small sample is as follows: if(lhs == 'a' and rhs=='a'): return 'aa' if(lhs == 'i' and rhs=='i'): return 'ii' if(lhs == 'u' and rhs=='u'): return 'uu' else: return 'invalid' I want to debug my programme so that I can find out which condition is satisfied. Where do I add such a breakpoint in pycharm so that I can find out which condition is invoked?
tagged with: python
accepted answer: http://stackoverflow.com/a/47139147
has comment: http://stackoverflow.com/comment/81227915
type: AnsweredQuestion
tagged with: pycharm
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81227588
answer count: 1
has title: finding satisfied condition while debugging in pycharm
upvote count: 1
has comment: http://stackoverflow.com/comment/81227880
favorite count: 0
has answer: http://stackoverflow.com/a/47139147

http://stackoverflow.com/a/47175995
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47175195
has body: .append is a method of a list, which means you should "call" it, for example like my_list.append(item). Also, input() accepts an argument, which is the string to print before getting the input - you can do something like input("enter your name &gt; "). Using this, it might make sense to write a reusable function that gets a score for a certain player and round: def get_score(player, round_): return int(input("Enter the score for player {}, round {}&gt; ".format(player, round_))) The round argument is named round_ as round is already a Python builtin. Beware that this will crash if the user doesn't enter an integer, but that would take quite a bit more logic to fix. We can also write a function that collects a player's scores for a whole round: def _get_round_scores(player, rounds): scores = [] for round_ in range(rounds): scores.append(get_score(player, round_ + 1)) return scores This uses a for loop to append a score for each round (note how the logic of actually getting the score has been abstracted away). It's prefixed with an underscore as this isn't the "final" version. Using this, we might even write a similar function to get scores for different players: def _get_player_scores(players, rounds): players = [] for player in range(players): players.append(_get_round_scores(player + 1, rounds)) return players However, we can actually rewrite both without needing append at all, with Python list comprehensions (which should be well documented elsewhere), like so: def get_round_scores(player, rounds): return [get_score(player, round_ + 1) for round_ in range(rounds)] def get_player_scores(players, rounds): return [get_round_scores(player + 1, rounds) for player in range(players)] Now, we can use our functions like so: scores = player1, player2 = get_player_scores(players=2, rounds=3) print(scores) print(player1) print(player2) To get this behaviour: Enter the score for player 1, round 1&gt; 1 Enter the score for player 1, round 2&gt; 2 Enter the score for player 1, r…
type: Answer
downvote count: 0

http://stackoverflow.com/a/47199983
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: As I mentioned, use np.argmin: yrs[np.abs(np.array(yrs) - _tmp).argmin()] convert yrs to a numpy.ndarray (skip if already array) broadcasting subtraction of _tmp from every elements in yrs np.abs finds the absolute value (we want absolute least) np.argmin finds the index of the smallest value index into yrs to finish the job.
answers question: http://stackoverflow.com/q/47196133
type: Answer
accepted answer of: http://stackoverflow.com/q/47196133

http://stackoverflow.com/q/47091803
downvote count: 0
upvote count: 1
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47092848
answer count: 3
score: 1
has comment: http://stackoverflow.com/comment/81133420
has title: One big list to specific dict
has answer: http://stackoverflow.com/a/47092134
has body: I'm trying to convert list to Dict. i tried many solutions but can't find way to do exactly like this python dict is one of the best things in python so i need Dict I have one big list like this [{ '1': { '1.1': '', '1.2': '', '1.3': False } }, { '2': { '2.1': False } }, { '3': { '3.1': [100, 91, 100, 100], '3.2': 5, '3.3': True, '3.5': ['Page has no headings', 'This form element has no label.', 'This link has no text inside it.', 'This link text is uninformative.'], '3.6': 4 } }, { '4': { '4.1': False, '4.2': False, '4.3': True } }, { '5': { '5.1': True, '5.2': '"2021-12-14 19:00:42"', '5.3': True } }] I only want Dict like this final_result ={ '1': { '1.1': '', '1.2': '', '1.3': False } '2': { '2.1': False } '3': { '3.1': [100, 91, 100, 100], '3.2': 5, '3.3': True, '3.5': ['Page has no headings', 'This form element has no label.', 'This link has no text inside it.', 'This link text is uninformative.'], '3.6': 4 } '4': { '4.1': False, '4.2': False, '4.3': True } '5': { '5.1': True, '5.2': '"2021-12-14 19:00:42"', '5.3': True } } I tried some ways but I'm having a bad day so can't get the solution thanx
has answer: http://stackoverflow.com/a/47092977
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/81279075
has text: I'm asking about the substitution for the x,y,z,a3,b3,c3 missing values in the original sequence
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47164436

http://stackoverflow.com/q/47149076
upvote count: 1
tagged with: tensorflow
favorite count: 0
has title: Tensorflow 1.4 Keras issue with respect to model_fn
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: keras-2
has comment: http://stackoverflow.com/comment/82181488
has answer: http://stackoverflow.com/a/47844140
score: 1
has comment: http://stackoverflow.com/comment/81421825
has body: I have a model function which accepts Features, targets and mode but when I add tf.keras layers I'm currently getting Exception pred must be a Tensor, a Variable, or a Python bool. But, When I run the same code with out using tf.keras but directly from keras(i.e. from keras.layers), It's working. Code : def model_fn(features, labels, mode): if mode == tf.estimator.ModeKeys.TRAIN: tf.keras.backend.set_learning_phase(1) else: tf.keras.backend.set_learning_phase(0) input_feature = features['x'] table = lookup.index_table_from_file(vocabulary_file='vocab.txt', num_oov_buckets=1, default_value=-1) text = tf.squeeze(input_feature, [1]) words = tf.string_split(text) densewords = tf.sparse_tensor_to_dense(words, default_value=PADWORD) numbers = table.lookup(densewords) padding = tf.constant([[0, 0], [0, MAX_FEATURES]]) padded = tf.pad(numbers, padding) sliced = tf.slice(padded, [0, 0], [-1, MAX_FEATURES]) print('words_sliced={}'.format(words)) #embeds = tf.keras.layers.Embedding(MAX_FEATURES, 50, input_length=MAX_FEATURES)(sliced) embeds = tf.contrib.layers.embed_sequence(sliced, vocab_size=MAX_FEATURES, embed_dim=50) print('words_embed={}'.format(embeds)) f1 = tf.keras.layers.Dropout(0.2)(embeds) f1 = tf.keras.layers.Conv1D(filters, kernel_size, padding='valid', activation='relu', strides=1)(f1) f1 = tf.keras.layers.GlobalAveragePooling1D()(f1) # f1 = layers.BatchNormalization()(f1) f1 = tf.keras.layers.Dense(hidden_dims)(f1) f1 = tf.keras.layers.Dropout(0.5)(f1) f1 = tf.keras.layers.Activation('relu')(f1) logits = tf.keras.layers.Dense(11)(f1) predictions_dict = { 'class': tf.argmax(logits, 1), 'prob': tf.nn.softmax(logits) } prediction_output = tf.estimator.export.PredictOutput({"classes": tf.argmax(input=logits, axis=1), "probabilities": tf.nn.softmax(logits, name="softmax_tensor")}) if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions_dict, export_outputs={ tf.saved_model.signature_constants.DEFAULT_SERVING_SIGN…
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81326988

http://stackoverflow.com/comment/81338571
comment on: http://stackoverflow.com/q/47191675
score: 0
has text: [try opening the file in append mode](https://stackoverflow.com/a/17531025/1278112)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47092185
type: AnsweredQuestion
tagged with: word-embedding
tagged with: python
has body: In this TensorFlow example a training of skip-gram Word2Vec model described. It contains the following code fragment, which explicitly requires CPU device for computations, i.e. tf.device('/cpu:0'): batch_size = 128 embedding_size = 128 # Dimension of the embedding vector. skip_window = 1 # How many words to consider left and right. num_skips = 2 # How many times to reuse an input to generate a label. # We pick a random validation set to sample nearest neighbors. Here we limit the # validation samples to the words that have a low numeric ID, which by # construction are also the most frequent. valid_size = 16 # Random set of words to evaluate similarity on. valid_window = 100 # Only pick dev samples in the head of the distribution. valid_examples = np.array(random.sample(range(valid_window), valid_size)) num_sampled = 64 # Number of negative examples to sample. graph = tf.Graph() with graph.as_default(), tf.device('/cpu:0'): # Input data. train_dataset = tf.placeholder(tf.int32, shape=[batch_size]) train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1]) valid_dataset = tf.constant(valid_examples, dtype=tf.int32) # Variables. embeddings = tf.Variable( tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0)) softmax_weights = tf.Variable( tf.truncated_normal([vocabulary_size, embedding_size], stddev=1.0 / math.sqrt(embedding_size))) softmax_biases = tf.Variable(tf.zeros([vocabulary_size])) # Model. # Look up embeddings for inputs. embed = tf.nn.embedding_lookup(embeddings, train_dataset) # Compute the softmax loss, using a sample of the negative labels each time. loss = tf.reduce_mean( tf.nn.sampled_softmax_loss(weights=softmax_weights, biases=softmax_biases, inputs=embed, labels=train_labels, num_sampled=num_sampled, num_classes=vocabulary_size)) # Optimizer. # Note: The optimizer will optimize the softmax_weights AND the embeddings. # This is because the embeddings are defined as a variable quantity and the # optimizer's `minimize` method will by defau…
has title: TensorFlow Word2Vec model running on GPU
type: Question
accepted answer: http://stackoverflow.com/a/47442005
score: 0
has answer: http://stackoverflow.com/a/47442005
answer count: 1
tagged with: word2vec
tagged with: tensorflow

http://stackoverflow.com/q/47169867
score: 0
has title: use == to check if two objects have the same value or not in python
has answer: http://stackoverflow.com/a/47169886
downvote count: 2
possible better answer: http://stackoverflow.com/a/47169886
answer count: 3
has comment: http://stackoverflow.com/comment/81289525
has comment: http://stackoverflow.com/comment/81289502
favorite count: 0
has body: The following is the code: class foo: def __init__(self,p1,p2): self.a1 = p1 self.a2 = p2 def main(): o1=foo("lucy","jack") o2=foo('lucy','jack') print(o1==o2) main() I understand that o1 and o2 are different objects. What confuses me is that, they have the same value, right? And the "==" is used to check to see if two objects have the same value or not, right? Did I miss something here?
type: Question
has answer: http://stackoverflow.com/a/47169996
has comment: http://stackoverflow.com/comment/81289501
has answer: http://stackoverflow.com/a/47169901
tagged with: python
upvote count: 2
accepted answer: http://stackoverflow.com/a/47169996
type: AnsweredQuestion

http://stackoverflow.com/a/47087393
has comment: http://stackoverflow.com/comment/81125033
type: Answer
accepted answer of: http://stackoverflow.com/q/47087099
has comment: http://stackoverflow.com/comment/81124932
answers question: http://stackoverflow.com/q/47087099
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81125052
downvote count: 0
has body: Is this what you want ? df['group'] = (~((df-df.shift()).diff().eq(0)|(df-df.shift(-1)).diff().eq(0))).cumsum() print(list(df.groupby('group').col.apply(list))) [[0], [1], [5], [8], [10, 20, 30, 40], [45], [48], [77], [100, 200, 300, 400]]
has comment: http://stackoverflow.com/comment/81124985
score: 3

http://stackoverflow.com/q/47076719
tagged with: excel
favorite count: 0
has body: I am trying to connect 20 excel files into one and save it to excel. It should be in one sheet. My idea so far was to read all the files into dataframes, concat them and save to excel. After concatening I have a dataframe which shape is (1245226, 20), after saving file the size in excel is (1048576, 20) and its size on disk is 61 MB. Below I am posting the methods I tested to save the file: &gt;&gt; df.shape (1245226, 20) Method 1 - getting (1048576, 20) instead of (1245226, 20) writer = pd.ExcelWriter(path) df.to_excel(writer, index=False) writer.close() Method 2 - not being able to save file, because of lack of memory (16 gb RAM) writer = pd.ExcelWriter(path, engine='openpyxl') df.to_excel(writer, index=False) writer.close() Method 3 - getting (1048576, 20) instead of (1245226, 20) writer = pd.ExcelWriter(path, enigne='xlsxwriter') df.to_excel(writer, index=False) writer.close() Any ideas how to save it? Maybe there is a method to append data straightly to excel file?
type: Question
tagged with: python
has title: Saving big xlsx files pandas python
linked to: http://stackoverflow.com/q/59951397
type: AnsweredQuestion
tagged with: pandas
score: 3
upvote count: 3
tagged with: save
answer count: 1
accepted answer: http://stackoverflow.com/a/47076820
downvote count: 0
has answer: http://stackoverflow.com/a/47076820
has comment: http://stackoverflow.com/comment/117982136

http://stackoverflow.com/comment/81177639
type: QuestionComment
has text: Thanks both. From the output, do you think the reason why I cannot see the bars in the chart is because the two columns from the dataframe have different types? Because If I don't arrange I can see the values in the chart on the x and y axis. Just not the bars :(
score: 0
comment on: http://stackoverflow.com/q/47113637
type: Comment

http://stackoverflow.com/comment/81155511
score: 0
has text: @ScottHunter Actually it *is* syntactically valid to have equal keys: `$ python -c 'print({"a": 1, "a": 2})'` outputs `{'a': 2}`, i.e. the last occurrence overrides previous values
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47102518

http://stackoverflow.com/a/47209314
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47206487
type: AcceptedAnswer
has body: If you are just trying to filter out events by their category, I believe you just need to add the "not" field: "dimensionFilterClauses": [ { "filters": [ { "dimensionName": "ga:eventCategory", "operator": "EXACT", "not": "true", "expressions": ["Operational Events"] }]}],
answers question: http://stackoverflow.com/q/47206487
has comment: http://stackoverflow.com/comment/83150300

http://stackoverflow.com/comment/81186442
type: QuestionComment
has text: There is a convention for USAGE lines to have the optional arguments in square brackets. So I don't think you really want [input.ext] and [output.ext] on the first line and having them in COMPULSORY section.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47118098

http://stackoverflow.com/comment/81312258
type: Comment
score: 0
type: AnswerComment
has text: [Finding the backend in use](https://stackoverflow.com/questions/3580027/how-do-you-determine-which-backend-is-being-used-by-matplotlib). I really think a screenshot could help.
comment on: http://stackoverflow.com/a/47181267

http://stackoverflow.com/comment/81385558
comment on: http://stackoverflow.com/q/47218038
score: 1
type: QuestionComment
has text: Explain the meaning of each quotation mark to your rubber duck. Then apply the mechanism shown in the Ansible documentation which you linked to.
type: Comment

http://stackoverflow.com/comment/81150373
type: QuestionComment
has text: `a &= 0xFFFFFFFFFFFFFFFF` discards all but the low 64 bits of the variable.
score: 2
comment on: http://stackoverflow.com/q/47100105
type: Comment

http://stackoverflow.com/comment/81248544
type: Comment
comment on: http://stackoverflow.com/q/47149270
type: QuestionComment
has text: @Nostalg.io it is based on a function that is static. So it is a constant addition function that would add a simple value over time. Maybe a “+1 every x hours”.
score: 0

http://stackoverflow.com/q/47089036
has body: I tried uploading modules to redshift through S3 but it always says no module found. please help CREATE or replace FUNCTION olus_layer(subs_no varchar) RETURNS varchar volatile AS $$ import plpydbapi dbconn = plpydbapi.connect() cursor = dbconn.cursor() cursor.execute("SELECT count(*) from busobj_group.olus_usage_detail") d=cursor.fetchall() dbconn.close() return d $$ LANGUAGE plpythonu; –
has title: how to use select query inside a python udf for redshift?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81128150
tagged with: user-defined-functions
has answer: http://stackoverflow.com/a/47093024
possible better answer: http://stackoverflow.com/a/47093024
tagged with: amazon-redshift
has comment: http://stackoverflow.com/comment/81128184
tagged with: python
type: Question
upvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/47090275
accepted answer: http://stackoverflow.com/a/47090275
tagged with: sql
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81128126
has comment: http://stackoverflow.com/comment/81127431
tagged with: amazon-web-services
favorite count: 0
has answer: http://stackoverflow.com/a/56714678
has comment: http://stackoverflow.com/comment/81165938

http://stackoverflow.com/comment/81194222
score: 0
has text: Didn't you mean [j][k] there at : `if coords[i][j][j] is in bounds, a`? Also, what shuffling are we talking about?
comment on: http://stackoverflow.com/q/47121919
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81163068
type: AnswerComment
comment on: http://stackoverflow.com/a/47104494
type: Comment
has text: @Rael consider accepting this answer if it solved your issue.
score: 0

http://stackoverflow.com/comment/81238390
has text: Does it have to use turtle? Because the other built-in GUI modules can move objects a million times more easily.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47144177
type: Comment

http://stackoverflow.com/q/47093345
answer count: 2
downvote count: 0
tagged with: pandas
type: UnansweredQuestion
has title: Querying a df using its index based on values of another index Python pandas
has answer: http://stackoverflow.com/a/47094064
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/47093894
score: 2
has body: I have two dataframes, and I want to create a filtered df_1 based on the timestamp index of df_2, shown below. For each index value of df_2, I want to take all the rows of df_1 that is within timedelta of 1 day of df_2 index value. Example: for df_2 index value 10/15/2017, I want to include in the new df_outcome, all the rows of df_1 that are between 10/14/2017 to 10/16/2017, which returns 10/14/2017 f and 10/15/2017 g. Any duplicates from the query are removed. df_1 Index Values 10/2/2017 a 10/4/2017 b 10/5/2017 c 10/7/2017 d 10/9/2017 e 10/14/2017 f 10/15/2017 g 10/20/2017 h df_2 Index Values 10/4/2017 Apple 10/6/2017 Banana 10/13/2017 Pear 10/15/2017 Pineapple df_outcome Index Values 10/4/2017 b 10/5/2017 c 10/7/2017 d 10/14/2017 f 10/15/2017 g Any help is appreciated, thanks. EDIT: I edited to change the index to timestamps, to reflect the actual problem. I'm so sorry for any confusion I did not anticipate it would be a problem. The timestamps are uneven.
upvote count: 2

http://stackoverflow.com/comment/81375879
score: 0
comment on: http://stackoverflow.com/q/47212841
type: Comment
has text: It might be useful to try grouping and counting by country first (`df.groupBy('mcc').count()`) then checking to see if 199k is plausible for Bangladesh compared to other countries. Are any of those fields useful for checking for duplicate records?
type: QuestionComment

http://stackoverflow.com/a/59280734
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/47214251
downvote count: 0
has body: tf.estimator use tf.train.ProfilerHook works! just add a ProfilerHook in TrainSpec hooks! hook = tf.train.ProfilerHook( save_steps=20, output_dir=os.path.join(args.model_dir, "tracing"), show_dataflow=True, show_memory=True) hooks = [hook] train_spec = tf.estimator.TrainSpec( hooks=hooks, input_fn=lambda: input_fn()) then, you could get the tracing file like timeline-{}.json in model_dir/tracing, and open chrome chrome://tracing to visual! refs: https://stackoverflow.com/a/48278275/6494418

http://stackoverflow.com/comment/81365675
type: QuestionComment
score: 0
has text: @iamsterdam I don't understand. need a label?
type: Comment
comment on: http://stackoverflow.com/q/47207713

http://stackoverflow.com/comment/81296928
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47173631
score: 1
has text: @jezrael You're free to do what you want, but I have a word of advice... if a question is not in a state that writing an answer is guaranteed to solve the OP's problem (as you yourself admit you're not sure), then leave it closed! Or, at least, vote to close as "too broad"/"no mcve".

http://stackoverflow.com/comment/81326935
type: Comment
comment on: http://stackoverflow.com/a/47165989
has text: @AidanL. First the input problem. There is another solution apart from the `input()` at the end of the line (not sure how useful it is) you can also use batch script. A script that would stop the console closing (Windows only) would be `@echo off`, `call <your app name>`, `pause`. save it in a a file with something with `.bat` extension and double click bat file to launch. Oh if you do. However it works under Windows ONLY is that it has loads of advantages. Changing color of text/console, setting title just to name a few.
type: AnswerComment
score: 0

http://stackoverflow.com/a/47118652
answers question: http://stackoverflow.com/q/47118379
type: Answer
has body: Here we that keeps track of positions you've already seen in a set object: In [25]: def kauhop(seq): ...: seen = set() ...: maxlen = len(seq) - 1 ...: def helper(pos): ...: if pos &gt; maxlen or pos &lt; 0 or pos in seen: ...: return False ...: elif pos == maxlen: ...: return True ...: else: ...: jump = seq[pos] ...: seen.add(pos) ...: left = helper(pos - jump) ...: right = helper(pos + jump) ...: return left or right ...: return helper(0) ...: In [26]: kauhop(a) Out[26]: True Essentially, you can use recursion to check every possible path. Consider your current position: if you are out of bounds in either direction, or you've already checked that position (it's in seen), then return False. Otherwise, mark the position as seen, check a left jump, and a right jump, and return if either left or right is a success. Note: I use an helper inner function. This lets me not have to keep passing the seen set around, since the helper is closed over seen, and for that matter, maxlen. Now I'm wondering if there is a better approach than brute-force.
score: 0

http://stackoverflow.com/comment/81212048
has text: It's just a bunch of print statements in a loop. What've you tried so far? Please don't assume you'll be handed over code on this website. Show your efforts
score: 5
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47131263

svd
type: Tag
tags question: http://stackoverflow.com/q/47208838
tag name: svd

http://stackoverflow.com/q/47098181
linked to: http://stackoverflow.com/q/19128540
has body: I have a Django app deployed on IIS. I am currently working through Django's deployment checklist to secure the app. I have an environment variable with the SECRET_KEY stored as the value. I am accessing the SECRET_KEY with this: SECRET_KEY = os.getenv('SECRET_KEY') print(SECRET_KEY) When I view the IIS hosted app, I get a 500 error. When I use runserver to host the same app, the development server runs with no issues, and the SECRET_KEY is printed out (and is therefore accessed from settings.py). However, this issue occurs when the app is viewed in the browser: ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. How is the SECRET_KEY empty if it's printed out in the command line? Edit: In case it helps, my wsgi.py looks like this: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings") application = get_wsgi_application()
tagged with: fastcgi
answer count: 0
has comment: http://stackoverflow.com/comment/81147674
type: Question
has comment: http://stackoverflow.com/comment/81147020
has comment: http://stackoverflow.com/comment/81147547
tagged with: iis
tagged with: wsgi
has comment: http://stackoverflow.com/comment/81146875
tagged with: django
type: UnansweredQuestion
tagged with: python
has title: Deploying Django App on IIS - Secret Key Improperly Configured
has comment: http://stackoverflow.com/comment/81147242
score: 0

http://stackoverflow.com/comment/81217183
type: QuestionComment
has text: Python doesn't have private vs. public class elements. If it exists, you can reference it.
comment on: http://stackoverflow.com/q/47133734
score: 2
type: Comment

http://stackoverflow.com/comment/81194049
score: 0
type: Comment
type: QuestionComment
has text: Don't use `list(<genexpr>)`. Just use a list comprehension (replace the `list(...)` with `[...]`).
comment on: http://stackoverflow.com/q/47122201

http://stackoverflow.com/q/47097263
type: Question
upvote count: 2
score: 2
downvote count: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47098402
has comment: http://stackoverflow.com/comment/81144260
tagged with: flask
has body: I'm new at Flask. I try to pass a parameter from the main, but it doesn't work. Hope somebody can help me. Here is my code from flask import Flask, render_template, request import controllFlask import pickle app = Flask(__name__) # creates a flask object import subprocess @app.route('/', methods=['GET', 'POST']) def ner(): '''controlls input of Webapp and calls proccessing methods''' knownEntities = pickle.load( open( "entityDictThis.p", "rb" )) print("loades") content = "" if request.method == 'POST': testText = (request.form['input']) app.ma = controllFlask.controll(testText, knownEntities) subprocess.call("controllFlask.py", shell=True) with open("test.txt", "r") as f: content = f.read() return render_template("ner.jinja2", content=content) def flaskApp(): app.debug = True app.run() I want to open entityDictThis in flaskApp and give it to the ner-function. Because I hope in this way it loads only one time. At the moment it loads every time the page is reloaded and it takes very long. Is there a easy way?
has comment: http://stackoverflow.com/comment/81144206
tagged with: python
linked to: http://stackoverflow.com/q/14860007
has title: pass parameters from Flask main
favorite count: 0

http://stackoverflow.com/a/47099398
accepted answer of: http://stackoverflow.com/q/47096887
has comment: http://stackoverflow.com/comment/81149307
answers question: http://stackoverflow.com/q/47096887
type: Answer
score: 0
type: AcceptedAnswer
has body: From the css3 selector docs: 8.3.1. Adjacent sibling combinator The adjacent sibling combinator is made of the "plus sign" (U+002B, +) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence immediately precedes the element represented by the second one. Which means in your selector td b:contains('Owner Address')+td, you're asking for a td that has the same parent as the b which contains 'Address' and is child of another td. This node does not exist. To make it work, you need to make sure that you're first partial selector matches the td, not the b node. Since they contain each other, the following would work: td:contains('Owner Address') + td Note that this td has no text (only child nodes), so your snippet from above only prints whitespaces.

http://stackoverflow.com/comment/81279786
comment on: http://stackoverflow.com/a/47164272
score: 0
type: Comment
type: AnswerComment
has text: j15, thanks for the direction. I missed the mark when given the problem in a coderpad session.

http://stackoverflow.com/comment/81229535
has text: [Extra fields on many-to-many relationships](https://docs.djangoproject.com/en/1.11/topics/db/models/#intermediary-manytomany)
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47139873

http://stackoverflow.com/comment/111804542
type: AnswerComment
type: Comment
has text: @Milano did you find a solution for this problem?
comment on: http://stackoverflow.com/a/47127002
score: 0

http://stackoverflow.com/a/47189801
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/81330504
downvote count: 1
answers question: http://stackoverflow.com/q/47189764
has body: You could do this x=.25 while int(x) != x: x=x*10
type: Answer
has comment: http://stackoverflow.com/comment/81330734
has comment: http://stackoverflow.com/comment/81330624

http://stackoverflow.com/q/47124136
has comment: http://stackoverflow.com/comment/81198517
duplicate of: http://stackoverflow.com/q/12423614
accepted answer: http://stackoverflow.com/a/47124234
has title: Python: Do string substitution with variables at function definition time
type: Question
tagged with: scope
has answer: http://stackoverflow.com/a/47124234
has body: I have a situation like the following: functions = [] some_list = [('a', 'b'), ('c', 'd')] for x, y in some_list: def foo(z): # do some things return "{} {} {}".format(x, y, z) functions.append(foo) But obviously this doesn't work, as x and y will always have the last values they had in the loop, i.e. 'c' and 'd', i.e. both functions in the functions list will return '{} c d'.format(z) in practice. How do I make it so that it does the string substitution immediately, so that on the first loop it defines foo(z) as the equivalent to def foo(z): # do some things return "{} a b".format(z) without any reference to the variables x and y? EDIT: I now realize I also need to store a copy of foo in functions, not foo itself, but the rest of the question stll stands.
has comment: http://stackoverflow.com/comment/81198381
tagged with: python
has comment: http://stackoverflow.com/comment/81198519
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81198454
score: 0
linked to: http://stackoverflow.com/q/12423614
linked to: http://stackoverflow.com/q/1132941
tagged with: functional-programming
has comment: http://stackoverflow.com/comment/81198642
answer count: 1

http://stackoverflow.com/a/47149825
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47149060
score: 3
answers question: http://stackoverflow.com/q/47149060
type: Answer
has body: Overall Answer The first three apostrophes start a multi-line string. The next apostrophe is just part of the contents of the string. Inspecting the Result The script stores the string in the __doc__ variable. After running the code interactively with python -i pox.py, it is easy to see the parsed docstring directly: &gt;&gt;&gt; print __doc__ 'true #export OPT="-u -O" export OPT="-u" export FLG="" if [ "$(basename $0)" = "debug-pox.py" ]; then export OPT="" export FLG="--debug" fi if [ -x pypy/bin/pypy ]; then exec pypy/bin/pypy $OPT "$0" $FLG "$@" fi if type python2.7 &gt; /dev/null 2&gt; /dev/null; then exec python2.7 $OPT "$0" $FLG "$@" fi exec python $OPT "$0" $FLG "$@" Note how the fourth apostrophe was kept as part of the docstring. Details According to the tokenize module, here is how Python views the above code: NL : '\n' COMMENT : '#!/bin/sh -' NL : '\n' NL : '\n' STRING : '\'\'\'\'true\n#export OPT="-u -O"\nexport OPT="-u"\nexport FLG=""\nif [ "$(basename $0)" = "debug-pox.py" ]; then\n export OPT=""\n export FLG="--debug"\nfi\n\nif [ -x pypy/bin/pypy ]; then\n exec pypy/bin/pypy $OPT "$0" $FLG "$@"\nfi\n\nif type python2.7 &gt; /dev/null 2&gt; /dev/null; then\n exec python2.7 $OPT "$0" $FLG "$@"\nfi\nexec python $OPT "$0" $FLG "$@"\n\'\'\'' NEWLINE : '\n' NAME : 'from' NAME : 'pox' OP : '.' NAME : 'boot' NAME : 'import' NAME : 'boot' NEWLINE : '\n' NAME : 'if' NAME : '__name__' OP : '==' STRING : "'__main__'" OP : ':' NEWLINE : '\n' INDENT : ' ' NAME : 'boot' OP : '(' OP : ')' NEWLINE : '\n' DEDENT : '' ENDMARKER : '' Tokenization Script Here is a Python 2.7 script that tokenizes the pox.py script: from __future__ import print_function import tokenize import token with open('pox.py') as f: for tok in tokenize.generate_tokens(f.readline): tok_type, tok_str, (srow, scol), (erow, ecol), logical_lineno = tok print('%-10s: %r' % (token.tok_name[tok_type], tok_str))
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/81301862
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47175265
has text: Hmmm, then reason should be some whitespaces like `df = pd.DataFrame({'b':['e','e',' ', ''],'c':['e','f','g', 'h']})`, check it by `(df.drop_duplicates('b', keep=False))`
type: Comment

http://stackoverflow.com/comment/81207684
has text: A job for [`asyncio`](https://docs.python.org/3/library/asyncio.html)?
score: 1
comment on: http://stackoverflow.com/q/47128671
type: Comment
type: QuestionComment

qfont
type: Tag
tag name: qfont
tags question: http://stackoverflow.com/q/47115171

http://stackoverflow.com/a/47172802
upvote count: 1
has body: I think I solved this myself. I created a thread in the constructor of the class. Also, it seems important to initialize the self variables used in the functions like speed. The rewritten code is class VS(): def __init__(self): #code to initialise bus self.message = bus.recv() #to receive 1 message self.t = Thread(target = self.speed, args = ()) self.t.start() def speed(self): while True: self.message = bus.recv() return self.message[1], self.message.timestamp
answers question: http://stackoverflow.com/q/47168819
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/95355931
has text: Also, as of 01.2019, the comment from @rgaut does not seem to to work. You need to edit `~/.jupyter/jupyter_notebook_config.py` and set: `c.NotebookApp.kernel_spec_manager_class = 'nb_conda_kernels.CondaKernelSpecManager'`
comment on: http://stackoverflow.com/a/47262847
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/81370338
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47210225
has text: @juanpa.arrivillaga And what do you think is the complexity of loading pre-build tuple?
score: 0

http://stackoverflow.com/a/47152886
answers question: http://stackoverflow.com/q/47152776
type: Answer
has body: You have to specify the filename as well: import shutil with open("bhushan.txt", 'wb') as f: shutil.move(str(f.name), "/home/bhushanpant/") Hope this helps :)
score: 0

http://stackoverflow.com/q/47111159
downvote count: 2
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81173360
has comment: http://stackoverflow.com/comment/81172440
type: UnansweredQuestion
tagged with: hough-transform
tagged with: matplotlib
has body: I am trying to read a raw image file, but the stored image array seems to be one dimensional. Not sure how to read a raw file and plot it. Any help would be appreciated Link to image TestImage1c.raw from scipy import misc from scipy import ndimage import numpy as np import matplotlib.pyplot as plt import math A = np.fromfile("TestImage1c.raw", dtype='int16', sep="") print("A.shape: %d", A.shape) print("A: ", A) img_gray = np.dot(A[..., :3], [0.30, 0.59, 0.11]) print("img_gray :", img_gray) print("img_gray shape: ", img_gray.shape) print("img_gray size: ", img_gray.size) plt.imshow(img_gray, cmap="gray") plt.show() OUTPUT: D:\Python36\python.exe D:/PycharmProjects/First/readrawimage.py A.shape: %d (1143072,) A: [-27746 -24987 26514 ..., 28808 -31403 18031] img_gray : -20149.59 img_gray shape: () img_gray size: 1 Traceback (most recent call last): File "D:/PycharmProjects/First/readrawimage.py", line 33, in &lt;module&gt; plt.imshow(img_gray, cmap="gray") File "D:\Python36\lib\site-packages\matplotlib\pyplot.py", line 3080, in imshow **kwargs) File "D:\Python36\lib\site-packages\matplotlib\__init__.py", line 1710, in inner return func(ax, *args, **kwargs) File "D:\Python36\lib\site-packages\matplotlib\axes\_axes.py", line 5194, in imshow im.set_data(X) File "D:\Python36\lib\site-packages\matplotlib\image.py", line 604, in set_data raise TypeError("Invalid dimensions for image data") TypeError: Invalid dimensions for image data Process finished with exit code 1
tagged with: python
tagged with: computer-vision
has title: How to read raw image in Python and plot as an image
tagged with: numpy
has answer: http://stackoverflow.com/a/47114171
has comment: http://stackoverflow.com/comment/81173496
score: 1
upvote count: 3

http://stackoverflow.com/q/47077323
downvote count: 0
has answer: http://stackoverflow.com/a/47280258
accepted answer: http://stackoverflow.com/a/47280258
favorite count: 0
type: Question
tagged with: multicast
tagged with: ipv6
has answer: http://stackoverflow.com/a/68875470
linked to: http://stackoverflow.com/q/47280816
tagged with: python
linked to: http://stackoverflow.com/q/45285419
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/47119843
possible better answer: http://stackoverflow.com/a/47119843
linked to: http://stackoverflow.com/q/29913516
type: AnsweredQuestion
tagged with: udp
has body: I am trying to send IPv6 UDP packets to all of the nodes on the local network segment, in python, over Windows. I have several network interfaces in my computer, and I want to know how to specify the network interface for sending the packets. I have tried sending the packets to the multicast address ff02::1, using socket.sendto (without binding), but the packets are sent in the wrong network interface. Any idea how can I specify the network adapter? (I read about BINDTODEVICE, but it won't work on windows, and some methods using bind to broadcast IP address classes, but only for IPv4). Thanks!
answer count: 3
has title: Sending IPv6 multicast packets through a specific network interface

http://stackoverflow.com/comment/81157341
comment on: http://stackoverflow.com/a/47102526
type: Comment
score: 0
type: AnswerComment
has text: Just to confirm, what you are calling a set is the same thing as a tuple, right? Or is this a new type I haven't bumped into yet?

http://stackoverflow.com/q/47165320
score: 9
has answer: http://stackoverflow.com/a/71820942
answer count: 2
tagged with: pytest
downvote count: 0
tagged with: unit-testing
favorite count: 0
has title: factoryboy pytest session management
type: Question
has answer: http://stackoverflow.com/a/48471480
has body: I am using pytest as framework for testing my application and I want to use pytest factoryboy as well. Thusfar, my conftest.py looks pretty much like the example: import factory from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from model import model engine = create_engine('sqlite://') session = scoped_session(sessionmaker(bind=engine)) # Create tables model.Base.metadata.create_all(engine) class ExampleFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = model.ExampleClass sqlalchemy_session = session label = factory.Sequence(lambda n: u'object_%d' % n) I have multiple factories like this. The problem is that when I use factories in this manner, the session will not be torn down every unit test. I'm basically using one big session for the lot of unit tests that I have. Not very ideal. Using fixtures I could refresh a session every unit test. Is there a way to do this using factoryboy pytest?
upvote count: 9
tagged with: factory-boy
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/47116987
upvote count: 3
downvote count: 0
has body: So I have found an answer for myself if anyone out there is looking for the same solution. You can use pandas to_json and read_json to encode it into JSON and save in the database and then read it back to a variable. Here is an example: x = pd.DataFrame(np.random.rand(3, 2), columns=['foo', 'bar'], index=['a', 'b', 'c']) x = x.to_json() y = pd.read_json(x)
score: 3
type: Answer
answers question: http://stackoverflow.com/q/47116443

http://stackoverflow.com/comment/140060726
type: Comment
comment on: http://stackoverflow.com/a/47071257
has text: I been using pip for ages. and since day one I always wonder why they didnt follow the "normal" steps that most apps use. It does not make sense, to "install" since is installed. But "it is what it is" :D
type: AnswerComment
score: 1

http://stackoverflow.com/a/47119353
upvote count: 1
score: 1
has body: You can try this &gt;&gt;&gt; lst=[{'createdTime': '2017-11-05T06:43:08.000Z', 'fields': {'Pair ID': 14}, 'id': 'rec5Y5ML3w2nlKCYx'}, {'createdTime': '2017-11-05T06:43:08.000Z', 'fields': {'Pair ID': 12}, 'id': 'recB8ioXO0c8f9AHc'}, {'createdTime': '2017-11-05T07:26:51.915Z', 'fields': {'Pair ID': 17}, 'id': 'recCxg3XzjbQ1z5zh'}] &gt;&gt;&gt; [i.get('id') for i in lst] ['rec5Y5ML3w2nlKCYx', 'recB8ioXO0c8f9AHc', 'recCxg3XzjbQ1z5zh'] &gt;&gt;&gt;
type: Answer
answers question: http://stackoverflow.com/q/47119303
downvote count: 0

http://stackoverflow.com/comment/81182182
has text: This is nice, thank you. I'll leave the question open a little longer, and if nothing solving it specifically comes in, accept this answer. Feel free to remind me if I forget. (I've set a timer for a month out.)
score: 0
comment on: http://stackoverflow.com/a/47115189
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81246009
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47147768
type: Comment
has text: Look I appreciate your comments but the base code isn't mine. I wasn't here to optimise OP's code or point out mistakes. I just helped him with the problem he mentioned. If you want to point out things I haven't changed, pls do it on the question. And if you have so much to add please post an answer of your own. I am not explaining myself further to you. Thanks!

http://stackoverflow.com/q/47193509
has comment: http://stackoverflow.com/comment/81336506
has answer: http://stackoverflow.com/a/47193866
has title: occurrence of tuples in column duplicates
has comment: http://stackoverflow.com/comment/81336370
downvote count: 1
has answer: http://stackoverflow.com/a/47193959
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81336191
answer count: 2
upvote count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: -1
possible better answer: http://stackoverflow.com/a/47193959
accepted answer: http://stackoverflow.com/a/47193866
has comment: http://stackoverflow.com/comment/81336549
has body: This code, extracted from another question, works perfectly. It counts the occurrences of each row in a column and output a csv file. I would like it to not remove duplicates in my output file input file example are word tags WP,VBZ VBZ,PRP PRP,VB VB,PRP WP,VBZ VBZ,PRP . def filtrar(): files3= glob.glob('C:/Users/Sebastian/Desktop/aristas/*.csv') for path in files3: dirname, filename = os.path.split(path) with open('C:/Users/Sebastian/Desktop/aristas/%s' %filename) as csvfile: occurrence = Counter(tuple(row[0:2]) for row in csv.reader(csvfile)) with open('C:/Users/Sebastian/Desktop/aristasPeso/%s' %filename,'w',newline='') as output2: writer = csv.writer(output2) for (dest, src), cnt in occurrence.items(): writer.writerow([dest,src,cnt]) I want this output for example: WP,VBZ,2 VBZ,PRP,1 PRP,VB,1 VB,PRP,1 WP,VBZ,2 VBZ,PRP,2 not like WP,VBZ,2 VBZ,PRP,2 PRP,VB,1 VB,PRP,1
type: AnsweredQuestion

http://stackoverflow.com/comment/81350806
type: AnswerComment
has text: @ElvirMuslic Thank you. That is extremely helpful.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47196228

http://stackoverflow.com/comment/81378855
has text: I'm not sure what `in_str` contains - could you give us an example?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47214664

http://stackoverflow.com/comment/81193589
type: Comment
comment on: http://stackoverflow.com/q/47121997
has text: Did you try: `df = pd.DataFrame(d); df.plot(subplots=True, kind='bar'); plt.show()`?
type: QuestionComment
score: 0

http://stackoverflow.com/a/47091377
accepted answer of: http://stackoverflow.com/q/47091016
answers question: http://stackoverflow.com/q/47091016
type: Answer
has body: Your TEMPLATES settings should be like this: TEMPLATES = [ { #### 'DIRS': [os.path.join(BASE_DIR, 'templates')] #### } ] then your folder structure: templates index.html ...other html geoff settings.py urls.py //using this wsgi.py homepage migrations-&gt;folder _init_.py .....others here views.py
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81202775
comment on: http://stackoverflow.com/q/47126285
type: Comment
type: QuestionComment
score: 0
has text: Need `[]` like `close = pd.concat([close1,close2])` ?

http://stackoverflow.com/comment/101238184
has text: have a look at my comment of the above answer. any tip?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47217928
score: 0

http://stackoverflow.com/q/47147283
has answer: http://stackoverflow.com/a/47147483
upvote count: 0
downvote count: 2
has title: How can I use a class' variables in another class?
has comment: http://stackoverflow.com/comment/81245151
has comment: http://stackoverflow.com/comment/81245080
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I have a Drone class and a Building class. The Building class has two attributes named x0 and y0. I want to use these two variables' values in the Drone class, but I haven't been able to wrap my head around how that would be done. Here's the code for Building: class Building(Agent): def __init__(self, pos, x0, y0, model, request=False): # Buildings won't have requests initially (set to false) super().__init__(pos, model) self.pos = pos self.x0 = x0 self.y0 = y0 self.model = model self.request = request And Drone: class Drone(Agent): grid = None x = None y = None moore = True def __init__(self, name, model, x, y, speed, battery, heading, moore=True): super().__init__(name, model) self.name = name self.model = model self.x = x self.y = y self.speed = speed self.battery = battery self.heading = heading self.moore = moore def step(self): if self.name == 1: if self.x &lt; Building.x0: self.x += 1 new_pos = self.x, self.y self.model.grid.move_agent(self, new_pos) elif self.x &gt; Building.x0: self.x -= 1 new_pos = self.x, self.y self.model.grid.move_agent(self, new_pos) if self.y &lt; Building.y0: self.y += 1 new_pos = self.x, self.y self.model.grid.move_agent(self, new_pos) elif self.y &gt; Building.y0: self.y -= 1 new_pos = self.x, self.y self.model.grid.move_agent(self, new_pos)
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/47147926
has comment: http://stackoverflow.com/comment/81244959
answer count: 2

http://stackoverflow.com/comment/104650359
score: 7
type: Comment
type: QuestionComment
has text: Using `@lru_cache` without parentheses works starting with Python 3.8.
comment on: http://stackoverflow.com/q/47218313

http://stackoverflow.com/a/47219490
type: Answer
has comment: http://stackoverflow.com/comment/81388349
has comment: http://stackoverflow.com/comment/81388623
has comment: http://stackoverflow.com/comment/81388472
score: 1
has comment: http://stackoverflow.com/comment/81388663
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81388524
has body: As I mentioned in my comment I don't see a reason for the way you are subclassing. So I put it together as one class Student like this: class Student: # Method def __init__(self): self.name = input("Name: ") self.age = int(input("Age: ")) self.gender = input("Gender: ") def setMarks(self): self.stuClass = input("YearGroup/Class: ") print("Enter the marks of the respective subjects") self.literature = int(input("Literature: ")) self.math = int(input("Math: ")) self.biology = int(input("Biology: ")) self.physics = int(input("Physics: ")) self.totalmarks=self.literature+self.math+self.biology+self.physics def display(self): print("\n\nName: ",self.name) print("Age: ",self.age) print("Gender: ",self.gender) print("Class Year Group: ",self.stuClass) self.totalmarks=self.literature+self.math+self.biology+self.physics print("Total Marks: ", self.literature + self.math + self.biology + self.physics) def eligible_for_reward(self): if self.totalmarks&gt;=90 and self.age&gt;13: print("You are eligible for the fabulous school sponsored trip to London") else: print("Sorry, you are not eligible and so are going nowhere....!") Example usage: s1 = Student() &gt;&gt;&gt; Name: Hans &gt;&gt;&gt; Age: 17 &gt;&gt;&gt; Gender: m s1.setMarks() &gt;&gt;&gt; YearGroup/Class: 2017 &gt;&gt;&gt; Enter the marks of the respective subjects &gt;&gt;&gt; Literature: 11 &gt;&gt;&gt; Math: 14 &gt;&gt;&gt; Biology: 42 &gt;&gt;&gt; Physics: 10 s1.display() &gt;&gt;&gt; Name: Hans &gt;&gt;&gt; Age: 17 &gt;&gt;&gt; Gender: m &gt;&gt;&gt; Class Year Group: 2017 &gt;&gt;&gt; Total Marks: 77 s1.eligible_for_reward() &gt;&gt;&gt; Sorry, you are not eligible and so are going nowhere....!
answers question: http://stackoverflow.com/q/47218970

http://stackoverflow.com/q/47106291
favorite count: 0
has answer: http://stackoverflow.com/a/47106411
has comment: http://stackoverflow.com/comment/81163457
tagged with: turtle-graphics
type: Question
upvote count: 2
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81163360
tagged with: python
has comment: http://stackoverflow.com/comment/81163377
has title: I'm messing around with the turtle import in python 2.7 with loops and the turtle won't move
has body: I'm messing around with the turtle import in python 2.7 with loops and I just see the screen flash and the program exits. Here is my code: import turtle colors = ["red", "orange", "yellow", "green", "blue", "purple"] dColors = dict(enumerate(colors)) def circleOfShapes(aTurtle): edges = 3 radius = 100 for i in range(5): for k in range(360 / 5): aTurtle.color(dColors.get(i)) aTurtle.circle(radius, None, edges) aTurtle.right(5) edges += 1 radius -= 10 turt = turtle.Turtle() turt.shape("arrow") window = turtle.Screen() window.bgcolor("white") window.exitonclick() circleOfShapes(turt) This is just me trying to make something cool for my kid and get him interested in programming at an early age like I wish I would have. Thanks for the help.
tagged with: python-2.7
score: 2
has comment: http://stackoverflow.com/comment/81163478
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81163372
accepted answer: http://stackoverflow.com/a/47106474
has comment: http://stackoverflow.com/comment/81163472
has answer: http://stackoverflow.com/a/47106474
possible better answer: http://stackoverflow.com/a/47106411

http://stackoverflow.com/comment/81108480
type: AnswerComment
comment on: http://stackoverflow.com/a/47078344
has text: I think you can probably work that out yourself -- check the docs for pandas.Series. You can for instance convert the row to a normal dict, like rowDict = row.to_dict() and have full control over how you choose to save this to your file. See https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_dict.html
type: Comment
score: 0

http://stackoverflow.com/a/47208651
has body: In the first step, you replace all a with b: "aba" -&gt; "bbb" and then replace b with ab: "bbb" -&gt; "ababab" If you want to replace character by charater you have to loop over script: SRS = { 'a':'b', 'b':'ab'} script = "aba" result = "" for ch in script: result += SRS[ch] print(result)
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/47208509
downvote count: 0

http://stackoverflow.com/comment/81136414
type: Comment
type: QuestionComment
has text: Basically they allevents must have tracked your scrapper and as a preventive measure they might have blocked ip address of your source system. There is nothing wrong at your end its allevents service which has disabled your spider. You can change your IP and check if it possible for you.
comment on: http://stackoverflow.com/q/47093405
score: 0

http://stackoverflow.com/q/47166451
tagged with: python
has comment: http://stackoverflow.com/comment/81286973
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81286494
tagged with: graph-traversal
has body: Trying to do a very quick connected components algorithm of a graph by taking each vertex, traversing it, then skipping to the next vertex that hasn't already been assigned to a component. graph This is the graph. The output I currently get is: [1, 1, 1, 1, 1, 0, 3, 3, 3, 3, 4, 4, 4] Which shows mostly correct output except that neither v1 or v4 correctly call v5 to assign it a group, so it's recognized as it's own group. Not sure why this is the case. adjacency_matrix = [[0,0,1,0,1,0,0,0,0,0,0,0,0], [0,0,1,1,0,1,0,0,0,0,0,0,0], [1,1,0,1,0,0,0,0,0,0,0,0,0], [0,1,1,0,0,0,0,0,0,0,0,0,0], [1,0,0,0,0,1,0,0,0,0,0,0,0], [0,1,0,0,1,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,1,0,0,0,0,0,0], [0,0,0,0,0,0,1,0,0,0,0,0,0], [0,0,0,0,0,0,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,1,1], [0,0,0,0,0,0,0,0,0,0,1,0,1], [0,0,0,0,0,0,0,0,0,0,1,1,0]] def Connected_Component(graph): # Number of vertices = Number of rows in matrix vertices = graph.__len__() # Array of zeroes to hold vertex component values components = [0] * vertices # Component groups start at 1, so 0 means unassigned current_component = 1 # Search all vertices connected def traverse(vertex): # For each edge of this vertex for edge in range(0,vertex.__len__()): if vertex[edge] == 1: # Base case: If the vertex corresponding to the edge has already been visited &amp; assigned a component if components[edge] &gt; 0: print "Base case on " + str(edge) + " current component " + str(current_component) return # Otherwise, recursively search each connected vertex else: components[edge] = current_component print "recursively traversing " + str(edge)+ " current component " + str(current_component) traverse(graph[edge]) for vertex in range(0,vertices): # If the component of the current vertex has already been assigned, skip this iteration if components[vertex] &gt; 0: print "skipping " + str(vertex) continue else: # Traverse this vertex print "traversing " + str(vertex)+ " current component " + str(current_component) tra…
type: Question
tagged with: graph-theory
has title: Connected components via recursive traversal missing one node [python]
type: UnansweredQuestion
tagged with: connected-components

http://stackoverflow.com/comment/81317956
comment on: http://stackoverflow.com/q/47184192
score: 0
type: Comment
type: QuestionComment
has text: not really, I want to know if there;s another way to get instance's name with "get the name of " from john, john.dog, john.cat without using @property or do not write the same property twice

http://stackoverflow.com/comment/81129698
has text: Ok, I get your point. Probably class design is ok, I should just improve unit tests. Thanks!
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47076218
type: Comment

data-analysis
tags question: http://stackoverflow.com/q/47111218
tags question: http://stackoverflow.com/q/47095122
tags question: http://stackoverflow.com/q/47073066
type: Tag
tags question: http://stackoverflow.com/q/47131193
tags question: http://stackoverflow.com/q/47148989
tags question: http://stackoverflow.com/q/47112161
tags question: http://stackoverflow.com/q/47096797
tag name: data-analysis

http://stackoverflow.com/q/47073384
answer count: 0
tagged with: cron
has comment: http://stackoverflow.com/comment/81103452
has comment: http://stackoverflow.com/comment/81097380
tagged with: unix
tagged with: daemon
type: Question
has body: I'm running python script at boot on background using crontab. Therefore, the terminal won't show up on boot and my printing messages doesn't appear to the user. How can I open up the terminal window at certain point of my program and print output from there? (also getting input from user) Thanks in advance!
tagged with: terminal
has title: Show output messages from background python script starting at boot
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81103043
has comment: http://stackoverflow.com/comment/81103730
has comment: http://stackoverflow.com/comment/81103417
score: 0

http://stackoverflow.com/comment/81361744
has text: Is there anything in [the Gallery](https://matplotlib.org/gallery.html) that looks like what you want?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47205918
type: QuestionComment

http://stackoverflow.com/comment/81127012
comment on: http://stackoverflow.com/q/47079936
has text: Good luck btw. Google shouldn't contain any Jenkins instances because of their `robots.txt`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81848645
comment on: http://stackoverflow.com/a/47197435
has text: @IlyaPukhov Please check my Update Answer 2 . I share my working steps with you. Please follow my steps and try again.
type: Comment
score: 0
type: AnswerComment

permissions
tag name: permissions
tags question: http://stackoverflow.com/q/47083929
type: Tag
tags question: http://stackoverflow.com/q/47130234

http://stackoverflow.com/q/47191296
tagged with: while-loop
type: Question
accepted answer: http://stackoverflow.com/a/47191863
has comment: http://stackoverflow.com/comment/81332087
has comment: http://stackoverflow.com/comment/81332132
has answer: http://stackoverflow.com/a/47191863
tagged with: loops
score: 1
has comment: http://stackoverflow.com/comment/81332032
has comment: http://stackoverflow.com/comment/81332022
has comment: http://stackoverflow.com/comment/81331998
has comment: http://stackoverflow.com/comment/81332147
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81332056
type: AnsweredQuestion
tagged with: function
downvote count: 0
has body: def tim(): cash = 100 while cash != 0: print("while loop:",cash) john(cash) def john(cash): print("john func:",cash) cash = cash -1 tim() Can someone explain why john() does not reduce the value of cash? I've been struggling with this for quite long.
has title: Altering variable's value in a function by calling another function as a subfunction
upvote count: 1
tagged with: python
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/81138825
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47087550
has text: Thanks for the reply. Unfortunately, the code is giving me an error. The error is as follows "AttributeError: 'list' object has no attribute 'stack'".
type: Comment

http://stackoverflow.com/a/47075167
has comment: http://stackoverflow.com/comment/81156187
has comment: http://stackoverflow.com/comment/81151554
has comment: http://stackoverflow.com/comment/81124141
has body: scikit-learn has default regularized logistic regression. The change in intercept_scaling parameter value in sklearn.linear_model.LogisticRegression has similar effect on the result if only C parameter is changed. In case of modification in intercept_scaling parameter, regularization has an impact on the estimation of bias in logistic regression. When this parameter's value is on higher side then the regularization impact on bias is reduced. Per official documentation: The intercept becomes intercept_scaling * synthetic_feature_weight. Note! the synthetic feature weight is subject to l1/l2 regularization as all other features. To lessen the effect of regularization on synthetic feature weight (and therefore on the intercept) intercept_scaling has to be increased. Hope it helps!
upvote count: 2
answers question: http://stackoverflow.com/q/47067906
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47067906
score: 2
has comment: http://stackoverflow.com/comment/139756712
type: AcceptedAnswer

http://stackoverflow.com/comment/81324950
has text: @kindall. Thanks. I can get the names by using `__slots__`. How can I get the values?
type: Comment
comment on: http://stackoverflow.com/q/47187707
type: QuestionComment
score: 0

http://stackoverflow.com/a/47199135
type: Answer
accepted answer of: http://stackoverflow.com/q/47198948
score: 39
answers question: http://stackoverflow.com/q/47198948
upvote count: 39
has comment: http://stackoverflow.com/comment/138600694
downvote count: 0
has comment: http://stackoverflow.com/comment/136463948
type: AcceptedAnswer
has body: If all you are looking for is an in-memory file-like object, I would be looking at from io import BytesIO file_like = BytesIO(b'this is a sample bytearray') print(file_like.read())

http://stackoverflow.com/comment/81162463
type: QuestionComment
has text: Sisyphus comes to mind when reading this...
comment on: http://stackoverflow.com/q/47105893
score: 0
type: Comment

sensors
type: Tag
tags question: http://stackoverflow.com/q/47103077
tag name: sensors

http://stackoverflow.com/a/47103526
has comment: http://stackoverflow.com/comment/81157613
downvote count: 1
has comment: http://stackoverflow.com/comment/81157433
type: Answer
has body: You have only one item in the values list for the print -- a list. You need to split out the individual integers. def print_board(turn, board): print(turn + " turn" + "\n {}{}{}\n {}{}{}\n {}{}{}".format( board[0], board[1], board[2], board[3], board[4], board[5], board[6], board[7], board[8] ))
score: 0
answers question: http://stackoverflow.com/q/47103483
upvote count: 1

http://stackoverflow.com/a/47123198
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81218507
has body: Please refer to the following explanations, solutions, and example for details. Button - Border Border information is in the format (bottom, right, top, left). Each value is in pixels. The border defaults to (16, 16, 16, 16). Use the following in kv File: Menu - Right Border On border: (0, 16, 0, 0) Sub-menu - All Border Off border: (0, 0, 0, 0) Dropdown Width By default, the width of the dropdown will be the same as the width of the attached widget. Set auto-width to False if you want to provide your own width. Use the following in kv File. Increase Dropdown Width auto-width: False width: 150 Text Alignment - Button/Label By default the text image (texture) is only just large enough to contain the characters and is positioned in the center. The valign property will have no effect and halign will only have an effect if your text has newlines; a single line of text will appear to be centered even though halign is set to left (by default). In order for the alignment properties to take effect, set the text_size, which specifies the size of the bounding box within which text is aligned. For instance, the following code binds this size to the size of the Button/Label, so text will be aligned within the widget bounds. This will also automatically wrap the text of the Button/Label to remain within this area. The padding_x is horizontal padding of the text inside the widget box. It defaults to 0. The following code has a value of 5 so that the text is not close to the right border. Left Alignment text_size: self.size valign: "middle" padding_x: 5 Image - Decrease Space AsyncImage means load an image asynchronously. It prevents your application from waiting until the image is loaded. If you want to display large images or retrieve them from URL’s, using AsyncImage will allow these resources to be retrieved on a background thread without blocking your application. For example, if you want your image to be close to the image before it, you could do the following: AsyncImage: c…
type: Answer
answers question: http://stackoverflow.com/q/47112878

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/47164849
tags question: http://stackoverflow.com/q/47178861
tags question: http://stackoverflow.com/q/47152691
tags question: http://stackoverflow.com/q/47086896
tags question: http://stackoverflow.com/q/47154743
type: Tag

http://stackoverflow.com/comment/81203264
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47089796
has text: It should be? I don't see that part in your code. Did You even tried to debug the code?
type: AnswerComment

http://stackoverflow.com/comment/81204358
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47126885
type: Comment
has text: @PrabhatDoongarwal Is it possible you have some `.pyc` files around in the directory, and you're actually executing an earlier version of the script? Alternatively, is it possible that the `(Episode, '0')` output is coming from either `env.action_space.sample()` or `env.step(action)`?

http://stackoverflow.com/a/47102430
upvote count: 1
has body: Use parameters! In Python, this looks like cur.execute(""" SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME LIKE ?""", (tableName)) Some databases may prefer %s rather than ?.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47102382
has comment: http://stackoverflow.com/comment/81155527
downvote count: 0

http://stackoverflow.com/comment/81084461
has text: @omijn Oh, stupid me :D I didn't notice it :)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47068199
type: QuestionComment

http://stackoverflow.com/comment/81108027
type: AnswerComment
score: 0
type: Comment
has text: Took the words out of my mouth :)
comment on: http://stackoverflow.com/a/47079120

http://stackoverflow.com/a/52006664
has comment: http://stackoverflow.com/comment/93672319
has comment: http://stackoverflow.com/comment/103669491
has body: Install arrow using: pip install arrow==0.12.0 fixed this issue for me
downvote count: 0
score: 20
answers question: http://stackoverflow.com/q/47179433
upvote count: 20
type: Answer

http://stackoverflow.com/a/47208090
type: Answer
answers question: http://stackoverflow.com/q/47187841
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47187841
type: AcceptedAnswer
score: 1
has body: So this seems to do the trick: from sympy import Sum, symbols, Indexed, lambdify from scipy.optimize import minimize import numpy as np def _eqn(y, variables, periods, sign=-1.0): x, i = symbols("x i") n = periods-1 s = Sum(Indexed('x', i)/(1+0.06)**i, (i, 0, n)) f = lambdify(x, s, modules=['sympy']) return float(sign*(y + f(variables))) z = 3 results = minimize(lambda x: _eqn(3, x, z),np.zeros(z)) print(results.x) Any further suggestions?
downvote count: 0

http://stackoverflow.com/comment/81387979
has text: 365 days* typo sorry
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47213385
score: 0

http://stackoverflow.com/comment/81393289
type: QuestionComment
has text: I can't reproduce your result. Using a dummy calculate_cross_rate function returning a random number, for me it works as expected.
comment on: http://stackoverflow.com/q/47221555
score: 0
type: Comment

http://stackoverflow.com/q/47104869
downvote count: 0
has body: I was not sure how to deal with a two dimensional array [stock returns] that has some missing values. I want to get geometric mean for each row [ average return for each month]. I got missing values for geometric mean for those months that I have missing values. One way is to filling the missing values with something like 1 or mean but I don't want to mess with the mean. Any advice how to calculate the gmean for each date just based on the not-missing values?
answer count: 1
tagged with: missing-data
tagged with: geometric-mean
has title: Scipy gmean with missing values
tagged with: statistics
type: AnsweredQuestion
upvote count: 1
score: 1
tagged with: python
tagged with: scipy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47105800
accepted answer: http://stackoverflow.com/a/47105800

http://stackoverflow.com/comment/124468226
comment on: http://stackoverflow.com/a/53869812
type: AnswerComment
score: 2
type: Comment
has text: side note: dropna parameter was introduced July, 2021

http://stackoverflow.com/a/47125435
answers question: http://stackoverflow.com/q/47125056
accepted answer of: http://stackoverflow.com/q/47125056
type: Answer
has comment: http://stackoverflow.com/comment/81201756
score: 0
has body: time.sleep() is a task that blocks the PyQt loop so it is not recommended to use it, the task can easily be substituted with a QTimer. To facilitate the work we will create a class that inherits from QLCDNumber and that uses a QTimer to update the values TimerLCDNumber.py from PyQt5 import QtCore, QtGui, QtWidgets class TimerLCDNumber(QtWidgets.QLCDNumber): def __init__(self, *args, **kwargs): QtWidgets.QLCDNumber.__init__(self, *args, **kwargs) self.timer = QtCore.QTimer(self) self.timer.setInterval(1000) self.timer.timeout.connect(self.onTimeout) self.finished = self.value() def setValue(self, value): self.finished = value self.timer.start() def onTimeout(self): current = self.value() if self.finished != current: count = 1 if self.finished &gt; current else -1 self.display(current + count) else: self.timer.stop() This task can be promoted through Qt Designer or simply change, assuming that the file generated by Qt Designer is called design.py: design.py self.lcdNumber = QtWidgets.QLCDNumber(self.centralwidget) self.lcdNumber_2 = QtWidgets.QLCDNumber(self.centralwidget) to: self.lcdNumber = TimerLCDNumber(self.centralwidget) self.lcdNumber_2 = TimerLCDNumber(self.centralwidget) In addition, the TimerLCDNumber class must be imported: from TimerLCDNumber import TimerLCDNumber It is advisable to separate the design from the logic so a new file called main.py is created that imports the design class and implements the logic: main.py from PyQt5 import QtCore, QtGui, QtWidgets from design import Ui_MainWindow class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self, *args, **kwargs): QtWidgets.QMainWindow.__init__(self, *args, **kwargs) self.setupUi(self) self.lineEdit.returnPressed.connect(lambda: self.lcdNumber.setValue(int(self.lineEdit.text()))) self.lineEdit_2.returnPressed.connect(lambda: self.lcdNumber_2.setValue(int(self.lineEdit_2.text()))) self.lcdNumber.display(0) self.lcdNumber_2.display(0) if __name__ == "__main__": import sys app = QtWidget…
has comment: http://stackoverflow.com/comment/81201863
type: AcceptedAnswer

http://stackoverflow.com/a/47209821
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47209734
score: 1
type: Answer
has body: If you want it to output anything you'll need to ask for input, and I would suggest not doing the while loop, you can look for a string in a list as follows: capital = ["London","New Dehli","Jerusalem","Paris","Washington DC","Riyadh","Kaula Lumpur"] user_search = input("Which capital do you wish to search for \n - ") if user_search in capital: print ("found it")

http://stackoverflow.com/comment/81122942
has text: Also, it seems like these are commands for the Phison chip that are being written with SCSI commands.
comment on: http://stackoverflow.com/q/47086505
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/47152660
type: Question
has comment: http://stackoverflow.com/comment/81254754
answer count: 0
has comment: http://stackoverflow.com/comment/81254808
type: UnansweredQuestion
tagged with: python
tagged with: delimiter
has title: Python delimiter in the sentence
linked to: http://stackoverflow.com/q/21527057
tagged with: http://stackoverflow.com/tag/csv
score: 0
has body: I have the following code: with open('comment.csv') as csvfile: readCSV = csv.DictReader(csvfile, delimiter=',') for row in readCSV: What will happen is that: it will use "," for parsing the csv. But everything will be screwed if there are extra "," in a column named "content". Is there a smart way to omit the "," in the column for normal parsing? Thanks,
duplicate of: http://stackoverflow.com/q/21527057

http://stackoverflow.com/comment/81194954
comment on: http://stackoverflow.com/q/47122613
score: 0
has text: Can you post an example of a data set (`name_list`) that you want use for searching? Also please post your desired data set
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47141693
upvote count: 7
has body: You can alter self.fields['email'] in the __init__ method. You need to call super() first. class RegisterMyBuisinessForm(forms.ModelForm): def __init__(self, *args, **kwargs): ... super(RegisterMyBuisinessForm, self).__init__(*args, **kwargs) self.fields['email'].required = True ...
score: 7
type: Answer
answers question: http://stackoverflow.com/q/47140951
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47140951

http://stackoverflow.com/a/47090150
score: 1
upvote count: 1
type: Answer
has body: Plugins in Sublime are essentially global in that they are only loaded once (generally, see below). As such there isn't a new copy loaded for each window that is created. In particular, Sublime loads plugins: When it initially starts When they first appear inside of a package (for newly added plugins) When the source file that they're in is changed on disk When the package that they're stored in is removed from the ignored_packages setting, making the package active once again. Similarly, plugins are only unloaded: When Sublime is about to re-load it because it changed on disk When the package that they're stored in is added to the ignored_packages setting, making the package no longer active That said, there is no foolproof way to detect when a window is actually closed, although depending on the reason you want to know that the window is being closed, there may be a work-around that works "good enough". One method is to use an EventListener to detect when the close_window command is either just about to be executed or has just finished executing. Problems with this method are that the command doesn't get executed if you use the window chrome to close the window, so you can only detect the window closing this way if the user uses the key binding or menu entry to close the window. Also the command is always fully executed even if the window doesn't actually close (i.e. if there is an unsaved file and you cancel) and it finishes executing while the window still exists, requiring you to wait a little bit before checking to see if the window still exists or not: import sublime import sublime_plugin class WindowCloseListener(sublime_plugin.EventListener): def check_closed(self, w_id): for window in sublime.windows(): if window.id() == w_id: return print("Window %d cancelled close" % w_id) print("Window %d has closed" % w_id) def on_window_command(self, window, cmd, args): if cmd == "close_window": print("window with id %d is about to close" % window.id()) def on_post_wi…
answers question: http://stackoverflow.com/q/47075691
downvote count: 0

http://stackoverflow.com/q/47215825
has answer: http://stackoverflow.com/a/47339150
downvote count: 0
tagged with: parameterized-tests
has answer: http://stackoverflow.com/a/47264590
has body: Basically, I realize that I am writing the same test case (test_update_with_only_1_field) for a similar URL for multiple models from django.test import RequestFactory, TestCase class BaseApiTest(TestCase): def setUp(self): superuser = User.objects.create_superuser('test', 'test@api.com', 'testpassword') self.factory = RequestFactory() self.user = superuser self.client.login(username=superuser.username, password='testpassword') class SomeModelApiTests(base_tests.BaseApiTest): def test_update_with_only_1_field(self): """ Tests for update only 1 field GIVEN the following shape and related are valid WHEN we update only with just 1 field THEN we expect the update to be successful """ shape_data = { 'name': 'test shape', 'name_en': 'test shape en', 'name_zh_hans': 'test shape zh hans', 'serial_number': 'test shape serial number', 'model_name': { 'some_field': '123' } } data = json.dumps(shape_data) response = self.client.post(reverse('shape-list-create'), data, 'application/json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) some_model = response.data['some_model'] new_some_field = '12345' data = json.dumps({'some_field': new_some_field, 'id': response.data['some_model']['id']}) response = self.client.put(reverse('some-model', args=[some_model['id']]), data, 'application/json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(new_some_field, response.data['some_field']) I need to do this for more than 10 times. Which I have already done so. the only difference each time, is the following phrases "some_model", "some-model", and "some_field" I was wondering if there's a faster way to do this. I can think abstractly two ways: create a template in a text editor that somehow can generate the final test case which I then copy and paste. I am using sublime text 3 though I am okay to switch to another text editor There's a way I can write slightly more code in the form of converting this test case into a behavior class that the indivi…
tagged with: django
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47270191
type: UnansweredQuestion
has title: is there a faster way to write similar test cases for Django views?
tagged with: python-unittest
tagged with: python
has answer: http://stackoverflow.com/a/47278450
upvote count: 4
score: 4
answer count: 4

http://stackoverflow.com/a/49256710
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/104265623
downvote count: 0
answers question: http://stackoverflow.com/q/47166191
accepted answer of: http://stackoverflow.com/q/47166191
type: Answer
has comment: http://stackoverflow.com/comment/85563321
score: 4
upvote count: 4
has body: Different results between 1 and 2 Since you haven't shown your code, I (maybe wrongly) suggest that the problem is that you might not have used preprocess_input when declaring ImageDataGenerator ? from keras.applications.inception_v3 import preprocess_input train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input) Make sure, though, that your saved image files range from 0 to 255. (Bit depth 24). Different shapes between 1 and 3 There are three possible types of model in this case: include_top = True -&gt; this will return classes include_top = False (only) -&gt; this implies in pooling = None (no final pooling layer) include_top = False, pooling='avg' or ='max' -&gt; has a pooling layer So, your declared model without an explicit pooling=something doesn't have the final pooling layer in keras. Then the outputs will still have the spatial dimensions. Solve that simply by adding a pooling at the end. One of these: pretrained_model = InceptionV3(include_top=False, pooling = 'avg', weights='imagenet', input_shape=(img_width, img_height, 3)) pretrained_model = InceptionV3(include_top=False, pooling = 'max', weights='imagenet', input_shape=(img_width, img_height, 3)) Not sure which one the model in the tgz file is using. As an alternative, you can also get another layer from the Tensorflow model, the one coming immediately before 'pool_3'.

http://stackoverflow.com/a/49363714
has body: Try to replace index = gensim.similarities.MatrixSimilarity(gensim.matutils.Dense2Corpus(model.wv.syn0)) to index = gensim.similarities.MatrixSimilarity(gensim.matutils.Dense2Corpus(model.wv.syn0.T))
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/47157286
type: Answer
score: 4

http://stackoverflow.com/a/47188208
type: Answer
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81326067
answers question: http://stackoverflow.com/q/47187819
has body: Well this is exactly what you told Python to do here: d[filename] = {location:{date: caption}} so replace it by this: d[filename] = [location,date,caption]

http://stackoverflow.com/a/47222494
accepted answer of: http://stackoverflow.com/q/47219325
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Is this what you wanted? Whether you use xpath or css selector, the result is always the same. Give this a shot: html_content=''' Ball Lightning *Foil* ''' from lxml.html import fromstring root = fromstring(html_content) item = root.cssselect(".cardname a")[0].text_content().strip() item_alternative = root.xpath("//*[@class='cardname']/a")[0].text_content().strip() print(item) print(item_alternative) Result: Ball Lightning *Foil* Ball Lightning *Foil*
type: Answer
answers question: http://stackoverflow.com/q/47219325
score: 1

http://stackoverflow.com/q/47164436
has comment: http://stackoverflow.com/comment/81279075
has comment: http://stackoverflow.com/comment/81279139
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81278706
answer count: 3
has body: I have a text file with the following entries: G1 X-387.7 A3=-1.0 B3=0.0 C3=0.0 F=R3 Y1.824 Z264.663 A3=-1.0 C3=0.0 I extracted the numbers(numerical equivalents) of the variable alphabets using the code import re with open('input file.txt','r') as file: for line in file: print re.findall("(?&lt;=[AZaz])?(?!\d*=)[0-9.+-]+",line) I got the results as follows: ['-387.7', '-1.0', '0.0', '0.0', '3'] ['1.824', '264.663', '-1.0', '0.0'] But I need only the values corresponding to x,y,z,a3,b3,c3. All other variables should be neglected. How to selectively remove other variables and substitute 0 in the plac of missing variable(x,y,z,a3,b3,c3)?
has answer: http://stackoverflow.com/a/47164984
score: 1
downvote count: 0
tagged with: string-parsing
has answer: http://stackoverflow.com/a/47165683
accepted answer: http://stackoverflow.com/a/47164899
has title: Substitute zero for missing values in python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47164899
has comment: http://stackoverflow.com/comment/81280474
possible better answer: http://stackoverflow.com/a/47164984
has comment: http://stackoverflow.com/comment/81279293
has comment: http://stackoverflow.com/comment/81278724
has comment: http://stackoverflow.com/comment/81279216
has comment: http://stackoverflow.com/comment/81280025
upvote count: 1
tagged with: python
tagged with: regex

grako
tags question: http://stackoverflow.com/q/47111525
tag name: grako
type: Tag

http://stackoverflow.com/q/47082636
type: Question
has comment: http://stackoverflow.com/comment/81121593
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47082910
has body: I am facing some issues while implementing multi-threading in python. The issue is very specific to my use case. Having gone through numerous posts on the same, I deployed the most widely suggested/used method for doing so. I start by defining my thread class as follows. class myThread(Thread): def __init__(self, graphobj, q): Thread.__init__(self) self.graphobj = graphobj self.q = q def run(self): improcess(self.graphobj, self.q) Post which I define my function that does all the processing required. def improcess(graphobj, q): while not exitFlag: queueLock.acquire() if not q.empty(): photo_id = q.get() queueLock.release() # Complete processing else: queueLock.release() Now comes the part where I am stuck. I am able to run the below mentioned code exactly as it is without any issues. However if I try and wrap the same in a function as such it breaks down. def train_control(graphobj, photo_ids): workQueue = Queue(len(photo_ids)) for i in range(1,5): thread = myThread(graphobj=graphobj, q=workQueue) thread.start() threads.append(thread) queueLock.acquire() for photo_id in photo_ids: workQueue.put(photo_id) queueLock.release() while not workQueue.empty(): pass exitFlag = 1 for t in threads: t.join() By breaking down I mean that the threads complete their work but they don't stop waiting i.e. the exitFlag is never set to 1. I am unsure as to how to make this work. Unfortunately the design of our systems is such that this piece of codes needs to be wrapped in a function which can be invoked by another module, so pulling it out is not really an option. Looking forward to hearing from experts on this. Thanks in advance. Edit : Forgot to mention this in the first draft. I globally initialize exitFlag and set its value to 0. Below is the minimum, verifiable code snippet that I created to capture this problem: import threading import Queue globvar01 = 5 globvar02 = 7 exitFlag = 0 globlist = [] threads = [] queueLock = threading.Lock() workQueue = Queue.Queue(16) class myThrea…
tagged with: python
has title: Multi-threading in Python
tagged with: queue
score: 2
upvote count: 2
tagged with: python-2.7
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47100131
has comment: http://stackoverflow.com/comment/81114899
tagged with: multithreading
has comment: http://stackoverflow.com/comment/81137352
favorite count: 0
tagged with: multiprocessing

http://stackoverflow.com/comment/81331637
type: Comment
comment on: http://stackoverflow.com/a/47190931
score: 0
type: AnswerComment
has text: @helpmeplz no problem, if you understood what I've done, the job is done, if you want more explain to the answer I can answer more doubts and question you have, let me know

http://stackoverflow.com/comment/81244416
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47147012
has text: @PeterGibson: I want a Python service running constantly, but the option to stop or restart it. Does this still require a daemon?
score: 0

http://stackoverflow.com/q/47129901
tagged with: python
has body: I am trying to filter out a subset of data in the following code. I want to filter those columns with FG='Y' if there is only one element in that group. Also, between those groups that have both combinations of 'N' and 'Y' in FG column, I will choose it if and only if the FG='Y' is submitted after 60 days of FG='N'. from datetime import timedelta import datetime as dt from dateutil.parser import parse import pandas as pd import numpy as np data={'Name':['A','A','A','B','B','B','C','D','D','D','E','E','E','F','G','G','G','H','H','H'],'FG':['Y','Y','Y','N','N','Y','Y','Y','Y','Y','Y','N','N','N','Y','N','N','Y','Y','N'], 'Program': ['Eval','Eval','Eval','IB','Eval','IB','PO','PO','Info','IB','Info','Info','Info','Ted', 'Info','Ted','Ted','PO','PO','PO'], 'Date':['2016/10/01','2017/10/01','2016/11/11','2017/10/01','2016/10/01','2017/10/02','2017/10/01','2017/10/01','2017/06/03', '2017/10/01','2017/10/21','2017/10/21','2017/08/01','2017/10/10', '2017/10/21','2017/08/01','2017/10/10', '2017/04/01','2017/01/30','2017/01/01']} df=pd.DataFrame(data=data,columns=['Name','FG','Program', 'Date']) df['Date']=pd.to_datetime(df['Date']).dt.date df=df.sort_values('Date', ascending=True).drop_duplicates(subset=['Name', 'FG','Program'], keep='last') df['check']=df.groupby(['Name', 'Program']).Date.transform('min') df['check']=df['check']+timedelta(60) mask=df.groupby(['Name','Program']).apply(lambda x : ((x.FG=='Y') &amp; (x.Date&gt;= x.check)) if len(x.Date)&gt;1 else x.FG=='Y')).values X=df[mask] The expected output should be Name FG Program Date A Y Eval 2017-10-01 C Y PO 2017-10-01 D Y Info 2017-06-03 D Y PO 2017-10-01 D Y IB 2017-10-01 G Y Info 2017-10-21 H Y PO 2017-04-01 It seems like my filter in the mask variable does not work. Also, any suggestion to compare the date for FG='N' to the FG='Y' would be greatly appreciated
type: Question
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/47130343
accepted answer: http://stackoverflow.com/a/47130343
possible better answer: http://stackoverflow.com/a/47130068
favorite count: 0
has answer: http://stackoverflow.com/a/47130068
type: AnsweredQuestion
downvote count: 0
has title: Pandas: Filtering groupby data based on some conditions
tagged with: pandas
score: 1
tagged with: group-by

http://stackoverflow.com/comment/81175393
comment on: http://stackoverflow.com/a/47112696
has text: That was it! :)
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81310378
type: Comment
has text: In Python 2.x yes. But in Python 3.x `xrange()` has been renamed as `range() `.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47180723

traitsui
tag name: traitsui
type: Tag
tags question: http://stackoverflow.com/q/47066239

http://stackoverflow.com/comment/81107721
type: Comment
has text: @Bharath Obviously :)
score: 0
comment on: http://stackoverflow.com/a/47078530
type: AnswerComment

http://stackoverflow.com/a/47211762
answers question: http://stackoverflow.com/q/47211732
upvote count: 3
type: Answer
downvote count: 0
has body: You'll need to serialize your object, which can be done with the pickle library.
score: 3

http://stackoverflow.com/comment/81175884
type: Comment
type: QuestionComment
score: 0
has text: can you share url ? and code snippet?
comment on: http://stackoverflow.com/q/47112972

kivy-language
tags question: http://stackoverflow.com/q/47176777
type: Tag
tags question: http://stackoverflow.com/q/47180782
tags question: http://stackoverflow.com/q/47128196
tags question: http://stackoverflow.com/q/47188642
tags question: http://stackoverflow.com/q/47203069
tags question: http://stackoverflow.com/q/47109012
tag name: kivy-language
tags question: http://stackoverflow.com/q/47112878
tags question: http://stackoverflow.com/q/47111074
tags question: http://stackoverflow.com/q/47158882
tags question: http://stackoverflow.com/q/47085937

http://stackoverflow.com/comment/81357277
comment on: http://stackoverflow.com/q/47204301
has text: The server redirects to the HTTP (without S) version anyway. So you might just try HTTP.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/81099341
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47074815
has text: What make you think the OP wants the locale to be "en_US", and how is this supposed to cure a problem that has nothing to do with the system's encoding ?

http://stackoverflow.com/comment/81180711
comment on: http://stackoverflow.com/a/47089800
type: Comment
score: 0
type: AnswerComment
has text: Did it help you?

http://stackoverflow.com/comment/81356605
comment on: http://stackoverflow.com/q/47203889
has text: Your code is actually working for me? Can you give an example where it prints the wrong number? EDIT: you are comparing lexicographically, convert input to integers with `int(...)` then its working correct.
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/81157601
comment on: http://stackoverflow.com/a/47103386
score: 0
type: AnswerComment
has text: You're welcome! Probably I shouldn't have to just give you the solution but only hints, letting you to find the answers, but the site is not oriented on that direction. But at the end, the important thing is for you to learn something. Regarding learning resources, I don't know... here are some tutorials: [\[Python\]: The Python tutorial](https://docs.python.org/3/tutorial/index.html#the-python-tutorial) or [\[TutorialsPoint\]: Python - Tutorial](http://www.tutorialspoint.com/python).
type: Comment

http://stackoverflow.com/comment/81278658
type: AnswerComment
score: 0
type: Comment
has text: This is probably the best I'm going to get. Specifically, and I may have not made this clear in the original question, I'm trying to find a way to make the point at which each string lines up, (eg. l1, l2, l3) modular such that they fall on the same word in each string. I might be able to add an index search into this that effects l1, l2, and l3. Thanks for the response!
comment on: http://stackoverflow.com/a/47148306

http://stackoverflow.com/a/47113082
has comment: http://stackoverflow.com/comment/81180826
has body: You need to convert your pandas dataframes to numpy arrays, the arrays are going to be ragged so you need to pad them. You also need to setup a dictionary of word vectors, as you cannot just pass words directly into a neural network. Some examples are, here,here, and here. Your're going to need to do your own research here, Its not possible to do much with the data sample you provided length = len(X_data) is how many samples of data you have, keras doesn't care about this, it wants to know how many words you have as an input, (has to be the same for each, which is why padding was stated earlier) so your input to the network is how many columns you have #assuming you converted X_data correctly to numpy arrays and word vectors model.add(Embedding(embedding_vecor_length, top_words, input_length=X_data.shape[1])) Your categorical values need to be binary. from keras.utils import to_categorical y = to_categorical(y) Your last dense layer is now 10, assuming that you have 10 categories and the correct activation is softmax for a mulitclass problem model.add(Dense(10, activation='softmax')) your loss now has to be categorical_crossentropy, since this is multiclass model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47112610
score: 3
has comment: http://stackoverflow.com/comment/81180308
has comment: http://stackoverflow.com/comment/81180690
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47112610
has comment: http://stackoverflow.com/comment/81183146

http://stackoverflow.com/a/47133639
has comment: http://stackoverflow.com/comment/81442210
answers question: http://stackoverflow.com/q/47129926
has comment: http://stackoverflow.com/comment/81251326
has comment: http://stackoverflow.com/comment/81442153
downvote count: 0
score: 1
upvote count: 1
has body: You have the wrong coords. ## sudo.png (563, 558, 3) ## tl-&gt;tr-&gt;br-&gt;bl pts1 = np.float32([[76,85],[490,70],[520,520],[35,512]]) pts2 = np.float32([[0,0],[300,0],[300,300], [0,300]])
type: Answer

http://stackoverflow.com/q/47138153
has title: ffmpeg: get duration using a script: Unable to find a suitable output format for '2>&1 | grep "Duration"'
accepted answer: http://stackoverflow.com/a/47138440
tagged with: ffmpeg
has comment: http://stackoverflow.com/comment/81226088
tagged with: python
has comment: http://stackoverflow.com/comment/81226625
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3172470
linked to: http://stackoverflow.com/q/13332268
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47138440
score: 1
upvote count: 1
has body: I am trying to get the duration of a media file I have by running these lines from a python script: test_file = 'path_to_file.mp4' ffmpeg_get_mediafile_length = ["ffmpeg", "-i", test_file, '2&gt;&amp;1 | grep "Duration"'] output = subprocess.Popen(ffmpeg_get_mediafile_length, stdout = subprocess.PIPE ).stdout.read() print output # this gives None matches = re_length.search(output) print matches Here is the ffmpeg logs I get alongside with the error I get: ffmpeg version 3.4 Copyright (c) 2000-2017 the FFmpeg developers built with Apple LLVM version 9.0.0 (clang-900.0.37) configuration: --prefix=/usr/local/Cellar/ffmpeg/3.4 --enable-shared --enable-pthreads --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-gpl --enable-libmp3lame --enable-libx264 --enable-libxvid --enable-opencl --enable-videotoolbox --disable-lzma libavutil 55. 78.100 / 55. 78.100 libavcodec 57.107.100 / 57.107.100 libavformat 57. 83.100 / 57. 83.100 libavdevice 57. 10.100 / 57. 10.100 libavfilter 6.107.100 / 6.107.100 libavresample 3. 7. 0 / 3. 7. 0 libswscale 4. 8.100 / 4. 8.100 libswresample 2. 9.100 / 2. 9.100 libpostproc 54. 7.100 / 54. 7.100 Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'path_to_media_file': Metadata: major_brand : isom minor_version : 512 compatible_brands: isomiso2avc1mp41 encoder : Lavf57.83.100 Duration: 00:22:25.89, start: 0.000000, bitrate: 6059 kb/s Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1920x1080, 6057 kb/s, 15 fps, 30 tbr, 90k tbn, 180k tbc (default) Metadata: handler_name : VideoHandler [NULL @ 0x7fedac802200] Unable to find a suitable output format for '2&gt;&amp;1 | grep "Duration"' 2&gt;&amp;1 | grep "Duration": Invalid argument
duplicate of: http://stackoverflow.com/q/13332268
possible better answer: http://stackoverflow.com/a/47138453
has comment: http://stackoverflow.com/comment/81225992
has answer: http://stackoverflow.com/a/47138453
favorite count: 0
type: Question

http://stackoverflow.com/comment/81380509
type: Comment
has text: im just going to assign it to r.text2 but im gonna leave the question open because there has to be an actual solution.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47215427

http://stackoverflow.com/a/47119671
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47119629
upvote count: 3
has body: missing must be a function of a single argument, but you could use a lambda to wrap fun and unpack the tuple: x = LRUCache(maxsize=100, missing=lambda args: fun(*args)) and call with: x[(a, b)]
has comment: http://stackoverflow.com/comment/81189015
score: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47119629

http://stackoverflow.com/q/47140927
has comment: http://stackoverflow.com/comment/81231871
answer count: 1
has comment: http://stackoverflow.com/comment/81233188
has comment: http://stackoverflow.com/comment/81231702
has comment: http://stackoverflow.com/comment/81232915
type: Question
has body: This might be just a syntax error in Windows Powershell, but I'm not able to run a python script with a specific python version (I have two installations). I have a batch file in which the following command works: "C:\Program Files\QGIS 2.18\bin\python.exe" myscript.py But if I open a PowerShell in the folder containing the python script, I get an error: At line:1 char:45 + ... C:\Program Files\QGIS 2.18\bin\python.exe" myscript.py + ~~~~~~~~~~~~~~~~~~~~~~~~~~ Unexpected token 'myscript.py' in expression or statement. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken I tried also without double-quotes, with single-quotes, and by specifying the path also to the python script: "C:\Program Files\QGIS 2.18\bin\python.exe" C:\mydata\myscript.py With quotes on both parts: "C:\Program Files\QGIS 2.18\bin\python.exe" "C:\mydata\myscript.py" But with a similar error. What is the correct way to write this command?
has comment: http://stackoverflow.com/comment/81233245
has title: Run a specific python version in powershell
has comment: http://stackoverflow.com/comment/81232160
tagged with: powershell
tagged with: python
has comment: http://stackoverflow.com/comment/81231970
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47142405
accepted answer: http://stackoverflow.com/a/47142405

http://stackoverflow.com/comment/81223737
has text: I updated my answer with an example, couldn't test it as I don't have a key right now but I hope it helps.
comment on: http://stackoverflow.com/a/47134784
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81119345
type: Comment
comment on: http://stackoverflow.com/q/47084766
score: 0
has text: Look at the DateTime package in Python. Look for the time zone controls. Do your best to write code to solve it; post again if you run into difficulty.
type: QuestionComment

http://stackoverflow.com/q/47125723
tagged with: recurrent-neural-network
has title: Keras LSTM for Text Generation keeps repeating a line or a sequence
favorite count: 0
has comment: http://stackoverflow.com/comment/92866545
type: Question
has answer: http://stackoverflow.com/a/57462676
answer count: 2
type: UnansweredQuestion
score: 16
upvote count: 16
tagged with: python
has comment: http://stackoverflow.com/comment/100199406
tagged with: keras
has comment: http://stackoverflow.com/comment/81205020
tagged with: lstm
has comment: http://stackoverflow.com/comment/93001399
has comment: http://stackoverflow.com/comment/81203693
tagged with: deep-learning
downvote count: 0
has answer: http://stackoverflow.com/a/57463174
has comment: http://stackoverflow.com/comment/92988784
has comment: http://stackoverflow.com/comment/84366403
has body: I roughly followed this tutorial: https://machinelearningmastery.com/text-generation-lstm-recurrent-neural-networks-python-keras/ A notable difference is that I use 2 LSTM layers with dropout. My data set is different (music data-set in abc notation). I do get some songs generated, but after a certain number of steps (may range from 30 steps to a couple hundred) in the generation process, the LSTM keeps generating the exact same sequence over and over again. For example, it once got stuck with generating URLs for songs: F: http://www.youtube.com/watch?v=JPtqU6pipQI and so on ... It also once got stuck with generating the same two songs (the two songs are a sequence of about 300 characters). In the beginning it generated 3-4 good pieces but afterwards, it kept regenerating the two songs almost indefinitely. I am wondering, does anyone have some insight into what could be happening ? I want to clarify that any sequence generated whether repeating or non-repeating seems to be new (model is not memorising). The validation loss and training loss decrease as expected. Andrej Karpathy is able to generate a document of thousands of characters and I couldn't find this pattern of getting stuck indefinitely. http://karpathy.github.io/2015/05/21/rnn-effectiveness/

http://stackoverflow.com/comment/81330731
type: Comment
has text: Please provide an example showing the contents of `allGood.txt` and the files in `C:\your\folder\path\here` and the expected and actual output. Also bear in mind that the backslashes in the path should be escaped: `"C:\\your\\folder\\path\\here"`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47190488

http://stackoverflow.com/comment/81335336
type: AnswerComment
comment on: http://stackoverflow.com/a/47192162
has text: It does, but is there a way to do it without writing another function and lambda?
type: Comment
score: 0

http://stackoverflow.com/comment/81382625
has text: BTW, `string` is not a good choice for a variable name: it's the name of a standard module.
comment on: http://stackoverflow.com/q/47216436
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81134179
has text: try `os.walk()`
comment on: http://stackoverflow.com/q/47092332
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47199246
answer count: 2
has answer: http://stackoverflow.com/a/47200163
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81347317
downvote count: 2
has comment: http://stackoverflow.com/comment/81347502
has title: How can I make elements of a list part of a regex?
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47200148
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81347606
has body: So I have a list of strings, lets say: my_list = ['hope', 'faith', 'help'] now I open a textfile with the name infile and seperate the words with for line in infile: line_list = line.split() now I want to make a regex that i can change by using for loop like this: for word in line_list: match = re.findall(word$, line_list) print(match) I've tried several ways to get 'word' into that regex but none seems to work Any ideas?
tagged with: python
score: -1
tagged with: regex

http://stackoverflow.com/a/47146546
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81243454
score: 2
has comment: http://stackoverflow.com/comment/81243609
has body: Why is it really an issue? I assume you installed the AWS CLI tool by downloading the installer directly. If you want to "fix" it then uninstall the CLI tool, and then install it through pip with pip install awscli.
type: Answer
has comment: http://stackoverflow.com/comment/81243568
answers question: http://stackoverflow.com/q/47146493

http://stackoverflow.com/a/47184076
score: 2
has body: Your question is vague but if I understand correctly, you are getting the right object with this line : corsi = Corso.objects.filter(pk=corso_id) So if your goal is to compare his f1 attribute, why not using : if corsi.f1: #do something when True EDIT Sorry it was my mistake, the line you use return a Queryset, corsi = Corso.objects.filter(pk=corso_id) Therefore use this: corsi = Corso.objects.get(pk=corso_id) Which will result in an instance and then use my conditional code. Another alternative would be to use built-in first() this will add a validation to check if the object exists. Then, you have to decide what you want to do if it is None. Use it like this: corsi = Corso.objects.filter(pk=corso_id).first()
accepted answer of: http://stackoverflow.com/q/47183153
upvote count: 2
has comment: http://stackoverflow.com/comment/81318297
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47183153
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81334905
score: 0
has text: The original sheet starts at row 2, however Pandas tends to automatically put first cells with text and assumes that row from former is a header. One way to get around is it to label csv and excel files though considering the load of excels I have not very viable.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47192659

http://stackoverflow.com/comment/83110283
type: AnswerComment
has text: Took two senior engineers 3 hours to track it down to this. If only we had searched sooner.
type: Comment
comment on: http://stackoverflow.com/a/47297539
score: 2

http://stackoverflow.com/q/47124810
tagged with: digraphs
downvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81237529
has body: I wrote a code to convert my MultiDiGraph() to a pydot graph to display self loops and arrows but after conversion, the pydot graph A has lost all the attributes of G. How can change the node size of graph A and set them equal to corresponding value in node_sizes[] list like I did for G? code: def draw_graph(graph, size): # extract nodes from graph nodes = set([n1 for n1, n2 in graph] + [n2 for n1, n2 in graph]) print("Nodes ",nodes,"\n") node_sizes = [] for n in nodes: #Scaling up the node importance by a factor of 2000 to make it visible node_sizes.append( size[n] * 2000) print("Node size ",node_sizes,"\n") # create networkx graph G=nx.MultiDiGraph() G.add_edges_from(edges) G.add_nodes_from(nodes) edge_colours = ['black' for edge in G.edges()] pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), node_size = node_sizes) nx.draw_networkx_labels(G, pos) nx.draw_networkx_edges(G, pos, edge_color='black', arrows=True) plt.show() # render pydot by calling dot, no file saved to disk A=nx.to_pydot(G, strict=True) png_str = A.create_png(prog='dot') # treat the dot output string as an image file sio = BytesIO() sio.write(png_str) sio.seek(0) img = mpimg.imread(sio) # plot the image imgplot = plt.imshow(img, aspect='equal') plt.show(block=False)
favorite count: 0
has answer: http://stackoverflow.com/a/47144180
type: Question
tagged with: pydot
tagged with: directed-graph
tagged with: python
linked to: http://stackoverflow.com/q/1265996
has comment: http://stackoverflow.com/comment/81200877
upvote count: 4
score: 4
has title: Is it possible to change node size of a pydot graph?

http://stackoverflow.com/q/47179671
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47179796
has title: How can I associate story_author name with request.user?
tagged with: django
tagged with: python
tagged with: forms
has body: My first problem is once I save a story, the story.author will not associate with request.user. So it brings to another problem, I have to add story_author from user list, and then select an author for the story manually. Here is my damin looks like models.py class StoryAuthor(models.Model): """ Model representing a author. """ user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) def get_absolute_url(self): """ Returns the url to access a particular story_author instance. """ return reverse('stories_by_author', args=[str(self.id)]) def __str__(self): """ String for representing the Model object. """ return self.user.username class Story(models.Model): author = models.ForeignKey(StoryAuthor,related_name='stories',null=True) sb_thing = models.CharField(max_length=30,null=True) sb_story = models.CharField(max_length=30,null=True) sb_name = models.CharField(max_length=30,null=True) views.py def story_new(request): if request.method == "POST": form = StoryForm(request.POST) #form.StoryAuthor = request.user if form.is_valid(): story = form.save(commit=False) StoryAuthor = request.user story.published_date = timezone.now() story.save() return redirect('story_detail', pk=story.pk) else: form = StoryForm() return render(request, 'story/story_create.html', {'form': form})
score: 0
has comment: http://stackoverflow.com/comment/81308232
tagged with: associated-object
answer count: 1

http://stackoverflow.com/a/47100922
accepted answer of: http://stackoverflow.com/q/47100325
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: Following the explanation already provided by @user6910411 (and saving me the time to do it myself), the remedy (i.e. the intermediate JSON representation) is to use read.json instead of toDF and your function: spark.version # u'2.0.2' jsonRDD = sc.parallelize([{"id": "14yy74hwogxoyl2l3v", "geoloc": {"country": {"geoname_id": 3017382, "iso_code": "FR", "name": "France"}}}]) df = spark.read.json(jsonRDD) df.collect() # result: [Row(geoloc=Row(country=Row(geoname_id=3017382, iso_code=u'FR', name=u'France')), id=u'14yy74hwogxoyl2l3v')] # just to have a look at what will be saved: df.toJSON().collect() # result: [u'{"geoloc":{"country":{"geoname_id":3017382,"iso_code":"FR","name":"France"}},"id":"14yy74hwogxoyl2l3v"}'] df.toJSON().saveAsTextFile("/tmp/json.test") For comparison, here is how your own df2 looks: df2.collect() # result: [Row(geoloc={u'country': {u'geoname_id': 3017382, u'iso_code': None, u'name': None}}, id=u'14yy74hwogxoyl2l3v')] df2.toJSON().collect() # result: [u'{"geoloc":{"country":{"name":null,"iso_code":null,"geoname_id":3017382}},"id":"14yy74hwogxoyl2l3v"}']
answers question: http://stackoverflow.com/q/47100325

http://stackoverflow.com/comment/81223950
type: AnswerComment
comment on: http://stackoverflow.com/a/47137401
has text: So your suggestion would be an addition to the code I already have present, correct? Can you provide code showing this?
score: 0
type: Comment

http://stackoverflow.com/q/47154856
has answer: http://stackoverflow.com/a/48508289
accepted answer: http://stackoverflow.com/a/48508289
tagged with: python
tagged with: splash-screen
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82606563
answer count: 2
upvote count: 5
score: 5
tagged with: redis
has answer: http://stackoverflow.com/a/61637761
possible better answer: http://stackoverflow.com/a/61637761
downvote count: 0
has title: Work-horse process was terminated unexpectedly RQ and Scrapy
tagged with: scrapy
has body: I am trying to retrieve a function from redis (rq), which generate a CrawlerProcess but i'm getting Work-horse process was terminated unexpectedly (waitpid returned 11) console log: Moving job to 'failed' queue (work-horse terminated unexpectedly; waitpid returned 11) on the line I marked with comment THIS LINE KILL THE PROGRAM What am I doing wrong? How I can fix it? This function I retrieve well from RQ: def custom_executor(url): process = CrawlerProcess({ 'USER_AGENT': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36", 'DOWNLOAD_TIMEOUT': 20000, # 100 'ROBOTSTXT_OBEY': False, 'HTTPCACHE_ENABLED': False, 'REDIRECT_ENABLED': False, 'SPLASH_URL': 'http://localhost:8050/', 'DUPEFILTER_CLASS': 'scrapy_splash.SplashAwareDupeFilter', 'HTTPCACHE_STORAGE': 'scrapy_splash.SplashAwareFSCacheStorage', 'DOWNLOADER_MIDDLEWARES': { 'scrapy_splash.SplashCookiesMiddleware': 723, 'scrapy_splash.SplashMiddleware': 725, 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810, }, 'SPIDER_MIDDLEWARES': { 'scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware': True, 'scrapy.spidermiddlewares.httperror.HttpErrorMiddleware': True, 'scrapy.downloadermiddlewares.httpcache.HttpCacheMiddleware': True, 'scrapy.extensions.closespider.CloseSpider': True, 'scrapy_splash.SplashDeduplicateArgsMiddleware': 100, } }) ### THIS LINE KILL THE PROGRAM process.crawl(ExtractorSpider, start_urls=[url, ], es_client=es_get_connection(), redis_conn=redis_get_connection()) process.start() and this is my ExtractorSpider: class ExtractorSpider(Spider): name = "Extractor Spider" handle_httpstatus_list = [301, 302, 303] def parse(self, response): yield SplashRequest(url=url, callback=process_screenshot, endpoint='execute', args=SPLASH_ARGS) Thank you
type: AnsweredQuestion

http://stackoverflow.com/a/47813173
answers question: http://stackoverflow.com/q/47119259
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/47119259
type: AcceptedAnswer
has body: I found that the issue was hdf optimizing the data storage and counting on the size of the largest value of each column, I found two ways to solve this: 1.Pre query the database to get the maximum data char length for each column 2.inserting each batch to a new key in the file then it works, each batch will be inserted to the hdf file using it's biggest value as biggest value in the column

http://stackoverflow.com/comment/81202940
has text: @zindarod fixed :-)
type: QuestionComment
comment on: http://stackoverflow.com/q/47126370
type: Comment
score: 1

http://stackoverflow.com/q/47128060
tagged with: multiple-matches
accepted answer: http://stackoverflow.com/a/47145843
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47145423
has answer: http://stackoverflow.com/a/47145843
score: 1
tagged with: python
tagged with: regex
tagged with: delimiter
has title: Find all repeating strings between a start and a stop and with a separator
answer count: 4
possible better answer: http://stackoverflow.com/a/47128175
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47128175
has answer: http://stackoverflow.com/a/47145182
has body: I'm trying to get one or more substring from a string like this : "theSTART:param1:param2:paramN:theEND" or "theSTART:param1:theEND" or any number of parameter saparated by ":" and delimited by "theSTART:" and ":theEND". I'm using Python3 regex but I can't find the right pattern to match a variable number of items: r"theSTART:((?:\w*)+):((?:[^:])*):((?:\w)+):theEND" works only for 3 items. And if I try : r"theSTART:((?:\w*)+):(((?:[^:])*):)+((?:\w)+):theEND" doesn't work as expected.
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47175561
answers question: http://stackoverflow.com/q/47175195
has body: You are trying to assing a value to list.append function. Rather you should give it as an argument to list.append function. Below code would do and is simplified one. player1=[] for i in range(1, 4): player1.append(int(input('please enter your score for player 1, round {}\n'.format(i)))) print(player1)
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81308618
type: Answer

http://stackoverflow.com/a/47254223
type: Answer
answers question: http://stackoverflow.com/q/47210965
accepted answer of: http://stackoverflow.com/q/47210965
type: AcceptedAnswer
score: 0
has body: As suggested in comments it was package-connected issue. In this case the proper solution to problem was using try statement: from __future__ import print_function from inputs import get_key from inputs import DeviceManager def main(): devices = DeviceManager() dictionaries = devices.codes qt = False try: while True: events = get_key() for event in events: if (event.code in dictionaries["Key"].values() and event.state == 1): print(event.code, event.state) except KeyboardInterrupt: return if __name__ == "__main__": main()

http://stackoverflow.com/comment/81367718
comment on: http://stackoverflow.com/q/47191412
score: 0
type: Comment
type: QuestionComment
has text: I have the same - PySerial 3.4 and Python 3.6 .

http://stackoverflow.com/comment/81122545
type: Comment
type: QuestionComment
has text: @knitti I think that is exactly the cause of the problem,SQLite automaps the str to name but Postgre maps it to the ID which is Integer. Any suggestion to fix the problem without breaking the entire code? I have attached the entire db to the problem. Both Category_ID and User_ID in items are string input
score: 0
comment on: http://stackoverflow.com/q/47065679

http://stackoverflow.com/comment/81112178
type: Comment
has text: @JacobBarnes ... and MySQL will not err out on such an evaluation as it implicitly casts string representation of numbers.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47081291

http://stackoverflow.com/comment/81150118
score: 0
comment on: http://stackoverflow.com/q/47097812
has text: Ah, interesting. (Just for clarity - i regard these migration speeds as non problematic!) We're on 1.10.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81219557
type: AnswerComment
comment on: http://stackoverflow.com/a/47131587
has text: I am getting this error, `TypeError: object of type 'float' has no len()` on `df2['val'] = df2[content_col].str.lower().str.findall(pat).apply(lambda x : x[0].strip() if len(x)>=1 else np.nan)`
type: Comment
score: 0

http://stackoverflow.com/comment/81372583
type: Comment
has text: you can't do that directly with a crontab, you should call another script that calls your script every second or modify your first script to do that
type: AnswerComment
comment on: http://stackoverflow.com/a/47211063
score: 0

http://stackoverflow.com/a/47104995
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47104498
has body: Looks like i have to explicitly source my .bashrc file (or equivalent). Changing the contents of my runpipenv.sh script to this #!/bin/bash source ~/.bashrc cd ~/myprojectdir pipenv run python (where my .bashrc file sets LANG) and then calling (setq py-shell-name "runpipenv.sh") in Emacs seems to work.

http://stackoverflow.com/comment/81247314
type: QuestionComment
comment on: http://stackoverflow.com/q/47148509
has text: SO has a lot of resources already- you should do research on your own before asking.
score: 0
type: Comment

http://stackoverflow.com/a/47079482
has comment: http://stackoverflow.com/comment/81141075
answers question: http://stackoverflow.com/q/47078480
type: Answer
has comment: http://stackoverflow.com/comment/81108246
has comment: http://stackoverflow.com/comment/81111619
has comment: http://stackoverflow.com/comment/81109462
has body: The pattern of the code is probably similar but I can't check this because I don't have your full xml. >>> from lxml import etree >>> tree = etree.parse('temp.xml') >>> for guide in tree.xpath('guide'): ... '---', guide.xpath('id')[0].text ... for pages in guide.xpath('.//pages'): ... for page in pages: ... '------', page.xpath('id')[0].text ... for description in page.xpath('.//asset/description'): ... '---------', description.text ... ('---', 'guide 1') ('------', 'page 1') ('---------', 'description') I assumed that your xml would have multiple guide elements. This is what I parsed. guide 1 page 1 <map_id></map_id> description <first_name></first_name> <last_name></last_name> I made life easier for myself by indenting the xml so that I could discern its structure.
accepted answer of: http://stackoverflow.com/q/47078480
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81109645

http://stackoverflow.com/a/47188650
has comment: http://stackoverflow.com/comment/81381954
has comment: http://stackoverflow.com/comment/81342330
score: 0
has body: Are you a victim of sampling? Whenever you query for non-standard dimensions (e.g. dateHour vs. date) you risk running into sampling which might badly affect the accuracy of your data (I've seen e-commerce revenue go to $0 because of it). Check your query results for the containsSampledData flag: https://developers.google.com/analytics/devguides/reporting/core/v3/reference#sampling Several ways to work-around sampling: Play with samplingLevel and see if that helps Break your query down into several smaller queries each querying for a shorter date range and re-combine the data on your server
has comment: http://stackoverflow.com/comment/81339420
answers question: http://stackoverflow.com/q/47185768
type: Answer

http://stackoverflow.com/q/47113527
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47114740
has title: how to find correct youtube xpath for python
tagged with: http://stackoverflow.com/tag/xml
type: Question
tagged with: xpath
possible better answer: http://stackoverflow.com/a/47114740
answer count: 2
has body: I want to get information including video title, videoID, video post time, video viewers from videos on Youtube. But I don't know how to find the correct xpath. The following code is suggested by How to extract the title of a youtube video using python I have tried to use inspect of 'Chrome' and firebug of 'firefox', but all these didn't work for the code (the xpath found is : //*[@id="container"]/h1). The result is all empty list. import lxml from lxml import etree youtube = etree.HTML(urllib.request.urlopen("https://www.youtube.com/watch? v=Tqyu6E_k_cg").read()) video_title = youtube.xpath("//span[@id='eow-title']/@title") print (''.join(video_title)) So how should I find the correct xpaths for videoID, viewers, postdate that can wor?
accepted answer: http://stackoverflow.com/a/47113641
has answer: http://stackoverflow.com/a/47113641
tagged with: python
tagged with: youtube
linked to: http://stackoverflow.com/q/8738916
tagged with: video

http://stackoverflow.com/comment/81392843
comment on: http://stackoverflow.com/a/47216885
type: AnswerComment
has text: @KaranGupta It is a dataframe.
score: 0
type: Comment

http://stackoverflow.com/comment/81173123
score: 0
type: Comment
has text: Thanks! If I wanted to add additional obs in the print line how might I do that? I tried adding obs['wind'] to get the wind direction, but got a keyerror. How did you get the temperature, pressure and dewpoint to print?
type: AnswerComment
comment on: http://stackoverflow.com/a/47111510

http://stackoverflow.com/q/47106357
has comment: http://stackoverflow.com/comment/81179913
has body: I created a kivy app to run on android. I'm using pyjinius to communicate to native java/android language. I'm using the AudioTrack class in order to write() streaming audio data to android device speakers. So the code basically works like this: Thread is created to set up AudioTrack class with proper variables, I then play() the AudioTrack [originally I had one thread for this, but i guess play() is blocking in python?? so I just made two threads], then I start a new thread which loops to collect socket.recv() data from peer, then gets rms(audio level) of data [this works fine], then write() audio data to the AudioTrack stream to output sound to speakers. It seems to work, but it's static-y / choppy audio - like a screeching noise. Is there something wrong with the AudioTrach set-up that is doing this? Any help or advice would be appreciated. class ReceiveVoiceThread(Thread): # Receive Voice Data def __init__(self, sock, name, pop): # Called on creation Thread.__init__(self) self.sock = sock self.name = name self.pop = pop def run(self): sample = AudioTrack.getNativeOutputSampleRate( AudioManager.USE_DEFAULT_STREAM_TYPE ) if not sample: sample = 44100 n = AudioRecord.getMinBufferSize( sample, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_8BIT, # 8 Bit for byte array data ) # n = 1024 self.audio_stream = AudioTrack( AudioManager.USE_DEFAULT_STREAM_TYPE, sample, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_8BIT, # 8 Bit for byte array data n, # bufsizbytes, AudioTrack.MODE_STREAM, ) self.audio_stream.play() audio_thread = AudioThread(self.audio_stream, n, self.sock, self.name, self.pop) audio_thread.start() class AudioThread(Thread): def __init__(self, audio_stream, n, sock, name, pop): # Called on creation Thread.__init__(self) self.sock = sock self.name = name self.pop = pop self.audio_stream = audio_stream self.n = n def run(self): while True: try: data = self.sock.recv(self.n) rms = self.get_rms(data, self.n) if rms &gt; 400: App.get_r…
tagged with: python
tagged with: kivy
has title: Static/choppy audio when using pyjinus, kivy, AudioTrack on android?
tagged with: audio
score: 0
answer count: 0
tagged with: java
has comment: http://stackoverflow.com/comment/81180879
has comment: http://stackoverflow.com/comment/81167743
type: Question
type: UnansweredQuestion
tagged with: android

http://stackoverflow.com/a/47110491
answers question: http://stackoverflow.com/q/47110297
has body: If it is just the value you are looking for, then generator expresshon should do it: max(d['index'] for d in data)
score: 0
type: Answer

http://stackoverflow.com/comment/81251292
has text: I tried in virtualenv also. No luck.
comment on: http://stackoverflow.com/q/47144624
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81245424
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47147563
type: QuestionComment
has text: You don't have to declare the types of variables. remove `SUM = int` and `byte = str`. They aren't doing what you expect them to

http://stackoverflow.com/comment/81368515
comment on: http://stackoverflow.com/a/47209392
type: AnswerComment
has text: I was almost there. Thanks for reply
score: 1
type: Comment

http://stackoverflow.com/a/47177069
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/47176964
downvote count: 0
type: AcceptedAnswer
has body: Slice with one-off shifted versions and thus compute the output in a vectorized manner - bins_mean = (bins[1:]-bins[:-1])/2 +bins[:-1]
type: Answer
answers question: http://stackoverflow.com/q/47176964

http://stackoverflow.com/q/47177648
has comment: http://stackoverflow.com/comment/81304257
has title: Add suffix to columns in pandas dataframe
linked to: http://stackoverflow.com/q/34049618
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81304632
tagged with: dataframe
duplicate of: http://stackoverflow.com/q/34049618
tagged with: python
has comment: http://stackoverflow.com/comment/81304424
score: 0
tagged with: pandas
answer count: 0
type: Question
has body: How to add extra word/characters to all the columns of dataframe in Python 3.6 I have data frame with 15+ columns &amp; I want to add a word " Code" to name of all the columns exist in dataframe. &gt;&gt;&gt; list(dataAll) ['Active Industry Rep Count', 'Active Reps Count', 'Age Bracket', 'Channel Type', 'Count Reps Changing BDF', 'Deregistration Date During Month', 'Exclude Non Producers', 'FileName', 'Firm', 'Firm Type', 'Gender', 'License', 'Net Rep Count', 'Quarter End', 'RIA Ownership Type', 'Registration Date During Month', 'Rep Count In', 'Rep Count Out', 'Retail BD Primary Type', 'Retail BD Type', 'Date', 'Year End', 'Years A Rep', 'value', 'variable', 'Indicator', 'Category', 'Frequency'] Now I want to add " Code" to all the column except column : value &amp; Frequency ex: dataAll.rename(columns = {'Active Industry Rep Count' : 'Active Industry Rep Count Code'}, inplace = True) Is it possible in single script?

http://stackoverflow.com/comment/81251027
score: 1
has text: See if this helps https://stackoverflow.com/questions/31663288/how-do-i-properly-use-connection-pools-in-redis. You are not using a connection pool and then created redis connection again and again to event fetch the connected clients info. You should not use `get_redis().info()['connected_clients']`. Rather create the object outside loop `r = get_redis()` and then inside loop use `r.info()['connected_clients']`
comment on: http://stackoverflow.com/q/47106592
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47102727
upvote count: 1
has body: My professor wanted us to add a new function to this program called loadtemperatureData. This function uses a loop to load temperatures in the temperature file (filename) to a list and return the list to the caller. she also wants us to modify the __init__ function: Modify __init__ function to add one more data attribute temperatureList. Inside __init__ function, call loadTemperatureData function and assign the returned value to temperatureList. Modify calculateAverage function to use the data attribute temperatureList to calculate average temperature. Main function remains unchanged. I keep getting this error: File "C:/Users/abrooks3/Downloads/temperatureadd.py", line 57, in main Temperatures = TemperatureFile('Temperatures.txt') TypeError: __init__() missing 1 required positional argument: 'temperatureList' This is my code: my original code is at the bottom im not sure what she wanted or if I attempted to do this correctly class TemperatureFile: def __init__(self, filename, temperatureList): self.__filename = filename self.temperatureList = [] self.loadTemperatureData(temperatureList) def getFilename(self): return self._Filename def setFilename(self): self._filename = filename def calculateAverage(self, temperaturelist): try: with open(self.__filename,'r') as temperatureFile: total = 0 temp = 0 for line in temperatureFile: amount = float(line.rstrip("\n")) total += amount temp = temp + 1 average = total/temp except ValueError as err: print(err) except IOError as err: print(err) else: average = total/temp print(average) finally: temperatureFile.close() def loadTemperatureData(self, filename): with open(self.__filename,'w') as temperartureFile: temps = [35, 63, 40] for temp in temps: temperatureFile.write(str(temp)+ 'n') temeperatureFile.close return temps def main(): num1 = 35 num2 = 63 num3 = 40 temperatureFile = open('Temperatures.txt', 'w') temperatureFile.write(str(num1) + '\n') temperatureFile.write(str(num2) + '\n') temperatureFile.write(str(num3) + '\n') tem…
possible better answer: http://stackoverflow.com/a/47102775
has answer: http://stackoverflow.com/a/47103386
has answer: http://stackoverflow.com/a/47102821
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81156228
has answer: http://stackoverflow.com/a/47102775
has answer: http://stackoverflow.com/a/47102802
type: AnsweredQuestion
tagged with: python
score: -2
has title: How to call a function inside the __init__ function?
answer count: 4
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81156513
accepted answer: http://stackoverflow.com/a/47103386
downvote count: 3

http://stackoverflow.com/comment/81187059
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47118527
type: Comment
has text: I already have my :<10 in there. Would I precede the <10, proceed it, or do something else? Thanks!

http://stackoverflow.com/a/47197357
type: Answer
has comment: http://stackoverflow.com/comment/81344045
answers question: http://stackoverflow.com/q/47196883
has body: Since the order of the words does not matter, why don't you just process the files in the order they appear in test.txt? There are a couple errors in your code, the first one on line 3 where you overwrite the content of splitted. I'm also particularly confused by your call to sort. Anyway, here's one way to do it. &gt;&gt;&gt; with open('test.txt') as filenames: ... for line in filenames: ... file_no, filename = line.strip().split(':') ... with open(filename) as f: ... for line in f: ... for word in line.split(): ... print '{} {}'.format(word, file_no) ... I 1 am 1 a 1 good 1 person 1 Bla 2 bla 2
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81583342
has comment: http://stackoverflow.com/comment/81344223

http://stackoverflow.com/comment/81322167
has text: Sorry, I didn't read your question properly. I know a bit of Numpy, but I don't know cv2. I don't understand how `img_data = np.array(img_data_list)` could give you that error message. Which array has the (128,128,3) shape?
type: Comment
comment on: http://stackoverflow.com/q/47186313
type: QuestionComment
score: 0

http://stackoverflow.com/q/47083219
tagged with: apache-spark-sql
type: Question
tagged with: aws-glue
tagged with: pyspark
downvote count: 0
has title: Convert Epoch to Datetime in AWS Glue / pyspark
tagged with: python
accepted answer: http://stackoverflow.com/a/47083611
answer count: 1
has answer: http://stackoverflow.com/a/47083611
tagged with: apache-spark
type: AnsweredQuestion
score: 1
upvote count: 1
has body: I have a dataframe that I'm processing in AWS Glue using pyspark and one of the messages in my df looks like this: { "version":"0.0.1", "device_id":"df4c13ddddb1bb8fea9fe762", "session_id":"721cf47cf8408b30bc57743717", "session_start":1508450739332, "source_id":"5", "body":{ "message_id":"2e6d83c677a7b4f3683366d", "message_type":1, "message_time":1508450739332, "url":"http://sample_url/" }, "partition_0":"2017", "partition_1":"10", "partition_2":"19", "partition_3":"22" } I'm trying to convert body.message_time (epoch in miliseconds) to date time field. I tried from_unixtime function: unnested_df.withColumn("messages_datetime", from_unixtime(unnested_df.body.message_time.divide(1000)).show() Giving me this error: TypeError: 'Column' object is not callable I'm simply passing that column into from_unixtime function. Any idea how this can be fixed? Thanks
favorite count: 0

http://stackoverflow.com/comment/81117661
type: Comment
has text: @HyperNeautrino You're right. I've editted my comment above to explain more thoroughly, but why would it immediately evaluate to true if I haven't had the chance to submit that form once being redirected to /index? It's like it's getting automatically submitted for me...
comment on: http://stackoverflow.com/a/47083708
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81280265
score: 0
comment on: http://stackoverflow.com/q/47165189
type: Comment
type: QuestionComment
has text: `sum(data_splitted)` is obviously wrong ;-) -- hint what is the type of the items in `data_splitted`?

http://stackoverflow.com/q/47066552
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/81081585
tagged with: turtle-graphics
tagged with: function
tagged with: python
has body: from turtle import * circle(60) first circle penup() setposition(-120, -40) pendown() circle(50) second circle penup() setposition(140, 0) pendown() circle(60) third circle penup() setposition(260, -40) pendown() circle(50) last circle I just want to know how to put 4 circles in a function.
accepted answer: http://stackoverflow.com/a/47068714
type: AnsweredQuestion
has title: How to put multiple circles code in one function? or loop?
has answer: http://stackoverflow.com/a/47068714
score: 0
possible better answer: http://stackoverflow.com/a/61168215
tagged with: loops
has answer: http://stackoverflow.com/a/61168215

http://stackoverflow.com/comment/92816108
score: 0
type: Comment
type: AnswerComment
has text: The ''--user'' is exactly what is needed in a virtualenv
comment on: http://stackoverflow.com/a/51117336

http://stackoverflow.com/comment/81270936
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47150220
has text: Is there no way I can have `fun()` called outside the scope of PyQt? In my application I have a process running and I think it's kind of ugly to move all my logic into a PyQt app only so I can get a popup. Using your example let's assume `fun()` is already being called and within it I'd like to create/show a popup on the first line and close it on the last line. Do you know if this is possible.
score: 0

http://stackoverflow.com/q/47093561
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/72044262
has answer: http://stackoverflow.com/a/77371209
has answer: http://stackoverflow.com/a/64025990
has answer: http://stackoverflow.com/a/68953182
has answer: http://stackoverflow.com/a/64547381
has answer: http://stackoverflow.com/a/47093793
tagged with: python
tagged with: directory
has answer: http://stackoverflow.com/a/59178861
has title: Remove empty folders (Python)
answer count: 13
has answer: http://stackoverflow.com/a/62122002
has answer: http://stackoverflow.com/a/65624165
possible better answer: http://stackoverflow.com/a/65624165
linked to: http://stackoverflow.com/q/3172470
has answer: http://stackoverflow.com/a/65182695
has answer: http://stackoverflow.com/a/61925409
has body: This is the folder tree: FOLDER\\ \\1\\file \\2\\file \\3\\ \\4\\file The script should scan (loop) for each folder in FOLDER and check if the sub-folders are empty or not. If they are, they must be deleted. My code, until now, is this: folders = ([x[0] for x in os.walk(os.path.expanduser('~\\Desktop\\FOLDER\\DIGITS\\'))]) folders2= (folders[1:]) This scan for folders and, using folders2 begin from the firs folder in DIGITS. In DIGITS there are numbered directories: 1,2,3,4,etc Now what? Tried using os.rmdir but it gives me an error, something about string. In fact, folders2 is a list, not a string, just saying...
accepted answer: http://stackoverflow.com/a/47093793
score: 23
has answer: http://stackoverflow.com/a/71385431
has answer: http://stackoverflow.com/a/73391782
downvote count: 1
upvote count: 24
favorite count: 0

http://stackoverflow.com/comment/81189952
score: 0
type: Comment
type: QuestionComment
has text: I think your problem is Gmail. Specifically Captcha. Use another provider as code works alright for me.
comment on: http://stackoverflow.com/q/47119868

http://stackoverflow.com/q/47135922
tagged with: python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81221810
has title: Finding specific keyword from website using beautifulsoup
tagged with: http://stackoverflow.com/tag/csv
type: Question
tagged with: beautifulsoup
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81305975
has body: hello I want to extract specific keywords from website listed in CSV file, and then list the number word word available in specific website but my code is not working, Could you guys please help me I have an excel sheet with name dai.csv and test.CSV, dai.csv contains wesites link in row from urllib.request import Request, urlopen import bs4 as bs import re import csv import pandas as pd import requests with open("dai.csv", "r") as scoreFile: scoreFileReader =csv.reader(scoreFile) scoreList = [] for row in scoreFileReader: if len (row) != 0: scoreList = scoreList + [row] scoreFile.close() req = Request('scoreList', headers={'User-Agent': 'Mozilla/5.0'}) webpage = urlopen(req).read() soup = bs.BeautifulSoup(webpage,'lxml') url = ("techyardnepal.com") text = soup.get_text() #word = input("Enter the word") word1 = input("input word") count1 = (text.count(word1)) #word = ("is") print(count1) print(url) with open("test.csv", "r") as scoreFile: scoreFileReader =csv.reader(scoreFile) scoreList = [] for row in scoreFileReader: if len (row) != 0: scoreList = scoreList + [row] scoreFile.close() with open ("test.csv","a") as scoreFile: scoreFileWriter =csv.writer(scoreFile) scoreFileWriter.writerow([url,word,count1]) scoreFile.close()

http://stackoverflow.com/q/47155862
type: Question
tagged with: qt
tagged with: hidpi
tagged with: cpu-usage
has body: The code below is a simple Python code with PyQt5 to display a GIF. I have two monitors, one is an imac 5k, and the other one is a QHD monitor. It is difficult to understand the CPU usage difference between the situations that run the Python file on different monitors. Even when I make the PyQt window full screen, the CPU usage becomes much higher. Why does this happen? from PyQt5.QtWidgets import QApplication, QDesktopWidget, QMainWindow, QLabel from PyQt5 import QtGui from PyQt5.QtCore import QTimer import sys class gifplayer(QMainWindow): def __init__(self): super(gifplayer, self).__init__() self.mainwidget = QMainWindow(self) self.setFixedSize(480, 330) self.center() self.timer = QTimer(self) self.timer.timeout.connect(self.play) self.timer.start(2650) self.player = QLabel(self) self.movie = QtGui.QMovie("./test.gif") self.player.setMovie(self.movie) self.player.setGeometry(0, 0, 480, 330) self.movie.start() self.show() def play(self): self.movie.start() # those lines def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) app = QApplication(sys.argv) ex = gifplayer() sys.exit(app.exec_())
tagged with: python
has title: PyQt: High CPU usage on HiDPI
has comment: http://stackoverflow.com/comment/81288845
answer count: 0
score: 2
upvote count: 2
tagged with: pyqt
type: UnansweredQuestion
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/81172528
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47098584
has text: It appears you have a relatively old version of the Dropbox library, which doesn't have that `Dropbox` attribute. You have 2.2.0, but [the latest version](https://github.com/dropbox/dropbox-sdk-python/releases) is currently 8.4.1. What output did you get from `sudo pip install dropbox`? Perhaps try `sudo pip install --upgrade dropbox`.

http://stackoverflow.com/q/47194856
tagged with: character-encoding
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/81339081
has comment: http://stackoverflow.com/comment/81339578
has comment: http://stackoverflow.com/comment/81338842
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81339602
answer count: 2
has comment: http://stackoverflow.com/comment/81339504
accepted answer: http://stackoverflow.com/a/47196053
has answer: http://stackoverflow.com/a/47196817
possible better answer: http://stackoverflow.com/a/47196817
has title: UnicodeDecodeError: 'utf-8' can't decode byte
upvote count: 1
has body: I have written a simple client/server socket program, where the server part is in C language whereas the client is in python. I am very much able to send the data from the client to the server but cannot send a response message/data back to the python script.. server.c #include&lt;stdio.h&gt; #include&lt;sys/socket.h&gt; #include&lt;arpa/inet.h&gt; //inet_addr #include&lt;unistd.h&gt; #include&lt;string.h&gt; #include&lt;stdlib.h&gt; int main(int argc , char *argv[]) { int socket_desc , new_socket , c, valread; struct sockaddr_in server, client ; char *message; char buffer[1024] = {0}; char *hello = "Hello from server"; //Create socket socket_desc = socket(AF_INET , SOCK_STREAM , 0); if (socket_desc == -1) { printf("Could not create socket"); } //Prepare the sockaddr_in structure server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons( 8888 ); //Bind if( bind(socket_desc,(struct sockaddr *)&amp;server , sizeof(server)) &lt; 0) { puts("bind failed"); } puts("bind done"); //Listen listen(socket_desc , 3); //Accept and incoming connection puts("Waiting for incoming connections..."); c = sizeof(struct sockaddr_in); new_socket = accept(socket_desc, (struct sockaddr *)&amp;client, (socklen_t*)&amp;c); if (new_socket&lt;0) { perror("accept failed"); } puts("Connection accepted\n"); valread = read(new_socket, buffer, 1024); printf("%s\n", buffer); send(new_socket, hello, strlen(hello),0); printf("Socket: Sent data!\n"); write(new_socket, "Some message", 1024); return 0; } Whenever I run the server and the client, I am able to connect them and send data to the server but the response to be sent back cannot be decoded by the client and gives me the following traceback call... Sending "This is the message. It will be repeated." Traceback (most recent call last): File "pythonclient.py", line 35, in &lt;module&gt; client_program() File "pythonclient.py", line 25, in client_program text += data.decode().strip() UnicodeDecodeError: 'utf-8' codec c…
downvote count: 1
favorite count: 0
type: Question
tagged with: sockets
has answer: http://stackoverflow.com/a/47196053
has comment: http://stackoverflow.com/comment/81339385
tagged with: python

security
tags question: http://stackoverflow.com/q/47104413
tags question: http://stackoverflow.com/q/47106792
tags question: http://stackoverflow.com/q/47143368
tags question: http://stackoverflow.com/q/47093717
tags question: http://stackoverflow.com/q/47209205
type: Tag
tag name: security

http://stackoverflow.com/comment/81186732
type: Comment
type: QuestionComment
score: 0
has text: To the first comment, so sorry. First/last/ID are student info, could be anything, i.e. John Smith 87. Parameters are for number of students and grades per student you'll be entering, as well as the counters for both. If the code is really redundant, it's because I'm completing assignments for an intro course -- so it's part professor requirements (e.g. have to have 3 functions for this, have to use parameters, etc.), part me not having complete command over the code.
comment on: http://stackoverflow.com/q/47118232

http://stackoverflow.com/q/47202138
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81388177
score: 0
has comment: http://stackoverflow.com/comment/81352869
tagged with: python
has comment: http://stackoverflow.com/comment/81352724
tagged with: paramiko
answer count: 0
has title: Python script timeouts while uploading to an ftp server
upvote count: 1
type: UnansweredQuestion
has body: I'm creating an csv file and uploading it to a ftp server. So the upload includes paths of multiple companies on that ftp server. like : COMANY1/FOO/BAR But for some companies at the end I get this traceback: Traceback (most recent call last): File "exporter.py", line 117, in &lt;module&gt; Exporter().run() File "exporter.py", line 115, in run self.upload(file, vendor['ftp_path'], filename) File "exporter.py", line 78, in upload sftp.chdir(dir) File "/home/johndoe/exports/daily/venv/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 580, in chdir if not stat.S_ISDIR(self.stat(path).st_mode): File "/home/johndoe/exports/daily/venv/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 413, in stat t, msg = self._request(CMD_STAT, path) File "/home/johndoe/exports/daily/venv/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 730, in _request return self._read_response(num) File "/home/johndoe/exports/daily/venv/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 781, in _read_response self._convert_status(msg) File "/home/johndoe/exports/daily/venv/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 807, in _convert_status raise IOError(errno.ENOENT, text) IOError: [Errno 2] The requested file does not exist I think the stack trace refers to the ftp path, that it doesn't exists (but It does exist). But when I try to run that script on those exact same paths alone (that are causing the problem) it passes? So, its not a logical error, and those ftp paths do exist - but can it be due to some timeout occurring? Thanks, Tom Update: I call the method like this: self.upload(file, vendor['ftp_path'], filename) And the actual method that does the uploading: def upload(self, buffer, ftp_dir, filename): for dir in ftp_dir.split('/'): if dir == '': continue sftp.chdir(dir) with sftp.open(filename, 'w') as f: f.write(buffer) f.close() sftp.close()
downvote count: 1
has comment: http://stackoverflow.com/comment/81388620
has comment: http://stackoverflow.com/comment/81388135

http://stackoverflow.com/a/47257577
score: 0
has comment: http://stackoverflow.com/comment/81471109
has comment: http://stackoverflow.com/comment/81506912
has body: I too had the same issue, It got resolved by exporting env variable GOOGLE_APPLICATION_CREDENTIALS with a value pointing to the path of your bucket credentials JSON file eg. export GOOGLE_APPLICATION_CREDENTIALS=/Users/myuser/Downloads/googleCredentials.json This command basically sets default account credentials. This Hope it helps you too.
type: Answer
answers question: http://stackoverflow.com/q/47180349

http://stackoverflow.com/comment/81120349
comment on: http://stackoverflow.com/q/47085156
score: 0
type: Comment
type: QuestionComment
has text: This actually as someone else linked:http://www.radford.edu/~nokie/classes/360/dp-rod-cutting.html

http://stackoverflow.com/q/47102518
has body: I have a dictionary of form myNestedDict=collections.defaultdict(dict) with example data: {'509582':{'509533': 65.499}, '509583':{'509534': -35.499},{'509568': -325.499}, '509584':{'509576': 0},{'509576': -1337} } And I am trying to get it to return both keys associated with the n smallest per value. So for this example if I am looking for 2 smallest: heapq.nsmallest(2, myNestedDict, key=???) I would like to return the dictionary: {'509584':{'509576': -1337}, '509583':{'509568': -325.499} } or,I actually don't really need the value anymore so it could return a non-nested dictionary if easier: {'509584':'509576', '509583':'509568'} As you can see, I can't figure out a proper key design for the heapq.nsmallest to sort on the innermost value. Any help hugely appreciated. Thanks NOTE - this dictionary is many millions of records, so efficiency is important. edit - this right here is what I have that actually runs, but its sorting on the first key only, I need to sort on the innermost value. note, they say itemgetter is way faster that lambda for this multi-million sized dictionary heapq.nsmallest( 2, myNestedDict.items(), key=itemgetter(0) )
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/81155549
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81155451
has comment: http://stackoverflow.com/comment/81155511
upvote count: 0
has comment: http://stackoverflow.com/comment/81155241
has comment: http://stackoverflow.com/comment/81155376
has comment: http://stackoverflow.com/comment/81155453
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81155385
has comment: http://stackoverflow.com/comment/81155555
type: Question
has comment: http://stackoverflow.com/comment/81155804
tagged with: python
has title: heapq.nsmallest on nested dictionary innermost value
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47116895
tagged with: dictionary

http://stackoverflow.com/a/47118495
has body: You need to use {0:.xf} where 0 is the argument number and x is the number of digits you want. &gt;&gt;&gt; print "{0:.3f} something".format(2.234234239) &gt;&gt;&gt; 2.234 something Please go through the documentation for more formatting details.
answers question: http://stackoverflow.com/q/47118454
type: Answer
has comment: http://stackoverflow.com/comment/81187066
has comment: http://stackoverflow.com/comment/81187051
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81332032
has text: Okay, why do you need an additional function to do the increasing and decreasing?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47191296
type: QuestionComment

http://stackoverflow.com/a/47203045
answers question: http://stackoverflow.com/q/47202528
has comment: http://stackoverflow.com/comment/81354700
has comment: http://stackoverflow.com/comment/81355291
downvote count: 0
score: 1
upvote count: 1
has body: I'd suggest using *args (or, well, call it *points possibly) and making the user unpack his points on his end. This allows you to call f(point), f(point1, point2, point3), or f(*list_of_points), with all three options working fine and you can simply do: def f(*points): ... for point in points: do_pointy_stuff(point) ...which is similar to g2 but without hacky isinstance checks which would fail if someone decided to throw in a tuple or something instead. However, there is a minor potential pitfall here - the user must knowingly unpack his lists of points. If you don't pay attention when using a single argument, you may pass a *[points] rather than a *list of points, which would result in the function treating each coordinate as a separate argument in itself and most likely throwing an error.
type: Answer

http://stackoverflow.com/q/47214877
tagged with: pandas
score: 3
upvote count: 3
linked to: http://stackoverflow.com/q/5036700
has title: Is there a way to iterate through a list and return variables named after its contents?
favorite count: 0
has answer: http://stackoverflow.com/a/47215022
type: Question
answer count: 2
tagged with: python
type: UnansweredQuestion
has body: I've got a pandas dataframe organized by date I'm trying to split up by year (in a column called 'year'). I want to return one dataframe per year, with a name something like "df19XX". I was hoping to write a "For" loop that can handle this... something like... for d in [1980, 1981, 1982]: df(d) = df[df['year']==d] ... which would return three data frames called df1980, df1981 and df1982. thanks!
has answer: http://stackoverflow.com/a/47215617
downvote count: 0
linked to: http://stackoverflow.com/q/1550479

http://stackoverflow.com/comment/81285618
type: Comment
type: AnswerComment
has text: Hello iamsankalp89, Thanks for your response. I have tried your Xpath. The first returns the "SIRET" text, and the second returns the other row "data-actual" text. What I nedd is the row "SIRET" whith his values. Please read the updated questions. Thank you very much for your time and apologise for the late updated. Much appreciated.
score: 0
comment on: http://stackoverflow.com/a/47159565

http://stackoverflow.com/comment/81182422
type: QuestionComment
comment on: http://stackoverflow.com/q/47115809
has text: No reason for that, I want to make repl outside of specific interpreter. So infrastructure of web repl will be separate from interpreter. Interpreter will be like module, roughly speaking I can attach any interpreter I want to this web repl.
type: Comment
score: 0

http://stackoverflow.com/comment/81374331
score: 0
type: Comment
type: QuestionComment
has text: `re.sub(r'[\t\n\r\p]', '', text)`
comment on: http://stackoverflow.com/q/47212409

http://stackoverflow.com/comment/81126722
comment on: http://stackoverflow.com/q/47088598
score: 0
type: Comment
type: QuestionComment
has text: Look at the block below the if statement, it needs to be indented.

http://stackoverflow.com/q/47137053
tagged with: python
downvote count: 1
favorite count: 0
has body: My programe needs to have an input with two elements to proceed (an integer and a name) but if someone press the letter 'q' it has to be terminated. So far i manage to do that by pressing q and comma ('q,') but i want to remove the comma. It has to be only the letter q. My code so far is: dic={} while True: am, name=input('ΑΜ, Name: ').split(',') if am =='q': break else: AM = int(am) dic[AM]=name print(dic) print('Dictionary contents') for char in sorted(dic): print(char, dic[char]) How can i do this?
answer count: 1
has answer: http://stackoverflow.com/a/47137346
has comment: http://stackoverflow.com/comment/81223213
score: -1
has title: Input has to accept two elements but checks one element condition
type: Question
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/47169221
linked to: http://stackoverflow.com/q/41427362
has answer: http://stackoverflow.com/a/47169340
tagged with: python
has body: I'm trying to build a simple tkinter GUI window around my flask application for noobs in my office. I want the script to perform these tasks in the following order: Start the flask web server Open a tkinter GUI window with one button. When pressed, that button opens the app's index page (e.g. http://127.0.0.1:5000) Terminate the flask web server when the tkinter gui window is closed This is what I have so far but the app runs independently of the tkinter window and I must terminate the flask app using crtl+c before I even see the gui window: from flask_app import app from tkinter import tk import webbrowser class GUI: def __init__(self): app.run() self.btn = tk.Button(root, text='Open in Browser', command:self.open_browser_tab).pack() def open_browser_tab(self): webbrowser.open(url='http:127.0.0.1:5000', new=2) if __name__ == '__main__': root = tk.Tk() GUI(root) root.mainloop() So how can I run a process while the app's running?
has comment: http://stackoverflow.com/comment/81288405
has title: Run GUI concurrently with Flask application
tagged with: flask
upvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81288801
answer count: 2
accepted answer: http://stackoverflow.com/a/47169280
possible better answer: http://stackoverflow.com/a/47169340
score: 3
tagged with: user-interface
downvote count: 3
has answer: http://stackoverflow.com/a/47169280
has comment: http://stackoverflow.com/comment/81288662
favorite count: 0
type: Question
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/81288429

http://stackoverflow.com/q/47169767
type: Question
has body: I was wondering how to find only the first preceding sibling that matches a specific criterial (ie. class='a')? Right now when I run the search it finds all of the nodes that match. Here is an example of what I mean: tr class = 'a' tr class = 'b' tr class = 'b' tr class = 'a' tr class = 'b' tr class = 'a' tr class = 'b' tr class = 'b' tr class = 'b' For every instance of b I am trying to find the first preceding tr that has class 'a', but when I run the code it finds all of the preceding tr that have class 'a'. I also cannot use tr[1] because there are varying lengths of class 'b' below each class 'a'. Here is what I am entering: //tr[@class='b']/preceding-sibling::tr[@class='a'] I can post my actual code if needed, but I think this example says it all.
has answer: http://stackoverflow.com/a/47178514
has comment: http://stackoverflow.com/comment/81289319
tagged with: python
has comment: http://stackoverflow.com/comment/81291317
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81289805
has comment: http://stackoverflow.com/comment/81290034
answer count: 1
has comment: http://stackoverflow.com/comment/81290123
tagged with: selenium-webdriver
has title: finding 'only' the first preceding sibling that matches
score: 0
tagged with: selenium
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81314391
type: QuestionComment
comment on: http://stackoverflow.com/q/47181660
score: 0
has text: So, `X` and `Y` are 10 elems, but PX and PY are 10000?
type: Comment

http://stackoverflow.com/comment/83780442
type: Comment
comment on: http://stackoverflow.com/a/47114731
type: AnswerComment
has text: can you elobrate? of which scirpt? cv2/__init__.py?
score: 1

http://stackoverflow.com/comment/81164897
type: Comment
score: 0
type: QuestionComment
has text: Are you asking about regular expression objects specifically or is it a general question. You always have the option of subclassing an object and defining or overwriting its [comparison methods](https://docs.python.org/3/reference/datamodel.html#object.__lt__) to have the behaviour you need/want.
comment on: http://stackoverflow.com/q/47107231

http://stackoverflow.com/comment/81239200
comment on: http://stackoverflow.com/a/47144579
score: 0
type: Comment
type: AnswerComment
has text: I'm getting: `AttributeError: 'str' object has no attribute 'decode'`

http://stackoverflow.com/a/47185064
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47184806
answers question: http://stackoverflow.com/q/47184806
has comment: http://stackoverflow.com/comment/81321192
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: itertools does not deal with epsilon elements in your sets; you will need to code that as a separate clause in each set. To each set, add a key element, such as epsilon: None; in your comprehension expressions, you'll need to add if clauses to ignore any such element, rather than including it in the output. Note that zip will no longer serve, because you want to generate entries of different lengths. Another possibility is to zip the lists, including the epsilon elements, but write an expression to exclude those elements from the zipped list's members. Can you take it from there?

http://stackoverflow.com/a/52910576
downvote count: 1
has comment: http://stackoverflow.com/comment/129847584
upvote count: 34
accepted answer of: http://stackoverflow.com/q/47097293
has comment: http://stackoverflow.com/comment/111074039
has comment: http://stackoverflow.com/comment/111079698
answers question: http://stackoverflow.com/q/47097293
type: Answer
score: 33
has body: From the Django docs: Because migrations are stored in version control, you’ll occasionally come across situations where you and another developer have both committed a migration to the same app at the same time, resulting in two migrations with the same number. Don’t worry - the numbers are just there for developers’ reference, Django just cares that each migration has a different name [emphasis added].
type: AcceptedAnswer

http://stackoverflow.com/q/47119489
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
score: 0
has body: I am using the following command for clearing the Recycle Bin in Python 3.3 using JetBrains Pycharm 5.0.1 IDE. import winshell winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=False) But I'm getting a No module named winshell error. Please help.
tagged with: python-3.3
tagged with: python
has answer: http://stackoverflow.com/a/52009576
type: Question
has title: Import WinShell command not working in Python 3.3
tagged with: pycharm
type: UnansweredQuestion

particles
tags question: http://stackoverflow.com/q/47129197
type: Tag
tag name: particles

http://stackoverflow.com/a/47106736
has comment: http://stackoverflow.com/comment/81164813
answers question: http://stackoverflow.com/q/47105812
score: 0
has comment: http://stackoverflow.com/comment/81164157
has comment: http://stackoverflow.com/comment/81164778
has body: I'm not sure that I'm understanding your question well. So, the problem is if you have some validation errors they appear in your "errors" div, only if you hover them? If it is, then it is related to your css or javascript. Check your scripts and css files. Maybe somewhere you trigger your .field-error element. About modal appearence. Well, it is about your AJAX request. In your code, you will get showing your modal anyway while the HTTP Request will get answer with 200 code. It means even if you will not have valid form you sending back JsonResponse with some msg and its bringing back to your page, which means your script will trigger success every time and that's why your modal is appearing. Instead of just sending some JsonResponse({"msg": "Error"}), try to use it also to handle error. function addNotifyEmail(e){ var notifyEmailForm = $("#notify-email-form"); var thanksModal = $("#thanks"); $.ajax({ type: 'POST', url: '/notify-email/add/', data: notifyEmailForm.serialize(), success: function(res){ if(res.msg !== "Error") { thanksModal.modal('show'); } } })} Take a look here for more details about handling error in AJAX requests.
type: Answer

http://stackoverflow.com/comment/81171386
comment on: http://stackoverflow.com/q/47110317
type: Comment
type: QuestionComment
has text: python3, and I remove the encoding='utf-8', it's working, but I was wondering how to remove the words that contain non English letters.
score: 0

http://stackoverflow.com/comment/81362543
type: AnswerComment
comment on: http://stackoverflow.com/a/47206839
has text: The result isn't. It is if you convert it to hex.
type: Comment
score: 0

http://stackoverflow.com/comment/81248302
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47066476
score: 0
has text: https://stackoverflow.com/questions/30996401/error-handling-in-python-mysql

multi-gpu
type: Tag
tags question: http://stackoverflow.com/q/47090096
tag name: multi-gpu

http://stackoverflow.com/q/47137356
score: 0
has body: I'm attempting to build a very simple Flask application using just Flask and Python. No databases or other plugins. The application runs perfectly fine on my local machine and I can navigate without errors, but when I deploy to Heroku, I receive a 404 Not Found error for any page that I try to visit, including the index. Here's my site's layout: Site Layout mbtaCrTracker.py is the root of my app. Here's what it currently looks like: from mbtaCrTracker import app from mbtaCrTracker import views app.run(host='0.0.0.0', debug=True) Here's my _ init _.py: from flask import Flask app = Flask(__name__) Here's my views.py: from flask import render_template, request, redirect from mbtaCrTracker import app from getTrainInfo import getTrainInfo @app.route('/') @app.route('/index') def index(): return render_template('index.html') @app.route('/map', methods=['GET']) def findTrain(): line = request.args.get('line') direction = request.args.get('direction') coords = getTrainInfo(line, direction) return render_template('map.html', coords=coords) Here's my Procfile: web: gunicorn mbtaCrTracker:app --log-file=- I think everything is set up properly because I'm able to run the app locally without any issues. When I deploy to Heroku, I can see that the site is Up, not Crashed, and I'm not receiving any server errors, just Not Found errors. It's almost as if my routes aren't working or something like that. Here's what I see in my Heroku logs when I try to access my site's homepage: 2017-11-06T12:23:17.717474+00:00 heroku[web.1]: Starting process with command `gunicorn mbtaCrTracker:app --log-file=-` 2017-11-06T12:23:19.795333+00:00 app[web.1]: [2017-11-06 12:23:19 +0000] [4] [INFO] Starting gunicorn 19.7.1 2017-11-06T12:23:19.796263+00:00 app[web.1]: [2017-11-06 12:23:19 +0000] [4] [INFO] Listening at: http://0.0.0.0:43494 (4) 2017-11-06T12:23:19.796405+00:00 app[web.1]: [2017-11-06 12:23:19 +0000] [4] [INFO] Using worker: sync 2017-11-06T12:23:19.800312+00:00 app[web.1]: [2017-11-06 …
has comment: http://stackoverflow.com/comment/81228505
accepted answer: http://stackoverflow.com/a/47137996
has answer: http://stackoverflow.com/a/47137996
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81226332
has comment: http://stackoverflow.com/comment/81226258
answer count: 1
upvote count: 1
tagged with: python
tagged with: flask
downvote count: 1
has comment: http://stackoverflow.com/comment/81224469
has title: 404 Error when running Flask app on Heroku
tagged with: heroku
type: AnsweredQuestion

http://stackoverflow.com/q/47206529
has comment: http://stackoverflow.com/comment/81362972
tagged with: django-models
tagged with: django-forms
has body: I want to change select option's label by user status. my model is class BookCategory(model): label_1 = char label_2 = char def __unicode__(self): #something here? class Book(model): name = char categoey = models.Foreignkey(BookCategory) BookCategory is used in createview for new book, and the page has modelform, textinput for book.name and choices for book.catgory. My goal is if user type==1: =>display category's label_1 if user type==2: =>display category's label_2 I know "__unicode__" can display instance's value, but I want to know change its field by user's status. Anyone knows the solution? add: my view and modelform are so simple. view is class CreateBook(CreateView): template_name = "template.html" model = Book form_class = BookForm success_url = "success_url" def form_valid(self, form): if form.is_valid(): form.save() and form is class LessonForm(ModelForm): class Meta: model = Book fields = ('name', 'category', ) widgets = { 'name': forms.Textarea(attrs={'class': 'text_box'}), 'category': forms.Textinput(attrs={'class': 'select_box'}), }
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47207353
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/81362163
answer count: 1
downvote count: 0
tagged with: django
tagged with: python
has title: django how to change __str__ label by user status?
has answer: http://stackoverflow.com/a/47207353
type: AnsweredQuestion

http://stackoverflow.com/comment/81232332
comment on: http://stackoverflow.com/q/47141242
type: QuestionComment
has text: We need a little more. Show code of things that you tried. Tell what's going wrong? Downloading large files with HTTP should be no problem.
score: 0
type: Comment

http://stackoverflow.com/a/47150028
answers question: http://stackoverflow.com/q/47143233
score: 1
type: Answer
has body: This might be due to you have used : &lt;div class="footer"&gt; Use "&lt;footer&gt;" tag insted of this. Might it will work..
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81249872

http://stackoverflow.com/a/71090558
score: 4
has body: Another solution is to set_index with "name" and explode "items". Then cast the resulting Series to a DataFrame. s = df.set_index('name')['items'].explode() out = pd.DataFrame(s.tolist(), index=s.index).reset_index() Output: name a b 0 this 2 1 1 this 4 3 2 that 2 1 3 that 4 3 It appears, set_index + explode + DataFrame is faster (at least for OP's data) than all the other options given in the other answers. %timeit -n 1000 out = pd.concat(df['items'].apply(pd.DataFrame).tolist(), keys=df["name"]).reset_index() %timeit -n 1000 ab = pd.DataFrame.from_dict(np.concatenate(df['items']).tolist()); lens = df['items'].str.len(); rest = df.drop('items', axis=1).iloc[df.index.repeat(lens)].reset_index(drop=True); out = ab.join(rest) %timeit -n 1000 out = pd.concat([pd.DataFrame(df1.iloc[0]) for x,df1 in df.groupby('name')['items']],keys=df.name).reset_index().drop('level_1',axis=1) %timeit -n 1000 s = df.set_index('name')['items'].explode(); out = pd.DataFrame(s.tolist(), index=s.index).reset_index() 2.5 ms ± 29.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) 1.75 ms ± 12.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) 3.82 ms ± 433 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) 1.46 ms ± 68 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/47148683

error-handling
tags question: http://stackoverflow.com/q/47165343
tags question: http://stackoverflow.com/q/47172634
tags question: http://stackoverflow.com/q/47119868
tag name: error-handling
tags question: http://stackoverflow.com/q/47103557
tags question: http://stackoverflow.com/q/47069054
tags question: http://stackoverflow.com/q/47193139
tags question: http://stackoverflow.com/q/47118721
tags question: http://stackoverflow.com/q/47107665
type: Tag
tags question: http://stackoverflow.com/q/47154587

http://stackoverflow.com/a/47195850
answers question: http://stackoverflow.com/q/47195778
has comment: http://stackoverflow.com/comment/81376436
type: Answer
has comment: http://stackoverflow.com/comment/81429842
score: 0
has comment: http://stackoverflow.com/comment/81354939
has comment: http://stackoverflow.com/comment/81377018
has comment: http://stackoverflow.com/comment/81346262
has comment: http://stackoverflow.com/comment/81376606
has body: Use your proxy authentication to handle the proxy with requests, not the session auth. Set the proxies with user:pass: proxies = { "http": "user:pass@your_proxy:port", "https": "user:pass@your_proxy:port", }

http://stackoverflow.com/q/47139515
answer count: 4
has answer: http://stackoverflow.com/a/76595661
score: 0
has comment: http://stackoverflow.com/comment/81228886
has body: Hey I have the following problem. I have a large parameter space. In my case I have like 10 dimensions. But to simplify lets assume I have 3 variables x1,x2 and x3. They are discrete numbers from 1 to 10. Now i create all possible parameter combinations and want to use them for postprocessing. In my real case that are too many combinatons. So I want to do a quasi random sequence search to reduce the search space. But the the combinations in the search space should cover it as good as possible. (uniform distributed). I want to prevent the parameter combination to Cluster in the search space, it should Cover the whole search space as good as possible. I need that to find preferences of the parameter combiantions in the processing of the parameters. There a many approaches to do that, like Haton, Hammersley or Sobol sequences. But they are not working for discrete numbers. One package which do quasi random sequences is chaospy. If i round the numbers of the sequences, variable numbers of each variable will occur more than once in the different variable combinations. That is not what I want. I want that every variable number only occurs Once and the variables are uniformly distributed in the search space. Is there a possibility to create from the beginning a random multi dimensional set of variable combination, in which every variable just appears once? For example In a two dimensional grid 10x10 one possible combination would be the diagonal. Of course in 3 dimensions I would need 100 combinations to Cover all Parameter value, Lets have an simplified example with three variables from 1-10 with Sobol Sequence: import numpy as np import chaospy as cp #Create a Joint distributuon of the three varaibles, which ranges going from 1 to 10 distribution2 = cp.J(cp.Uniform(1, 10),cp.Uniform(1, 10),cp.Uniform(1, 10)) #Create 10 numbers in the variable space samplesSobol = distribution2.sample(10, rule="S") #Transpose the array to get the variable combinations in subarrays sobolPo…
has comment: http://stackoverflow.com/comment/81232452
has comment: http://stackoverflow.com/comment/81231863
has answer: http://stackoverflow.com/a/47141252
has answer: http://stackoverflow.com/a/55815126
tagged with: scipy
favorite count: 0
has comment: http://stackoverflow.com/comment/81230181
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81228690
has answer: http://stackoverflow.com/a/47141414
upvote count: 2
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/81229441
has title: Python: Alternative to quasi random sequences

http://stackoverflow.com/comment/81265134
has text: OK, I put everything I have to my answer, and made a correction in the code. I hope, it helps.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47156710

http://stackoverflow.com/comment/81150763
score: 0
type: Comment
has text: I don't think you need the `.div` part.
type: QuestionComment
comment on: http://stackoverflow.com/q/47100398

http://stackoverflow.com/comment/81249158
type: Comment
score: 0
has text: What is `ade` supposed to be?
type: QuestionComment
comment on: http://stackoverflow.com/q/47149662

join
tags question: http://stackoverflow.com/q/47205555
type: Tag
tag name: join
tags question: http://stackoverflow.com/q/47144979
tags question: http://stackoverflow.com/q/47166545
tags question: http://stackoverflow.com/q/47147332

http://stackoverflow.com/comment/81324968
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47155431
score: 2
has text: Right, but in these cases, the first step in debugging should be `conda update pyarrow` (or `pip install -U`). We are not yet at a stage of development where we can do bugfix-only releases of older major versions of the library. There's really no point chasing down a bug in an outdated version of a rapidly evolving software project if the bug does not exist in the latest release

http://stackoverflow.com/q/47112902
has title: Install PyQt and SIP for Python3.6 on Windows7
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81281482
has comment: http://stackoverflow.com/comment/81360279
has comment: http://stackoverflow.com/comment/81189405
tagged with: python
has comment: http://stackoverflow.com/comment/81318670
tagged with: python-sip
has comment: http://stackoverflow.com/comment/82078172
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/81360390
has comment: http://stackoverflow.com/comment/81284716
has comment: http://stackoverflow.com/comment/81241377
has comment: http://stackoverflow.com/comment/81281243
tagged with: qt
has comment: http://stackoverflow.com/comment/81275112
has comment: http://stackoverflow.com/comment/81281348
score: 0
has comment: http://stackoverflow.com/comment/81285467
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/81281426
has comment: http://stackoverflow.com/comment/81259132
has body: I found TONS of answers online but nothing helped. I found this question: How to install SIP &amp; PyQT on windows 7 Which kind of helped but I got stuck on this part: (Step I Got Stuck On) After pasting "C:\Qt\Qt5.8.0\5.8\msvc2015\bin\qtenv2.bat"into my cmd it said that The system cannot find the path specified. Also, I tried skiping ahead to see if the further steps work for me. The command nmake didn't work either. What am I missing? I'm using: Windows7 Python3.6 sip4.19.4 PyQt5.9.1 VisualStudio2017 Also, please don't mark this question as a duplicate of the question linked above as I did read it but I had troubles with doing what the answer said.
linked to: http://stackoverflow.com/q/32054021
type: Question
has comment: http://stackoverflow.com/comment/81242986
has comment: http://stackoverflow.com/comment/81241955
has comment: http://stackoverflow.com/comment/81284412
answer count: 0
has comment: http://stackoverflow.com/comment/81274608
has comment: http://stackoverflow.com/comment/81284279

http://stackoverflow.com/a/47170444
has comment: http://stackoverflow.com/comment/81290707
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47170280
has body: np.squeeze takes an axis argument so you can pass that rather than iterate: In [11]: a = np.arange(9).reshape(3, 3, 1) In [12]: a Out[12]: array([[[0], [1], [2]], [[3], [4], [5]], [[6], [7], [8]]]) In [13]: np.squeeze(a, -1) Out[13]: array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) You can also do multiple axis at once: In [21]: b = np.arange(9).reshape(3, 1, 3, 1) In [22]: b Out[22]: array([[[[0], [1], [2]]], [[[3], [4], [5]]], [[[6], [7], [8]]]]) In [23]: np.squeeze(b, (1, 3)) Out[23]: array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])

http://stackoverflow.com/comment/81162858
score: 0
comment on: http://stackoverflow.com/a/47104433
type: Comment
has text: it's IMPORTANT for the href links to be from the class called `"signed button"`. - also, The website has a tab below that reads "Load More", so it's not picking up everything unless the end user hits "Load More". How can I surpass this?
type: AnswerComment

http://stackoverflow.com/q/47208863
has title: Why do Chrome.exe and chromedriver.exe still appear in the computer's memory, despite using driver.close() and driver.quit()?
has body: The code I've written successfully does its part in crawling through a website with the appropriate date and time formatted in the URL, grabbing the table from the underlying HTML source code, and appending the results to a cache. This python file gets run several dozen times (there are many agent IDs whose info I need to grab); after the script runs, however, dozens of chrome.exe and chromedriver.exe instances still appear in the computer's memory (this is visible in the computer's "Resource Monitor.") Below is my code. I've used driver.quit() as well as driver.close() and even both together (with driver.close() coming first). Isn't the driver.quit() supposed to close the instances in the computer's system? Why are they appearing in the memory? Is there a solution to this issue? Please let me know if I can provide any further information. Thank you in advance. from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from datetime import datetime, timedelta import credentials_page def get_updated_url(agent_id_num): now = datetime.utcnow() today = datetime(now.year, now.month, now.day) yesterday = today - timedelta(days=1) previous_date_string = str(yesterday)[:10] return 'https://examplewebsite.com/agentId/'+agent_id_num+'/orderBy/ASC/startDate/'+previous_date_string+'%204:00%20AM/endDate/'+previous_date_string+'%2010:30%20PM' def login_entry(username, password, browser): # logs into website login_email = browser.find_element_by_id('UserName') login_email.send_keys(username) login_password = browser.find_element_by_id('Password') login_password.send_keys(password) submit_elem = browser.find_element_by_xpath("//button[contains(text(), 'Log in')]") submit_elem.click() def get_element(xpath, browser): # grabs element, turns it into needed table in raw HTML format table_of_interest = browser.find_element_by_xpath(xpath) # this has …
answer count: 1
tagged with: chromium
tagged with: python
favorite count: 0
score: 3
tagged with: python-2.7
upvote count: 3
tagged with: selenium
has answer: http://stackoverflow.com/a/47215446
has comment: http://stackoverflow.com/comment/81369486
has comment: http://stackoverflow.com/comment/81367972
type: Question
tagged with: selenium-chromedriver
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/81319977
type: AnswerComment
has text: Could you please explain why this is the answer, why a sleep is needed etc.. Also, you forgot a print
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47184663

http://stackoverflow.com/comment/81233581
type: AnswerComment
has text: add file_stem = file.split('/')[-1] inside the loop, then append [file_stem,MaxFF,Maxspikes] instead of [file,MaxFF,Maxspikes].
type: Comment
comment on: http://stackoverflow.com/a/47135657
score: 0

http://stackoverflow.com/a/47166926
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47158220
upvote count: 1
has body: To answer your first question, this is the correct way to catch exceptions. The caveat is that you need to know what exceptions the code inside the try block raises. In your case arduino.readline() will only raise an exception on a serial port issue. In other words you don't need to call raise yourself because that means it will always look like a failure. Using except Exception as e allows you to handle specific exceptions that code in the try block might raise. This way you can respond in different ways. For example you might have different response for different errors: except OSError as err: print("OS error: {0}".format(err)) except ValueError: print("Could not convert data to an integer.") except: print("Unexpected error:", sys.exc_info()[0]) raise
has comment: http://stackoverflow.com/comment/82144040
type: Answer

http://stackoverflow.com/a/47168344
upvote count: 1
has body: you can pass the port or label via the lambda: editmenu.add_command(label=list[x].device, command=lambda label=list[x].device:app.setPort(label)) You then just need to define setPort to accept the label as a parameter.
type: Answer
answers question: http://stackoverflow.com/q/47167874
score: 1
downvote count: 0

sl4a
tag name: sl4a
type: Tag
tags question: http://stackoverflow.com/q/47119348

http://stackoverflow.com/comment/81377689
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47214029
has text: Not sure if this helps, but this is some sample text. YOUNG COLIN Yeah. COSTELLO tells the Proprietor to takes three loaves of bread and some soup off the shelves and puts them in Colin's bag. COSTELLO Get him three loaves of bread. And a couple of half gallons of milk. And some soup. He goes over to the fridge and puts two half gallons of milk in the bag. Some soup. Costello turns to Colin.

http://stackoverflow.com/q/47103483
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47103555
has comment: http://stackoverflow.com/comment/81157470
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81157331
has title: Tuple index out of range python
upvote count: 2
score: 2
has body: start = [0,0,0,0,0,0,0,0,0] def print_board(turn, board): print(turn + " turn" + "\n {}{}{}\n {}{}{}\n {}{}{}".format(board)) current_turn = "your" print_board(current_turn, start) The above stuff gives Traceback (most recent call last): File "so.py", line 5, in &lt;module&gt; print_board(current_turn, start) File "so.py", line 3, in print_board print(turn + " turn" + "\n {}{}{}\n {}{}{}\n {}{}{}".format(x for x in board)) IndexError: tuple index out of range I've got 9 values in my tuple or list and 9 curly brackets. Right?
has answer: http://stackoverflow.com/a/47103575
has answer: http://stackoverflow.com/a/47103526
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81158212
favorite count: 0
type: Question

http://stackoverflow.com/q/47192230
has title: Lines in a bar chart Matplotlib
tagged with: python-3.x
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47192407
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47192407
tagged with: python
has comment: http://stackoverflow.com/comment/81333904
has comment: http://stackoverflow.com/comment/81333890
type: Question
has body: My goal is to have a bar chart represent allocated hours. The allocated hours should be represented as tot_hrs above the sched_hrs. So, a line at 7 should be right above bar of 1 at 'Blairstone FL'. However, the plot comes out with three lines 7, 8, and 9 all above 'Blairstone FL', 'Bonifay FL', and 'Calhoun FL'. The main issue exists the code below for tt in range(len(service_areas)):. Any help is much appreciated. sched_hrs=[1, 2, 3] tot_hrs=[7, 8, 9] columnstart = -0.5 columnend = 0.5 service_areas = ['Blairstone FL', 'Bonifay FL', 'Calhoun FL'] plt.figure(figsize=(len(service_areas) + 4.5, 4)).canvas.set_window_title('Click') ind = np.arange(len(service_areas)) width = 0.18 plt.bar(ind, sched_hrs,width, label='Scheduled Hours', color='green', align="center") for tt in range(len(service_areas)): plt.plot([columnstart, columnend], [tot_hrs, tot_hrs], color='#228B22', linestyle='-', linewidth=2) columnstart +=1 columnend +=1 plt.xticks(ind, service_areas, rotation=10) plt.yticks(np.arange(0, max(1, max(tot_hrs) + 2), 1)) plt.title("Allocated Hours") plt.xlabel("Areas") plt.ylabel("Hours") plt.legend() plt.show()
answer count: 1
tagged with: bar-chart
downvote count: 0
upvote count: 1
score: 1
favorite count: 0

http://stackoverflow.com/comment/81110355
type: Comment
has text: There is an argument [`skip_header`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.genfromtxt.html) to skip N number of lines at the beginning
type: AnswerComment
score: 3
comment on: http://stackoverflow.com/a/47080538

http://stackoverflow.com/q/47100760
score: -2
has comment: http://stackoverflow.com/comment/81151756
has comment: http://stackoverflow.com/comment/81151837
tagged with: python
has answer: http://stackoverflow.com/a/47100932
upvote count: 0
downvote count: 2
has body: I've been struggling with this issue for quite some time now. Basically I want to automate a multiple choice test with 60 questions that has 4 radio types per question. The ID is static ;however the value changes for each option. I have coded a loop to handle the 60 questions ,and I want to click on the first radio option for every question ;however since the value changes dynamically it only works for the 1st question. Please help HTML &lt;input data-val="true" data-val-number="The field AnswerId must be a number." id="examResult_AnswerId" name="examResult.AnswerId" type="radio" value="62"&gt; while count &lt; 59: q1 = browser.find_element_by_id('examResult_AnswerId') q1.send_keys(62) q1 = browser.find_element_by_id('btnNext') q1.click() count += 1 HTML Code for test i want to automate My Python code
tagged with: dynamic
tagged with: automation
type: UnansweredQuestion
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/81151565
has comment: http://stackoverflow.com/comment/81152066
has title: Python selenium: iterate through radio buttons that have dynamic values for multiple choice exam
favorite count: 0
type: Question
tagged with: r-exams

http://stackoverflow.com/a/47102407
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47101613
has comment: http://stackoverflow.com/comment/81228634
has body: Something like this? df['state'] = np.where(df.place.str.contains('edit'), df.place, np.nan) df['region'] = np.where(df.place.str.contains('\('), df.place, np.nan) df.drop('place', 1, inplace =True) df['state'].ffill(inplace = True) df.set_index('state', inplace = True) region state Alabama[edit] NaN Alabama[edit] Auburn (something somethign) Alabama[edit] Florence (something somethign) California[edit] NaN California[edit] Angwin (something something) California[edit] Arcata (something something)
answers question: http://stackoverflow.com/q/47101613
type: Answer
has comment: http://stackoverflow.com/comment/81221596
has comment: http://stackoverflow.com/comment/81225171

http://stackoverflow.com/q/47105563
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47105896
has comment: http://stackoverflow.com/comment/81161921
has comment: http://stackoverflow.com/comment/81162234
has comment: http://stackoverflow.com/comment/81162362
score: 1
has comment: http://stackoverflow.com/comment/81161773
has comment: http://stackoverflow.com/comment/81161722
has comment: http://stackoverflow.com/comment/81161988
has comment: http://stackoverflow.com/comment/81161756
favorite count: 0
type: Question
has body: I've been told it's bad form to use locals() to dynamically create variables in Python. However, I'm writing a class (using Django and Wagtail), and I really do need these things to go in the class dict, a.k.a. the class statement's local variables, not in a separate data structure: class BlogPage(Page): for language in languages: locals()['body_' + language] = RichTextField(blank=True) I don't think I can set these after the class statement with setattr, either, because Django's metaclass processing will already have happened by then. Is there a better way?
has title: Better way to create class dict entries from a loop than locals()
tagged with: wagtail
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/81253379
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47151826
type: QuestionComment
has text: `conv3x3` is a function which expects two arguments, but, it can returns another function which just expects one argument. Is it explicit enough? Or I should write an answer with examples?

http://stackoverflow.com/a/62922356
downvote count: 1
has comment: http://stackoverflow.com/comment/133369653
type: Answer
answers question: http://stackoverflow.com/q/47223143
has comment: http://stackoverflow.com/comment/120572981
has body: You can mock a function of same module using mock.patch and refering this module as __main__ code.py from unittest.mock import patch def sum(): print("called method sum") pass def call_sum(): sum() def return_mock(): print("I'm a mocked method") return True with patch('__main__.sum', return_value=return_mock()) as mock_test: call_sum() mock_test.assert_called_once() # assure that mocked method was called, not original. You could also use the path of lib (my_project.code.sum) instead of __main__.sum.
has comment: http://stackoverflow.com/comment/120585743
has comment: http://stackoverflow.com/comment/120598948
has comment: http://stackoverflow.com/comment/120585785
score: 6
upvote count: 7

http://stackoverflow.com/comment/81282757
has text: Is this the only way to append to values? Essentially my df only has 1 row.
type: Comment
comment on: http://stackoverflow.com/a/47166438
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81313454
comment on: http://stackoverflow.com/a/47177558
type: Comment
score: 0
type: AnswerComment
has text: @ArneRecknagel it's a matter of choice, since you don't address it anymore in your code besides your lambda definition - both options are clear enough.

http://stackoverflow.com/comment/81100485
type: QuestionComment
comment on: http://stackoverflow.com/q/47075874
type: Comment
has text: In case it helps, I am rather new to web programming and, therefore am not using Javascript or Ajax yet. As a result, I end up doing things in Django that aren't exactly the way I want but get the job done. I figure I can clean them up in the longer term, once I've got my base app done. For example, in your case, I might develop a template that presents a 'select Empresa' screen, bring the result back to Django and then follow up with a screen showing the Filial. It's not perfect but it gets the job done as I'm learning the technologies.
score: 0

http://stackoverflow.com/comment/81179384
comment on: http://stackoverflow.com/q/47114800
type: QuestionComment
has text: share your data with us, e.g df.head().to_dict(). Nan is normally replaced with fillna: http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.fillna.html
type: Comment
score: 0

http://stackoverflow.com/a/47181170
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: How about using: dist = 2 results = [] for sub_dict in d.values(): sub_dict_keys = sorted(sub_dict.keys()) l = [] for k in sub_dict_keys: if l and k &gt; prev_key + dist: results.append(l) l = [] l.extend(sub_dict[k]) prev_key = k if l: results.append(l) print(results) It's a lot cleaner with no need to import modules, but doesn't work well if any of the lists are empty (i.e. they won't get appended to result).
answers question: http://stackoverflow.com/q/47179055

http://stackoverflow.com/comment/81166736
has text: There is no `d["results"]` in the second JSON.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47108188
score: 0

http://stackoverflow.com/q/47161480
has comment: http://stackoverflow.com/comment/81272703
has title: converting String that contains Letters to Datetime
tagged with: datetime
has answer: http://stackoverflow.com/a/47161719
tagged with: python
has body: i got a string that looks like : 2012-10-01 13:00:00 +0000 UTC i want to change it to DateTime format in python, I've tried this data['dt']=pd.to_datetime(data['dt']) and got the following errors: 1- TypeError: Unrecognized value type: &lt;class 'str'&gt; 2- ValueError: Unknown string format also tried to add format='%d%b%Y %H:%M' but got errors number 1 and ValueError: time data '2012-10-01 12:00:00 +0000 UTC' does not match format '%d%b%Y %H:%M' (match)
has comment: http://stackoverflow.com/comment/81272668
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47161682
answer count: 2
has comment: http://stackoverflow.com/comment/81272689
possible better answer: http://stackoverflow.com/a/47161719
tagged with: pandas
has answer: http://stackoverflow.com/a/47161682
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/52374927
type: AcceptedAnswer
type: Answer
has body: I recently made the same mistake (using hdbscan), and it was the cause of some 'strange' results. For example, the same point would sometimes be included in a cluster, and sometimes be flagged as a noise point. "How can this be?", I kept wondering. It turned out to be because I was passing lat/lon directly and not converting to radians first. The OP's self-supplied answer is correct, but short on details. One could, of course, just multiply the lat/lon values by &pi;/180, but—if you're already using numpy anyway—the simplest fix is to change this line in the original code: db = DBSCAN(eps=epsilon, ... metric='haversine').fit(X) to: db = DBSCAN(eps=epsilon, ... metric='haversine').fit(np.radians(X))
answers question: http://stackoverflow.com/q/47206563
score: 2
accepted answer of: http://stackoverflow.com/q/47206563
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/81249866
type: QuestionComment
comment on: http://stackoverflow.com/q/47150077
score: 0
type: Comment
has text: Also, you better do `response.get('reports', {})` or you'll get an `AttributeError`...

http://stackoverflow.com/a/47162897
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47134358
type: Answer
has body: Assuming you are using this library? https://github.com/cloudfoundry-community/cf-python-client, if not please clarify as your question leaves ambiguity. The docs state that each entity manager exposes a generic _create method, and the App Entity manager does not look to expose a specific push method. You may be able to use the generic _create and pass a dict defining the application. But I would suggest looking at the CF-CLI or Java Client which are both maintained by cloud foundry community, and much more well documented.
answers question: http://stackoverflow.com/q/47134358
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47184884
downvote count: 0
tagged with: travis-ci
favorite count: 0
type: Question
score: 3
has body: I have a PR build that's failed and another build that's passed successfully. The only difference between them is one is running in Ubuntu "trusty" and the other in "precise". I think when this PR was submitted the default was "precise" but the new default is "trusty". If I try to restart the build it seem to retain the old default even though it's not specified in ".travis.yml". Is there a way to restart a build and have it use the latest config defaults? Specifically, the failed build reports "precise" as the distribution used in the "View config", but it's not being explicitly set and the new default should be "trusty". A "restart" doesn't change the config.
tagged with: python
has title: Restarting Travis CI build using new defaults
answer count: 0
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/q/47145201
tagged with: python
accepted answer: http://stackoverflow.com/a/47146469
has answer: http://stackoverflow.com/a/47146469
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81243279
tagged with: pandas-groupby
tagged with: pandas
score: 1
tagged with: python-datetime
has comment: http://stackoverflow.com/comment/81243239
downvote count: 0
answer count: 1
has body: I got a list of dynamic values (e.g. observations). It records all value changes of an entity (e.g. display). df +----+---------------------+-----------------+---------+ | | time | display_index | value | |----+---------------------+-----------------+---------| | 0 | 2017-11-06 13:00:00 | 1 | val1 | | 1 | 2017-11-06 14:00:00 | 1 | val2 | | 2 | 2017-11-06 15:00:00 | 1 | val1 | | 3 | 2017-11-06 13:30:00 | 2 | val3 | | 4 | 2017-11-06 14:05:00 | 2 | val4 | | 5 | 2017-11-06 15:30:00 | 2 | val1 | +----+---------------------+-----------------+---------+ Now I got a second list of timestamps and I'm interested in the values that each display has shown at that time. Note that the first timestamp (13:00) for display_index 2 is before any value is even known for that one (first record is 13:30). df_times +----+---------------------+-----------------+ | | time | display_index | |----+---------------------+-----------------| | 0 | 2017-11-06 13:20:00 | 1 | | 1 | 2017-11-06 13:40:00 | 1 | | 2 | 2017-11-06 13:00:00 | 2 | | 3 | 2017-11-06 14:00:00 | 2 | +----+---------------------+-----------------+ I tried calculating the period between both timestamps and chose the observation with the minimum value for that period: df_merged = df_times.merge(df, on='display_index', how='outer', suffixes=['','_measured']) df_merged['seconds'] = (df_merged.time_measured - df_merged.time).astype('timedelta64[s]') df_merged['seconds'] = df_merged['seconds'].apply(math.fabs) df_merged = df_merged.sort_values('seconds').groupby(['time', 'display_index'], as_index=False).first() print(tabulate(df_merged, headers='keys', tablefmt='psql')) +----+---------------------+-----------------+---------------------+---------+-----------+ | | time | display_index | time_measured | value | seconds | |----+---------------------+-----------------+---------------------+---------+-----------| | 0 | 2017-11-06 13:00:00 | 2 | 2017-11-06 13:30:00 | val3 | 1800 | | 1 | 2017-11-06 13:20:00 | 1 | 2017-11-06 13:00:00 | val1 |…
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81243320
has title: Pandas: get observations by timestamp

http://stackoverflow.com/a/47128027
has body: This shows how to copy a whole data block from numpy array to ctypes array: import numpy as np import ctypes # Preparing example class TransferData(ctypes.Structure): _fields_ = [ ('statusReady', ctypes.c_bool), ('velocity', ctypes.c_double * 4), ('pressure', ctypes.c_double * 4) ] data = TransferData() output = np.array([12., 13., 11., 10.]) # Actual code # Both values should be equal but there could be problems with alignment settings assert ctypes.sizeof(data.pressure) == output.nbytes ctypes.memmove(ctypes.byref(data.pressure), output.ctypes.data, output.nbytes) print(list(data.pressure))
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47127575
answers question: http://stackoverflow.com/q/47127575
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/81239216
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/81160354
has text: but I want to get the first 10 items to be shown in histogram. I added 'bins = 10' into my_plot = data.sort(columns='Number of Tweets',ascending=False).plot( kind='bar',legend=None,title="Tweet Numbers Per Source", bins = 10) but I get an error message.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47104697

http://stackoverflow.com/q/47178150
score: 0
tagged with: asterisk
answer count: 1
has title: "Extended" template-based INI file parsing in Python
tagged with: parsing
type: Question
type: UnansweredQuestion
has body: I need to parse (and feed to a database) configuration files like this one (actually it is Asterisk's sip.conf): [client-template](!,natted-template) foo=foovalue moo=moovalue [client](client-template) bar=barvalue This syntax means that client-template is a template itself (because of ! in parentheses) based on natted-template (defined elsewhere). And client is an object definition, based on client-template. I could use ConfigParser, but it looks like I need something more powerful or customized?
tagged with: python
tagged with: ini
tagged with: configparser
has answer: http://stackoverflow.com/a/47204631

http://stackoverflow.com/q/47089597
has comment: http://stackoverflow.com/comment/81158547
score: 1
has body: I'm not sure whether is this a good place for this kind of question, but I haven't got a better idea. I am dealing with financial OHLC (+Volume) data (basically they are time series) in my python/pandas project, where some records may miss from any dataset or can be an outlier. The data comes from two different data sources (only!) and there are some differences between them. I wan't to improve the quality of the data, somehow merge the information from the two datasoures or multiple time series and always give back an approximately correct OHLC (+Volume) information regarding to the queried symbol for the given datetime interval. If there would be at least three data sources, I could do some weighted linear approximation or use a voting based mechanism, but what can I do if I only have two datasources?
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has title: How to merge or consolidate data from two datasources?
tagged with: dataframe
tagged with: python
tagged with: data-science
tagged with: http://stackoverflow.com/tag/r
answer count: 0
tagged with: pandas

http://stackoverflow.com/comment/81274243
type: QuestionComment
has text: Is your process deterministic? i.e., is it possible to seed the randomness and reproduce the same sequence?
type: Comment
comment on: http://stackoverflow.com/q/47146905
score: 0

http://stackoverflow.com/q/47147653
has title: Write to files with dynamic file names?
has comment: http://stackoverflow.com/comment/81245816
has answer: http://stackoverflow.com/a/47148078
possible better answer: http://stackoverflow.com/a/47147925
tagged with: bigdata
has comment: http://stackoverflow.com/comment/81245671
tagged with: python
has answer: http://stackoverflow.com/a/47147925
has body: I need to split a large txt file (about 100GB, 1 billion rows) by DATE. The file looks like this ID*DATE*company 1111*201101*geico 1234*201402*travelers 3214*201003*statefarm ... Basically there are 60 months so I should be getting 60 sub-files. My Python script is with open("myBigFile.txt") as f: for line in f: claim = line.split("*") with open("DATE-"+str(claim[1])+".txt", "a") as fy: fy.write(claim[0]+"*"+claim[2]+"\n") Now since the number of records is huge, this runs too slow because it needs to open/close file for every row. So I'm thinking about first open 60 sub-files and then scan the file, write each row to corresponding sub-file. The sub-files are not closed until all the rows are scanned. However since python automatically close the file whenever the reference is removed (http://blog.lerner.co.il/dont-use-python-close-files-answer-depends/), I have to use some dynamic file name, something like claim[1].write(claim[0]+"*"+claim[2]+"\n") Note that you can't name a fy and fy.write(claim[0]+"*"+claim[2]+"\n") because that will close the file whenever fy is changed. Is that possible in Python? Thanks!
has comment: http://stackoverflow.com/comment/81245819
type: AnsweredQuestion
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/81245675
accepted answer: http://stackoverflow.com/a/47147768
type: Question
has answer: http://stackoverflow.com/a/47147768

http://stackoverflow.com/comment/81160831
comment on: http://stackoverflow.com/a/47102408
type: Comment
type: AnswerComment
has text: @Abrar: If it works, it works. You could also just use `attributes.keys()` and leave it as a dictionary.
score: 1

http://stackoverflow.com/comment/81165691
has text: Are you asking how to build the Tkinter interface or how to read the CSV file or both?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47107692
score: 0

http://stackoverflow.com/comment/81619750
comment on: http://stackoverflow.com/a/47113836
type: AnswerComment
score: 0
has text: Why still "-1".isnumeric() is False?
type: Comment

http://stackoverflow.com/q/47215432
score: -1
has comment: http://stackoverflow.com/comment/81380299
upvote count: 0
tagged with: file
has comment: http://stackoverflow.com/comment/81380372
has title: Can someone help me see why this code is not working?
has body: A_file = open("ReadME.txt","r") print(A_file.read()) The output I am getting is 2 new lines and that is it... The text i am trying to get is "Line 1, Line 2, Line 3".
has comment: http://stackoverflow.com/comment/81380339
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81380308
has comment: http://stackoverflow.com/comment/81380430
has comment: http://stackoverflow.com/comment/81380396
type: Question
has comment: http://stackoverflow.com/comment/81380270
has comment: http://stackoverflow.com/comment/81382404
has answer: http://stackoverflow.com/a/47215476
has comment: http://stackoverflow.com/comment/81380406
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/47202621
has body: When I have a bug in Django, the stacktrace usually showed only Django's internal files, not my application files (usually view.py,..) that caused the bug. How can I make Django show me the full stacktrace?
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81355574
answer count: 0
has comment: http://stackoverflow.com/comment/81354116
has comment: http://stackoverflow.com/comment/81353916
score: 0
tagged with: django
tagged with: stack-trace
tagged with: debugging
type: Question
has title: Django stacktrace not informative

http://stackoverflow.com/comment/81246260
comment on: http://stackoverflow.com/a/47147995
score: 0
type: AnswerComment
type: Comment
has text: Thanks Ajax1234 - but its not printing the right output. productItem2 has two records - keys are same but the field which we are seeing to identify the duplicate records that are different? How will handle that scenario?

http://stackoverflow.com/q/47126680
type: Question
has comment: http://stackoverflow.com/comment/81226616
tagged with: python
tagged with: twitter
type: UnansweredQuestion
tagged with: tweepy
has body: I literally haven't used my keys and secret tokens in over 12 hours and I still get the 420 error for rate limit. Here's the code. import tweepy from tweepy import OAuthHandler from tweepy import Stream from tweepy.streaming import StreamListener consumer_key = '' consumer_secret = '' access_token = '' access_secret = '' auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) data = api.rate_limit_status() print data['resources']['statuses']['/statuses/home_timeline'] print data['resources']['users']['/users/lookup'] and I get the following: {u'reset': 1509916835, u'limit': 15, u'remaining': 15} {u'reset': 1509916835, u'limit': 900, u'remaining': 900} 420 420 420 What happened? Am I banned? I've tried using multiple accounts to no avail...
has comment: http://stackoverflow.com/comment/81214634
upvote count: 2
score: 0
downvote count: 2
has title: Why have I been getting Twitter's rate limit error for over 15 minutes?
answer count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/81205646
has comment: http://stackoverflow.com/comment/81206385

http://stackoverflow.com/comment/81223163
type: AnswerComment
comment on: http://stackoverflow.com/a/47134052
has text: Hey @smassey in my csv file there are many unwanted data and when I use your code it returns UnicodeDecodeError: 'utf-8' codec can't decode byte 0x98 in position 826: invalid start byte error.
type: Comment
score: 0

http://stackoverflow.com/comment/81310588
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47180302
type: QuestionComment
has text: I would take a look at MySQL to store data instead of using XML files

http://stackoverflow.com/comment/81275786
has text: Actually, I was operating under the assumption that none of the `where` functions existed for 0.9, so I guess my answer is no longer valid. :-(
comment on: http://stackoverflow.com/a/47163041
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81170997
comment on: http://stackoverflow.com/q/47110304
has text: Or maybe interactive plotting would be useful for you... using `ion()` and `plt.draw()` instead of `plt.show()`. See [this](https://www.raspberrypi.org/learning/visualising-sorting-with-python/lesson-1/worksheet/)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81259756
score: 0
type: QuestionComment
has text: **Stop iterate multiple ports with `SINGLE CONNECTION`**, You can't scan multiple ports with a single connection! Which is faster? Do you read buffer memory or create a new connection? You should stop raping the Kernel. The time of opening and closing the socket is a minimum of 200 milliseconds (you can test it yourself). How do you know which process the error message came from?
type: Comment
comment on: http://stackoverflow.com/q/47151298

http://stackoverflow.com/q/47182630
tagged with: python
score: 0
has title: Pandas Grouping Summary
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81314304
has body: I have a pandas dataframe like so: I want to be able to output this into a summary by price point kinda like this: face_value | section | count | 50.5 | 101 | 200 50.5 | 301 | 365 where count is the cumulative total of all sections where available = True and for that specific price point. It's possible that the same section has multiple face values, so i would hope to aggregate them separately. Let's say I had multiple face_values for section 101, here would be the output if there was only section 101 in this data. face_value | section | count | 50.5 | 101 | 200 97.5 | 101 | 365 So basically I would like to group by the price points and sum the counts if availability is true and ticket_type is primary. Looking through the pandas documentation and I'm having issues figuring anything out.
has answer: http://stackoverflow.com/a/47182851
type: UnansweredQuestion

http://stackoverflow.com/comment/81187835
has text: I'm guessing related to this https://stackoverflow.com/a/25291492/1240268 (your example is a worst case for number of groups edit: it's no _wost_ case actually... just a lot of 'em, and we're stuck in python with the lambda).
score: 0
comment on: http://stackoverflow.com/a/47118796
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47124100
favorite count: 0
tagged with: python-2.7
has title: How to get the shape of a sparse tensor and convert it to list?
has body: I have some codes of reading datas from a file and use them as the input of a tensorflow network. import tensorflow as tf reader = tf.TFRecordReader() filename_queue = tf.train.string_input_producer(['/home/stuart/Desktop/tfrecords/m_6803.tfrecords']) _, serialized_example = reader.read(filename_queue) features = tf.parse_single_example( serialized_example, features={ 'label': tf.FixedLenFeature([], tf.string), 'user_behavior': tf.VarLenFeature(tf.float32), }) label = tf.cast(tf.decode_raw(features['label'], tf.uint8), tf.float32) user_behavior = tf.cast(features['user_behavior'], tf.float32) sess = tf.Session() coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) print(user_behavior.get_shape().as_list()) # output: [None] print(sess.run(tf.shape(user_behavior)) # output: (376), type: Tensor("Shape/Cast:0", shape=(1,), dtype=int32) Now I need to get the shape of the tensor 'user_behavior' because it varies from the files(I have more than one file to read although there is only one here). And then use the shape in defining the weight matrix. The sess.run(tf.shape()) do work, but it returns the shape as a tensor which could not be used in tf.Variable([], shape=[]) because the arg shape here requires a list. Although I know tensor.get_shape().as_list() returns a list, since I use tf.VarLenFeature(), it creates a sparse tensor. If I use this method on it, the output will be [None]. So is there a way to get the shape of this sparse tensor and use it to define the shape of another tensor?
tagged with: tensorflow
type: Question
tagged with: python-3.x
score: 2
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/56558546
answer count: 1
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/81339266
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47195051
score: 1
has text: If possible, just use Python 3 :)

http://stackoverflow.com/q/47120360
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81190821
has comment: http://stackoverflow.com/comment/81190573
answer count: 1
downvote count: 1
tagged with: amazon-web-services
tagged with: aws-lambda
has body: I am using python 2.7 trying to achieve the user utterance so after I can prompt it back to user. I tried mess = intent_request['currentIntent']['slots']['drink']['inputTranscript'] I want to access the user utterance(current utterance), example "can i order pizza". I am using python 2.7 aws lambda. How can i get this utterance? My code: import os import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) def lambda_handler(event,context): logger.debug('event.bot.name={}'.format(event['bot']['name'])) return dispatch(event) def dispatch(intent_request): intent_name = intent_request['currentIntent']['name'] #prompt = intent_request['currentIntent']['inputTranscript'] if intent_name == 'BurgerType': return get_burger(intent_request) if intent_name == 'drinks': return get_drink(intent_request) def get_drink(intent_request): slot = intent_request['currentIntent']['slots'] value2 = intent_request['currentIntent']['slots']['drink'] mess = intent_request['currentIntent']['slots']['drink']['inputTranscript'] session_attributes = {} return close( session_attributes, 'Fulfilled',{ 'contentType':'PlainText', 'content':'Your order of 000'+mess }) def get_burger(intent_request): slots = intent_request['currentIntent']['slots'] value = intent_request['currentIntent']['slots']['Burgers'] #value2 = intent_request['currentIntent']['slots']['cheese'] session_attributes = {} return close( session_attributes, 'Fulfilled',{ 'contentType': 'PlainText', 'content':'Your order of '+value+' burger '#+value2+'has been placed' }) def close(session_attributes, fulfillment_state, message): response = { 'sessionAttributes': session_attributes, 'dialogAction':{ 'type':'Close', 'fulfillmentState': fulfillment_state, 'message': message } } return response
favorite count: 0
type: Question
has title: Access the user utterance(first) which triggers the bot(lambda function) in Python aws lex?
tagged with: python
has answer: http://stackoverflow.com/a/47455117
tagged with: amazon-lex
tagged with: python-2.7
score: 0

http://stackoverflow.com/a/47130052
answers question: http://stackoverflow.com/q/47129464
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81676104
type: Answer
has comment: http://stackoverflow.com/comment/81697361
accepted answer of: http://stackoverflow.com/q/47129464
upvote count: 2
score: 2
has body: This solution uses the str.find method to find all copies of an ngram within the txt string, saving the indices of each copy to the indices set so we can easily handle overlapping matches. We then copy txt, char by char to the result list, inserting angle brackets where required. This strategy is more efficient than inserting the angle brackets using multiple .replace call because each .replace call needs to rebuild the whole string. I've extended your data slightly to illustrate that my code handles multiple copies of an ngram. txt = "how does this work now chisolm" ngrams = ["ow ", "his", "s w"] print(txt) print(ngrams) # Search for all copies of each ngram in txt # saving the indices where the ngrams occur indices = set() for s in ngrams: slen = len(s) lo = 0 while True: i = txt.find(s, lo) if i == -1: break lo = i + slen print(s, i) indices.update(range(i, lo-1)) print(indices) # Copy the txt to result, inserting angle brackets # to show matches switch = True result = [] for i, u in enumerate(txt): if switch: if i in indices: result.append('&lt;') switch = False result.append(u) else: result.append(u) if i not in indices: result.append('&gt;') switch = True print(''.join(result)) output how does this work now chisolm ['ow ', 'his', 's w'] ow 1 ow 20 his 10 his 24 s w 12 {1, 2, 10, 11, 12, 13, 20, 21, 24, 25} h&lt;ow &gt;does t&lt;his w&gt;ork n&lt;ow &gt;c&lt;his&gt;olm If you want adjacent groups to be merged, we can easily do that using the str.replace method. But to make that work properly we need to pre-process the original data, converting all runs of whitespace to single spaces. A simple way to do that is to split the data and re-join it. txt = "how does this\nwork now chisolm hisow" ngrams = ["ow", "his", "work"] #Convert all whitespace to single spaces txt = ' '.join(txt.split()) print(txt) print(ngrams) # Search for all copies of each ngram in txt # saving the indices where the ngrams occur indices = set() for s in ngrams: slen = len(s) lo = 0 while Tru…
downvote count: 0

http://stackoverflow.com/q/47149317
favorite count: 0
type: Question
has body: I am working on the pandas dataset. For 2D dataframe try to return/append one column which return the column name whose value is over 0.95. import pandas as pd import numpy as np Exp_day_list = ["EXP_DAY_1","EXP_DAY_2","EXP_DAY_3","EXP_DAY_4","EXP_DAY_5","EXP_DAY_6","EXP_DAY_7","EXP_DAY_8","EXP_DAY_9","EXP_DAY_10","EXP_GT_DAY_10"] test = raw_databased.head() Exp_day_percentage = test[Exp_day_list] def over_95_percent(x): for column in x: if x[column] &gt; 0.95: return column break Exp_day_percentage.apply(over_95_percent,axis = 1) I test Exp_day_percentage and result is as what I need. Exp_day_percentage Out[2]: EXP_DAY_1 EXP_DAY_2 EXP_DAY_3 EXP_DAY_4 EXP_DAY_5 EXP_DAY_6 \ 0 0.0 0.0 0.52 0.94 0.94 1.0 1 0.0 0.0 0.00 0.66 1.00 1.0 2 0.0 1.0 1.00 1.00 1.00 1.0 3 0.0 0.0 0.92 1.00 1.00 1.0 4 0.0 0.0 0.95 0.97 1.00 1.0 EXP_DAY_7 EXP_DAY_8 EXP_DAY_9 EXP_DAY_10 EXP_GT_DAY_10 0 1.0 1.0 1.0 1.0 0.0 1 1.0 1.0 1.0 1.0 0.0 2 1.0 1.0 1.0 1.0 0.0 3 1.0 1.0 1.0 1.0 0.0 4 1.0 1.0 1.0 1.0 0.0 but when I run the apply function to that dataframe, error function as following: TypeError: ("cannot do label indexing on &lt;class 'pandas.indexes.base.Index'&gt; with these indexers [0.0] of &lt;type 'numpy.float64'&gt;", u'occurred at index 0') ideal result will be following: EXP_DAY_1 EXP_DAY_2 EXP_DAY_3 EXP_DAY_4 EXP_DAY_5 EXP_DAY_6 \ 0 0.0 0.0 0.52 0.94 0.94 1.0 1 0.0 0.0 0.00 0.66 1.00 1.0 2 0.0 1.0 1.00 1.00 1.00 1.0 3 0.0 0.0 0.92 1.00 1.00 1.0 4 0.0 0.0 0.95 0.97 1.00 1.0 EXP_DAY_7 EXP_DAY_8 EXP_DAY_9 EXP_DAY_10 EXP_GT_DAY_10 Column 0 1.0 1.0 1.0 1.0 0.0 EXP_DAY_5 1 1.0 1.0 1.0 1.0 0.0 EXP_DAY_5 2 1.0 1.0 1.0 1.0 0.0 EXP_DAY_2 3 1.0 1.0 1.0 1.0 0.0 EXP_DAY_4 4 1.0 1.0 1.0 1.0 0.0 EXP_DAY_3 if anyone can help me on that, I would much appreciate that. I search all internet and could not find similar thing. thank you
type: UnansweredQuestion
has title: pandas return column name apply function for each row
tagged with: dataframe
tagged with: python
tagged with: apply
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/47149419
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81278348
has text: But in my real code that can't be static because it calls other methods on self.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47164074

http://stackoverflow.com/a/47122672
type: Answer
has comment: http://stackoverflow.com/comment/81199583
answers question: http://stackoverflow.com/q/47122459
upvote count: 3
has comment: http://stackoverflow.com/comment/81304725
downvote count: 0
has comment: http://stackoverflow.com/comment/81305196
score: 3
has comment: http://stackoverflow.com/comment/81197611
has body: I think you need to go for dual groupby (Hope sensor_id is sorted if not we need to sorted them first) i.e df['new'] = df.groupby('sensor_id').apply( lambda x : x.groupby(x['time'].dt.hour).ngroup()+1).values Output : sensor_id event_id time new 0 A e1 2017-02-14 05:30:00 1 1 A e2 2017-02-14 05:45:00 1 2 A e3 2017-02-14 08:30:00 2 3 B e3 2017-02-14 05:20:00 1 4 B e4 2017-02-14 05:30:00 1 5 B e6 2017-02-14 05:45:00 1 6 C e1 2017-02-14 05:30:00 1 7 C e3 2017-02-14 07:30:00 2 8 C e7 2017-02-14 09:35:00 3

http://stackoverflow.com/comment/81161128
type: QuestionComment
comment on: http://stackoverflow.com/q/47100670
type: Comment
has text: Sorry, I don't get that. Could you add an example to your question, please?
score: 0

http://stackoverflow.com/q/47071694
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
has body: Suppose I have a small Python package: /mypack /mypack/__init__.py /mypack/mod1.py /mypack/mod2.py /mypack/table.csv If I need something from mod1 in mod2, I can easily do a relative import: # mod2.py from .mod2 import something This package can be copied to and accessed from anywhere and will work right away. Now suppose I also need that /mypack/table.csv in mod2. How can I access that file in a way that will work no matter from where I access the module or to where I might copy it? Two remarks: Without the data file, I just need to copy the folder. I'd like to maintain that capability, instead of using deployment tools. (Because I currently rsync the Python code to several remote computers and just run it there. Not very convenient if more tools would come into play.) There's the option to query the path of a source file with the os package. But this doesn't seem to be fully portable.
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81091428
linked to: http://stackoverflow.com/q/918154
tagged with: python
has title: How to access a data file of a Python package
type: Question
has answer: http://stackoverflow.com/a/47073306

http://stackoverflow.com/comment/81159258
has text: Can you pass the `object` from main.py to `function_y` as a parameter?
comment on: http://stackoverflow.com/q/47104318
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81260389
type: AnswerComment
score: 1
has text: I also don't think you need to range to length +1. That includes the last named second, which isn't usually included in a time range. So I edited that out.
comment on: http://stackoverflow.com/a/47146874
type: Comment

http://stackoverflow.com/comment/81264772
type: Comment
comment on: http://stackoverflow.com/q/47157536
score: 0
type: QuestionComment
has text: this is what it showed: `Alahärmä 2014 0 0.1 0.2 0 Alajärvi 2014 10171 5102 5069 1 Alastaro 2014 0 0 0 2 Alavieska 2014 2687 1400 1287 3 Alavus 2014 12103 6102 6001 4 Anjalankoski 2014 0 0 0`

http://stackoverflow.com/comment/81324184
has text: You'd have to set `onsubmit` on the form, not an input element, and it should be a function not a string.
comment on: http://stackoverflow.com/q/47187441
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/47100346
downvote count: 0
has comment: http://stackoverflow.com/comment/81155041
has comment: http://stackoverflow.com/comment/81155068
score: 2
has body: I am having problems getting a program to import the mysql.connector Note: Running on a Windows 10 machine. I have done the following 1) Installed anaconda (install properly) I checked that the anaconda paths are in my pathname variable Here is the PATH var: C:\Users\john.fox\AppData\Local\Continuum\anaconda3;C:\Users\john.fox\AppData\Local\Continuum\anaconda3\Library\mingw-w64\bin;C:\Users\john.fox\AppData\Local\Continuum\anaconda3\Library\usr\bin;C:\Users\john.fox\AppData\Local\Continuum\anaconda3\Library\bin;C:\Users\john.fox\AppData\Local\Continuum\anaconda3\Scripts;C:\Users\john.fox\AppData\Local\Continuum\anaconda3\envs\Python34; 2) Change the python version to python3.4 (was python3.6) This was needed to get mysql-connector to work properly The Python34 path is in the pathname variable 3) Installed the mysql-connector using anaconda (installed correctly) 4) Did a "conda search mysql-connector" It came back with all the mysql.connectors (the one for py34_0 is present) C:\Users\john.fox&gt;conda search mysql.connector Fetching package metadata ............. mysql-connector-python 2.0.3 py26_0 defaults 2.0.3 py27_0 defaults 2.0.3 py33_0 defaults 2.0.3 py34_0 defaults 2.0.3 py35_0 defaults 2.0.4 py27_0 defaults 2.0.4 py34_0 defaults 2.0.4 py35_0 defaults 2.0.4 py36_0 defaults 5) Attempted to run a script with import mysql.connector Received: Traceback (most recent call last): File "jira_export5_Beta.py", line 3, in &lt;module&gt; import mysql.connector ModuleNotFoundError: No module named 'mysql' 6) Went to Python 3.6.2 for default 7) Attempted to run again, same results. If anyone has words of wisdom (for this problem) I would appreciate hearing them. Thanks JWF
tagged with: anaconda
tagged with: python
tagged with: mysql-connector-python
favorite count: 0
type: Question
answer count: 0
has title: ModuleNotFoundError: No module named 'mysql' even when mysql.connector installed
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/47135549
tagged with: pyinstaller
tagged with: python
has body: Working on Ubuntu 16.04, python 2.7.12, I have this code (codec.py): #!usr/bin/env python # -*- coding: utf-8 -*- import codecs text = u'pi: \u03c0' print text Start program with: python codec.py work fine, and display: pi: π After compile this code with pyinstaller 3.3 I try to execute program with ./codec, but receive this error: Traceback (most recent call last): File "codec.py", line 7, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode character u'\u03c0' in position 4: ordinal not in range(128) [6816] Failed to execute script codec I have no solution for that issue. Have you ? Solution was to modify line 7: print text.encode("utf-8") After compile with pyinstaller, program work fine, without error.
has title: PyInstaller codecs issues
score: 0
has answer: http://stackoverflow.com/a/47135683
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/3224268
answer count: 1
type: Question
linked to: http://stackoverflow.com/q/3828723

colander
type: Tag
tags question: http://stackoverflow.com/q/47116855
tags question: http://stackoverflow.com/q/47102536
tag name: colander

http://stackoverflow.com/comment/81179228
has text: Gives an error: slice indices must be integers or None or have an __index__ method
type: AnswerComment
comment on: http://stackoverflow.com/a/47114375
score: 0
type: Comment

http://stackoverflow.com/q/47160098
score: 5
upvote count: 5
tagged with: stderr
tagged with: stdout
tagged with: python
tagged with: unbuffered
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81323061
has title: Python is not working in unbuffered mode
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81270072
has comment: http://stackoverflow.com/comment/81269772
accepted answer: http://stackoverflow.com/a/47160440
has body: I'm stuggeling with an issue with python. I used Python 2.7.13 and Python 3.6.0 on Red Hat Enterprise Linux Server release 7.1 (Maipo). In order to monitor the proccesses output, I want to use tail -f to take a live look into the STDOUT and STDERR. The Keyword here is unbuffered output. Many suggestion on the internet say use python -u ... or the environment variable PYTHONUNBUFFERED like PYTHONUNBUFFERED=1 python ... or stdbuf -e0 -o0 python .... Nevertheless nothing is wokring for the following test script. import sys import time while(True): print("Test String") time.sleep(1); For all different commands I always have buffered output. Even though when I want to use STDERR. It's still buffered which really confuses me because STDERR should be unbuffered by default. Using sys.stdout.flush() or sys.stderr.flush() is also not doing the job. When using flush=True inside print() it's working as intended. I'm looking for a solution which doesn't make it necessary to edit code because I can't edit all programs in order to get unbuffered and immediately flushed out output. How can I achieve this? Looking forward to your answers! Best wishes!
favorite count: 0
has comment: http://stackoverflow.com/comment/81269810
tagged with: buffering
type: Question
has answer: http://stackoverflow.com/a/47160440
has comment: http://stackoverflow.com/comment/81365090

http://stackoverflow.com/a/47145844
downvote count: 0
has comment: http://stackoverflow.com/comment/81242391
has comment: http://stackoverflow.com/comment/81253828
type: Answer
has comment: http://stackoverflow.com/comment/81242013
has body: Yeah it is possible. Here’s a code sample in the child class. No changes needed in the parent class: def __init__(self, user_input): if (condition 1): self.__func__ = self.func1 else: self.__func__ = self.func2 def __func1(self, your arguments): code def __func2(self, your arguments) other code As I do not know the arguments of the functions or the condition, this is as specific as I can get.
answers question: http://stackoverflow.com/q/47145798
upvote count: 2
has comment: http://stackoverflow.com/comment/81242119
score: 2

http://stackoverflow.com/q/47196799
downvote count: 1
favorite count: 0
score: 0
has body: I want to implement a new model language for spaCY. I have installed spaCy (using the guide of the official web site) on my Windows SO but I haven't understand where and how I could write and run my future files. Help me, Thanks.
has answer: http://stackoverflow.com/a/47233007
tagged with: windows
tagged with: python
tagged with: cython
has title: How write code and run python's files using spaCy? (using windows)
tagged with: nlp
type: Question
tagged with: spacy
type: UnansweredQuestion
answer count: 1
upvote count: 1
linked to: http://stackoverflow.com/q/3701646

http://stackoverflow.com/q/47075280
has title: Can't choose the pattern I should pursue
has answer: http://stackoverflow.com/a/47075924
tagged with: python
has comment: http://stackoverflow.com/comment/81099037
tagged with: selenium-webdriver
has body: I'm seriously confused about putting a line in my scraper in it's right position. I'm trying to use python in combination with selenium defining 10 seconds of explicit wait. However, i'm pasting the two for your consideration to tell me which one I should pursue and why? (don't overlook the commented out line in two scripts) This is what I tried with: driver = webdriver.Chrome() wait = WebDriverWait(driver, 10) ##Notice this line having been placed before "get" driver.get(some_url) wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "some_selector"))) driver.quit() This is another: driver = webdriver.Chrome() driver.get(some_url) wait = WebDriverWait(driver, 10) ##Notice this line having been placed after "get" wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "some_selector"))) driver.quit()
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81099052
upvote count: 1
has comment: http://stackoverflow.com/comment/81099006
answer count: 1
downvote count: 1
tagged with: selenium
accepted answer: http://stackoverflow.com/a/47075924
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/81099105
has comment: http://stackoverflow.com/comment/81098818
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81099240
has comment: http://stackoverflow.com/comment/81098897

http://stackoverflow.com/a/47164439
score: 1
upvote count: 1
has body: df['max']=df['max'].apply(pd.Series) df Out[1428]: idCaseMax idCaseMin lineId max min 0 5 10 1 120 -110 1 27 23 2 150 -205 2 15 40 3 110 -80 3 11 8 4 90 -150 Data Input df = pd.DataFrame({"lineId":[1,2,3,4], "idCaseMin": [10, 23, 40, 8], "min": [-110, -205, -80, -150], "idCaseMax": [5, 27, 15, 11], "max": [[120], [150], [110], [90]]})
answers question: http://stackoverflow.com/q/47164230
type: Answer
downvote count: 0

http://stackoverflow.com/comment/81353786
has text: There is alwasys this format? empty french, filled englis, empty dutch?
comment on: http://stackoverflow.com/q/47201578
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47192731
has body: My list is like this: [['a','b'],['c','a'],['k','f'],['s','b'],['a','b']...] I want to get a new list which has no duplicate elements from it. What is the fastest way to realize it ?
has title: How to get the distinct elements from a python list?
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/47192754
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81334897
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/2213923
tagged with: python
duplicate of: http://stackoverflow.com/q/2213923

http://stackoverflow.com/a/47180454
downvote count: 0
has comment: http://stackoverflow.com/comment/101955782
accepted answer of: http://stackoverflow.com/q/47179297
score: 9
upvote count: 9
answers question: http://stackoverflow.com/q/47179297
type: AcceptedAnswer
type: Answer
has body: Do requires_system_checks = False class Command(BaseCommand): requires_system_checks = False ... def add_arguments(self, parser): #rest of code For more info
has comment: http://stackoverflow.com/comment/112538603

http://stackoverflow.com/comment/81283045
type: Comment
comment on: http://stackoverflow.com/a/47166576
type: AnswerComment
has text: @juanpa.arrivillaga You create one anyway?
score: 0

http://stackoverflow.com/q/47211563
tagged with: python-3.x
tagged with: recursion
has comment: http://stackoverflow.com/comment/81372990
has comment: http://stackoverflow.com/comment/81372552
linked to: http://stackoverflow.com/q/2353768
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81372960
has title: Python Dictionary recursive searching
has answer: http://stackoverflow.com/a/47211881
has comment: http://stackoverflow.com/comment/81372899
score: 2
answer count: 2
has body: The way it works is that the keys can turn into any value from the lists they're associated with. So the question I'm trying to answer is can maximus turn into bumble. The function should return True because maximus -> bee -> bumble. My function so far works with the following logic: for i in transformers[start]: if i in transformers values: if desired in transformers[start]: return True else: return search(transformers, i,desired) So what happens is it goes through the first recursion and says "okay, maximus is now prime." but in the second recursion with prime being start, it returns form the function and doesn't even check what would happen if maximus turned into bee, since once it hit OldPrime, it just returned with nothing. transformers = { "maximus" : ["prime", "bee", "bomber"], "prime" : ["oldPrime","youngerPrime"], "bee" : ["bumble","oldBumble"], "plareon" : ["moltrees"] }
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47211826
favorite count: 0
type: Question

http://stackoverflow.com/comment/81410548
type: AnswerComment
comment on: http://stackoverflow.com/a/47214490
has text: As I said, you may need to do some tweaking. Does the error occur when you do `[:]`? If that is the case, then the object that you are trying to index may have more keys. You can check that by using `.keys()` method.
type: Comment
score: 0

http://stackoverflow.com/q/47133997
favorite count: 0
type: Question
has body: with a button (envoi) I open a new window and write values of elements in an array (choices). After i close this window and call a function (window2). I want to read choices in this function If i write print choices.get(), I have an error : global name 'choices' is not defined # -*- coding: utf-8 -*- from Tkinter import * root = Tk() group = LabelFrame(root, text=" 1. Paramètrage: ") group.grid(row=0, columnspan=5, sticky='W', \ padx=5, pady=5, ipadx=5, ipady=5) dropVar2=StringVar() dropVar2.set("----") opt3 = OptionMenu(group, dropVar2, '----', 'Pondéraux', 'Atomiques') opt3.grid(row=4, column=1, columnspan=7, sticky='WE', padx=5, pady=2) def state(): if dropVar2.get()=='Atomiques': winE=Toplevel(root) group = LabelFrame(winE, text="Pourcentages atomiques", padx=5,pady=5) group.pack(padx=25, pady=25) entries = [] j = 0 choices = ['C', 'Ni', 'Co', 'Fe', 'Cr', 'Al', 'Ti', 'Ta', 'Nb', 'Hf', 'V', 'Re', 'Mo', 'W', 'B', 'Zr', 'Mg', 'Y'] while j &lt; len(choices) : valeurOneLabel = Label(group, text=choices[j]) valeurOneLabel.grid(row=j+1, column=0, columnspan=1, sticky='WE', padx=5, pady=2) en = Entry(group, text="") en.grid(row=j+1, column=1) entries.append(en) j+=1 for s in range(len(choices)): choices[s] = entries[s] exitButton = Button(winE, text = 'Close', command = lambda: window2(winE)).pack() def window2(winE): winA=Toplevel(root) winA.geometry('400x600+600+50') print choices.get() winE.destroy() Button(group, text='envoi', command = state).grid(row=5, column=0) root.geometry("450x350+100+100") root.title("Développement d'alliages") root.mainloop()
has comment: http://stackoverflow.com/comment/81218430
has answer: http://stackoverflow.com/a/47139681
tagged with: python
has title: python 2.7 Tkinter how to pass an array in another function
type: AnsweredQuestion
tagged with: python-2.7
tagged with: tkinter
tagged with: toplevel
accepted answer: http://stackoverflow.com/a/47139681
score: 0
answer count: 1
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/81373512
score: 2
has text: Please do not post your entire homework assignment as a question. Focus your question on a specific issue. For example, you could post just line 10 of your code and the exception you are getting, and ask how to convert string to float properly.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47211965

http://stackoverflow.com/comment/81203568
score: 0
type: Comment
has text: @DanielLynes No, not quite as I assume `BIKES_AVAILABLE` as the `column` (?) so you would then be trying to do `.index` on an `integer` which just wouldn't work. I have updated my answer with how to get the `row` properly...
type: AnswerComment
comment on: http://stackoverflow.com/a/47125864

http://stackoverflow.com/a/68001205
has comment: http://stackoverflow.com/comment/134508062
has comment: http://stackoverflow.com/comment/130796633
answers question: http://stackoverflow.com/q/47201358
score: 85
upvote count: 85
downvote count: 0
has comment: http://stackoverflow.com/comment/138030437
type: Answer
has body: pytest's magic is clever enough. By writing assert {'a': {'b': 2, 'c': {'d': 4} } } == {'a': {'b': 2, 'c': {'d': 4} } } you will have a nested test on equality.

http://stackoverflow.com/a/47066368
answers question: http://stackoverflow.com/q/47066252
has comment: http://stackoverflow.com/comment/81081039
score: 1
downvote count: 0
upvote count: 1
has body: The documentation clearly states that files will be closed once the with statement is exited. However, if that is not proof enough - here is a way you can check for yourself; Files have a .closed property that you can check. with open("file.txt", "r") as f: print(f.closed) # will print False print(f.closed) # will print True The same property can be used when dealing with files the non-with way. f = open("file.txt", "r") print(f.closed) # will print False f.close() print(f.closed) # will print True. This should service as sufficient proof that the file is indeed being closed.
type: Answer

http://stackoverflow.com/comment/81213113
score: 0
type: QuestionComment
has text: ya, I will work wtih both the solutions then answer
comment on: http://stackoverflow.com/q/47131193
type: Comment

http://stackoverflow.com/q/47148803
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47161952
tagged with: matplotlib
tagged with: curve-fitting
has answer: http://stackoverflow.com/a/47161952
tagged with: python
tagged with: data-fitting
has comment: http://stackoverflow.com/comment/81268373
has title: Scipy Curve Fit Optimize not working for log scale values
has comment: http://stackoverflow.com/comment/81252345
has body: So I am trying to fit a set of data points to this equation: abs(I) = Io(exp((qV)/(nKT)) - 1) --- Shockley diode equation to a bunch of data points I was given. Knowing the V and the I values, I need to optimize the Io and the n values to get me data closely matching the data set I was given. However, scipy optimize curve fit is not giving me the values I want, which is where n = ~1.15 and Io = ~1.8E-13, and is instead giving me n = 2.12 and I = 2.11E-11. I suspect this is due to the data set values being very small numbers, messing with the optimization, but even when i set the initial guess to be n = 1.15 and Io = 1.8E-13, the optimization values do not change. Does anyone have any tips on how to fix this? import numpy as np import math import matplotlib.pyplot as plt from scipy.optimize import curve_fit Voltage = np.array([-0.5 , -0.49, -0.48, -0.47, -0.46, -0.45, -0.44, -0.43, -0.42, -0.41, -0.4 , -0.39, -0.38, -0.37, -0.36, -0.35, -0.34, -0.33, -0.32, -0.31, -0.3 , -0.29, -0.28, -0.27, -0.26, -0.25, -0.24, -0.23, -0.22, -0.21, -0.2 , -0.19, -0.18, -0.17, -0.16, -0.15, -0.14, -0.13, -0.12, -0.11, -0.1 , -0.09, -0.08, -0.07, -0.06, -0.05, -0.04, -0.03, -0.02, -0.01, 0. , 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1 , 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2 , 0.21, 0.22, 0.23, 0.24, 0.25, 0.26, 0.27, 0.28, 0.29, 0.3 , 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4 ]) Current = np.array([ 6.99000000e-13, 6.83000000e-13, 6.57000000e-13, 6.46000000e-13, 6.19000000e-13, 6.07000000e-13, 5.86000000e-13, 5.73000000e-13, 5.55000000e-13, 5.37000000e-13, 5.27000000e-13, 5.08000000e-13, 4.92000000e-13, 4.75000000e-13, 4.61000000e-13, 4.43000000e-13, 4.32000000e-13, 4.18000000e-13, 3.99000000e-13, 3.91000000e-13, 3.79000000e-13, 3.66000000e-13, 3.54000000e-13, 3.43000000e-13, 3.34000000e-13, 3.18000000e-13, 3.06000000e-13, 2.96000000e-13, 2.86000000e-13, 2.77000000e-13, 2.66000000e-13, 2.59000000e-13, 2.54000000e-13, 2.43000000e-13, 2…
has comment: http://stackoverflow.com/comment/81291204
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81262762
score: 1
upvote count: 1
tagged with: scipy

http://stackoverflow.com/a/47213859
has comment: http://stackoverflow.com/comment/81797092
has comment: http://stackoverflow.com/comment/117146106
has comment: http://stackoverflow.com/comment/81775416
has comment: http://stackoverflow.com/comment/81863256
downvote count: 0
has body: For the moment there is an open issue : Add ability to change Python version But as a workaround, everything is explain here (All credits to the author: Murat Eken) Create your function. Installing a site extension with an alternative Python version and configuring the handler mapping to use that installation by default.. 2.1. Go to "Platform features > All Settings > Extensions > + Add 2.2. Install the "Python 3.6.2 x86" extension. 2.3. Go to "Platform features > Applications Settings 2.4. Add an handler mapping: extension : fastCgi processor: D:\home\python362x86\python.exe arguments: D:\home\python362x86\wfastcgi.py 2.5 Add an application setting called WEBSITE_USE_PLACEHOLDER and set its value to 0. This is necessary to work around an Azure Functions issue that causes the Python extension to stop working after the function app is unloaded. 2.6. Save your app settings. Here is the output of my function "3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)]" you can automate these step using an ARM Template, here are the interesting part of the template: { "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json", "contentVersion": "1.0.0.0", "parameters": { //... }, "variables": { // ... }, "resources": [ // ... { "type": "Microsoft.Web/sites", // ... "kind": "functionapp", "properties": { // ... "siteConfig": { "handlerMappings": [{ "arguments": "D:\\home\\python362x86\\wfastcgi.py", "extension": "fastCgi", "scriptProcessor": "D:\\home\\python362x86\\python.exe" }] // ... }, "resources": [{ "name": "python362x86", "type": "siteextensions", "apiVersion": "2016-08-01", "properties": {} // ... }] // ... } } ] }
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81865362
accepted answer of: http://stackoverflow.com/q/47208325
answers question: http://stackoverflow.com/q/47208325
type: Answer
score: 11
upvote count: 11

http://stackoverflow.com/comment/81161783
comment on: http://stackoverflow.com/a/47095148
type: AnswerComment
score: 0
type: Comment
has text: Cannot do anything with QListView... can you help me please? other stuff was correct! Now im in a trouble: self.gui.listView.addItem(item) AttributeError: 'NoneType' object has no attribute 'addItem'

http://stackoverflow.com/comment/81201241
comment on: http://stackoverflow.com/q/47125438
score: 1
type: QuestionComment
has text: Try `print(form.errors)`. That should tell you what the problem is.
type: Comment

http://stackoverflow.com/comment/81146581
comment on: http://stackoverflow.com/a/47097871
score: 0
type: Comment
has text: If your actual string is in one line, then why don't you have it that way in your question?
type: AnswerComment

http://stackoverflow.com/comment/81137558
type: Comment
comment on: http://stackoverflow.com/a/47093980
has text: corrupted means ?
type: AnswerComment
score: 0

http://stackoverflow.com/a/47227738
answers question: http://stackoverflow.com/q/47191930
score: 0
accepted answer of: http://stackoverflow.com/q/47191930
type: AcceptedAnswer
has body: In case someone comes across this post while trying to plot IMS 1-km resolution data with Python I have a poor-man solution which will work fine. The memory error is raised by the plot routines but the array can still be stored into python. So, instead of subsetting using a where function, I just tried to use explicit indexing like lat_subset=lat[imin:imax, jmin:jmax] and then plotting the result with plot.imshow() without doing a contour plot or use a map projection in order to have an idea of how the data were looking. This allowed me to choose the indices span in a way that my region of interest was inside. Now I was able to make the contour plot without having a memory error. I have a small repository with a notebook which shows how to plot those data: https://github.com/guidocioni/snow_ims/blob/mistral/plot_ims.ipynb. It has the advantage of read the file directly online although the coordinate files still need to be downloaded given their size.
type: Answer

http://stackoverflow.com/q/47157240
answer count: 3
has answer: http://stackoverflow.com/a/47157509
accepted answer: http://stackoverflow.com/a/47157509
has answer: http://stackoverflow.com/a/47157452
possible better answer: http://stackoverflow.com/a/47157452
upvote count: 4
has body: I have a text file data.txt that contains 2 rows of text. first_row_1 first_row_2 first_row_3 second_row_1 second_row_2 second_row_3 I would like to read the second row of the text file and convert the contents into a list of string in python. The list should look like this; txt_list_str=['second_row_1','second_row_2','second_row_3'] Here is my attempted code; import csv with open('data.txt', newline='') as f: reader = csv.reader(f) row1 = next(reader) row2 = next(reader) my_list = row2.split(" ") I got the error AttributeError: 'list' object has no attribute 'split' I am using python v3. EDIT: Thanks for all the answers. I am sure all of them works. But can someone tell me what is wrong with my own attempted code? Thanks.
type: Question
tagged with: python-3.x
downvote count: 0
has title: Read and convert row in text file into list of string
has comment: http://stackoverflow.com/comment/81263787
has comment: http://stackoverflow.com/comment/81264341
tagged with: python
score: 4
favorite count: 0
has answer: http://stackoverflow.com/a/47157631
type: AnsweredQuestion

http://stackoverflow.com/comment/81202095
type: Comment
type: QuestionComment
score: 0
has text: Glad I could instigate a solution.
comment on: http://stackoverflow.com/q/47125695

http://stackoverflow.com/comment/81292251
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47170119
has text: Cool, glad it works for you, cheers :)

http://stackoverflow.com/a/47133430
score: 0
has comment: http://stackoverflow.com/comment/81322998
has comment: http://stackoverflow.com/comment/81314748
has comment: http://stackoverflow.com/comment/81246244
has comment: http://stackoverflow.com/comment/81217209
has comment: http://stackoverflow.com/comment/81217024
type: Answer
answers question: http://stackoverflow.com/q/47133011
has body: Could you be a little more specific about the rule you're trying to create? You enter 1 into the Hit column even though entries from the next 5 minutes after that record have 0s in Bool. Did you mean last 5 minutes?
has comment: http://stackoverflow.com/comment/81333882

http://stackoverflow.com/q/47188976
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81327611
has answer: http://stackoverflow.com/a/76806543
answer count: 5
has answer: http://stackoverflow.com/a/47191685
accepted answer: http://stackoverflow.com/a/47191685
has answer: http://stackoverflow.com/a/63825425
type: Question
upvote count: 20
has answer: http://stackoverflow.com/a/79439015
has comment: http://stackoverflow.com/comment/81331894
score: 20
has title: How to get the IDENTITY value when using INSERT ... OUTPUT with pyodbc
downvote count: 0
has body: I am trying to get the ID of a newly inserted row by using OUTPUT. However, I encountered the HY010 error. The following query/code is what I use: string = """ SET NOCOUNT ON; DECLARE @NEWID TABLE(ID INT); INSERT INTO dbo.t1 (Username, Age) OUTPUT inserted.id INTO @NEWID(ID) VALUES(?, ?) SELECT ID FROM @NEWID """ cursor.execute(string, "John Doe", 35) cursor.commit() id = cursor.fetchone()[0] the last line id = cursor.fetchone()[0] led to a HY010 error (see below). Any advice would be greatly appreciated! pyodbc.Error: ('HY010', '[HY010] [Microsoft][ODBC SQL Server Driver]Function sequence error (0) (SQLFetch)')
tagged with: python
tagged with: pyodbc
has answer: http://stackoverflow.com/a/60872000
favorite count: 0
possible better answer: http://stackoverflow.com/a/63825425
tagged with: sql-server

http://stackoverflow.com/a/53098510
answers question: http://stackoverflow.com/q/47217880
type: Answer
score: 22
upvote count: 22
has comment: http://stackoverflow.com/comment/120473874
downvote count: 0
has comment: http://stackoverflow.com/comment/132750450
has comment: http://stackoverflow.com/comment/97303411
has comment: http://stackoverflow.com/comment/120058800
has comment: http://stackoverflow.com/comment/120036501
has body: I got similar problem. It solved for me to update the version of gunicorn to 19.9.0 gunicorn 19.9.0 and for others that might experience the same problem - make sure to add the timeout. I personally use gunicorn app.wsgi:application -w 2 -b :8000 --timeout 120

http://stackoverflow.com/q/47118481
has answer: http://stackoverflow.com/a/47118551
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: pandas
has title: How to transpose a row within a pandas dataframe and create a columns?
accepted answer: http://stackoverflow.com/a/47118551
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
has body: I have the following list: list_1 = [{'28d_click': '2', 'action_type': 'comment', 'value': '2'}, {'28d_click': '1779', '7d_view': '11144', 'action_type': 'offsite_conversion.custom.xx', 'value': '9425'}, {'28d_click': '122', 'action_type': 'landing_page_view', 'value': '122'}, {'28d_click': '21', 'action_type': 'like', 'value': '21'}, {'28d_click': '175', 'action_type': 'link_click', 'value': '175'}, {'28d_click': '1', 'action_type': 'post', 'value': '1'}, {'28d_click': '23', 'action_type': 'post_reaction', 'value': '23'}, {'28d_click': '222', 'action_type': 'page_engagement', 'value': '222'}, {'28d_click': '201', 'action_type': 'post_engagement', 'value': '201'}, {'28d_click': '1936', '7d_view': '11171', 'action_type': 'offsite_conversion', 'value': '9607'}] I have then used this list to create a pandas DataFrame: df = pd.DataFrame(list_1) What I would like to do is use the action_type as columns and store the values in the rows beneath: Below is just an example - please NOTE: some action_types (conversions) will need to have two fields (28d_click) and (7d_view) as separate columns. EG: Column1: Conversion_1 (28d_click) | Column2: Conversion_1 (7d_view) landing_page_view link_click offsite_conversion.custom.xx (28d_click) offsite_conversion.custom.xx (7d_view). 122 175 7 16 What I have tried: df = pd.DataFrame(list_1).T Almost got the headings the way I wanted, but not quite with the 28d and 7d values print([d['action_type'] for d in list_1 if 'action_type' in d]) print([d['value'] for d in list_1 if 'value' in d]) print([d['28d_click'] for d in list_1 if '28d_click' in d]) print([d['7d_view'] for d in list_1 if '7d_view' in d]) This creates individual lists, but then not entirely sure what to do with them Is what I'm asking for possible? I have another DataFrame which I want to join this with but wanted to get this right first. Any help would be greatly appreciated. Thanks, Adrian

http://stackoverflow.com/comment/81130694
has text: I went with @gil.fernandes ' solution and added the ? to the https part. I didn't need python code, just the RegEx :) Still thanks for the explanation.
comment on: http://stackoverflow.com/a/47073044
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47150813
has comment: http://stackoverflow.com/comment/81290496
has answer: http://stackoverflow.com/a/47152005
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81251618
answer count: 1
type: Question
has body: When one wants to find and process all occurrences of a regex in a string, what is the qualitative difference between re.findall and iterating over its returned list versus iterating directly with re.search? In code, what is the qualitative difference between the findall version: sbls = "some big ... long string" for i in some_regex.findall( sbls ) process_item( i ) And the iterative search version: sbls = "some big ... long string" m = some_regex.search( sbls ) while m: process_item( m.group() ) m = some_regex.search(sbls, m.end()) In a very large string and a poorly chosen/low-cardinality regex, would the findall version consume more memory (perhaps via the list)? Conversely, would the search version take noticeably more time? Up to the constraints of the hardware to which I have access, I have not been able to discern a non-negligible difference, so would much appreciate others' insights.
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/47152005
has title: What is the _qualitative_ difference between re.findall and an iterative re.search?

http://stackoverflow.com/q/47163143
type: Question
has comment: http://stackoverflow.com/comment/81276433
score: 2
has answer: http://stackoverflow.com/a/78690026
has title: How to make a Format Check for registration plates
answer count: 2
upvote count: 2
tagged with: validation
has body: def FormatCheck(choice): while True: valid = True userInput = input(choice).upper() firstPart = userInput[:2] secondPart = userInput[2:4] thirdPart = userInput[4:] firstBool = False secondBool = False thirdBool = False if firstPart.isalpha() == True: firstBool = True elif secondPart.isdigit() == True: secondBool = True elif thirdPart.isalpha() == True: thirdBool = True else: print ("Your registration plate is private or is incorrect") firstBool = False secondBool = False thirdBool = False if firstBool == True and secondBool == True and thirdBool == True: return userInput break choice = FormatCheck("Please enter your registration plate") print(choice) Above is my very inefficient attempt at trying to display a format check on registration plates. It checks the three sections of the registration plate. THe sections being the first two characters, to make sure they were strings, then the next two characters, making sure they were integers, and the last three characters had to be strings. The code above does work, but I fee like there is an easier and shorter way of doing so, I just don't know how. Firstly, is there a way to create some sort of boolean list, add the result of each Format Check to it, and then if any of the results are false, make the user enter the registration plate again. This would remove the need for long if statements and redundant variables. Secondly, is there something I could do in a while loop, to check the three sections, instead of using three if statements? Thanks in advance
downvote count: 0
favorite count: 0
type: AnsweredQuestion
tagged with: format
accepted answer: http://stackoverflow.com/a/47163546
has answer: http://stackoverflow.com/a/47163546
has comment: http://stackoverflow.com/comment/81276600
tagged with: python
possible better answer: http://stackoverflow.com/a/78690026

http://stackoverflow.com/a/47226612
has body: I'll give you a hint. You're multiplying momentum by the previous_weight in your implementation, which is another parameter of the network on the same step. This obviously blows up quickly. What you should do instead is remember the whole update vector, l_rate * neuron['delta'] * inputs[j], on the previous backpropagation step and add it up. It might look something like this: velocity[j] = l_rate * neuron['delta'] * inputs[j] + momentum * velocity[j] neuron['weights'][j] += velocity[j] ... where velocity is an array of the same length as network, defined with a bigger scope than updateWeights and initialized with zeros. See this post for details.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47211478
score: 8
has comment: http://stackoverflow.com/comment/84719700
upvote count: 8
answers question: http://stackoverflow.com/q/47211478
type: Answer

http://stackoverflow.com/comment/81192561
type: Comment
has text: it does not have any
type: AnswerComment
comment on: http://stackoverflow.com/a/47121381
score: 0

http://stackoverflow.com/comment/81133513
type: QuestionComment
comment on: http://stackoverflow.com/q/47091061
score: 0
has text: fwiw when I install ipython 1.2.1 in a python 2.7.14 venv, the pid's in $VIRTUAL_ENV/bin/ipython and later in the interactive session match, it didn't spawn another process for executing commands in, so you probably started bin/ipython with the wrong interpreter which is decided by that shebang/the shell that reads that shebang
type: Comment

http://stackoverflow.com/comment/81264053
comment on: http://stackoverflow.com/q/47157458
type: QuestionComment
type: Comment
score: 0
has text: I think better is [pandas](http://pandas.pydata.org/) here.

http://stackoverflow.com/comment/81236843
type: Comment
type: QuestionComment
score: 3
has text: Resize it down to 16x16 using default interpolation, scale it back up to original size using nearest neighbour interpolation.
comment on: http://stackoverflow.com/q/47143332

http://stackoverflow.com/comment/81114886
has text: @alfasin. Based on the error: `C`
comment on: http://stackoverflow.com/q/47082785
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81173573
has text: @AlexHall may this be the reason why it is 'eating' results? While I do havE 6 items in my dict before, I get only 4 back in the grouped dict.
type: Comment
comment on: http://stackoverflow.com/a/47105219
type: AnswerComment
score: 0

http://stackoverflow.com/q/47180482
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81324975
has comment: http://stackoverflow.com/comment/81350561
has title: Python wrong multiple output
tagged with: python
has body: I have a func that retrieve information from program. It point the mouse grab an image, resize it, then get recognized with tesseract and add to ValueIndex. from PIL import Image import pytesseract import pyscreenshot as ImageGrab from pynput.mouse import Button, Controller import re def GetValues(): #Read matrix of digit from pytesseract.pytesseract.tesseract_cmd ='C:\\Program Files (x86)\\Tesseract-OCR\\tesseract' mouse = Controller() Mul=2 ValueIndex=[0 for i in range(0,170)] # Results y1=163 if __name__ == "__main__": for j in range(0,1):# get 1 line for example y1=y1+67 x1=1350 for i in range(0,13): x1=x1+67 mouse.position = (x1, y1) mouse.press(Button.left) mouse.release(Button.left) im=ImageGrab.grab(bbox=(1485, 1112,1680, 1177)) x,y = im.size x=x*Mul y=y*Mul size=x,y im_resized = im.resize(size, Image.ANTIALIAS) # resize for tesseract im_resized.save('test%s.png' % i) data = pytesseract.image_to_string(im_resized) q=''.join(re.findall('\d',data)) # gt digits from str if (len(q)==4): q=indexq[:2]+'.'+q[2:] if len(q)==3: q=q[:1]+'.'+q[1:] GetInd=j*13+i+1 ValueIndex[GetInd]=float(q) print(i,' ',data,' ',ValueIndex[GetInd]) # print to see the progress return(ValueIndex) GetValues() #When i comment it, print only 1 time print('Why so many times?:)') It work properly, but when i add print in body of prorgam it output multiple times. It's not in func loop, whats wrong? Why so many times?:) 0 +9.76% 9.76 Why so many times?:) 1 +619% 6.19 Why so many times?:) 2 +5.36% 5.36 and so on
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81314412
type: Question
tagged with: tesseract
has comment: http://stackoverflow.com/comment/81311580
tagged with: python-imaging-library

http://stackoverflow.com/comment/81368261
type: Comment
type: QuestionComment
has text: @AthulMuralidharan just use the content from [this](https://stackoverflow.com/questions/280435/escaping-regex-string-in-python) post to escape the joined list. You should have something like `"(?<!\d)\s*[" + re.escape(lst.join()) + "](?!\s*\d)"` (note the actual code I just wrote might not work - I can't test it at the moment - but it will resemble this)
score: 0
comment on: http://stackoverflow.com/q/47208877

http://stackoverflow.com/q/47202575
has comment: http://stackoverflow.com/comment/81353724
has body: I use an API to download ticket numbers from a website and then I count the unique ticket IDs in the arrays that I create that only accept one instance of an ID. This is very slow... I have tried using sets, and it is worse. I have seen mention of other tools, such as itertools but no clear explanation on how I could use it in a situation similar to mine. The good and bad variables store a type of Generator from what I can tell. Thanks so much for your help!!! good = self._client.satisfaction_ratings(score="good",sort_order="asc",start_time=thirty_days,end_time=today) bad = self._client.satisfaction_ratings(score="bad", sort_order="asc", start_time=thirty_days, end_time=today) good_array = [] bad_array = [] for g in good: if g.ticket.id not in good_array: good_array.append(g.ticket.id) for b in bad: if b.ticket.id not in bad_array: bad_array.append(b.ticket.id) goodnum = len(good_array) badnum = len(bad_array)
tagged with: optimization
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81353767
tagged with: list
answer count: 2
has comment: http://stackoverflow.com/comment/81353503
score: 1
possible better answer: http://stackoverflow.com/a/47203627
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47203627
has answer: http://stackoverflow.com/a/47202652
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47202652
tagged with: duplicates
tagged with: python
has title: Faster way to eliminate duplicates from list

http://stackoverflow.com/q/47212355
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/47212446
tagged with: file
has title: "Local variable referenced before assignment" warning when "else" loop missing
has comment: http://stackoverflow.com/comment/81374243
has comment: http://stackoverflow.com/comment/81374206
has comment: http://stackoverflow.com/comment/81374202
has comment: http://stackoverflow.com/comment/81374207
tagged with: python
score: -1
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/110712147
has comment: http://stackoverflow.com/comment/81374790
tagged with: python-3.x
tagged with: pycharm
has body: I have the following code: def readTweet(): tweets = open("tweets.txt", "r", encoding="utf-8") counter = 0 coordinates = [] try: line = tweets.readline() if line != "": lineList = line.split() else: # &lt;----- This statement return 0 for word in lineList: phrase = word.strip("[],.?!#") if counter == 0 or counter == 1: coordinates.append(float(phrase)) counter = counter + 1 except IOError: print("Input error, not a number.") My problem is that when I remove else statement else: return 0, I get a warning saying Local variable 'lineList' might be referenced before assignment If I were to print such as print(coordinates), I get the same output, regardless if the else statement is present or not. My question is, why is Python giving me this warning?
type: UnansweredQuestion

http://stackoverflow.com/q/47167891
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81305718
has comment: http://stackoverflow.com/comment/81306685
favorite count: 0
has comment: http://stackoverflow.com/comment/81288948
type: Question
tagged with: pyspark
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/67996485
has body: it's my first time using Apache-Spark with python (pyspark), and I was trying to run Quick Start Examples, but when I run the line saying: &gt;&gt;&gt; textFile = spark.read.text("README.md") it gives me the following error (I'm pasting just the first part because i think it's the most important): Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/daniele/Scaricati/spark/python/pyspark/sql/readwriter.py", line 311, in text return self._df(self._jreader.text(self._spark._sc._jvm.PythonUtils.toSeq(paths))) File "/home/daniele/Scaricati/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__ File "/home/daniele/Scaricati/spark/python/pyspark/sql/utils.py", line 63, in deco return f(*a, **kw) File "/home/daniele/Scaricati/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value py4j.protocol.Py4JJavaError: An error occurred while calling o22.text. : java.lang.reflect.InaccessibleObjectException: Unable to make field private transient java.lang.String java.net.URI.scheme accessible: module java.base does not "opens java.net" to unnamed module @779d0812 at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:335) Can someone help me to solve this? Sorry if my post is not that clear, but it's the first one on this forum. Thanks to everyone who will try to help, Daniele.
has title: Apache-Spark error on python : java.lang.reflect.InaccessibleObjectException
has comment: http://stackoverflow.com/comment/81287371
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/81296172
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81303779

http://stackoverflow.com/comment/81169476
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47106515
has text: Maybe it's the cable, I bought a "TipRX RingTX SlvGND" cable and I had another choice "TipTX RingRX SlvGND", I don't know how I can be sure...
score: 0

http://stackoverflow.com/comment/138030437
score: 1
comment on: http://stackoverflow.com/a/68001205
has text: AFAICT this doesn't work correctly on large dicts/json. I'm seeing "errors" with pytest that seem related to sort/display order, which unittest handles correctly.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81259976
type: Comment
type: QuestionComment
has text: You didn't actually execute the `whily_naughty()` future. You only wrapped it.
score: 2
comment on: http://stackoverflow.com/q/47154893

http://stackoverflow.com/a/47077716
answers question: http://stackoverflow.com/q/47077290
type: Answer
score: 0
has body: There is a tool called pandas that would actually help you with this. Numpy is not good for operations based on strings. import pandas as pd m = pd.DataFrame([["type1", 1, 2, 3], ["type2", 3, 4, 1], ["type1", 0.5, 0.5, 1], ["type2", 1, 1, 0.5]]) arr = m.groupby([0],as_index=False).mean().values Output of arr array([['type1', 0.75, 1.25, 2.0], ['type2', 2.0, 2.5, 0.75]], dtype=object)

http://stackoverflow.com/q/47214966
has title: function + swticher in python
has answer: http://stackoverflow.com/a/47215097
has comment: http://stackoverflow.com/comment/81379443
has answer: http://stackoverflow.com/a/47215164
tagged with: switchers
type: Question
has comment: http://stackoverflow.com/comment/81379397
answer count: 2
has body: I have an issue with the use of functions and switcher in python: I have this production cost function: def fcostoproduccion (X,periodo): if X &gt; 0: switcher = { 1: 200 + 15 * X, 2: 100 + 20 * X, 3: 100 + 4 * (X ** (1 / 2)), 4: 100 + 3 * X, 5: 150 + 6 * X, 6: 200 + 12 * (X ** (1 / 2)), 7: 200 + 15 * X, 8: 100 + 10 * X, 9: 100 + 6 * (X ** (1 / 2)), 10: 200 + 5 * (X ** (1 / 2)), 11: 100 + 10 * X, 12: 150 + 6 * X } return And at the end I'm trying to look for the value: for l in range(j+1, k+1): Ordenar = O[l] Produccion = fcostoproduccion(Demanda, l) I know I'm making a mistake but don't know how to solve it. Thanks in advance.
tagged with: function
possible better answer: http://stackoverflow.com/a/47215097
has comment: http://stackoverflow.com/comment/81379480
tagged with: python
has comment: http://stackoverflow.com/comment/81379431
has comment: http://stackoverflow.com/comment/81379418
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81379607
accepted answer: http://stackoverflow.com/a/47215164

http://stackoverflow.com/q/47117269
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81184646
has title: Does everything in my code look good?
has comment: http://stackoverflow.com/comment/81184666
has answer: http://stackoverflow.com/a/47117335
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81184601
has comment: http://stackoverflow.com/comment/81184617
type: AnsweredQuestion
has body: Anything I could improve on?? I am a python beginner. Is there anything I could do to make my code look cleaner or just make it look more professional? Thanks while True: print('What password will you be storing?') PassChoice = input() print('What is your username or email for this account?') UserOrEmail = input() print("What is the password for " + str(PassChoice) + '?') Password = input() print('Your password for ' + str(PassChoice) + ' has been stored.') WebsiteAndPassword = (str(PassChoice) + '| ' + str(UserOrEmail) +': ' + str(Password) + '\n') break PasswordFile = open('importantpasswords.txt', 'a') PasswordFile.write(str(WebsiteAndPassword)) PasswordFile.close()
answer count: 2
has answer: http://stackoverflow.com/a/47117298
possible better answer: http://stackoverflow.com/a/47117298
downvote count: 2
accepted answer: http://stackoverflow.com/a/47117335
upvote count: 1

http://stackoverflow.com/comment/81207957
comment on: http://stackoverflow.com/q/47128907
has text: Are you trying to make a single list that contains these values? `[cell.column for row in row2 for cell in row if cell.value == 'a']`
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81247309
comment on: http://stackoverflow.com/a/47148397
has text: @slothish1 you're dividing `b` by itself in your comment ^_^
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47100559
type: Question
has body: I am solving a system of differential equations using scipy's odeint and I have a problem now that I can't seem to fix: if a certain condition is met, I have to 'go back in time' to an earlier state, change a (global) parameter and continue integrating from there. At first I thought, although you can't really go back in time with odeint that I will store the time(s) at which the condition is met, change the state of the system (the variable that is integrated) and just continue the integration from there. Unfortunately I can't find a way to access the values of the variable for past times from within odeint. Does somebody know a way to solve my dilemma? If that is not possible, can somebody suggest a different way to do this? Performance is an issue, so I would really like to not have to write my own solver in python. I could do it in C, but that would require me to change the whole implementation and that would cost me a lot of time.
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/81152704
tagged with: python
has title: Acessing earlier values using scipy's odeint
tagged with: numpy
has comment: http://stackoverflow.com/comment/81172777
answer count: 0
tagged with: differential-equations
has comment: http://stackoverflow.com/comment/81152442
downvote count: 0
tagged with: odeint
upvote count: 1
tagged with: scipy
favorite count: 0

http://stackoverflow.com/a/47169182
type: Answer
has body: Consider no single for loop (except loop over the files), if logic, or helper dictionary/lists objects. Simply run XSLT, the transformation language that can convert XML to other XML, HTML, and especially for your CSV/TXT files. However, in order to run an XSLT 1.0 scripts you need Python's third-party module, lxml, and not the built-in etree. There are external processors Python can call though even built-in ones such as Window's System.Xml.Xsl and Linux/Mac's xsltproc. XSLT (save as .xsl, another special well-formed .xml file) &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output indent="yes" method="text"/&gt; &lt;xsl:strip-space elements="*"/&gt; &lt;xsl:template match="/CAT"&gt; &lt;xsl:text&gt;Id_Customer,Segment,Nature,Extrainfo,zipcode,zipcode2,zipcode3,street,street2,street3,number,number2,number3&amp;#xa;&lt;/xsl:text&gt; &lt;xsl:apply-templates select="Customer"/&gt; &lt;/xsl:template&gt; &lt;xsl:template match="Customer"&gt; &lt;xsl:value-of select="concat(Id_Customer, ', ', Segment, ', ', Event/Nature, ', ', Event/Extrainfo, ', ', Address[1]/zipcode, ', ', Address[2]/zipcode, ', ', Address[3]/zipcode, ', ', Address[1]/street, ', ', Address[2]/street, ', ', Address[3]/street, ', ', Address[1]/number, ', ', Address[2]/number, ', ', Address[3]/number)"/&gt;&lt;xsl:text&gt;&amp;#xa;&lt;/xsl:text&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; Python (integrate your XML through this process) import lxml.etree as et # LOAD XML AND XSL doc = et.parse('Input.xml') xsl = et.parse('XSLTScript.xsl') # TRANSFORM XSLT transform = et.XSLT(xsl) result = transform(doc) # SAVE RESULT TO FILE with open('Output.csv', 'w') as f: f.write(str(result)) Input Sample (extended from previous question post) &lt;?xml version="1.0"?&gt; &lt;CAT&gt; &lt;Header&gt;...&lt;/Header&gt; &lt;Add&gt;...&lt;/Add&gt; &lt;Customer&gt; &lt;Id_Customer&gt;xyz1&lt;/Id_Customer&gt; &lt;Segment&gt;abc1&lt;/Segment&gt; &lt;Event&gt; &lt;Nature&gt;inf…
score: 0
answers question: http://stackoverflow.com/q/47168749

http://stackoverflow.com/q/47179791
has comment: http://stackoverflow.com/comment/81308476
score: 1
has title: python ModuleNotFoundError: import works from console but not from nested modules
has body: I have a module called _local at the root of my project, and a file in another module that imports it: when I run python _devtools/test_import.py from root folder, I get an error: python _devtools/test_import.py Traceback (most recent call last): File "_devtools/test_import.py", line 1, in &lt;module&gt; import _local ModuleNotFoundError: No module named '_local' when I try to import this module from the console, while staying in the same root folder, it works: python Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import _local &gt;&gt;&gt; What should I modify in my environment variables to make the import work?
answer count: 1
downvote count: 0
upvote count: 1
tagged with: import
favorite count: 0
type: Question
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47180283
has answer: http://stackoverflow.com/a/47180283

http://stackoverflow.com/a/47191137
score: 0
has body: With the nested lists of names, you could use the following: playerDict = dict.fromkeys([p[0] for p in playerNames, 0]) or even: playerDict = {p[0]:0 for p in playerNames} I would advise however that you make only a list of names (instead of a nested list) by appending only the name with the following change: playerNames.append(row[0])
answers question: http://stackoverflow.com/q/47190916
type: Answer

http://stackoverflow.com/a/47083162
type: Answer
has body: The problem is that you don't have get_by_natural_key method defined in you manager. This is the method that the library uses to retrieve user object: https://github.com/GetBlimp/django-rest-framework-jwt/blob/0a0bd402ec21fd6b9a5f715d114411836fbb2923/rest_framework_jwt/authentication.py#L59 To resolve it, simply add this method to your AccountManager: def get_by_natural_key(self, username): return self.get(username=username) Not sure why this isn't documented in more detail in django-rest-framework-jwt docs..
has comment: http://stackoverflow.com/comment/81128338
upvote count: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47073515
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/47073515
has comment: http://stackoverflow.com/comment/81126333

http://stackoverflow.com/comment/81192980
has text: put you solution i would love to see your approach
type: Comment
comment on: http://stackoverflow.com/a/47104764
score: 0
type: AnswerComment

http://stackoverflow.com/q/47069058
answer count: 1
tagged with: yuv
type: Question
has body: I am trying to enhance my image by first converting RGB color space to YUV color space and do histogram equalization to Y value. However, the output image does not look good. For histogram equalization, I use the method found on Wikipedia. Here is the input image: Here is the output image: I really don't know where the problem is, can anyone help me or give me some hint? Below is my code, import cv2 import numpy as np img = cv2.imread('/Users/simon/Documents/DIP/Homework_3/input4.bmp') shape = img.shape Y_origin_hist = [0] * 256 U_origin = [[0 for i in range(0, shape[1])] for j in range(0, shape[0])] V_origin = [[0 for i in range(0, shape[1])] for j in range(0, shape[0])] Y_hist = [0] * 256 # Read RGB value and calculate YUV value for i in range(0, shape[0]) : for j in range(0, shape[1]) : px = img[i,j] y = int(0.299 * px[2] + 0.587 * px[1] + 0.114 * px[0]) u = int(-0.169 * px[2] - 0.331 * px[1] + 0.5 * px[0]) + 128 v = int(0.5 * px[2] - 0.419 * px[1] - 0.081 * px[0]) + 128 Y_origin_hist[y] = Y_origin_hist[y] + 1 U_origin[i][j] = u V_origin[i][j] = v # Histogram equalization for i in range(0, 256) : Y_hist[i] = int(((sum(Y_origin_hist[0:i]) - min(Y_origin_hist) - 1) * 255) / ((shape[0] * shape[1]) - 1)) # Write back to RGB value for i in range(0, shape[0]) : for j in range(0, shape[1]) : px = img[i,j] px[0] = int(Y_hist[px[0]] + 1.77216 * (U_origin[i][j] - 128) + 0.00099 * (V_origin[i][j] - 128)) px[1] = int(Y_hist[px[1]] - 0.3437 * (U_origin[i][j] - 128) - 0.71417 * (V_origin[i][j] - 128)) px[2] = int(Y_hist[px[2]] - 0.00093 * (U_origin[i][j] - 128) + 1.401687 * (V_origin[i][j] - 128)) cv2.imwrite('/Users/simon/Documents/DIP/Homework_3/output4.bmp', img)
score: 0
has comment: http://stackoverflow.com/comment/81113521
tagged with: python
tagged with: image-processing
tagged with: rgb
accepted answer: http://stackoverflow.com/a/52337689
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52337689
has title: Image enhancement with python and OpenCV

http://stackoverflow.com/q/47088329
tagged with: python
has title: Python logging module not logging info even after level is set
has answer: http://stackoverflow.com/a/47088541
possible better answer: http://stackoverflow.com/a/47088541
type: AnsweredQuestion
upvote count: 3
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/47088434
has body: I'm trying to do some basic logging. I'm doing the following: log = logging.getLogger('test') log.error('test') # 'test' gets logged log.info('test') # Nothing gets logged, as expected log.setLevel(logging.INFO) # Now info should be logged, right? log.info('test') # No output log.setLevel(logging.INFO) # Getting desperate log.info('test') # Still nothing What aspect of the logging module am I missing?
has answer: http://stackoverflow.com/a/64247536
has comment: http://stackoverflow.com/comment/113608913
tagged with: logging
favorite count: 0
type: Question
tagged with: python-3.x
score: 3
has answer: http://stackoverflow.com/a/47088434

http://stackoverflow.com/q/47166711
answer count: 2
tagged with: zlib
tagged with: pickle
upvote count: 1
tagged with: scikit-learn
has body: I am using the pickle and zlib libraries to serialize and compress 3 objects for storage in TSQL as nvarchar(MAX), using pyodbc. When retrieving these objects from SQL on the other end, 2 successfully translate back to their original form (2d numpy array and sklearn.StandardScaler). The third object (sklearn.GradientBoostingRegressor) does not translate back. Below is a summary of the code used. Should also note that I'm using Pandas for some SQL work. Below is the pickling, compression and upload to SQL code: model_pickle = zlib.compress(pickle.dumps(est)) scaler_pickle = zlib.compress(pickle.dumps(scaler),1) boundary_pickle = zlib.compress(pickle.dumps(bounds),1) cnxn = pyodbc.connect('driver={SQL Server};server=XXX;database=XYZ;trusted_connection=true') cursor = cnxn.cursor() cursor.execute("""INSERT INTO AD_RLGNMNT_MDL_PICKLE (CHAIN_NUM,AD_LENGTH,GL_CODE,AD_TYPE,MODEL_PICKLE,SCALER_PICKLE,WFA_TEST,BOUNDS_PICKLE) VALUES (?,?,?,?,?,?,?,?);""", (chain_num.astype(np.int32),ad_length.astype(np.int32),gl_code.astype(np.int32),ad_type,model_pickle,scaler_pickle,WFA,boundary_pickle)) cursor.commit() cursor.close() cnxn.close() Below is the code for pulling from SQL, decompressing and unpickling the objects: model_pickle = pd.read_sql("""SELECT A.MODEL_PICKLE from AD_RLGNMNT_MDL_PICKLE A WHERE A.CHAIN_NUM = %s and A.ad_length = %s and A.GL_CODE = %s and A.AD_TYPE in ('%s');""" % (Current_chain_num, Current_ad_length, Current_GL, Current_ad_type),cnxn) scaler_pickle = pd.read_sql("""SELECT A.SCALER_PICKLE from AD_RLGNMNT_MDL_PICKLE A WHERE A.CHAIN_NUM = %s and A.ad_length = %s and A.GL_CODE = %s and A.AD_TYPE in ('%s');""" % (Current_chain_num, Current_ad_length, Current_GL, Current_ad_type),cnxn) bounds_pickle = pd.read_sql("""SELECT A.BOUNDS_PICKLE from AD_RLGNMNT_MDL_PICKLE A WHERE A.CHAIN_NUM = %s and A.ad_length = %s and A.GL_CODE = %s and A.AD_TYPE in ('%s');""" % (Current_chain_num, Current_ad_length, Current_GL, Current_ad_type),cnxn) combos_list.set_value(i, 'mod…
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47166894
type: AnsweredQuestion
score: 0
tagged with: sql
has answer: http://stackoverflow.com/a/47167089
possible better answer: http://stackoverflow.com/a/47167089
tagged with: python
has title: Information lost when pickling, compressing Python object and storing in SQL
accepted answer: http://stackoverflow.com/a/47166894
type: Question
has comment: http://stackoverflow.com/comment/81283467

http://stackoverflow.com/comment/81353303
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47202397
has text: I would like to split it in 80% training to 20% test. What will be the code then?
score: 0

http://stackoverflow.com/comment/81158456
type: QuestionComment
comment on: http://stackoverflow.com/q/47103063
has text: @PRMoureu I just swapped it out for django 1.11 and the same issue occurs. Also updated the version in my original post. (For clarity's sake, I was originally using 1.10.)
score: 0
type: Comment

http://stackoverflow.com/q/47113813
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48577227
has title: Using pyarrow how do you append to parquet file?
answer count: 5
has answer: http://stackoverflow.com/a/47114713
score: 58
tagged with: python
upvote count: 58
has answer: http://stackoverflow.com/a/74272955
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47191675
tagged with: parquet
tagged with: pandas
has body: How do you append/update to a parquet file with pyarrow? import pandas as pd import pyarrow as pa import pyarrow.parquet as pq table2 = pd.DataFrame({'one': [-1, np.nan, 2.5], 'two': ['foo', 'bar', 'baz'], 'three': [True, False, True]}) table3 = pd.DataFrame({'six': [-1, np.nan, 2.5], 'nine': ['foo', 'bar', 'baz'], 'ten': [True, False, True]}) pq.write_table(table2, './dataNew/pqTest2.parquet') #append pqTest2 here? There is nothing I found in the docs about appending parquet files. And, Can you use pyarrow with multiprocessing to insert/update the data.
has answer: http://stackoverflow.com/a/70817689
tagged with: pyarrow
downvote count: 0
accepted answer: http://stackoverflow.com/a/47839247
possible better answer: http://stackoverflow.com/a/48577227
has comment: http://stackoverflow.com/comment/103317235
has answer: http://stackoverflow.com/a/47839247

http://stackoverflow.com/comment/81386028
comment on: http://stackoverflow.com/a/47217907
type: Comment
score: 0
type: AnswerComment
has text: Then it comes to the same error : expected time_distributed_1 to have 3 dimensions, but got array with shape (25000, 1)

http://stackoverflow.com/q/47201539
has answer: http://stackoverflow.com/a/57845903
possible better answer: http://stackoverflow.com/a/57845903
has body: I'm using QtableView to show my logs and to filter them by column, QSortFilterProxyModel is used. If i filter one column using certain value, and with the filtered data, if i try to filter second column, last filter gets reset and data are displayed corresponding to filter on second column. I want to achieve multiple column filter on Qtableview. Code snippet: self.tableView = QTableView() self.model = QtGui.QStandardItemModel(self) self.proxy = QtGui.QSortFilterProxyModel(self) self.proxy.setSourceModel(self.model) self.tableView.setModel(self.proxy) def updateTable(self): self.model.invisibleRootItem().appendRow(,,,,) def filterTable(self, stringAction, filterColumn): filterString = QtCore.QRegExp( stringAction, QtCore.Qt.CaseSensitive, QtCore.QRegExp.FixedString ) self.proxy.setFilterRegExp(filterString) self.proxy.setFilterKeyColumn(filterColumn)
has title: How to filter Multiple column in Qtableview?
tagged with: pyqt4
tagged with: python
has answer: http://stackoverflow.com/a/47203950
tagged with: qtableview
score: 8
type: AnsweredQuestion
tagged with: python-2.7
answer count: 3
downvote count: 0
tagged with: pyqt
accepted answer: http://stackoverflow.com/a/47203950
upvote count: 8
has answer: http://stackoverflow.com/a/77532929
favorite count: 0
type: Question

http://stackoverflow.com/comment/81142821
type: AnswerComment
comment on: http://stackoverflow.com/a/47094049
has text: @Chris72H, as was mentioned in my answer: `multiprocessing.Pool.map` function can split the whole initial array into needed number of chunks without custom `split()` functions
type: Comment
score: 0

odt
tags question: http://stackoverflow.com/q/47076418
tag name: odt
type: Tag

http://stackoverflow.com/q/47110016
downvote count: 0
favorite count: 0
type: Question
tagged with: package
has answer: http://stackoverflow.com/a/47110115
accepted answer: http://stackoverflow.com/a/47110115
tagged with: python
has body: I have a following directory structure: source source_1.py __init__.py source1.py has class Source defined source1.py class Source(object): pass I am able to import using this &gt;&gt;&gt; from source.source1 import Source &gt;&gt;&gt; Source &lt;class 'source.source1.Source'&gt; However when trying to import using the below method it fails. &gt;&gt;&gt; from source import * &gt;&gt;&gt; source1.Source Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'source1' is not defined Please let me know how can we use the 2nd import ?
has title: Error when importing python module from folders
type: AnsweredQuestion
tagged with: python-2.7
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/81321636
type: QuestionComment
comment on: http://stackoverflow.com/q/47186213
has text: The for-loop in textfilemanage() waits until the thread finishes so the thread is useless.
type: Comment
score: 0

http://stackoverflow.com/comment/81094460
type: QuestionComment
has text: Well, it is not a known issue. I have done my homework regarding this and I posted it here since DSX points me to post me the question here. If it helps, I can include the set of things that I tried. Do you have a solution? Which project forum are you referring to?
score: 1
comment on: http://stackoverflow.com/q/47072935
type: Comment

http://stackoverflow.com/a/47150467
has comment: http://stackoverflow.com/comment/81281396
upvote count: 2
has comment: http://stackoverflow.com/comment/81280709
downvote count: 0
has comment: http://stackoverflow.com/comment/81281137
has comment: http://stackoverflow.com/comment/81282361
has comment: http://stackoverflow.com/comment/81279646
score: 2
has comment: http://stackoverflow.com/comment/81272922
answers question: http://stackoverflow.com/q/47142311
has comment: http://stackoverflow.com/comment/81279432
has comment: http://stackoverflow.com/comment/81279551
type: Answer
has body: The error says it all Cannot switch to US keyboard layout - some keys may be interpreted incorrectly. This error have introduced some more errors as: [2.035][INFO]: RESPONSE InitSession unknown error: chrome failed to start [2.035][DEBUG]: Log type 'driver' lost 0 entries on destruction [2.035][DEBUG]: Log type 'browser' lost 0 entries on destruction So basically this error is not of Selenium or Chrome as such. Here are the 3 best possible solutions to your problem. Update : As you have got rid of the error Cannot switch to US keyboard layout - some keys may be interpreted incorrectly but you still see WebDriverException: Message: unknown error: chrome failed to start follow the steps as below : Uninstall Chrome through Revo Uninstaller with Moderate Memory Scan so that the unwanted registry entries are cleared. Run CCleaner tool before and after executing your Tests to wipe off all the OS chores. Reboot your system. Execute your Test as: driver=webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe')
has comment: http://stackoverflow.com/comment/81279702
has comment: http://stackoverflow.com/comment/81273232

http://stackoverflow.com/q/47067443
tagged with: scipy
tagged with: append
has comment: http://stackoverflow.com/comment/81082900
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47067874
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/81083470
has title: append used in different versions of scipy
answer count: 1
has body: I have questions with regards to the function of append in different versions of scipy. If I used the following script in the Python 2.7.3 and scipy 0.10.1 (numpy1.6.2), everything works out well. a=(1,2,3);b=(4,5,6);append(a,b,1);array([1,2,3,4,5,6]) a=[];b=(4,5,6);append(a,b,1);array([4,5,6]) But if I run these in the python2.7 and scipy1.0.0 (numpy 1.13.3): a=(1,2,3);b=(4,5,6);append(a,b,1); a=[];b=(4,5,6);append(a,b,1); Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 5152, in append return concatenate((arr, values), axis=axis) numpy.core._internal.AxisError: axis 1 is out of bounds for array of dimension 1 But I have checked the functions of append in the function_base.py, they are identical in both version of numpy. Do you guys know why this would happen? Another question is that if I am using python2.7, it is possible for me to use an older version of scipy/numpy installed under python2.6? Thank you in advance.

http://stackoverflow.com/comment/81259277
comment on: http://stackoverflow.com/a/47153241
has text: If you suppose `numpy.genfromtxt`, it doesn't work. Although, I don't know what part exactly you wanted to replace with that code.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47118796
upvote count: 3
has comment: http://stackoverflow.com/comment/81188373
downvote count: 0
type: AcceptedAnswer
has body: I think in v1 and v2 are no NaNs, so use transform + size: df = df[df.groupby(['v1', 'v2'])['v2'].transform('size') == 6] print (df) v1 v2 v3 0 0 -30 -15.00000 1 0 -30 -7.50000 2 0 -30 -11.25000 3 0 -30 -13.12500 4 0 -30 -14.06250 5 0 -30 -13.59375 6 0 -10 -5.00000 7 0 -10 -7.50000 8 0 -10 -6.25000 9 0 -10 -5.62500 10 0 -10 -5.93750 11 0 -10 -6.09375 Detail: print (df.groupby(['v1', 'v2'])['v2'].transform('size') == 6) 0 True 1 True 2 True 3 True 4 True 5 True 6 True 7 True 8 True 9 True 10 True 11 True 12 False 13 False 14 False Name: v2, dtype: bool Unfortunately filter is really slow, so if need better performance use transform: np.random.seed(123) N = 1000000 L = list('abcdefghijkl') df = pd.DataFrame({'v1': np.random.choice(L, N), 'v2':np.random.randint(10000,size=N), 'value':np.random.randint(1000,size=N), 'value2':np.random.randint(5000,size=N)}) df = df.sort_values(['v1','v2']).reset_index(drop=True) print (df.head(10)) In [290]: %timeit df.groupby(['v1', 'v2']).filter(lambda x: len(x) == 6) 1 loop, best of 3: 12.1 s per loop In [291]: %timeit df[df.groupby(['v1', 'v2'])['v2'].transform('size') == 6] 1 loop, best of 3: 176 ms per loop In [292]: %timeit df[df.groupby(['v1', 'v2']).v2.transform('count').eq(6)] 10 loops, best of 3: 175 ms per loop N = 1000000 ngroups = 1000 df = pd.DataFrame(dict(A = np.random.randint(0,ngroups,size=N),B=np.random.randn(N))) In [299]: %timeit df.groupby('A').filter(lambda x: len(x) &gt; 1000) 1 loop, best of 3: 330 ms per loop In [300]: %timeit df[df.groupby(['A'])['A'].transform('size') &gt; 1000] 10 loops, best of 3: 101 ms per loop Caveat The results do not address performance given the number of groups, which will affect timings a lot for some of these solutions.
has comment: http://stackoverflow.com/comment/81188514
has comment: http://stackoverflow.com/comment/81187886
has comment: http://stackoverflow.com/comment/81188614
accepted answer of: http://stackoverflow.com/q/47118756
has comment: http://stackoverflow.com/comment/81188555
has comment: http://stackoverflow.com/comment/81188435
score: 3
has comment: http://stackoverflow.com/comment/81187793
answers question: http://stackoverflow.com/q/47118756
has comment: http://stackoverflow.com/comment/81188502
has comment: http://stackoverflow.com/comment/81188577
has comment: http://stackoverflow.com/comment/81187819
type: Answer
has comment: http://stackoverflow.com/comment/81188596
has comment: http://stackoverflow.com/comment/81187835

http://stackoverflow.com/comment/81208065
comment on: http://stackoverflow.com/q/47127233
score: 0
has text: If you increase the size of the font, but keep the widget the same, letters will be cut off unable to read. Why would you want this?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81159069
type: AnswerComment
has text: Or just use the split function. `a=re.split(",\n", tulokset)`
comment on: http://stackoverflow.com/a/47104268
score: 1
type: Comment

http://stackoverflow.com/a/47170167
has comment: http://stackoverflow.com/comment/81290290
has comment: http://stackoverflow.com/comment/81290173
has comment: http://stackoverflow.com/comment/81290008
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: We can go through the array directly by the elements (more precisely by a pair of neighboring elements) simultaneously forming the result. We initialize our result with a sublist of the 1st element of the array and then: if the next element is greater than the previous one, we add it to the last sublist otherwise - we add a new sublist with this element to the result. array = [1,2,1,1,2,3,1,2,1,2,3,1,2,3,4,5] new_array = [[array[0]]] # assume the array is not empty for a,b in zip(array, array[1:]): if a&lt;b: new_array[-1].append(b) else: new_array.append([b]) print(new_array) # [[1, 2], [1], [1, 2, 3], [1, 2], [1, 2, 3], [1, 2, 3, 4, 5]] UPD. Alternatively, we can implement it with indices. (based on this answer by @fortran) First, prepare indices to split the array: idxs_to_split = [idx for idx in range(1, len(array)) if not array[idx-1] &lt; array[idx]] pairs = zip([0] + idxs_to_split, idxs_to_split + [None]) Second, implement the splitting itself: new_array = [array[i:j] for i,j in pairs] print(new_array) # [[1, 2], [1], [1, 2, 3], [1, 2], [1, 2, 3], [1, 2, 3, 4, 5]]
has comment: http://stackoverflow.com/comment/81290319
accepted answer of: http://stackoverflow.com/q/47170102
score: 3
has comment: http://stackoverflow.com/comment/81290189
type: Answer
answers question: http://stackoverflow.com/q/47170102
has comment: http://stackoverflow.com/comment/81290211

http://stackoverflow.com/q/47091791
type: Question
has body: I have a measuring device (connected to Raspberry) which outputs a series of zeros and ones. Without penetrating into the very essence of the measured value, Raspberry reads the state of input 1 thousand times per second. Measurement is that every second I have to count the number of zeros that have occurred in the last 30 seconds. Hence I have a string of 30,000 bits in which I have to count the number of zeros every second. Since of course the SD card is not suitable for this, I created a ramdisk (64 Mb) where the data can be saved at high speed without storing anything on the SD. I have a request to the Colleagues for advice. I would like to write a program in Python that counts these zeros, but I completely have no idea what algorithm to handle this and Python will handle it. It seems that you need to create some 30,000 bit software shift register and count the number of zeros in this registry every second. Do Colleagues have an idea for something like this?
has answer: http://stackoverflow.com/a/47103338
tagged with: algorithm
has title: Count number of zeros in registry in Python
tagged with: python
score: -2
upvote count: 0
type: UnansweredQuestion
downvote count: 2
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/81180530
comment on: http://stackoverflow.com/a/47115366
has text: Using `f-string` would be even more readable :)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81246386
has text: Thanks @thebjorn actually splitting by DATE is already a 'divide and conquer'.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47148078
type: Comment

http://stackoverflow.com/comment/81370591
has text: @juanpa.arrivillaga How is the structure loaded to memory before you run the script? I absolutely have no idea what caching has to do with anything. Again: what is being measured here anyway?
type: QuestionComment
comment on: http://stackoverflow.com/q/47210225
type: Comment
score: 0

http://stackoverflow.com/comment/81222211
has text: I'm not sure what you mean. As in change the range of the colorbar? Or actually change the data itself?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47135791
type: Comment

http://stackoverflow.com/comment/81258819
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47154519
has text: For starters, make `listn2` a `set`. `if x in y` is an `O(1)` operation on avg if `y` is a set and `O(len(y))` on avg if `y` is a list. Also, try to work with `numpy` so you can vectorize some operations.

http://stackoverflow.com/a/47200287
has body: This was a bug and was fixed as part of this JIRA https://0xdata.atlassian.net/browse/SW-569. This bug fix will be included in the next release of Sparkling Water.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47080618

http://stackoverflow.com/a/47095095
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/47094437
type: Answer
has body: Use: x = np.zeros(38) for i in range(0, 10): col_name = "char_" + str(i) df[col_name] = pd.Series([x], index=df.index) print (type(df.loc[0,'char_9'])) &lt;class 'numpy.ndarray'&gt;
has comment: http://stackoverflow.com/comment/81139577
answers question: http://stackoverflow.com/q/47094437
has comment: http://stackoverflow.com/comment/81139493

http://stackoverflow.com/q/47163757
has body: Is there a function that returns the arrays that are in a list according to the search? For example I want to get the list of tables containing the letter A myLst = [[ABC], [BCV], [BAD]] return [[ABC], [BAD]] Do I have to make my own function ?
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81277376
answer count: 2
has comment: http://stackoverflow.com/comment/81277246
score: -2
linked to: http://stackoverflow.com/q/3437059
has title: Is it possible to get all element in a list in python?
tagged with: python
has comment: http://stackoverflow.com/comment/81277322
has comment: http://stackoverflow.com/comment/81277280
type: AnsweredQuestion
upvote count: 0
downvote count: 2
possible better answer: http://stackoverflow.com/a/47164445
has answer: http://stackoverflow.com/a/47171950
accepted answer: http://stackoverflow.com/a/47171950
has answer: http://stackoverflow.com/a/47164445

http://stackoverflow.com/q/47194600
score: 0
has comment: http://stackoverflow.com/comment/81338894
has body: I'm trying to use subprocess to call another script, but being a beginner I'm not quite getting there. The first script defines the variables, and it will be saved in differing locations so it can't have an absolute path. The second script calls in the variables from the first script and will use them to do its thing. This script will stay in the same directory. This is what I have so far script1.py: import os import sys import subprocess x = 'VALUE' import subprocess subprocess.call(["python", "/mnt/scratch/script2.py"]) script2.py: import sys import subprocess from script1 import x Seems pretty basic but the error coming up is: ImportError: No module named x Cheers
has answer: http://stackoverflow.com/a/47195643
answer count: 1
has title: error using subprocess when calling from another script in python
type: Question
tagged with: subprocess
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81338459

http://stackoverflow.com/comment/81252063
comment on: http://stackoverflow.com/a/47143989
type: Comment
has text: hey perfect! it works for me... very thanks @daemon24. it's little syntax error only from your code you just missed the parenthesis on typing.. user_device_token_mappings = dict([(u['_id'],u['devicetoken']) for u in db.users.find({'_id' : {'$in':users}},{"devicetoken":1})])
type: AnswerComment
score: 1

http://stackoverflow.com/comment/81352569
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47201262
type: Comment
has text: in this data I have one more column that contains different values for this column with location names. is it possible to sort these location names with that column values and get the counts?

http://stackoverflow.com/a/47210832
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47210486
downvote count: 0
type: Answer
upvote count: 1
has body: Using base R you can do the following: set.seed(12345) #getting training data set sizes of .20 (in this case 20 out of 100) train.x&lt;-sample(1:100, 20) train.y&lt;-sample(1:100, 20) #simulating random data x&lt;-rnorm(100) y&lt;-rnorm(100) #sub-setting the x data training.x.data&lt;-x[train] testing.x.data&lt;-x[-train] #sub-setting the y data training.y.data&lt;-y[train] testing.y.data&lt;-y[-train]
score: 1
answers question: http://stackoverflow.com/q/47210486

http://stackoverflow.com/comment/81289039
type: QuestionComment
has text: I'm also a newbie so i wouldn't understand the answers of other 'advanced' posts.
type: Comment
comment on: http://stackoverflow.com/q/47169556
score: 0

http://stackoverflow.com/comment/81384797
type: QuestionComment
has text: If you want to keep things tidy, you could put your models in `models.py` and your serializers in `serializers.py` and then import your models into `serializers.py`.
comment on: http://stackoverflow.com/q/47216928
score: 0
type: Comment

http://stackoverflow.com/a/50584298
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88178464
accepted answer of: http://stackoverflow.com/q/47094382
has comment: http://stackoverflow.com/comment/88179327
answers question: http://stackoverflow.com/q/47094382
has body: It looks like Kalman filters family are doing what I expect. This is because they are optimal in terms of "Mean square error". Implementation can be found here for example.
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/comment/81098324
score: 1
has text: In Python we usually use either string formatting or (for filesystem path stuff) `os.path.join()` instead of string concatenation. And the official naming convention is "all_lower_with_underscores" for variable names.
comment on: http://stackoverflow.com/a/47074735
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47165683
has body: I would avoid using a regex here and just parse it with string manipulations: def read_commands(data): last_command = [] for token in data.split(): if token.startswith('G') and token[1:].isnumeric(): if last_command: yield last_command last_command = [token] else: last_command.append(token) yield last_command def parse_command(command): code = command[0] args = {} for arg in command[1:]: if '=' in arg: key, value = arg.split('=') else: key = arg[0] value = arg[1:] args[key] = value return code, args if __name__ == '__main__': data = ''' G1 X-387.7 A3=-1.0 B3=0.0 C3=0.0 F=R3 Y1.824 Z264.663 A3=-1.0 C3=0.0 G1 X-387.7 A3=-1.0 B3=0.0 C3=0.0 F=R3 Y1.824 Z264.663 A3=-1.0 C3=0.0 G1 X0 Y0 Z0 ''' for command in read_commands(data): code, args = parse_command(command) print(args.get('A3', 0))
type: Answer
has comment: http://stackoverflow.com/comment/81284297
has comment: http://stackoverflow.com/comment/81284150
has comment: http://stackoverflow.com/comment/81282806
score: 0
answers question: http://stackoverflow.com/q/47164436
has comment: http://stackoverflow.com/comment/81288701

http://stackoverflow.com/comment/81283527
type: QuestionComment
has text: While this is distinct from your [previous question](https://stackoverflow.com/questions/47146905/turning-a-generator-of-pairs-into-a-pair-of-generators), the same problems still apply; you're not going to be able to iterate over one of these generators without storing data in memory to feed the other generator. If you can't rerun `simulate`, you'll have to store data in memory, run your consumers in separate threads, or rewrite the consumers so you can interleave their execution.
comment on: http://stackoverflow.com/q/47166701
score: 2
type: Comment

http://stackoverflow.com/comment/81228622
type: Comment
has text: Yes, however not in the context of a `Parent` and a `Child`.
comment on: http://stackoverflow.com/a/47137989
type: AnswerComment
score: 1

http://stackoverflow.com/comment/81086033
comment on: http://stackoverflow.com/a/47068264
score: 0
type: AnswerComment
has text: @hpaulj True and I knew that. Unfortunately I did my tests with `flatnonzero` when I mistakenly thought that arrays are 1D and I never returned to testing `flatnonzero` again with 2D.
type: Comment

http://stackoverflow.com/comment/81285890
has text: The reason why I'm trying to store `datetime.utcnow().date()` that `time_created_day ` must contain only year,month and day. Do you know how can I get datetime object that will represent current `year,month and day`?
comment on: http://stackoverflow.com/q/47167412
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81273007
type: AnswerComment
has text: You shouldn't recommend this, it doesn't work with string columns.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47161719

http://stackoverflow.com/comment/81207839
type: Comment
has text: heh, nope... but thanks. I'm more of a groovy/java guy. My Python class from Trey last year kicked in when I saw this.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47128738

http://stackoverflow.com/comment/90895338
score: 0
type: Comment
has text: @StevenVascellaro, does it work for you to use `pytest` instead of `unittest`?
type: QuestionComment
comment on: http://stackoverflow.com/q/47143368

http://stackoverflow.com/q/47167490
has body: Ok, so Im not sure if this is even possible. I am trying to plot a graph in python, using matplotlib, that has a natural log function of both x and y. First, I looked for posts containing instructions on how-to plot using a natural log. I found part of an answer here and the other part here. The problem is, I am trying to plot two lines onto one graph. The equations are: 1) 0.91 - 0.42 * P = Q 2) 6.999 - .7903 * ln (P) = ln (Q) Is it possible to overlay these two lines onto one graph given the scale issue? How would I do it? I tried the following: from pylab import * import matplotlib.pyplot as plt import matplotlib get_ipython().magic('matplotlib inline') import numpy as np import pandas as pd P = np.linspace(0, 1, 11) P matplotlib.rcParams['xtick.major.pad'] = 5 matplotlib.rcParams['ytick.major.pad'] = 5 fig, ax = plt.subplots(figsize = (12,6)) axes = plt.gca() axes.set_ylim([0, 16]) ax.plot(P, 0.91 - 0.42 * P, color = "BLUE", lw = 3, label = 'C1') x = P ** np.e y = 6.999 - .7903 * x y1 = y ** np.e ax.loglog(x, y, basex = np.e, basey = np.e) ax.legend() ax.set_title("Cluster 1 Pricing") ax.xaxis.labelpad = 5 ax.yaxis.labelpad = 5 ax.set_xlabel("Norm P") ax.set_ylabel("Norm Q"); But this returns the error: ValueError: posx and posy should be finite values
downvote count: 2
accepted answer: http://stackoverflow.com/a/47168940
upvote count: 1
answer count: 1
tagged with: plot
type: AnsweredQuestion
tagged with: natural-logarithm
linked to: http://stackoverflow.com/q/773814
tagged with: matplotlib
linked to: http://stackoverflow.com/q/23312803
tagged with: python
has title: Matplotlib plotting ln functions
has answer: http://stackoverflow.com/a/47168940
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/81285078
type: Question
has comment: http://stackoverflow.com/comment/81284778

http://stackoverflow.com/a/47169848
has comment: http://stackoverflow.com/comment/82033586
accepted answer of: http://stackoverflow.com/q/47169673
type: Answer
has comment: http://stackoverflow.com/comment/81318794
answers question: http://stackoverflow.com/q/47169673
has comment: http://stackoverflow.com/comment/81321142
has body: Instead of storing into arrays in the first place and then manipulating, you can store straight into dictionaries! For instance, first_user = { 'username' : "ErikMendez", 'password' : "Mendez1995", 'balance' : 100.0 } Afterwards, you can access the dictionary by key values. For example, first_user['username'] returns the string ErikMendez. If you want to be able to create and access a list containing these bindings, you could do this: list = [] first_user = { 'username' : "ErikMendez", 'password' : "Mendez1995" } list.append(first_user) print(list[0]['username']) # prints ErikMendez print(list[0]['password']) # prints Mendez1995 Edit: Based on Blckknght's suggestion, here's something even better you can do: since dictionaries are based on 'key' : 'value' pairs, you could use username's as keys and use another dictionary as values to store the info! For instance: user_dictionary = { 'ErikMendez' : { 'password' : "Mendez1995", 'balance' : 100.0 }, 'Reinhardt' : { 'password' : "Honor&amp;Glory", 'balance' : 500.0 } } You can access this dictionary using print(user_dictionary['ErikMendez']) # prints { 'password' : "Mendez1995", 'balance' : 100.0 } print(user_dictionary['ErikMendez']['password']) # prints Mendez1995
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/81290077

http://stackoverflow.com/q/47127195
has comment: http://stackoverflow.com/comment/81204605
has comment: http://stackoverflow.com/comment/81204725
type: AnsweredQuestion
tagged with: terminal
score: 1
accepted answer: http://stackoverflow.com/a/47127257
tagged with: macos
has answer: http://stackoverflow.com/a/47127257
type: Question
has comment: http://stackoverflow.com/comment/81204587
linked to: http://stackoverflow.com/q/8967843
has title: How do you program Mac Terminal to shorten commands
has body: Suppose you have to write several commands all beginning with 'python manage.py' but you do not want to write those words each and every time. How do you create an alias where 'python manage.py' is shortened to two letters? So what I would like is to input 'pm'. And then I can input a command such as 'runserver'. This would then activate: 'python manage.py runserver'? Thanks in advance.
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/81300200
comment on: http://stackoverflow.com/q/47175043
type: Comment
has text: Thanks! That was the problem apparently
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81228448
comment on: http://stackoverflow.com/q/47137229
score: 0
has text: If the first one has the same shape, it cannot be a matrix because it has 3 dimensions. But I do not know which of the objects throws the exception. The usual numpy message would be more like ``shapes do not match`` or something similar.
type: Comment
type: QuestionComment

asterisk
tags question: http://stackoverflow.com/q/47155576
tags question: http://stackoverflow.com/q/47178150
tags question: http://stackoverflow.com/q/47191662
type: Tag
tag name: asterisk

http://stackoverflow.com/comment/81291130
has text: do you have headers? if so use pandas or csv module.
type: Comment
comment on: http://stackoverflow.com/a/47148531
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81294207
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47172373
has text: Are you using Numpy / Pandas?

http://stackoverflow.com/comment/81344133
comment on: http://stackoverflow.com/q/47196329
type: QuestionComment
has text: `type('MyClass',(),{})()`
score: 1
type: Comment

http://stackoverflow.com/a/74209756
has comment: http://stackoverflow.com/comment/134819211
downvote count: 0
has comment: http://stackoverflow.com/comment/137984998
has comment: http://stackoverflow.com/comment/137256795
type: Answer
score: 33
has body: Looks like its possible to append row groups to already existing parquet file using fastparquet. This is quite a unique feature, since most libraries don't have this implementation. Below is from pandas doc: DataFrame.to_parquet(path, engine='auto', compression='snappy', index=None, partition_cols=None, **kwargs) we have to pass in both engine and **kwargs. engine{‘auto’, ‘pyarrow’, ‘fastparquet’} **kwargs - Additional arguments passed to the parquet library. **kwargs - here we need to pass is: append=True (from fastparquet) import pandas as pd from pathlib import Path df = pd.DataFrame({'col1': [1, 2,], 'col2': [3, 4]}) file_path = Path("D:\\dev\\output.parquet") if file_path.exists(): df.to_parquet(file_path, engine='fastparquet', append=True) else: df.to_parquet(file_path, engine='fastparquet') If append is set to True and the file does not exist then you will see below error AttributeError: 'ParquetFile' object has no attribute 'fmd' Running above script 3 times I have below data in parquet file. If I inspect the metadata, I can see that this resulted in 3 row groups. Note: Append could be inefficient if you write too many small row groups. Typically recommended size of a row group is closer to 100,000 or 1,000,000 rows. This has a few benefits over very small row groups. Compression will work better, since compression operates within a row group only. There will also be less overhead spent on storing statistics, since each row group stores its own statistics.
answers question: http://stackoverflow.com/q/47191675
upvote count: 33

http://stackoverflow.com/comment/81304242
has text: You're quite right my bad. I haven't written any code using global variables in years so I was a little fuzzy on it and decided to play it safe.
type: Comment
comment on: http://stackoverflow.com/a/47176891
score: 0
type: AnswerComment

http://stackoverflow.com/q/47199515
has comment: http://stackoverflow.com/comment/81348888
has comment: http://stackoverflow.com/comment/81347923
has comment: http://stackoverflow.com/comment/81348745
type: Question
has answer: http://stackoverflow.com/a/47200397
has body: with code from different sources found here I put together a cleanup function to remove illegal characters from strings to include in an XML file. Some of it is redundant is it is quite messy. None of the functions I found have worked by themselves. I still get some problems trying to import the resulting XML file and punctuation has been removed. Everything is specified as UTF-8. I am not familiar with encodings, so a more elegant function that works would be greatly appreciated, thanks. def doclean(s): ranges=[(0, 8),(0xb,0x1f),(0x7f,0x84),(0x86,0x9f),(0xd800,0xdfff),(0xfdd0,0xfddf),(0xfffe,0xffff)] bad=dict.fromkeys(r for start, end in ranges for r in range(start,end+1)) s=s.translate(bad) s=re.sub(u"[^\x01-\x7f]+",'',s) s=re.sub(u'[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F%s]','',s) s=s.replace('\x0b','') # Take anything out that isn't UTF-8: s=s.decode('utf-8','ignore').encode('utf-8','ignore') return s
has comment: http://stackoverflow.com/comment/81355325
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81348758
tagged with: python
has title: UTF-8 to XML Python cleanup function woes
tagged with: http://stackoverflow.com/tag/xml
score: 0
has comment: http://stackoverflow.com/comment/81348038
answer count: 1

http://stackoverflow.com/comment/81226040
comment on: http://stackoverflow.com/a/47137989
type: Comment
score: 0
type: AnswerComment
has text: @tyteen4a03 Why would you want to offer all the API from the parent on the children? Both approaches are valid, depends on the design. For example, if I wanted to make a `Rest` class with methods `get`, `post`, ... and then I make a `TwitterRest` class that has methods according to Twitter's API, I don't want the user to be able to do `get` calls as they already have the more abstract methods, and thus wrapping `Rest` class would be a better approach instead of inheritance.

http://stackoverflow.com/comment/81301010
has text: The real question is why doesn't it survive daemonization? It doesn't matter that it's not the same process as there is quite a lot preserved when forking. The issue is that daemonizing often means [closing open file handles](https://pagure.io/python-daemon/blob/master/f/daemon/daemon.py#_88). As a result, the daemon process loses access to the log file and you see no more entries. [Linux Application Development](http://www.amazon.com/gp/product/0321563220/) has a lot of useful information about daemonizing and many other topics.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47175043

http://stackoverflow.com/q/47203445
tagged with: postgresql
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47231980
upvote count: 5
has answer: http://stackoverflow.com/a/47231980
has title: SQLalchemy query get aggregate array of dicts
tagged with: sqlalchemy
type: Question
score: 5
has body: Is it possible to get an aggregate array containing dictionaries from an SQLAlchemy query? e.g. session.query( Object.name, func.array_agg({Location.id: Location.name}).label('locations') )\ .join(Location)\ .all() So the expected result will be: [ ('Horizontal neutral circuit', [{143:'A5'},{145:'A8'},{765:'B12'}]), ('Fletcher, Lopez and Edwards', [{41:'A1'},{76:'B8'},{765:'B12'}]), ]
answer count: 1
downvote count: 0
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/81217187
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47133734
has text: Python is not `C#`. I suppose what you're trying to achieve has a much more `pythonic` equivalent.
score: 2

http://stackoverflow.com/q/47150440
type: Question
has answer: http://stackoverflow.com/a/47150680
type: UnansweredQuestion
has title: Exception: real is not double (PYTHON)
tagged with: python
tagged with: ta-lib
score: 0
tagged with: pandas
answer count: 1
tagged with: dataframe
upvote count: 1
has body: I'm trying to take the moving average of a stocks volume using TA-Lib but I'm getting the error above. Any suggestions on how to fix this? Thanks! See code below: import pandas_datareader as pdr import datetime import pandas as pd import numpy as np import talib as ta #Download Data aapl = pdr.get_data_yahoo('AAPL', start=datetime.datetime(2006, 10, 1), end=datetime.datetime(2012, 1, 1)) #Saves Data as CSV on desktop aapl.to_csv('C:\\Users\\JDOG\\Desktop\\aapl_ohlc.csv', encoding='utf-8') #Save to dataframe df = pd.read_csv('C:\\Users\JDOG\\Desktop\\aapl_ohlc.csv', header=0, index_col='Date', parse_dates=True) twenty_ma = 20 signals = pd.DataFrame(index=aapl.index) signals['signal'] = 0.0 signals['20 MA'] = ta.SMA(aapl.Volume.values,twenty_ma)
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81137107
score: 0
has text: Why can't you write the unmodified text to the file?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47093661

http://stackoverflow.com/comment/81105599
type: QuestionComment
comment on: http://stackoverflow.com/q/47076323
score: 0
has text: @jonatan This is what I did before and then the newline worked fine. But I had trouble with some languages (Turkish for example) which led me to change to doing it this way. Now Turkish is fine but the newline is not :/ I'm hoping to find a way to do the encoding without hardcoding a replace as I fear this would lead to problems in a unix environment
type: Comment

http://stackoverflow.com/a/47079481
has body: You can get all common elements of all 3 lists using set intersection: intersection = set(listA) &amp; set(listB) &amp; set(listC) common = bool(intersection) # True if not empty A contains-checks on two lists in a loop has time complexity O(A*(B+C)) (quadratic). This is O(A+B+C) (linear). If the entire intersection is more info than you need, you can still do the following and benefit from an early break: setBC = set(listB) &amp; set(listC) common = any(x in setBC for x in listA)
accepted answer of: http://stackoverflow.com/q/47079367
type: Answer
score: 6
upvote count: 6
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47079367

http://stackoverflow.com/comment/81215579
score: 0
has text: Don't know if this will fix your immediate problem, but change:. res.iter_content to response.iter_content
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47132884

http://stackoverflow.com/a/47171997
upvote count: 6
has comment: http://stackoverflow.com/comment/81293869
type: Answer
has comment: http://stackoverflow.com/comment/81293711
accepted answer of: http://stackoverflow.com/q/47171944
downvote count: 0
type: AcceptedAnswer
score: 6
has body: Use a comprehension with pd.date_range pd.DataFrame( [[c, d] for c, d1, d2 in df.itertuples(index=False) for d in pd.date_range(d1, d2, freq='MS')], columns=['Category', 'Date'] ) Category Date 0 a 2017-01-01 1 a 2017-02-01 2 a 2017-03-01 3 a 2017-04-01 4 a 2017-05-01 5 a 2017-06-01 6 a 2017-07-01 7 a 2017-08-01 If you have more than 3 columns and you want just Category and Date pd.DataFrame( [[c, d] for c, d1, d2, *_ in df.itertuples(index=False) for d in pd.date_range(d1, d2, freq='MS')], columns=['Category', 'Date'] ) The *_ unpacks the rest of the tuple. Otherwise, we could trap the entire tuple and just grab the bits we need. pd.DataFrame( [[t[0], d] for t in df.itertuples(index=False) for d in pd.date_range(t[1], t[2], freq='MS')], columns=['Category', 'Date'] )
has comment: http://stackoverflow.com/comment/81293738
answers question: http://stackoverflow.com/q/47171944
has comment: http://stackoverflow.com/comment/81293806

http://stackoverflow.com/a/47197674
has body: well I got this code: from selenium import webdriver driver = webdriver.Chrome() #driver.maximize_window() driver.get('http://whatis.techtarget.com/definition/IFrame-Inline-Frame') driver.switch_to_frame("google_ads_iframe_/3618/swht/DEFINITION_0") # OR we can use XPATH as follows: # # element = driver.find_element_by_xpath('PASTE_COPIED_XPATH') # driver.switch_to.frame(element) # for switching to the intended frame element_to_click = driver.find_element_by_xpath('//* [@id="DfaVisibilityIdentifier_1417699170"]/a/img') element_to_click.click() # do whatever you want to do here driver.switch_to_default_content() # for switching back to main frame driver.close() for now it has errors and a long one: NoSuchElementException: Message: u'no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="DfaVisibilityIdentifier_1417699170"]/a/img"}\n (Session info: chrome=62.0.3202.89)\n (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 6.1.7601 SP1 x86_64)'
score: 1
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47196042

http://stackoverflow.com/comment/81238035
score: 0
comment on: http://stackoverflow.com/a/47143321
type: Comment
has text: So what would the file structure be? What file is this?
type: AnswerComment

http://stackoverflow.com/comment/81201560
score: 1
comment on: http://stackoverflow.com/q/47125591
type: Comment
type: QuestionComment
has text: It's what Python does well, may as well do more of it.

http://stackoverflow.com/comment/81210606
type: Comment
type: QuestionComment
has text: @arno_v Thanks, It's working
score: 0
comment on: http://stackoverflow.com/q/47097805

http://stackoverflow.com/comment/81261987
comment on: http://stackoverflow.com/q/47156179
type: Comment
type: QuestionComment
has text: Try `requests`. BTW try googling first.
score: 0

http://stackoverflow.com/q/47165414
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47190166
accepted answer: http://stackoverflow.com/a/47190166
tagged with: python
has comment: http://stackoverflow.com/comment/81599410
tagged with: outlook
upvote count: 2
answer count: 1
downvote count: 0
tagged with: header
has title: Python Outlook headers
has body: I got a script to extract Gmailheaders. There is a lot of information to extract. When I try to extract data from outlook it feels like im getting a small part. The script I currently got is: import win32com.client import re outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) messages = inbox.Items message = messages.GetFirst() rec_time = message.CreationTime body_content = message.body while message: To = message.To Recipients = message.Recipients Sender = message.Sender address = message.Sender.Address cc = message.CC Importance = message.Importance LastModificationTime = message.LastModificationTime It prints the following fields: print message.subject print message.CreationTime print To print Sender print address print cc print Importance print LastModificationTime Is there just a limit amount of Outlook headers you can extract or? I've tryed to look on sources like: https://msdn.microsoft.com/en-us/VBA/Outlook-VBA/articles/mailitem-object-outlook I am missing important information like sender IP-adresses. Is there anyway of extracting more information without using a 3partytool? Thanks! Edit: Works: outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) messages = inbox.Items for message in messages: msg = message.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001F")
favorite count: 0
type: Question

http://stackoverflow.com/comment/81118626
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47084190
score: 0
has text: I want to too, but i dont know how to. Sorry, first time using stack

http://stackoverflow.com/q/47132954
has title: Django UpdateView doesn't get the values of the object and get blank instead
has comment: http://stackoverflow.com/comment/81217425
has body: So I'm creating a django website and I have an Edit Button. The edit shows a pop up with a few forms to edit. The problem is that the forms to edit are blank! instead of having the previous data. e.g- ServerName="Yossi" When I click edit instead of having "Yossi" in the form I have nothing. What do I need to add to the index.html or the Class of PostEdit so I will have the previous data in the forms and not blank forms? models.py - from django.db import models # Create your models here. class serverlist(models.Model): ServerName = models.CharField(max_length = 30) Owner = models.CharField(max_length = 50) Project = models.CharField(max_length = 30) Description = models.CharField(max_length = 255) IP = models.CharField(max_length = 30) ILO = models.CharField(max_length = 30) Rack = models.CharField(max_length = 30) Status = models.CharField(max_length = 30) #date = models.DateTimeField(auto_now=True) views.py - # Create your views here. from django.shortcuts import render_to_response from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() if query: posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query)) else: posts = serverlist.objects.all() args = {'form' : form, 'posts' : posts} return render(request, self.template_name, args) def post(self,request): form = HomeForm(request.POST) posts = serverlist.objects.all() if f…
tagged with: http://stackoverflow.com/tag/html
tagged with: mysql
upvote count: 1
tagged with: web
has comment: http://stackoverflow.com/comment/81216673
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81217577
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81216623
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81524783
has comment: http://stackoverflow.com/comment/81218837
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81217539

http://stackoverflow.com/q/47179866
has title: Split: ValueError: need more than 1 value to unpack python
answer count: 3
has answer: http://stackoverflow.com/a/47180618
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81309037
has comment: http://stackoverflow.com/comment/81308848
favorite count: 0
type: Question
tagged with: split
has body: I have the following part of code. When i give the value 'q' as input to x, I would like to stop the execution of the program. di={} while True: x,y=raw_input('Key, Value: ').split(',') a=int(x) di[a]=y if (x=='q'): break else continue I get an error message that the input command cannot unpack because i gave only one argument. Any help? Key, Value: 454,fds Key, Value: 239,ada Key, Value: q Traceback (most recent call last); File "tmp.py", line 3, in &lt;module&gt; x,y=raw_input('Key,Value: ').split(',') ValueError: need more than 1 value to unpack I cannot write 'q' in both x and y.
has answer: http://stackoverflow.com/a/47179897
tagged with: python
has comment: http://stackoverflow.com/comment/81308538
has comment: http://stackoverflow.com/comment/81309252
has comment: http://stackoverflow.com/comment/81308675
linked to: http://stackoverflow.com/q/38666283
has answer: http://stackoverflow.com/a/47180107
tagged with: user-input
has comment: http://stackoverflow.com/comment/81309106

directed-acyclic-graphs
type: Tag
tag name: directed-acyclic-graphs
tags question: http://stackoverflow.com/q/47188370

http://stackoverflow.com/q/47106105
has title: How to retrieve changed values of previous rows while within apply at pandas?
favorite count: 0
has body: I have a dataframe like this: Name Range N 0 Name1 0.11 0.900000 &lt;- # Beginning of Name1 1 Name1 0.20 0.000000 2 Name1 0.30 0.000000 3 Name2 0.40 0.300000 &lt;- # Beginning of Name2 4 Name2 0.50 0.000000 5 Name3 0.60 0.500000 &lt;- # Beginning of Name3 5 Name3 0.70 0.000000 6 Name3 0.80 0.000000 I want to change the values of N. Basically, I have a initial value for N for each name (which for names name1, name2 and name3 are 0.90000, 0.300000 and 0.500000 respectively), and I want, for each name, change the values of N's according to a function that depends on the N of the previous row. My formula is as follows: meaning the N on the ith row is 2 times N of the previous row plus the Range of current row. How can I do that using pandas? I have 1 Million rows so Iterating doesn't seem like a good idea. Any help is appreciated! I though of using apply function but it does not seem to work
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/47106353
has answer: http://stackoverflow.com/a/47108545
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81163024
has answer: http://stackoverflow.com/a/47106512
type: AnsweredQuestion
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/47108545
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/81163053
has answer: http://stackoverflow.com/a/47106353
downvote count: 1

matlab
tags question: http://stackoverflow.com/q/47106963
type: Tag
tag name: matlab
tags question: http://stackoverflow.com/q/47136614
tags question: http://stackoverflow.com/q/47172758
tags question: http://stackoverflow.com/q/47132638
tags question: http://stackoverflow.com/q/47192677
tags question: http://stackoverflow.com/q/47175250
tags question: http://stackoverflow.com/q/47157832
tags question: http://stackoverflow.com/q/47192413

http://stackoverflow.com/comment/134615338
has text: Thanks for this nugget of gold @jezrael !
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47094610
score: 1

http://stackoverflow.com/q/47131440
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81213029
has body: Hello I have a csv with data for 25 bridges that have undergone maintenance from 1992-2016. The first column corresponds to the bridge number. The next 25 columns corresponds to the condition ratings from 1992 to 2016. If the condition rating increased, that means the bridge underwent maintenance. Now that I've figured out how to get the amount of times each bridge underwent maintenance, I have to create an input that allows users to input any year from 1992-2016 and then print the total number of bridges who's maintenance count increased. I believe it will be a separate "if" statement at the end like such. f = open("BridgeExam1.csv", "r") year = int(input("Please give a year between 1992 - 2016: ")) for line in f: temp = line.split(",") i = 1 maintenance = 0 while i &lt; len(temp) - 1: if int(temp[i]) &lt; int(temp[i+1]): maintenance+=1 i = i+1 temp[0]=temp[0] + 1992 print("Bridge "+ temp[0], maintenance) f.close()
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81213162
tagged with: count
tagged with: python
has answer: http://stackoverflow.com/a/47131654
score: 2
upvote count: 3
answer count: 1
tagged with: grouping
has title: Read and plot from csv with a counter

http://stackoverflow.com/comment/81396906
comment on: http://stackoverflow.com/a/47223565
type: Comment
has text: Cool!! Thanks a lot
type: AnswerComment
score: 0

http://stackoverflow.com/q/47214246
upvote count: 2
has body: I am trying to create proper program with python which can be executable on a friend's computer. To do this I am using cx_Freeze and following the steps outlined here How can I convert a .py to .exe for Python 3.6? However when I type python setup.py build in the prompt it gives me the following error. I have googled this but am not sure how to go about fixing it. Thank you for any help in advance. PS C:\Users\jhgwa&gt; python setup.py build running build running build_exe creating directory build\exe.win-amd64-3.6 copying C:\Users\jhgwa\Anaconda3\lib\site-packages\cx_Freeze\bases\Console.exe -&gt; build\exe.win-amd64-3.6\Announcement Keyword From Headline Puller.exe copying C:\Users\jhgwa\Anaconda3\api-ms-win-crt-stdio-l1-1-0.dll -&gt; build\exe.win-amd64-3.6\api-ms-win-crt-stdio-l1-1-0.dll copying C:\Users\jhgwa\Anaconda3\python36.dll -&gt; build\exe.win-amd64-3.6\python36.dll copying C:\Users\jhgwa\Anaconda3\VCRUNTIME140.dll -&gt; build\exe.win-amd64-3.6\VCRUNTIME140.dll copying C:\Users\jhgwa\Anaconda3\api-ms-win-crt-math-l1-1-0.dll -&gt; build\exe.win-amd64-3.6\api-ms-win-crt-math-l1-1-0.dll copying C:\Users\jhgwa\Anaconda3\api-ms-win-crt-locale-l1-1-0.dll -&gt; build\exe.win-amd64-3.6\api-ms-win-crt-locale-l1-1-0.dll copying C:\Users\jhgwa\Anaconda3\api-ms-win-crt-string-l1-1-0.dll -&gt; build\exe.win-amd64-3.6\api-ms-win-crt-string-l1-1-0.dll copying C:\Users\jhgwa\Anaconda3\api-ms-win-crt-runtime-l1-1-0.dll -&gt; build\exe.win-amd64-3.6\api-ms-win-crt-runtime-l1-1-0.dll copying C:\Users\jhgwa\Anaconda3\api-ms-win-crt-convert-l1-1-0.dll -&gt; build\exe.win-amd64-3.6\api-ms-win-crt-convert-l1-1-0.dll copying C:\Users\jhgwa\Anaconda3\api-ms-win-crt-time-l1-1-0.dll -&gt; build\exe.win-amd64-3.6\api-ms-win-crt-time-l1-1-0.dll copying C:\Users\jhgwa\Anaconda3\api-ms-win-crt-environment-l1-1-0.dll -&gt; build\exe.win-amd64-3.6\api-ms-win-crt-environment-l1-1-0.dll copying C:\Users\jhgwa\Anaconda3\api-ms-win-crt-process-l1-1-0.dll -&gt; build\exe.win-amd64-3.6\api-m…
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49294623
favorite count: 0
type: Question
tagged with: cx-freeze
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: How do I fix this cx_Freeze ValueError?
linked to: http://stackoverflow.com/q/41570359
score: 2

http://stackoverflow.com/comment/132889100
score: 1
type: Comment
has text: It can be solved by not using `PostStatus` and manually pass list of enum values, later on you can just add/remove enum value from the existing type.
type: AnswerComment
comment on: http://stackoverflow.com/a/65173731

http://stackoverflow.com/a/47168349
has comment: http://stackoverflow.com/comment/81288582
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81324874
accepted answer of: http://stackoverflow.com/q/47098286
has comment: http://stackoverflow.com/comment/81318712
has comment: http://stackoverflow.com/comment/81324855
answers question: http://stackoverflow.com/q/47098286
type: Answer
has body: Here's an example in which I store references to the two bullet groups inside of the players. If you press the fire key ('f' or space) a bullet instance is added to the player's bullet group and the all_sprites group which blits and updates them. The collision detection takes place in the update method where I check if the player collides with bullets of the self.enemy_bullets group. If there are collisions, I reduce the self.health and if it's &lt;= 0, I call self.kill() to remove the sprite from all sprite groups. import pygame as pg from pygame.math import Vector2 class Player(pg.sprite.Sprite): def __init__(self, pos, color, left, right, up, down, fire, all_sprites, bullets, enemy_bullets): super().__init__() self.image = pg.Surface((30, 50)) self.image.fill(color) self.rect = self.image.get_rect(topleft=pos) self.vel = Vector2(0, 0) self.pos = Vector2(self.rect.topleft) self.dt = 0.03 self.key_left = left self.key_right = right self.key_up = up self.key_down = down self.key_fire = fire # Store the groups as attributes, so that you can add bullets # and use them for the collision detection in the update method. self.all_sprites = all_sprites self.bullets = bullets self.enemy_bullets = enemy_bullets self.fire_direction = Vector2(350, 0) self.health = 3 def update(self, dt): self.dt = dt self.pos += self.vel self.rect.center = self.pos # Check if enemy bullets collide with the player, reduce # health and kill self if health is &lt;= 0. collided_bullets = pg.sprite.spritecollide(self, self.enemy_bullets, True) for bullet in collided_bullets: self.health -= 1 if self.health &lt;= 0: self.kill() def handle_event(self, event): if event.type == pg.KEYDOWN: if event.key == self.key_left: self.vel.x = -90 * self.dt self.fire_direction = Vector2(-350, 0) elif event.key == self.key_right: self.vel.x = 90 * self.dt self.fire_direction = Vector2(350, 0) elif event.key == self.key_up: self.vel.y = -90 * self.dt self.fire_direction = Vector2(0, -350) elif event.key == self.key…

http://stackoverflow.com/comment/96775003
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47175108
type: Comment
has text: Even before 3.7 made `dict` insertion ordered, `keys` and `values` were guaranteed to iterate in the same order as each other, [per the docs](https://docs.python.org/3.5/library/stdtypes.html#dictionary-view-objects): "If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond" so you don't need the generator expression here to replicate the `keys` ordering. In 3.7+, the order is guaranteed to be insertion ordered, but even before then, it was guaranteed to be consistent.

http://stackoverflow.com/comment/81382984
type: QuestionComment
comment on: http://stackoverflow.com/q/47216630
score: 0
has text: Please try to attach the error log (for these type of queries) so that it would be helpful for us to answer to the point
type: Comment

http://stackoverflow.com/comment/81371546
has text: I break the while loop by setting qt to True
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47211059
type: AnswerComment

http://stackoverflow.com/comment/81123507
comment on: http://stackoverflow.com/a/47086873
type: Comment
has text: I want the averages for all the marks in a1, a2, a3, and a4. I want everyone's a1 avg, a2 avg, and a3 avg like this a1: 99, 11, 78. The avg of that and same with the other assignments.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81111845
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47080985
has text: This won't work if you change the lower bound on `l` or use a totally different list e.g. `l=[8,4,2]`. I suggest using `range` a second time: `[sum(l[:i+1]) for i in range(len(l))]`
score: 0

http://stackoverflow.com/comment/81139950
type: AnswerComment
has text: @Wman Did you re-try Vlad's solution? There is no way to do this easily in python but Vlad's solution should work for you.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47095264

http://stackoverflow.com/comment/89485800
type: Comment
score: 17
type: QuestionComment
has text: This was probably downvoted because you didn't google it, but the irony is that googling it brought me here.
comment on: http://stackoverflow.com/q/47117884

arrays
tags question: http://stackoverflow.com/q/47166551
tags question: http://stackoverflow.com/q/47165446
tags question: http://stackoverflow.com/q/47119693
tag name: arrays
tags question: http://stackoverflow.com/q/47121045
tags question: http://stackoverflow.com/q/47067043
tags question: http://stackoverflow.com/q/47206914
tags question: http://stackoverflow.com/q/47103742
tags question: http://stackoverflow.com/q/47107228
tags question: http://stackoverflow.com/q/47110381
type: Tag
tags question: http://stackoverflow.com/q/47188054
tags question: http://stackoverflow.com/q/47075622
tags question: http://stackoverflow.com/q/47156936
tags question: http://stackoverflow.com/q/47090519
tags question: http://stackoverflow.com/q/47096290
tags question: http://stackoverflow.com/q/47124143
tags question: http://stackoverflow.com/q/47173057
tags question: http://stackoverflow.com/q/47121919
tags question: http://stackoverflow.com/q/47129107
tags question: http://stackoverflow.com/q/47118677
tags question: http://stackoverflow.com/q/47186604
tags question: http://stackoverflow.com/q/47173198
tags question: http://stackoverflow.com/q/47135700
tags question: http://stackoverflow.com/q/47131525
tags question: http://stackoverflow.com/q/47168312
tags question: http://stackoverflow.com/q/47155767
tags question: http://stackoverflow.com/q/47138318
tags question: http://stackoverflow.com/q/47097607
tags question: http://stackoverflow.com/q/47095513
tags question: http://stackoverflow.com/q/47161060
tags question: http://stackoverflow.com/q/47135866
tags question: http://stackoverflow.com/q/47102190
tags question: http://stackoverflow.com/q/47103582
tags question: http://stackoverflow.com/q/47213485
tags question: http://stackoverflow.com/q/47125884
tags question: http://stackoverflow.com/q/47184099
tags question: http://stackoverflow.com/q/47117353
tags question: http://stackoverflow.com/q/47198948
tags question: http://stackoverflow.com/q/47183992
tags question: http://stackoverflow.com/q/47150890
tags question: http://stackoverflow.com/q/47177437
tags question: http://stackoverflow.com/q/47106112
tags question: http://stackoverflow.com/q/47151148
tags question: http://stackoverflow.com/q/47145741
tags question: http://stackoverflow.com/q/47146800
tags question: http://stackoverflow.com/q/47086910
tags question: http://stackoverflow.com/q/47109769
tags question: http://stackoverflow.com/q/47214855
tags question: http://stackoverflow.com/q/47168948
tags question: http://stackoverflow.com/q/47106101
tags question: http://stackoverflow.com/q/47077290
tags question: http://stackoverflow.com/q/47196133
tags question: http://stackoverflow.com/q/47109886
tags question: http://stackoverflow.com/q/47218811
tags question: http://stackoverflow.com/q/47168056
tags question: http://stackoverflow.com/q/47146190
tags question: http://stackoverflow.com/q/47082454
tags question: http://stackoverflow.com/q/47191836
tags question: http://stackoverflow.com/q/47161162
tags question: http://stackoverflow.com/q/47129403
tags question: http://stackoverflow.com/q/47179246
tags question: http://stackoverflow.com/q/47145099
tags question: http://stackoverflow.com/q/47070220
tags question: http://stackoverflow.com/q/47126162
tags question: http://stackoverflow.com/q/47178966
tags question: http://stackoverflow.com/q/47204134
tags question: http://stackoverflow.com/q/47084045
tags question: http://stackoverflow.com/q/47143712
tags question: http://stackoverflow.com/q/47145311
tags question: http://stackoverflow.com/q/47127843
tags question: http://stackoverflow.com/q/47171356
tags question: http://stackoverflow.com/q/47191930
tags question: http://stackoverflow.com/q/47122632
tags question: http://stackoverflow.com/q/47122770
tags question: http://stackoverflow.com/q/47143004
tags question: http://stackoverflow.com/q/47149109
tags question: http://stackoverflow.com/q/47081658
tags question: http://stackoverflow.com/q/47170102
tags question: http://stackoverflow.com/q/47200447

http://stackoverflow.com/comment/110024759
type: Comment
comment on: http://stackoverflow.com/a/62204900
has text: Please put your answer always in context instead of just pasting code. See [here](https://stackoverflow.com/help/how-to-answer) for more details.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81307376
has text: Only default values of the fields will be changing with every pricing plan?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47179188
type: QuestionComment

http://stackoverflow.com/q/47214731
tagged with: keras
has comment: http://stackoverflow.com/comment/81436655
has comment: http://stackoverflow.com/comment/81455570
type: Question
score: 0
has body: I am currently trying to train a DNN for speech recognition with large number of speakers, each having their own label (output_classes = Total number of speakers). My database right now has 300 speakers and the Keras model summary is as follows: 1240 (input size) --> 256 hidden --> 256 hidden --> 256 hidden (0.5 dropout) --> 256 (0.5 dropout) --> Softmax (300) I am feeding the data in batches (each speaker data = one batch) and using the following optimizer: model.compile( loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy']) and fit_generator as follows: model.fit_generator( trainGen(i=0), steps_per_epoch=num_class, epochs=500, validation_data=(x_test, y_test)) where trainGen is my generator function While training, the cross-validation accuracy always settles to 0.0033 i.e. 1/300. The training and cross-validation losses are falling after each epoch though. Any suggestions?
tagged with: python
tagged with: keras-2
has title: Keras cross-validation accuracy settling at (1/output_classes) after each epoch
type: UnansweredQuestion
answer count: 1
tagged with: neural-network
tagged with: machine-learning
has answer: http://stackoverflow.com/a/49701584

http://stackoverflow.com/q/47178618
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: web-crawler
type: Question
has body: When I do the crawl, I usually utilize scripts before parsing with python. Since this allows to get JSON which can be easily structured and parsed. &gt;&gt;&gt; import requests &gt;&gt;&gt; r = requests.get('~.json') &gt;&gt;&gt; r.json() However, encountering this page, https://www.eiganetflix.jp/%E3%82%BF%E3%82%A4%E3%83%97/tv-%E3%82%B7%E3%83%AA%E3%83%BC%E3%82%BA It seems there's no interaction to call JSON to show materials on the page. And it is hard to find pagination javascript functions. (Actually, there is, but I mean it seems hard to execute. ) In this case, how can I utilize existing requests and json method? Or is there any easy way to crawl this?
score: 0
accepted answer: http://stackoverflow.com/a/47178866
has title: python crawl with requests to get json
answer count: 1
has answer: http://stackoverflow.com/a/47178866
tagged with: python-requests
type: AnsweredQuestion

http://stackoverflow.com/q/47064870
answer count: 2
has title: Using python to determine if two strings are opposites given conditions
has answer: http://stackoverflow.com/a/47065110
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47064992
type: Question
has comment: http://stackoverflow.com/comment/81078051
tagged with: function
upvote count: 0
type: UnansweredQuestion
has body: If we had certain conditions to fulfill such as a is the opposite of b c is the opposite of h l is the opposite of r the opposite of the string acl would be bhr Do you guys think you can help me figure out how I would go about building a function that when given two strings will return a boolean that lets me know whether the given strings are opposite. for example input: opposite("ahl","bcr") would return True while ("ahl","bbr") would return False.
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81077934
has comment: http://stackoverflow.com/comment/81078085

http://stackoverflow.com/comment/81374735
comment on: http://stackoverflow.com/a/47209010
type: AnswerComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/158637/discussion-between-wen-and-tomasz-przemski).
score: 0
type: Comment

http://stackoverflow.com/q/47171700
has comment: http://stackoverflow.com/comment/81293122
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
has title: How do i change function returns into an integer
type: Question
has comment: http://stackoverflow.com/comment/81292966
has body: Hi im kind of new to this just trying to make a quick damage calculator for a game using python 3.6 and i need to multiply 2 values that derive from user input def armCalc(armV): '''Returns Armour Reduction Value''' return "%.2f" % ((armV / (armV+(50*70))) * 100) def resCalc(phys, cold, fire, light, pois, arc): '''Returns AVG All Resist + Reduction''' allRes = (phys + cold + fire + light + pois + arc) / 6 return "%.2f" % (allRes / (allRes + (5 * 70))) Basically i need to multiply resCalc and armCalc but python says it cant because they're not integers and a search only leads me to input examples. Thanks :)
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47171774
score: 0
has comment: http://stackoverflow.com/comment/81293016
has comment: http://stackoverflow.com/comment/81293082
has comment: http://stackoverflow.com/comment/81293099
has comment: http://stackoverflow.com/comment/81293056

http://stackoverflow.com/comment/81704355
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47357222
has text: Hello, this could be used as some kind of source: https://stackoverflow.com/a/100146

http://stackoverflow.com/q/47072836
has answer: http://stackoverflow.com/a/47073920
answer count: 2
tagged with: automation
has answer: http://stackoverflow.com/a/47073170
type: UnansweredQuestion
downvote count: 0
tagged with: selenium
has body: I am trying to write a code that I can use to automate a training course that I have to do every year. It is the same material and the same training year after year, so I figured why not automate it. The part that I am stuck is clicking on a radio button. I am able to select the radio button through using find element by xpath, but because the answers are randomized I would like to find the element by the text related to the radio button. I have tried using find_element_by_partial_link and had no luck, I could also being doing it wrong. This is what I have tried: test = browser.find_element_by_partial_link_text('Is this achievable?'). Here is the element that I am trying to access: Is this achievable? Any help will be greatly appreciated. Thank You.
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81119927
has comment: http://stackoverflow.com/comment/81119925
has title: How do I use python and selenium to find the element of a radio button using the text related to the radio button?
has comment: http://stackoverflow.com/comment/81094233
has comment: http://stackoverflow.com/comment/81130587
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81097051
has comment: http://stackoverflow.com/comment/81098999

http://stackoverflow.com/comment/81207257
comment on: http://stackoverflow.com/q/47128588
score: 0
type: Comment
has text: @Blurp 4,5,6 for `num_sequence_A` and 3,4,5 for `num_sequence_B`
type: QuestionComment

http://stackoverflow.com/comment/81153554
score: 0
comment on: http://stackoverflow.com/q/47101750
type: Comment
has text: Also, you might think you're on Python 3, but that `print` output says you're not. (Python 3 would have printed `[9] 10`.)
type: QuestionComment

http://stackoverflow.com/q/47166818
possible better answer: http://stackoverflow.com/a/47167005
has title: only outer join python pandas
has answer: http://stackoverflow.com/a/47167005
favorite count: 0
type: Question
answer count: 3
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81283635
upvote count: 6
accepted answer: http://stackoverflow.com/a/47166883
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47166883
tagged with: outer-join
tagged with: pandas
has body: I have two DataFrames that have the same column names with some matching data and some unique data. I want to exclude the middle and only save what is unique to both DataFrames. How would I concat or merge or join these two dataframes to do so? For instance in this image I do not want the middle in this image, I want both sides but not the middle: Here's my code right now: def query_to_df(query): ... df_a = pd.DataFrame(data_a) df_b = pd.DataFrame(data_b) outer_results = pd.concat([df_a, df_b], axis=1, join='outer') return df Let me give you an example of what I need: df_a = col_a col_b col_c a1 b1 c1 a2 b2 c2 df_b = col_a col_b col_c a2 b2 c2 a3 b3 c3 # they only share the 2nd row: a2 b2 c2 # so the outer result should be: col_a col_b col_c col_a col_b col_c a1 b1 c1 NA NA NA NA NA NA a3 b3 c3 or I'd be just as happy with 2 dataframes result_1 = col_a col_b col_c a1 b1 c1 result_2 = col_a col_b col_c a3 b3 c3 Lastly, you'll notice that a2 b2 c2 were excluded because all of the columns match - how do I specify that I want to join based on all the columns, not just 1? If df_a had had a2 foo c2 I would have wanted that row to be in result_1 as well.
has answer: http://stackoverflow.com/a/47167012
downvote count: 0
score: 6

http://stackoverflow.com/comment/81087859
comment on: http://stackoverflow.com/q/47069744
score: 1
type: Comment
type: QuestionComment
has text: That's true for "training". If you feed it a new unseen text on your old dictionary, it would be div by zero?

http://stackoverflow.com/q/47116374
tagged with: python
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47118464
answer count: 1
has body: I have a graph, where the convolutional layers are created with tf.layers.conv2d. It works, but I would like to see the kernel and bias in tensorboard. I've found the answer, that instead of calling the tf.layers.conv2d function, I should create an instance of tf.layers.Conv2D. If I do this, I get this error: module 'tensorflow.python.layers.layers' has no attribute 'Conv2D' The code is the same as in the linked answer: conv1_layer = tf.layers.Conv2D( filters = 16, kernel_size = (8,8), strides=(4, 4), padding='same', kernel_initializer=tf.contrib.layers.xavier_initializer(), bias_initializer=tf.zeros_initializer(), kernel_regularizer=None, name = 'conv1', activation = tf.nn.elu ) conv1 = conv1_layer.apply(x) Why is python not available to find Conv2D? If I run inspect.getmembers(tf.layers, inspect.isclass), I get an empty list as result
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47118464
linked to: http://stackoverflow.com/q/44731808
tagged with: tensorflow
favorite count: 0
type: AnsweredQuestion
score: 1
has title: Module tensorflow.python.layers.layers has no attribute Conv2D

http://stackoverflow.com/comment/81154476
type: QuestionComment
has text: Any luck with this Dave?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47078562

http://stackoverflow.com/comment/81272152
comment on: http://stackoverflow.com/q/47161162
score: 1
type: Comment
type: QuestionComment
has text: To get the proper values in the `x` array, you can use `numpy.linspace`

http://stackoverflow.com/q/47169539
tagged with: themes
type: Question
has comment: http://stackoverflow.com/comment/93280444
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: 4
upvote count: 4
tagged with: jupyter-notebook
has body: I use jupytherthemes module to change Jupyter notebook theme to solarized. For some reason, I needed to reinstall the Anaconda. After that I was not able to use jupytherthemse and I just used another custom.css file and left it in .jupyter/custom directory. My notebook theme is fine but when I export it as html, nbconver uses the old theme--solarized. I searched a lot to find a way to reset the template to the default template or to custom.css I am using for notebook. I was not able to find any solution. any thought would be much appreciated. here is full.tpl content: {%- extends 'basic.tpl' -%} {% from 'mathjax.tpl' import mathjax %} {%- block header -%} {%- block html_head -%} {{resources['metadata']['name']}} {%- if "widgets" in nb.metadata -%} {%- endif-%} {% for css in resources.inlining.css -%} {% endfor %} {{ mathjax() }} {%- endblock html_head -%} {%- endblock header -%} {% block body %} {{ super() }} {%- endblock body %} {% block footer %} {{ super() }} {% endblock footer %}
tagged with: nbconvert
answer count: 0
downvote count: 0
favorite count: 0
has title: How to change Jupyter notebook html output template?

http://stackoverflow.com/q/47097447
tagged with: pandas
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47100776
has body: I am new to Python so apologies if this is a simple fix. I currently have a column of times that are currently stored as strings and look as below when I view my dataframe: bus_no time Bus1 2.0 Bus2 840.0 Bus3 2340.0 Bus4 15.0 Bus5 1205.0 Bus6 1304.0 Bus7 1620.0 Bus8 9.0 So 9.0 equates to 00:09, 1620 to 16:20. (It is a rather large dataset with many more fields so I created that example to easily show the format it is showing) Each time I have tried to convert it to time it also forms a date and merges part of the time into the date thus producing an inaccurate output. Any help would be appreciated.
favorite count: 0
has answer: http://stackoverflow.com/a/59405668
has title: Convert string to HH:MM time in Python
has answer: http://stackoverflow.com/a/47097558
type: Question
tagged with: datetime
answer count: 5
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47097580
has answer: http://stackoverflow.com/a/47097642

http://stackoverflow.com/q/47072050
answer count: 0
has body: I'm modifying code from this github (https://github.com/hehefan/Video-Classification) so it can accept my own input. When I try to run it one video at a time for 5 epoch, it run with no problem. But when I try to get it run from multiple video in succession it run to Memory Error in sess.run() line. Code: import sys import os import numpy as np import tensorflow as tf import gzip #import cPickle import _pickle as cPickle import random from config import FLAGS from models import DynamicRNN from models import AveragePooling filename = ['D2N2Sur', 'H2N2A', 'H2N2C', 'H2N2D', 'H2N2S', 'N2A', 'N2C', 'N2D', 'N2H', 'N2S', 'N2Sur', 'S2N2H'] #TRAINING LABEL batch_label = list(range(12)) #DATA PROCESSING data = [] batch_length = [] for name in filename: #READ DATA counter = 0 frame = 0 video=[] l = "" f = open("Train1/"+name+".txt", "r") for line in f: l = l + line[:-1] counter += 1 if (counter == 365): l = list(l) video.append(l) l = "" counter = 0 frame += 1 #MAKE SURE ALL VIDEO HAVE SAME LENGTH #PAD BY 0 frame = FLAGS.max_video_length - frame for number in range(frame): video.append([0]*FLAGS.feature_size) #APPEND VIDEO TO DATA data.append(video) batch_length.append(FLAGS.max_video_length) training_steps_per_epoch = len(data) // FLAGS.batch_size if not os.path.exists(FLAGS.checkpoint_dir): os.makedirs(FLAGS.checkpoint_dir) model = AveragePooling(feature_size=FLAGS.feature_size, max_video_length=FLAGS.max_video_length, num_classes=FLAGS.num_classes, cell_size=FLAGS.size, use_lstm=FLAGS.use_lstm, learning_rate=FLAGS.learning_rate, learning_rate_decay_factor=FLAGS.learning_rate_decay_factor, min_learning_rate=FLAGS.min_learning_rate, training_steps_per_epoch=training_steps_per_epoch, max_gradient_norm=FLAGS.max_gradient_norm, keep_prob=FLAGS.keep_prob, is_training=True) with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir) if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path): print("Reading model parameters from %s" % ckpt.model_ch…
has comment: http://stackoverflow.com/comment/81135034
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/81101402
has comment: http://stackoverflow.com/comment/97867997
type: Question
has title: sess.run() Memory Error
type: UnansweredQuestion
tagged with: python
score: 0

http://stackoverflow.com/comment/81185917
type: Comment
has text: Do you know, Why "return self - (-other)" code worked correctly?
comment on: http://stackoverflow.com/a/47117902
score: 0
type: AnswerComment

scons
tag name: scons
tags question: http://stackoverflow.com/q/47185207
tags question: http://stackoverflow.com/q/47212500
type: Tag

http://stackoverflow.com/a/47097217
has comment: http://stackoverflow.com/comment/81144326
score: 0
has body: Change project strucutre from bot/ engine_bot/ engine_bot/ spiders/ __init__.py main_spider.py __init__.py items.py middlewares.py pipelines.py settings.py utils.py __init__.py helper.py main.py __init__.py To bot/ some_new_name/ engine_bot/ spiders/ __init__.py main_spider.py __init__.py items.py middlewares.py pipelines.py settings.py utils.py __init__.py helper.py main.py __init__.py See I renamed engine_bot to some_new_name
has comment: http://stackoverflow.com/comment/81144274
answers question: http://stackoverflow.com/q/47096616
type: Answer

http://stackoverflow.com/a/47226528
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47187153
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47187153
has body: If you replace np.stack((solx[0:,0],soly[0:,0]),axis=0) np.stack((solx[0:,i],soly[0:,i]),axis=0) with: list(zip(solx[0:,0],soly[0:,0])) list(zip(solx[0:,i],soly[0:,i])) or (if you want to use numpy arrays instead of lists: np.array([solx[0:,0],soly[0:,0]]).T np.array([solx[0:,i],soly[0:,i]]).T in the aninit() and aniupdate(i) functions the behaviour should be as expected. Here's the code I used to make the plots: def aninit(): offsetlist = np.array([solx[0:,0],soly[0:,0]]).T osc3.set_offsets(offsetlist) return osc3, def aniupdate(i): offsetlist = np.array([solx[0:,i],soly[0:,i]]).T osc3.set_offsets(offsetlist) return osc3, References: Rain Simulation old_animation example code: dynamic_collection.py

http://stackoverflow.com/q/47192457
type: Question
possible better answer: http://stackoverflow.com/a/47192517
answer count: 2
has answer: http://stackoverflow.com/a/47192517
upvote count: 3
accepted answer: http://stackoverflow.com/a/47192474
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47192474
favorite count: 0
type: AnsweredQuestion
score: 3
has body: I have two list of lists of the same length, something like the following. list1 = [[],[],[1,2,3,4],[],[2,5,6]] list2 = [[],[],[1,9,3,9],[],[1,8,6]] I want to join these lists so that if there are values in the list it will be added to the same index in the list, eg [[],[],[1,2,3,4,9],[],[1,2,5,6,8]]. I was trying to use map(list,zip(list1,list2)) but that merges both lists into a list giving for example two empty lists inside index[0]. Instead of this I want to the values from both lists in index[0] added to index[0] and if there are no values in either list then this list should remain empty. What would be the best way to do this ?
has title: joining two lists of lists by index

http://stackoverflow.com/a/47155309
answers question: http://stackoverflow.com/q/47148068
has body: Maybe you have a misunderstand of the dynamic typing of python. First, pool_string was never an object of the class multiprocessing.pool.Pool You just have called its__str__ method: &gt;&gt;&gt; pool_string '&lt;multiprocessing.pool.Pool object at 0x000001F8495BCC18&gt;' &gt;&gt;&gt; dir(_pool)[26] '__str__' &gt;&gt;&gt; _pool.__str__() '&lt;multiprocessing.pool.Pool object at 0x000001F8495BCC18&gt;' That was and string from the beginning to the end of your script. Maybe you just want to make another reference to your actual _pool: _pool2 = _pool
has comment: http://stackoverflow.com/comment/111088197
has comment: http://stackoverflow.com/comment/81271131
score: 1
downvote count: 0
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/81284483

music21
type: Tag
tag name: music21
tags question: http://stackoverflow.com/q/47109915

http://stackoverflow.com/q/47075492
has comment: http://stackoverflow.com/comment/81099421
tagged with: series
has body: I have a question and I am not sure what function should be used to perform it. I have two date frames where I wanna two compare if the values in one (finaldf) are higher than the values in the other one (dfres0) and if they are I wanna to set to zero in (finaldf). Here are some example what this date frame looks like: finaldf .. NEG_00_04 NEG_04_08 NEG_08_12 NEG_12_16 NEG_16_20 NEG_20_24 \ datum_von 2017-10-18 9.58 8.08 0.39 2.32 0.54 0.60 2017-10-19 6.34 6.20 0.15 1.32 0.46 0.56 2017-10-20 7.68 5.86 0.29 1.04 0.48 0.54 2017-10-21 13.40 10.52 2.50 3.09 2.97 2.44 2017-10-22 25.53 17.33 4.05 12.62 2.35 1.14 dfres0 ... produktname NEG_00_04 NEG_04_08 NEG_08_12 NEG_12_16 NEG_16_20 NEG_20_24 \ datum_von 2017-10-18 12.440 11.012 0.604 4.189 0.900 0.912 2017-10-19 10.144 8.880 0.465 2.700 0.740 0.832 2017-10-20 10.370 8.280 0.394 1.970 0.694 0.732 2017-10-21 14.207 10.800 1.940 2.940 2.334 2.164 2017-10-22 24.750 20.285 3.900 18.241 2.476 1.870 Thanks in advance
type: AnsweredQuestion
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/81099279
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81099663
tagged with: loops
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47075658
has comment: http://stackoverflow.com/comment/81099375
has answer: http://stackoverflow.com/a/47075658
upvote count: 1
tagged with: python
has title: Comparing two dateframes and setting values

http://stackoverflow.com/comment/81365106
comment on: http://stackoverflow.com/a/47207993
type: AnswerComment
has text: Check the answer https://stackoverflow.com/questions/46398396/oserror-tunnel-connection-failed-407-proxy-authentication-required
score: 0
type: Comment

http://stackoverflow.com/q/47094705
has comment: http://stackoverflow.com/comment/81139369
has comment: http://stackoverflow.com/comment/81139344
answer count: 2
downvote count: 0
tagged with: scipy
favorite count: 0
has answer: http://stackoverflow.com/a/72383624
type: Question
has comment: http://stackoverflow.com/comment/81144709
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81138786
has answer: http://stackoverflow.com/a/51358087
tagged with: python
score: 4
upvote count: 4
has title: Python : Halton and Hammersley quasi random sequences
has body: I am trying to construct Hammersley and Halton quasi random sequences. I have for example three variables x1, x2 and x3. They all have integer values. x1 has a range from 2-4, x2 from 2-4 and x3 from 1-7. Is there any python package which can create those sequences? I saw that there are some procject like sobol or SALib, but they do not implemented Halton and Hammersley. Best regards
tagged with: numpy

http://stackoverflow.com/comment/81126960
comment on: http://stackoverflow.com/q/47088661
type: Comment
type: QuestionComment
score: 0
has text: You want **all** the rows in the new column to have the same value? `df['foo'] = df.index[4][1]*2` works for me.

http://stackoverflow.com/comment/81239157
comment on: http://stackoverflow.com/q/47144456
type: Comment
type: QuestionComment
has text: I answered, but overlooked the "by while loop" part which makes your question a "write a dumb code for my homework assignment" question. Do it yourself. Note: a while loop is the worst control structure for this kind of thing.
score: 1

http://stackoverflow.com/comment/81260551
comment on: http://stackoverflow.com/a/47093908
score: 0
type: AnswerComment
has text: Which version of Python do you use? May be it's a key. Mine is 3.6
type: Comment

http://stackoverflow.com/q/47145346
answer count: 1
tagged with: decomposition
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/30893292
tagged with: factorization
score: 3
has body: While I have seen posts about finding prime factors and divisors, I haven't found an answer to my question about factorisations in Python. I have a list of prime factors, i.e. for 24 it is [2,2,2,3]. I want from this list all possible factorisations, i.e. for 24 the output should be [[2,12], [3,8], [4,6], [2,2,6], [2,3,4], [2,2,2,3]]. I tried itertool approaches, but this created lots of duplicate answers and forgot others (like finding [2,3,4] but ignoring [4,6]). I am specifically interested in an approach using the generated prime factor list. I have found a workaround with a recursive function. def factors(n, n_list): for i in range(2, 1 + int(n ** .5)): if n % i == 0: n_list.append([i, n // i]) if n // i not in primes: #primes is a list containing prime numbers for items in factors(n // i, []): n_list.append(sorted([i] + items)) fac_list = n #[n] has to be added manually for facs in n_list: #removes double entries if facs not in fac_list: fac_list.append(facs) return fac_list But this is time consuming for large n, since it has to look through all numbers, not just prime numbers. A combinatorics approach for a prime factor list should be much faster. Edit: After looking through several resources, the best explanation of a good strategy is the highest rated answer here on SO. Concise and easy to implement in any language, one prefers. Case closed.
tagged with: algorithm
has comment: http://stackoverflow.com/comment/81256454
tagged with: python
has title: Create all possible factorisations from a prime factor list in Python
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/47145820
accepted answer: http://stackoverflow.com/a/47145820
downvote count: 0
has comment: http://stackoverflow.com/comment/82395089
linked to: http://stackoverflow.com/q/8558292

http://stackoverflow.com/comment/81236758
type: Comment
type: QuestionComment
has text: `x[1,1]` is a simple way to say : `x[1,1,:,:]`. See if that makes any difference.
score: 3
comment on: http://stackoverflow.com/q/47143361

http://stackoverflow.com/comment/81104558
score: 0
comment on: http://stackoverflow.com/q/47076311
type: Comment
has text: Hi Hendrik. Thank you for your response. You're absolutely right that the second attempt makes no sense. I believe the first one should work, but it does not. I have done an actual login to the site using Chrome and grabbed the headers from there. I will update the original post with those headers. The "auth_form" that I am posting is a dictionary with the expected username and password.
type: QuestionComment

http://stackoverflow.com/comment/88358358
type: Comment
comment on: http://stackoverflow.com/a/50195230
type: AnswerComment
has text: This answer is awesome! While maybe less readable it is more generalizable. Seems to work for tensors of arbitrary dimensions after dimension 1. For example it still gives back what you expect for `a = tf.constant([[[1,2,3],[4,5,6]],[[1,1,1],[1,1,1]]])` `b = tf.constant([[[7,8,9],[10,11,12]]])`
score: 2

http://stackoverflow.com/comment/81330669
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47188292
has text: @AsadSaeeduddin what do you mean by "replacing the messed up character with `\n` "?

http://stackoverflow.com/a/47087027
type: Answer
has body: entries['resultset'] is a dict object and it doesn't have '0' key. It has only 'headers', 'rowset', 'name'. Just remove '[0]' from the below two lines of code, this will work. csv_output.writerow(entries['resultSet']['headers']) csv_output.writerows(entries['resultSet']['rowSet'])
score: 0
has comment: http://stackoverflow.com/comment/81124126
has comment: http://stackoverflow.com/comment/81124075
answers question: http://stackoverflow.com/q/47086615
has comment: http://stackoverflow.com/comment/81124343
has comment: http://stackoverflow.com/comment/81123873
has comment: http://stackoverflow.com/comment/81124192

http://stackoverflow.com/a/47126748
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47117592
score: 1
has body: Found that the proxy server must be started after the call to register the new type; it appears that registrations made after the proxy was started will not function.

http://stackoverflow.com/a/55160320
score: 40
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/128197300
type: Answer
has comment: http://stackoverflow.com/comment/138269876
accepted answer of: http://stackoverflow.com/q/47206201
upvote count: 40
has body: Why real values in DB are 'DRAFT', 'APPROVE', 'PUBLISHED', but not draft, etc? I supposed there should be ENUM values, not names. As Peter Bašista's already mentioned SQLAlchemy uses the enum names (DRAFT, APPROVE, PUBLISHED) in the database. I assume that was done because the enum values ("draft", "approve", ...) can be arbitrary types in Python and they are not guaranteed to be unique (unless @unique is used). However since SQLAlchemy 1.2.3 the Enum class accepts a parameter values_callable which can be used to store enum values in the database: status = db.Column( db.Enum(PostStatus, values_callable=lambda obj: [e.value for e in obj]), nullable=False, default=PostStatus.DRAFT.value, server_default=PostStatus.DRAFT.value ) Why type poststatus was not created on DB-level automatically? In the similar migration it was. I think basically you are hitting a limitation of alembic: It won't handle enums on PostgreSQL correctly in some cases. I suspect the main issue in your case is Autogenerate doesn't correctly handle postgresql enums #278. I noticed that the type is created correctly if I use alembic.op.create_table so my workaround is basically: enum_type = SQLEnum(PostStatus, values_callable=lambda enum: [e.value for e in enum]) op.create_table( '_dummy', sa.Column('id', Integer, primary_key=True), sa.Column('status', enum_type) ) op.drop_table('_dummy') c_status = Column('status', enum_type, nullable=False) add_column('posts', c_status)
answers question: http://stackoverflow.com/q/47206201
downvote count: 0

http://stackoverflow.com/comment/81186724
score: 0
has text: @Dante you know nothing about code why you are wasting time here dude
type: Comment
comment on: http://stackoverflow.com/a/47096528
type: AnswerComment

http://stackoverflow.com/comment/81288761
has text: @JamesHollis yes, well, while I appreciate that, I'm very concerned with making sure OP understands the distinction between arrays and lists. It's my own little personal crusade on this tag :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47169253
type: Comment

http://stackoverflow.com/a/47145884
has comment: http://stackoverflow.com/comment/81242053
has comment: http://stackoverflow.com/comment/81242470
downvote count: 0
answers question: http://stackoverflow.com/q/47145798
upvote count: 1
score: 1
has body: I think you'll need to store the user input from __init__ into an instance attribute: class Parent(object): def func(self): raise NotImplementedError class Child(Parent): def __init__(self, user_input): self.user_input = user_input def func(self): if self.user_input == "func1": self._func1() elif self.user_input == "func2": self._func2() else: # make sure to guard against other possible inputs! def _func1(self): # implementation here def _func2(self): # implementation here EDIT: Here's a simple variant that doesn't store the user input. There are other, more complicated ways to do this perhaps. But this is one of the simplest: class Parent(object): def func(self): raise NotImplementedError class Child(Parent): def __init__(self, user_input): if user_input == "func1": self.func = self._func1 elif user_input == "func2": self.func = self._func2 else: pass # make sure to guard against other possible inputs! def _func1(self): print("from func1!") def _func2(self): print("from func12")
type: Answer
has comment: http://stackoverflow.com/comment/81242378

http://stackoverflow.com/comment/81156843
has text: Can you help us to understand your actual goal here? Are you trying to create a file with the indicated content? Or are you trying write an `np.ndarray` to a file, adding an index? To put it another way, is `numpy` an essential element of the solution?
comment on: http://stackoverflow.com/q/47102954
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81183619
comment on: http://stackoverflow.com/q/47116678
type: QuestionComment
type: Comment
has text: Every time the user presses space, you simply set the label to the exact same thing. It doesn’t append to the label.
score: 1

http://stackoverflow.com/a/47194203
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47193232
has comment: http://stackoverflow.com/comment/81416849
has body: You can not query the furniture in a "mutation" scope. It is two separate actions: mutation { newFurniture(input: {name: "graphFurniture", content: "This furniture is cool", category: "Bedroom Items"}) { clientMutationId } } query { furniture { name content category { name } } }

http://stackoverflow.com/a/47112698
has comment: http://stackoverflow.com/comment/81175416
answers question: http://stackoverflow.com/q/47112666
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81175440
downvote count: 0
has comment: http://stackoverflow.com/comment/81175521
upvote count: 1
has body: set_index +rename_axis df.set_index('val1').T.rename_axis(None,1) Out[499]: A1.1 A1.2 A1.3 val2 A2.1 A2.2 A2.3 val3 A3.1 A3.2 A3.3 val4 A4.1 A4.2 A4.3 df.set_index('val1').T.rename_axis(None,1).reset_index().rename(columns={'index':'new_col'}) Out[524]: new_col A1.1 A1.2 A1.3 0 val2 A2.1 A2.2 A2.3 1 val3 A3.1 A3.2 A3.3 2 val4 A4.1 A4.2 A4.3

http://stackoverflow.com/a/47188665
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47187642
has body: Not a clean solution, but easy to grasp and might save your day. f = {} dcts = map(lambda l: dict([l]), list2+list3) for dct in dcts: for k in dct.iterkeys(): f[k] = w.get(k, 0) + d[k] final_list = map(list, f.items()) however, if you are familiar with itertools import groupby from itertools merged = list2+list3 final_list = [] for key, group in groupby(merged, key = lambda e: e[0]): final_list.append([key, sum(j for i, j in group)]) or a oneliner [[k, sum(j for i, j in g)] for k, g in groupby(list3+list2, key = lambda e: e[0])]

http://stackoverflow.com/comment/81254369
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47151298
has text: If you wait 5 seconds and then close the socket, you will only have a connection rejected error. `sock.settimeout(5)` mean ?

http://stackoverflow.com/comment/81401366
type: Comment
comment on: http://stackoverflow.com/a/47221049
type: AnswerComment
score: 0
has text: but, which is the url thati would to send the request? Like tihs?: http://127.0.0.1:8000/horario/?fecha_inicio=2017-11-08T10:00:00

http://stackoverflow.com/a/47127002
has comment: http://stackoverflow.com/comment/81204157
has body: Why not have a count property on the spider initialized to 0, and the on your parse method you can def parse(self, response): if self.count &gt;= 100: return self.count += 1 # do actual parsing here
upvote count: 0
has comment: http://stackoverflow.com/comment/111804542
answers question: http://stackoverflow.com/q/47126973
downvote count: 1
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/81212447

http://stackoverflow.com/q/47190218
type: AnsweredQuestion
has body: The method __getitem__() for a sequence (such as a list) can return a single item, or a sequence of items. For example, given the function decoration below: def __getitem__(self, index) -&gt; Union[Product, Generator[Product, None, None]]: return super(Products, self).__getitem__(index) Example usage: i1 = 34 for product in products[i1:]: print(product.name) I believe Union[Product, Generator[Product, None, None]] to be correct, but PyCharm flags this as improper. Am I misusing the typing library, or is this a PyCharm issue? Thanks!
tagged with: pycharm
answer count: 1
score: 6
has comment: http://stackoverflow.com/comment/81330006
downvote count: 0
accepted answer: http://stackoverflow.com/a/47230826
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81331860
has answer: http://stackoverflow.com/a/47230826
has title: proper type hint for __getitem__()
tagged with: python
upvote count: 6
tagged with: python-typing

http://stackoverflow.com/comment/81186525
comment on: http://stackoverflow.com/a/47118156
score: 0
type: AnswerComment
has text: Ok, then either pass (len(header) - 4) as number of assignments as a second parameter in this function, or initialize the marks variable as a None and then put an if statement inside the loop where you check whether marks is None, if it is then assign marks = [[]] * (len(grades_list) - 4)
type: Comment

http://stackoverflow.com/q/47127918
answer count: 1
upvote count: 1
tagged with: python-requests
has answer: http://stackoverflow.com/a/47127979
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81205953
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: bottle
score: 1
has title: bottle.py seems to strip some headers
has body: Using python requests I sent headers that included {'foo': 'bar'}. Sending code was like: session = requests.Session() session.headers.update({'foo':'bar'}) session.post('http://localhost:8000/whatever', json={a=1, b=2}) I also tried it without the session and with explicit headers={'foo':'bar'}. Same result. In my receiving method of form: @app.post('/whatever') def do_something(): do_something_with(request.get_header('foo')) I find that foo is missing. Why would that be? I am certain that it was there in the sending session.

http://stackoverflow.com/q/47144573
downvote count: 1
has body: I have a function that should return the number of words that contain each vowel (all lowercase), but I keep getting a key error. I'd appreciate any help in figuring it out. Thank you. def vowelUseDict(t): '''computes and returns a dictionary with the number of words in t containing each vowel ''' vowelsUsed = {} strList = t.split() newList = [] vowels ='aeiou' for v in vowels: for strs in strList: if v in strs and strs not in newList: newList.append(strs) vowelsUsed[v] = 1 if v in strs and strs in newList: vowelsUsed[v] += 1 return vowelsUsed text = 'like a vision she dances across the porch as the radio plays' print(vowelUseDict(text)) #{'e': 5, 'u': 0, 'o': 4, 'a': 6, 'i': 3}
has answer: http://stackoverflow.com/a/47145415
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81239575
has comment: http://stackoverflow.com/comment/81239385
has comment: http://stackoverflow.com/comment/81239759
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81239290
has answer: http://stackoverflow.com/a/47146521
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81239679
has comment: http://stackoverflow.com/comment/81240118
has comment: http://stackoverflow.com/comment/81239788
answer count: 2
linked to: http://stackoverflow.com/q/10260953
upvote count: 0
has title: Python key error in function

http://stackoverflow.com/a/47186242
answers question: http://stackoverflow.com/q/47186040
type: Answer
has comment: http://stackoverflow.com/comment/81321604
has body: pd.pivot_table(df,index=['start','end'],columns='id',values='type',aggfunc='sum').reset_index() Out[1587]: id start end XXX YYY 0 2017-01-01 2017-01-31 car truck 1 2017-02-01 2017-03-03 car truck 2 2017-03-04 2017-04-03 car truck 3 2017-04-04 2017-05-04 car truck
has comment: http://stackoverflow.com/comment/81321833
downvote count: 0
upvote count: 7
score: 7
has comment: http://stackoverflow.com/comment/81321728
has comment: http://stackoverflow.com/comment/81321969

http://stackoverflow.com/q/47188698
score: 0
has comment: http://stackoverflow.com/comment/81327069
answer count: 1
has title: replace the numerical value with another value in each line when some text is matched
tagged with: scripting
tagged with: gawk
type: Question
has comment: http://stackoverflow.com/comment/81330374
tagged with: sed
has body: I have a large file and want to process the numerical values on each line if some text is matched on the corresponding line. For example if I have the following lines in a large text file: system.membus.respLayer1.occupancy 55000 # Layer occupancy (ticks) system.membus.respLayer1.utilization 5.5 # Layer utilization (%) system.l2.prefetcher.prefetcher.num_hwpf_identified 0 # number of hwpf identified I want to replace 55000 with with its doubled value and 5.5 with its half value if the text at the beginning of each line is matched. These values may vary for different files, i.e. 55000 and 5.5 are not fixed. Can anyone please help me how to achieve this using Python, sed, awk,etc
has comment: http://stackoverflow.com/comment/81330049
tagged with: awk
has comment: http://stackoverflow.com/comment/81327164
tagged with: python
accepted answer: http://stackoverflow.com/a/47190831
has comment: http://stackoverflow.com/comment/81326695
has comment: http://stackoverflow.com/comment/81329256
has answer: http://stackoverflow.com/a/47190831
type: AnsweredQuestion

http://stackoverflow.com/comment/81176185
comment on: http://stackoverflow.com/q/47111379
score: 0
type: QuestionComment
has text: You're right, I edited my question and added the code.
type: Comment

http://stackoverflow.com/a/47196612
score: 1
has comment: http://stackoverflow.com/comment/81342920
has body: A quick and dirty way to do this would be: def text_to_date(date_text): if not date_text: raise ValueError('Empty Date') month = int(date_text[0:2]) day = int(date_text[3:5]) year = int(date_text[6:10]) date_time = datetime.date(year,month,day) return date_time
answers question: http://stackoverflow.com/q/47195630
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47191345
downvote count: 0
answer count: 1
tagged with: bundle
upvote count: 1
tagged with: macos
favorite count: 0
type: Question
tagged with: hidden
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47192638
has title: python os.scandir shows apple dmg, app, bundle as directory
score: 1
has body: I'm writing a program for parallel file checksums. I'm stuck with subdirectories count because python os.scandir() shows Apple DMG, apps as directory. So far I've got following code. import os, sys ### variables PATH_SRC = os.getcwd() EXCLUDE_FILES = ('__', '.') EXCLUDE_DIRS = ('__', '.', '*.app', '*.dmg') LIST_FILES = [] LIST_DIRS = [] COUNT_DIRS = 0 COUNT_FILES = 0` with os.scandir(PATH_SRC) as it: for entry in it: if not entry.name.startswith(EXCLUDE_FILES): if entry.is_dir() and entry.name.startswith(EXCLUDE_DIRS): LIST_DIRS.append(entry.path) COUNT_DIRS = COUNT_DIRS + 1 elif entry.is_file(): LIST_FILES.append(entry.path) COUNT_FILES = COUNT_FILES + 1 print ('Source path contains ', COUNT_DIRS, ' subdirectories.') print ('Source path contains ', COUNT_FILES, ' file(s).') print (LIST_DIRS) print (LIST_FILES) source path contains 10 subdirectories but above by mentioned code shows 16 because there is some apps, dmg and they are shown as directory. I need to recursively list files inside the source path and exclude hidden and bundles (dmg,app). Count them...it would be used as decision whether to use parallelisation or not. I usually copy photos from flash cards but sometimes I copy whole try on my file server. Idea behind it is...count all files inside source path...if there is more than 10 files for example...run parallel checksum of files...SSD can handle about >4 files at once and saturate CPU. My workstation has got 2 CPUs with 4 cores each...but there will be SSD bottleneck. Furthermore RAID 10 file server can handle about 2-3 files at once. I'm new to Python so don't be surprised about complicated code. AlGORITM: 1. check how many files total and decide for MP (Multiprocessing or multithread) recursively check source path, exclude hidden files and bundles...then run checksum sha512 on them every dir/subdir must have own checksum file. I don't want one large checksum file in source path I hope you understand. Please any suggestions? Regards Hajes
tagged with: scandir

http://stackoverflow.com/a/47204059
has comment: http://stackoverflow.com/comment/81356762
has comment: http://stackoverflow.com/comment/81357927
has body: Assuming with "numbers" you mean integers, use this: all(isinstance(n, int) for n in numbers) As you can see in this example: &gt;&gt;&gt; numbers = [34, 39, 110, 303, 889, 223, 982, 7676] &gt;&gt;&gt; all(isinstance(n, int) for n in numbers) True
has comment: http://stackoverflow.com/comment/81358328
score: 2
type: Answer
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47203951

http://stackoverflow.com/comment/81158218
has text: Don't name the ForeignKey fields with `_id` endings, like `user_id` and `operator_id`. Django generates automatically properties with endings `_id`. In your case you'll have `operator_id` storing an object Operator and `operator_id_id` storing the actual value of the foreign key.
comment on: http://stackoverflow.com/q/47103798
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81327146
score: 0
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/158544/discussion-between-lemon-and-mad-wombat).
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47163477

http://stackoverflow.com/comment/81103097
type: AnswerComment
comment on: http://stackoverflow.com/a/47077036
score: 0
type: Comment
has text: @flyingmeatball Oh, yes. Didn't think of that. Yes, you should.

http://stackoverflow.com/comment/81547301
type: Comment
comment on: http://stackoverflow.com/a/47197435
type: AnswerComment
has text: @IlyaPukhov Hi, any progress now?
score: 0

http://stackoverflow.com/comment/81261860
comment on: http://stackoverflow.com/q/47156168
score: 5
has text: @ZeinabAbbasimazar Not in Python 3.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47159416
type: AnsweredQuestion
has title: Remove all non-letter characters and separate into new columns
has comment: http://stackoverflow.com/comment/81269900
tagged with: pandas
has body: I have a column in my DataFrame called "amenities" and this is what 1 records looks like: print(df["amenities"][0]) {"Wireless Internet",Kitchen,"Free parking on premises",Breakfast,Heating,Washer,Dryer,"Smoke detector","Carbon monoxide detector",Essentials,Shampoo,Hangers,"Hair dryer","Laptop friendly workspace","translation missing: en.hosting_amenity_49","translation missing: en.hosting_amenity_50"} What I'm trying to do is remove the special characters and then I want to separate them so that every amenity has its own column Room Amenity1 Amenity2 Amenity3 Amenity4 1 Wireless Internet Kitchen Free Parking Breakfast What I did is: import re df['amenities'] = df['amenities'].map(lambda x:re.sub('\W+',' ', x)) Wireless Internet Air conditioning Pool Kitchen Free parking on premises Gym Hot tub Indoor fireplace Heating Family kid friendly Suitable for events Washer Dryer Smoke detector Carbon monoxide detector First aid kit Fire extinguisher Essentials Shampoo Lock on bedroom door 24 hour check in Hangers Hair dryer Iron Laptop friendly workspace . This cleans the string but now I do not know how to separate them into its own columns because Wireless Internet should be onle column, not two.
has comment: http://stackoverflow.com/comment/81268727
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81268449
answer count: 1
has answer: http://stackoverflow.com/a/47160362
tagged with: data-cleaning
accepted answer: http://stackoverflow.com/a/47160362
downvote count: 0
tagged with: python
score: 2

http://stackoverflow.com/a/47177901
type: Answer
upvote count: 6
type: AcceptedAnswer
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/47176726
accepted answer of: http://stackoverflow.com/q/47176726
has body: The answer to "is it possible to have a Mock object return a value when called as well as execute a statement when called?" is obviously yes, just make side_effect do everything: import unittest.mock as mock def side_effect(): print('Side effect executed') return 'Returned Foo' mocked_func = mock.Mock(side_effect=side_effect) print(mocked_func()) # output Side effect executed Returned Foo Of course you can do it with a lambda too: import unittest.mock as mock mocked_func = mock.Mock( side_effect=lambda: (print('Side effect executed'), 'Returned Foo')[1] ) print(mocked_func()) # output Side effect executed Returned Foo It does not look any cleaner to me but to each their own. If you just want to avoid polluting your namespace you can do this: def mocked_func(): print('Side effect executed') return 'Returned Foo' mocked_func = mock.Mock(side_effect=mocked_func) Or using a decorator: def mock_it(f): return mock.Mock(side_effect=f) @mock_it def mocked_func(): print('Side effect executed') return 'Returned Foo' Combining return_value and side_effect does not seem to be possible as you already noticed.

http://stackoverflow.com/comment/81127431
type: Comment
comment on: http://stackoverflow.com/q/47089036
type: QuestionComment
score: 0
has text: Welcome to SO. This no code service site. Please try for yourself first and come back if there's an issue with your script.

http://stackoverflow.com/q/47102378
tagged with: apache-spark
accepted answer: http://stackoverflow.com/a/47102643
has answer: http://stackoverflow.com/a/47102643
type: Question
upvote count: 4
has title: Transpose a RowMatrix in PySpark
downvote count: 0
tagged with: pyspark
answer count: 1
tagged with: python
score: 4
has body: Hi I am wondering how to transpose a RowMatrix in PySpark. data = [(MLLibVectors.dense([1.0, 2.0]), ), (MLLibVectors.dense([3.0, 4.0]), )] df=sqlContext.createDataFrame(data, ["features"]) features=df.select("features").rdd.map(lambda row: row[0]) mat=RowMatrix(features) print mat.rows.first() #[1.0,2.0] mat=mat.Transpose() print mat.rows.first() #[1.0,3.0] Anyone implement this in Python? I've seen similar posts but everything is in Scala. Thanks.
favorite count: 0
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/30556478

nested-lists
tags question: http://stackoverflow.com/q/47117359
tags question: http://stackoverflow.com/q/47205663
tags question: http://stackoverflow.com/q/47183707
tags question: http://stackoverflow.com/q/47090088
tags question: http://stackoverflow.com/q/47129229
tags question: http://stackoverflow.com/q/47203167
type: Tag
tags question: http://stackoverflow.com/q/47081372
tag name: nested-lists

asynchronous
tags question: http://stackoverflow.com/q/47121572
tags question: http://stackoverflow.com/q/47064757
tags question: http://stackoverflow.com/q/47073276
tags question: http://stackoverflow.com/q/47173574
tags question: http://stackoverflow.com/q/47212451
tags question: http://stackoverflow.com/q/47103401
type: Tag
tags question: http://stackoverflow.com/q/47173186
tags question: http://stackoverflow.com/q/47100781
tags question: http://stackoverflow.com/q/47106773
tags question: http://stackoverflow.com/q/47143939
tag name: asynchronous
tags question: http://stackoverflow.com/q/47178187
tags question: http://stackoverflow.com/q/47080682
tags question: http://stackoverflow.com/q/47154893

http://stackoverflow.com/comment/81121422
score: 0
comment on: http://stackoverflow.com/q/47085830
has text: if the `else` is executed, then it is never defined
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47131542
has comment: http://stackoverflow.com/comment/81221289
has body: I setup ckan 2.7.2 for development. I got problem, the server return error 500 every submit new or updated data (group, organization, dataset). Here is the output of ckan-default.error.log [Tue Oct 31 23:05:58.261643 2017] [wsgi:error] [pid 29258:tid 140278908057344] 2017-10-31 23:05:58,261 INFO [ckan.lib.base] /group render time 0.110 seconds [Tue Oct 31 23:05:58.543091 2017] [wsgi:error] [pid 29257:tid 140278908057344] 2017-10-31 23:05:58,542 INFO [ckan.lib.base] /api/i18n/en render time 0.003 seconds [Tue Oct 31 23:05:58.543759 2017] [wsgi:error] [pid 29257:tid 140278908057344] [remote 127.0.0.1:34363] mod_wsgi (pid=29257): Exception occurred processing WSGI script '/etc/ckan/default/apache.wsgi'. [Tue Oct 31 23:05:58.543801 2017] [wsgi:error] [pid 29257:tid 140278908057344] [remote 127.0.0.1:34363] Traceback (most recent call last): [Tue Oct 31 23:05:58.543822 2017] [wsgi:error] [pid 29257:tid 140278908057344] [remote 127.0.0.1:34363] File "/usr/lib/ckan/default/src/ckan/ckan/config/middleware/__init__.py", line 136, in __call__ [Tue Oct 31 23:05:58.543861 2017] [wsgi:error] [pid 29257:tid 140278908057344] [remote 127.0.0.1:34363] return self.apps[app_name](environ, start_response) [Tue Oct 31 23:05:58.543875 2017] [wsgi:error] [pid 29257:tid 140278908057344] [remote 127.0.0.1:34363] File "/usr/lib/ckan/default/lib/python2.7/site-packages/paste/cascade.py", line 130, in __call__ [Tue Oct 31 23:05:58.543894 2017] [wsgi:error] [pid 29257:tid 140278908057344] [remote 127.0.0.1:34363] return self.apps[-1](environ, start_response) [Tue Oct 31 23:05:58.543905 2017] [wsgi:error] [pid 29257:tid 140278908057344] [remote 127.0.0.1:34363] File "/usr/lib/ckan/default/src/ckan/ckan/config/middleware/common_middleware.py", line 61, in __call__ [Tue Oct 31 23:05:58.543929 2017] [wsgi:error] [pid 29257:tid 140278908057344] [remote 127.0.0.1:34363] return elf.app(environ, start_response) [Tue Oct 31 23:05:58.543969 2017] [wsgi:error] [pid 29257:tid 140278908057344] [remote 127.0…
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81235375
has comment: http://stackoverflow.com/comment/81415312
type: Question
has title: CKAN ERROR 500 EVERY SUBMIT DATA
type: UnansweredQuestion
tagged with: wsgi
tagged with: python
has comment: http://stackoverflow.com/comment/81214529
tagged with: ckan

http://stackoverflow.com/comment/81284283
score: 1
type: QuestionComment
has text: This question may answer yours https://stackoverflow.com/questions/35805078/how-do-i-convert-a-password-into-asterisks-while-it-is-being-entered/35805111
comment on: http://stackoverflow.com/q/47167139
type: Comment

http://stackoverflow.com/a/47180481
upvote count: 1
has comment: http://stackoverflow.com/comment/81312212
has body: Check below solution and let me know if some improvements required: for items in soup.select(".second-child"): for text_nodes in items.select("p"): name = " \n".join([item for item in text_nodes.strings if item]) print(name) Output D Daiwa House Industry Danske Bank DaVita HealthCare Partners Delphi Automotive Denso Dentsply International Deutsche Boerse Deutsche Post Deutsche Telekom Diageo Dialight Digital Realty Trust Donaldson Company DSM DS Smith E East Japan Railway Company eBay EDP RenovÃ¡veis Edwards Lifesciences Elekta EnerNOC Enphase Energy Essilor Etsy Eurazeo European Investment Bank (EIB) Evonik Industries Express Scripts F Fielmann First Solar FMO Ford Motor Fresenius Medical Care
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47179002
has comment: http://stackoverflow.com/comment/81311232
has comment: http://stackoverflow.com/comment/81312467
accepted answer of: http://stackoverflow.com/q/47179002
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47220727
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47224392
has comment: http://stackoverflow.com/comment/81391927
has comment: http://stackoverflow.com/comment/81391696
has body: I'm trying to record grouping in expressions, like: condition_a = Condition( "x = 5 ") condition_b = Condition( "y &gt; 6 " ) condition_c = Condition( "z = 7 " ) condition_c &amp; ( condition_a | condition_b ) These are expressions a user can write to configure a SQL query, so the above would ultimately be expressed as x = 5 AND (y &gt; 6 OR z = 7). I tried this: class Condition( object ) : def __init__( self, expr ) : .... def __and__( self , other ) : print 'calling and' .... return self def __or__( self , other ) : print 'calling or' .... return self def __call__( self , other ) : print 'calling ()' .... return self I would expect this code : condition_a = Condition( "x = 5 ") condition_b = Condition( "y &gt; 6 " ) condition_c = Condition( "z = 7 " ) condition = condition_c &amp; ( condition_a | condition_b ) expected = "z = 7 AND ( x = 5 OR y &gt; 6 )" to print the calling () but it does not. I just see : calling or calling and It seems I am not using a call, so something like condition_a(1), so __call__ is not called. Is there a way to achieve what I want? You can check the expected which is what I want to have (and and or works, it's just I don't have the parenthesis around part of the expression).
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47224392
has comment: http://stackoverflow.com/comment/81393057
upvote count: 0
has title: How to capture grouping in an expression?
tagged with: expression
answer count: 1
downvote count: 1
tagged with: grouping
has comment: http://stackoverflow.com/comment/81392353
tagged with: python
score: -1
tagged with: parentheses

http://stackoverflow.com/comment/81381427
comment on: http://stackoverflow.com/q/47215744
type: Comment
type: QuestionComment
has text: What version of Numpy are you using? Do the contents of each image have the shape and dtype you're expecting?
score: 1

http://stackoverflow.com/a/50251702
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47167412
score: 1
downvote count: 0
has body: Ok, here is one way that I did this. If you need to add tzinfo, you may use the below. from datetime import datetime import pytz time_created_day = datetime.datetime.utcnow().date() time_created_day_with_tz_info = datetime(time_created_day.year, time_created_day.month, time_created_day.day, tzinfo=pytz.timezone('UTC')) &gt; print time_created_day_with_tz_info &gt; datetime.datetime(2018, 5, 9, 0, 0, tzinfo=&lt;UTC&gt;)

http://stackoverflow.com/q/47116015
possible better answer: http://stackoverflow.com/a/47116053
has body: This can be an infinite list of numbers, So far I can't figure out how to switch the first and last of the list without knowing where the list ends. If the list is (1,2,3,4,5) the output should be (5,2,3,4,1) Really stuck, first language, wondering if anyone can offer some help! def swapFirstAndLast(list): for position in range(0, len(list)): list[position] = list[position] =
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/81182043
has comment: http://stackoverflow.com/comment/81182041
downvote count: 0
has comment: http://stackoverflow.com/comment/81181963
tagged with: python
has title: Take a Python list as parameter and modifiy the list parameter by swapping its first and last elements
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47116048
has answer: http://stackoverflow.com/a/47116053
accepted answer: http://stackoverflow.com/a/47116048

http://stackoverflow.com/q/47125737
type: Question
has title: python: how to select specific values in a column and make them into a new column
has comment: http://stackoverflow.com/comment/81201899
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47125846
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81201889
has comment: http://stackoverflow.com/comment/81201557
upvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/47127066
tagged with: pandas
has body: here is the sample data frame year month 2011 1 2012 1 2013 1 2011 2 2011 3 2013 2 I want to select year &gt; 2012 and make it a new column "new year".
downvote count: 1
favorite count: 0

google-oauth
type: Tag
tag name: google-oauth
tags question: http://stackoverflow.com/q/47150564

http://stackoverflow.com/comment/81101961
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47071235
type: Comment
has text: @Meitham, sorry, I could not edit up anymore. They are always sorted indeed but always x != y, so (x < y)

http://stackoverflow.com/comment/81278143
score: 0
has text: What Christian said – it's a fun problem but a "bad" question because you haven't shown any work yet
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47164054

http://stackoverflow.com/comment/81388513
type: Comment
has text: Hi COLDSPEED, Could you please help me about my question? I have edited. Actually I need No of Distinct Position for each user, each day.
score: 0
comment on: http://stackoverflow.com/q/47123666
type: QuestionComment

http://stackoverflow.com/comment/81396925
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47220857
type: Comment
has text: In windows and in Linux systems, the filesystem preview shows that its an image but when I click on it, it freezes the system like the viewer is not able to unpack it.

http://stackoverflow.com/q/47130141
tagged with: python
has comment: http://stackoverflow.com/comment/81210320
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81210115
score: 1
linked to: http://stackoverflow.com/q/47109031
answer count: 1
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/46256279
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
has body: How can I get an element-wise count of each element's number of occurrences in a numpy array, along a given axis? By "element-wise," I mean each value of the array should be converted to the number of times it appears. Simple 2D input: [[1, 1, 1], [2, 2, 2], [3, 4, 5]] Should output: [[3, 3, 3], [3, 3, 3], [1, 1, 1]] The solution also needs to work relative to a given axis. For example, if my input array a has shape (4, 2, 3, 3), which I think of as "a 4x2 matrix of 3x3 matrices," running solution(a) should spit out a (4, 2, 3, 3) solution of the form above, where each 3x3 "submatrix" contains counts of the corresponding elements relative to that submatrix alone, rather than the entire numpy array at large. More complex example: suppose I take the example input above a and call skimage.util.shape.view_as_windows(a, (2, 2)). This gives me array b of shape (2, 2, 2, 2): [[[[1 1] [2 2]] [[1 1] [2 2]]] [[[2 2] [3 4]] [[2 2] [4 5]]]] Then solution(b) should output: [[[[2 2] [2 2]] [[2 2] [2 2]]] [[[2 2] [1 1]] [[2 2] [1 1]]]] So even though the value 1 occurs 3 times in a and 4 times in b, it only occurs twice in each 2x2 window.
accepted answer: http://stackoverflow.com/a/47130262
has comment: http://stackoverflow.com/comment/81210232
has answer: http://stackoverflow.com/a/47130262
has title: element-wise count along axis of values in numpy array

http://stackoverflow.com/comment/81366883
comment on: http://stackoverflow.com/q/47208640
type: Comment
type: QuestionComment
has text: Think you should follow the links and search for the other funcs docs that I have stated. They have much more info than I can compile here.
score: 0

http://stackoverflow.com/q/47217475
has comment: http://stackoverflow.com/comment/81384533
favorite count: 0
has comment: http://stackoverflow.com/comment/81384662
type: Question
has answer: http://stackoverflow.com/a/47217949
has body: I am working on a question in a coding website and got some problem in solving it. The question is: Print 1 to N - Digits Count [ZOHO] A positive integer N is passed as the input. If we print all the numbers from 1 to N continuosly, the program must find the number of characters(digits) C printed and print the count C as the output. Input Format: The first line contains N. Output Format: The first line contains C. Boundary Conditions: 1 &lt;= N &lt;= 9999999 Example Input/Output 1: Input: 2 Output: 2 Explanation: We print 12 and hence the total number of characters is 2. Example Input/Output 2: Input: 15 Output: 21 Explanation: We print 123456789101112131415 and hence the total number of characters is 21. I solved the problem, but my code didn't pass all the test cases (they are hidden). This is my code: n = int(input()) assert 1&lt;=n&lt;=9999999 a = [str(i) for i in range(1,n+1)] b = ''.join(a) print(len(b)) Is this is the right way to solve the problem or is there any other way which can be used to solve this problem?
has answer: http://stackoverflow.com/a/47219531
possible better answer: http://stackoverflow.com/a/47219531
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/47220768
accepted answer: http://stackoverflow.com/a/47217949
has title: Print 1 to N - Digits Count
type: AnsweredQuestion
score: 2
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/81399399
has comment: http://stackoverflow.com/comment/81385526
downvote count: 0

http://stackoverflow.com/a/47088418
downvote count: 0
score: 1
upvote count: 1
has body: I'm not sure why id=count didn't work. It's possible there's some weird interaction with the yt-view-count-renderer tag. I tested the CSS selector, span.view-count and it works just fine. BTW, you can test your CSS selectors in the devtools in Chrome using $$(), e.g. $$("span.view-count"). $$() is sorta the equivalent of driver.find_elements_by_css_selector(). For more details on this and other commands you can use the devtools, see this link.
type: Answer
answers question: http://stackoverflow.com/q/47087229

http://stackoverflow.com/q/47204711
downvote count: 1
accepted answer: http://stackoverflow.com/a/47216514
type: AnsweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47216514
has body: I am trying to change the column width for n number of columns. I am able to do this for rows as per the below code. rowheight = 2 while rowheight &lt; 601: ws.row_dimensions[rowheight].height = 4 rowheight += 1 The problem I have is that columns are in letters and not numbers.
favorite count: 0
type: Question
answer count: 2
has title: openpyxl - change width of n columns
tagged with: openpyxl
score: 6
upvote count: 7
has answer: http://stackoverflow.com/a/47204846
possible better answer: http://stackoverflow.com/a/47204846

http://stackoverflow.com/a/52694509
has body: I know this is old but just in case someone else has a look...I was actually just looking at this problem. I think the issue is here that these dp problems can be tricky when handling indices. The previous answer is not going to print the solution correctly simply because this line needs to be adjusted... cur_max_index = j which should be cur_max_index = j + 1 The rest... def cut_rod(prices, length): values = [0] * (length + 1) cuts = [-1] * (length + 1) max_val = -1 for i in range(1, length + 1): for j in range(i): temp = prices[j] + values[i - j - 1] if temp &gt; max_val: max_val = prices[j] + values[i - j - 1] cuts[i] = j + 1 values[i] = max_val return values[length], cuts def print_cuts(cuts, length): while length &gt; 0: print(cuts[length], end=" ") length -= cuts[length] max_value, cuts = cut_rod(prices, length) print(max_value) print_cuts(cuts, length)
answers question: http://stackoverflow.com/q/47085156
score: 0
type: Answer

http://stackoverflow.com/comment/81255335
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47152344
has text: 1k x 1k matrix = 1M values, from which 1k are known (the string with itself): 0 and half of the rest are duplicates as `dist(A, B) = dist(B, A)`. That means 499k5 values to be computed. Do you really need to calculate the distance of every possible pair?

http://stackoverflow.com/comment/81365162
has text: What language & framework are we talking about here? Is it Python with scikit-learn? Please clarify (specific tagging could also do the job)...
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47207361
score: 1

http://stackoverflow.com/comment/81178607
comment on: http://stackoverflow.com/q/47114272
has text: `fitness = chromosome[2] for chromosome in population` what is this means ? What is the logic for assigning fitness ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81275575
score: 0
has text: I deleted my answer, since it was essentially the same as yours (20sec later), but please do add some explanation and details.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47162885

http://stackoverflow.com/q/47129771
tagged with: python-ggplot
downvote count: 0
linked to: http://stackoverflow.com/q/33539214
tagged with: python
has answer: http://stackoverflow.com/a/47129800
has body: I have a similar problem as this post, however this fix didn't work for me. I am working in Spyder, Python 3.6 and want to run ggplot. After installing ggplot with pip, I am still unable to locate the module import ggplot Traceback (most recent call last): File "&lt;ipython-input-5-1140326dc452&gt;", line 1, in &lt;module&gt; import ggplot ModuleNotFoundError: No module named 'ggplot' EDIT: I have also installed it in Anaconda Prompt with pip install ggplot and followed with conda install ggplot but have this error message PackageNotFoundError: Packages missing in current channels: - ggplot
score: 1
answer count: 1
upvote count: 1
linked to: http://stackoverflow.com/q/35750572
has title: how to get ggplot in ipython
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82102040
type: UnansweredQuestion

http://stackoverflow.com/a/47065329
has comment: http://stackoverflow.com/comment/81141053
has comment: http://stackoverflow.com/comment/81136965
has comment: http://stackoverflow.com/comment/81140570
downvote count: 0
has comment: http://stackoverflow.com/comment/81090242
has comment: http://stackoverflow.com/comment/81141142
answers question: http://stackoverflow.com/q/47065228
has comment: http://stackoverflow.com/comment/81120995
has comment: http://stackoverflow.com/comment/81120999
has comment: http://stackoverflow.com/comment/81139561
has comment: http://stackoverflow.com/comment/81140974
has comment: http://stackoverflow.com/comment/81089506
has body: I don't think there are any statistics involved here. You can plot the value as a function of a and b. import pandas as pd import numpy as np import matplotlib.pyplot as plt A,B = np.meshgrid(np.arange(10),np.arange(10)) df = pd.DataFrame({"a" : A.flatten(), "b" : B.flatten(), "value" : np.random.rand(100)}) ax = df.plot.scatter(x="a",y="b", c=df["value"]) plt.colorbar(ax.collections[0]) plt.show() The darker the dots, the higher the value.
type: Answer
has comment: http://stackoverflow.com/comment/81140689
has comment: http://stackoverflow.com/comment/81121195
has comment: http://stackoverflow.com/comment/81080993
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81139346

http://stackoverflow.com/q/47191862
has comment: http://stackoverflow.com/comment/81333271
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47212718
type: AnsweredQuestion
score: 2
has title: How can I convert my text string(which I think is a bytearray) to an image?
has comment: http://stackoverflow.com/comment/81333170
answer count: 1
has comment: http://stackoverflow.com/comment/81333072
linked to: http://stackoverflow.com/q/18491416
accepted answer: http://stackoverflow.com/a/47212718
favorite count: 0
type: Question
has body: I am trying to convert, what I think is a bytearray pulled from a database to an image using python PIL. I have access to the imagetype(jpg, png,..), the image height/width, and the bytearray. The bytearray is of the format 0xffd8ffe000104a46494600010101006000600000ffe111164578..... I have tried many of the PIL options such as .fromstring and .frombuffer. I've also tried converting the bytearray into other forms (Base64,etc..) and then converting it to an image from there. None of these have worked and the image file is always corrupted. If i follow the advice from this question: image = Image.open(io.BytesIO(imagestring)) image.save(imageToSave.jpg) I get this error: IOError: cannot identify image file type(imagestring) returns type 'bytearray' Thanks for reading and for any answers, let me know if I should edit this post with more info.
upvote count: 2

http://stackoverflow.com/comment/81118737
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47084578
has text: Down votes without explanation aren't very helpful.
type: Comment

http://stackoverflow.com/a/47134221
has comment: http://stackoverflow.com/comment/81229314
accepted answer of: http://stackoverflow.com/q/47129383
has comment: http://stackoverflow.com/comment/81229019
has comment: http://stackoverflow.com/comment/81229188
has comment: http://stackoverflow.com/comment/81230783
has comment: http://stackoverflow.com/comment/81228825
type: Answer
answers question: http://stackoverflow.com/q/47129383
has comment: http://stackoverflow.com/comment/81230003
has body: No, it won't be the same, because the number of channels of input layer determines the shape of convolutional filters, hence the number of parameters and how they are applied. Compare these two convolutional networks: [32x32x3] input shape, batch_size=5, 5x5 receptive field, then each neuron in the conv layer will have weights to a [5x5x3] region in the input volume, for a total of 5*5*3 = 75 weights (and +1 bias parameter). [32x32x15] input shape, batch_size=1, same 5x5 receptive field, then each neuron will have weights to a [5x5x15] region, for a total of 5*5*15 = 325 weights (and the same +1 bias parameter). In both cases, the two conv layers sees 15 RGB images, but the second network will use 5 times more parameters to learn the same data, while the first one will reuse the same parameters for different images. Also note that the second network will have dedicated parameters to each first image, each second image, etc. Obviously, the first approach is better, not only because it saves the resources, it's also invariant to the order of training images in a batch.
has comment: http://stackoverflow.com/comment/81229707
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/81336312
has text: Thanks, but my links aren't working, any clue why this is happening?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47193014
type: Comment

http://stackoverflow.com/comment/81321985
score: 0
type: Comment
has text: Also another possible approach would be to somehow gather (nd ?) needed elements - this would avoid the py_func hack
type: AnswerComment
comment on: http://stackoverflow.com/a/47137142

http://stackoverflow.com/comment/81150565
comment on: http://stackoverflow.com/q/47100230
type: Comment
type: QuestionComment
score: 0
has text: Not working :( @Divakar

http://stackoverflow.com/comment/81393111
type: AnswerComment
score: 0
type: Comment
has text: explanation is difference which can help the OP
comment on: http://stackoverflow.com/a/47221780

http://stackoverflow.com/comment/81239648
type: Comment
has text: @ChristianDean there's no newline in the example...
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47144750

http://stackoverflow.com/a/47103964
has body: This is a very common bug. In tkinter, you must keep a reference to the image object or it gets garbage collected. def changeimage(): path.set(cwd + '/img/' + imageVar.get() + '.png') img = ImageTk.PhotoImage(Image.open(path.get())) panel.configure(image = img) panel.img = img # keep a reference
type: Answer
answers question: http://stackoverflow.com/q/47103714
score: 0

http://stackoverflow.com/comment/81196133
score: 0
has text: @Flabetvibes True, same for me. But it makes absolutely no sense??
type: Comment
comment on: http://stackoverflow.com/q/47123035
type: QuestionComment

http://stackoverflow.com/a/47147107
answers question: http://stackoverflow.com/q/47146905
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/81245137
has comment: http://stackoverflow.com/comment/81244474
has comment: http://stackoverflow.com/comment/81244739
has comment: http://stackoverflow.com/comment/81244621
downvote count: 0
has comment: http://stackoverflow.com/comment/81244624
has comment: http://stackoverflow.com/comment/81244544
has body: There's a fundamental problem here. Say you get your two iterators iter1 and iter2, and you pass iter1 to a function that eats the whole thing: def consume(iterable): for thing in iterable: do_stuff_with(thing) consume(iter1) That's going to need to iterate through all of tuple_gen to get the first items, and then what do you do with the second items? Unless you're okay with rerunning the generator to get the second items again, you need to store all of them, in memory unless you can persist them to disk or something, so you're not much better off than if you'd just dumped tuple_gen into a list. If you do this, you have to consume the iterators in parallel, or run the underlying generator twice, or spend a lot of memory saving the tuple elements you're not processing so the other iterator can go over them. Unfortunately, consuming the iterators in parallel will require either rewriting the consumer functions or running them in separate threads. Running the generator twice is simplest if you can do it, but not always an option.

http://stackoverflow.com/comment/81080194
type: QuestionComment
comment on: http://stackoverflow.com/q/47065693
has text: A "variable" in Python is better thought of as just as label for an object. The object exists with or without any labels attached to it (well, sort of--if the object isn't referred to by any other object then it is destroyed but that's an aside). Point being the object exists independently of the label or labels attached to it. For example `l1 = l2 = [1, 2, 3]` creates two labels stuck on the same list. This has nothing to do with mutability or immutability of the object. When one label is assigned to one object, and then you assign it to a different object, you're just swapping that label.
score: 2
type: Comment

http://stackoverflow.com/q/47180026
tagged with: python
score: -2
has body: I started learning django and just deployed my first app when this showed up. Any suggestions would be useful. (https://i.sstatic.net/GgMjG.png)
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/47180117
downvote count: 2
tagged with: django
favorite count: 0
type: Question
has title: Django local server error
has answer: http://stackoverflow.com/a/47180543
type: UnansweredQuestion

http://stackoverflow.com/comment/81174762
comment on: http://stackoverflow.com/q/47111379
has text: Well, now I know where does the divergence come from. I have two matrices, Gxx and Gyy, that are the same in Python and C++, at least for the first 10 significative digits. Here is the C++ code: `Mat denom; sqrt(Gxy_squared + Gxx_minus_Gyy_squared, denom); Mat sin2theta = Gxy / denom;` and my Python code: `denom = cv2.sqrt(Gxy_squared + Gxx_minus_Gyy_squared); sin2theta = Gxy/denom;` And here, the "sin2theta" matrix starts to be pretty different between C++ and Python.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81105456
score: 1
comment on: http://stackoverflow.com/a/47078082
type: Comment
type: AnswerComment
has text: No. You need to do these things (install python & pip, install requests using pip, zip the bundle etc.) on a system. Doesn't need to be EC2; can be your Windows PC or mac

http://stackoverflow.com/comment/81265481
score: 0
type: QuestionComment
type: Comment
has text: updated with the data
comment on: http://stackoverflow.com/q/47157878

http://stackoverflow.com/comment/81280279
score: 0
type: AnswerComment
has text: ah, that is how to apply `idxmax`. I was at a loss for the correct application
comment on: http://stackoverflow.com/a/47165239
type: Comment

http://stackoverflow.com/comment/81311508
type: QuestionComment
has text: https://stackoverflow.com/questions/6319207/are-lists-thread-safe
comment on: http://stackoverflow.com/q/47181150
score: 1
type: Comment

http://stackoverflow.com/a/47217501
score: 0
type: Answer
has body: The code looks right. If you call or print gene_line outside of the for loops, then it is only going to print the last assigned value of the gene_line variable, which would be the last line of the file.
answers question: http://stackoverflow.com/q/47217314

http://stackoverflow.com/q/47193493
tagged with: plot
has body: I'd like to merge data of Series. But as result,These data was divided to three. How can I merge these data to one? (python3 jupyter notebook) fp_price = pd.Series(data) keep = [] for i in fp_price: fp_price_merge = i keep.append(fp_price_merge) print(keep) result [487832.87560916983, 488448.86992150272, 490797.3482372716, 490127.78920212726, 490493.25684214354, 490632.19034193602] [481897.10423319356, 482361.70278453565, 482144.11241496605, 481998.03776126896, 482209.0344832759, 482318.84407537803] [483650.51656619791, 483357.08254157269, 483476.66114698362, 483627.19449776667, 483503.16349747358, 483547.58143689478]
answer count: 3
tagged with: pandas
downvote count: 3
has answer: http://stackoverflow.com/a/47193556
favorite count: 0
has answer: http://stackoverflow.com/a/47193858
type: Question
tagged with: numpy
has title: How can I merge data of pandas?
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81336119
tagged with: python
has answer: http://stackoverflow.com/a/47194482
tagged with: merge
score: -3

http://stackoverflow.com/a/47230883
score: 0
answers question: http://stackoverflow.com/q/47216419
has body: I actually found a pretty handy solution (and very fast) using deque: from collections import deque queue = deque([100]*(4)) close = [] for num in range(0,len(close.index-4): nextval = queue[-1] + queue[0] close.append(nextval) queue.popleft() queue.append(nextval) close = pd.DataFrame(close,index=close.index)
type: Answer

http://stackoverflow.com/q/47092115
has body: Given a directory containing say a few thousand files, please output a list of all the names of the files in the directory that are exactly the same, I can write script to read files from dir, but i need to compare contents of each and every file in the directory and output should be like matches {f1,f2} {f4,f6} #!/usr/bin/env python import sys import glob import errno path = '/home/harish/myfiles' files = glob.glob(path) for name in files: # 'file' is a builtin type, 'name' is a less-ambiguous variable name. try: with open(name) as f: # No need to specify 'r': this is the default. sys.stdout.write(f.read()) except IOError as exc: if exc.errno != errno.EISDIR: # Do not fail if a directory is found, just ignore it. raise # Propagate other kinds of IOError.
has answer: http://stackoverflow.com/a/47093051
answer count: 1
has comment: http://stackoverflow.com/comment/81134691
has title: Need a python script which outputs a list of files with the same content in a single directory
has comment: http://stackoverflow.com/comment/81134544
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/254350
score: 0
has comment: http://stackoverflow.com/comment/81133636
has comment: http://stackoverflow.com/comment/81133749

http://stackoverflow.com/q/47163112
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: c++
tagged with: boost-python
linked to: http://stackoverflow.com/q/1446347
score: 2
answer count: 1
has body: I am trying to compile boost against my custom build of python and getting "undefined reference" errors. Here go details: 1) I build python with support unicode=ucs4 as required by autodesk maya ./configure --prefix=/v/pkgs/python/dep/2.7.14 --enable-unicode=ucs4 make make install 2) Build boost with this command b2 -j 4 --layout=versioned --build-type=complete --debug-configuration stage and config file ./tools/build/src/user-config.jam to use my build of python. using python : 2.7 : /v/pkgs/python/dep/2.7.14 ; This is part of b2 output, to confirm python selection success: notice: [python-cfg] Configuring python... notice: [python-cfg] user-specified version: "2.7" notice: [python-cfg] user-specified cmd-or-prefix: "/v/pkgs/python/dep/2.7.14" notice: [python-cfg] Checking interpreter command "/v/pkgs/python/dep/2.7.14/bin/python2.7"... notice: [python-cfg] running command '/v/pkgs/python/dep/2.7.14/bin/python2.7 -c "from sys import *; print('version=%d.%d\nplatform=%s\nprefix=%s\nexec_prefix=%s\nexecutable=%s' % (version_info[0],version_info[1],platform,prefix,exec_prefix,executable))" 2&gt;&amp;1' notice: [python-cfg] ...requested configuration matched! notice: [python-cfg] Details of this Python configuration: notice: [python-cfg] interpreter command: "/v/pkgs/python/dep/2.7.14/bin/python2.7" notice: [python-cfg] include path: "/v/pkgs/python/dep/2.7.14/include/python2.7" notice: [python-cfg] library path: "/v/pkgs/python/dep/2.7.14/lib/python2.7/config" "/v/pkgs/python/dep/2.7.14/lib" 3) To verify I try to build following test.cpp #include &lt;Python.h&gt; #include &lt;boost/python.hpp&gt; int main () { Py_Initialize(); boost::python::object obj; return 0; } with this command (new lines for easier reading): g++ -g -O2 -I/v/pkgs/python/dep/2.7.14/include/python2.7 -I/v/pkgs/boost/dep/1_61_0 -L/v/pkgs/boost/dep/1_61_0/stage/lib -lboost_python-gcc48-mt-1_61 -L/v/pkgs/python/dep/2.7.14/lib -lpython2.7 ./test.cpp I am getting following errors: /v/pkgs/boost/dep/1_61…
favorite count: 0
has title: building boost against custom python
type: Question
has answer: http://stackoverflow.com/a/51519704

http://stackoverflow.com/a/47108649
downvote count: 0
type: AcceptedAnswer
score: 3
upvote count: 3
has body: You need to update driver_setup fixture as below if you want access to driver in tests. @pytest.fixture() def driver_setup(request): driver = webdriver request.cls.driver = driver yield driver.quit() For more details refer to http://computableverse.com/blog/pytest-sharing-class-fixtures.
accepted answer of: http://stackoverflow.com/q/47108331
type: Answer
answers question: http://stackoverflow.com/q/47108331

http://stackoverflow.com/q/47131525
score: 0
has title: Replicating Python Array Index System in JavaScript
linked to: http://stackoverflow.com/q/8859828
has body: Is there any way to replicate Python's array indexing system in JavaScript. To access the last element in JavaScript, I would need to do this: last = arr[arr.length - 1] secondLast = arr[arr.length - 2] Is there any way I could access the elements using Python's way, eg: last = arr[-1] secondLast = arr[-2] This gets really annoying when you have an array of arrays. arr = [[1, 2], [3, 4], [5, 6]] // In JavaScript, to get 6: lastJS = arr[arr.length - 1][arr[arr.length - 1].length - 1] # In Python, simple: lastPy = arr[-1][-1] Any ideas? All I have seen online only allows arr.last or arr.last() by using Array.prototype.
has answer: http://stackoverflow.com/a/47131758
type: Question
has answer: http://stackoverflow.com/a/47131703
type: UnansweredQuestion
tagged with: arrays
tagged with: javascript
tagged with: python
has answer: http://stackoverflow.com/a/47131687
answer count: 4
has answer: http://stackoverflow.com/a/47131574

http://stackoverflow.com/q/47185093
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47185174
answer count: 4
has answer: http://stackoverflow.com/a/47185454
has answer: http://stackoverflow.com/a/47185161
has answer: http://stackoverflow.com/a/47185232
downvote count: 0
has title: How to find the count/occurrence of one string(can be multi-word) in another string(sentence) in python
score: 1
upvote count: 1
tagged with: string
favorite count: 0
type: Question
has body: I have to count the occurrence of a string(which can be 1 or more words) in another string (which is a sentence) and should not be case-sensitive. For instance - a = "Hi my name is Alex and hi to you as well. How high is the building? The highest floor is 18th. Highlights .... She said hi as well. Do you know highlights of the match ... hi." b = "hi" #word/sentence to find count of I tried - a.lower().count(b) which returns &gt;&gt; 8 while the required answer should be &gt;&gt; 4. For multi-word, this method seems to work but I am not sure of the limiting cases. How can I fix this?
tagged with: algorithm

http://stackoverflow.com/comment/81333962
type: QuestionComment
has text: Your `deleted` URL requires you to specify a `pk` but you didn't. You need to do `{% url 'deleted' <pk here> %}`.
comment on: http://stackoverflow.com/q/47192327
type: Comment
score: 1

http://stackoverflow.com/q/47141558
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47142109
type: AnsweredQuestion
answer count: 3
tagged with: algorithm
has answer: http://stackoverflow.com/a/47141941
tagged with: python
has title: How to the get the intersections of multiple periods
has comment: http://stackoverflow.com/comment/81233324
has answer: http://stackoverflow.com/a/47142109
score: 2
upvote count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/47143333
linked to: http://stackoverflow.com/q/325933
has answer: http://stackoverflow.com/a/47143333
has comment: http://stackoverflow.com/comment/81234101
has body: Psudo code: timelines = [ (range(&lt;from&gt;, &lt;to&gt;), range(&lt;from&gt;, &lt;to&gt;)), (range(&lt;from&gt;, &lt;to&gt;), range(&lt;from&gt;, &lt;to&gt;)), (range(&lt;from&gt;, &lt;to&gt;), range(&lt;from&gt;, &lt;to&gt;)), ] &lt;from&gt; and &lt;to&gt; represent datetime objects This "picture" shows after "Intersection" the values I need to calculate: |----------| |----------| |------------| |-------| |---------| |------------| Intersection |--| |---| |--| How do I calculate these intersections? I'm coding in python, but answers in any programming language are welcome, as I only need to understand the algorithm

http://stackoverflow.com/comment/81115794
type: Comment
has text: Revised to use the isdigit() function: https://docs.python.org/2/library/stdtypes.html#str.isdigit
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47083026

http://stackoverflow.com/q/47193003
tagged with: pyqt5
has title: Python 3.6 | PyQt5 | QLabel doesn't display QPixmap
favorite count: 0
tagged with: python-3.x
tagged with: qlabel
type: Question
has comment: http://stackoverflow.com/comment/81344300
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81335276
tagged with: qt
upvote count: 2
has comment: http://stackoverflow.com/comment/81344419
score: 2
has body: I'm trying to display a PNG image in a Widget using QLabel. I built the Widget using Qt Designer and the label shows the image properly. When I load the .ui into mi .py and execute it, everything shows up well, except for the label. I tried loading the QPixmap manually on the python code, but it didn't work either. from PyQt5.QtWidgets import (QApplication, QLabel) from PyQt5.QtGui import (QPixmap) from PyQt5 import uic import sys import os form = uic.loadUiType('gui/Files/Login.ui') class LoginWindow(form[0], form[1]): def __init__(self): super().__init__() self.setupUi(self) self.logoLabel.setPixmap(QPixmap(os.path.abspath(os.path.join(os.path.dirname(__file__), 'logo.png')))) self.logoLabel.show() if __name__ == '__main__': app = QApplication(sys.argv) win = LoginWindow() win.show() app.exec_() Any idea what am I doing wrong? Any sugestions on how could I display the image other than with QLabel?
downvote count: 0

http://stackoverflow.com/comment/81435889
type: Comment
comment on: http://stackoverflow.com/a/47229103
has text: @AidanL. That makes sense. Ok let me know when it's convenient.
score: 0
type: AnswerComment

http://stackoverflow.com/q/47140951
has title: Django Crispy form set model field as required
answer count: 1
tagged with: django-forms
favorite count: 0
type: Question
score: 5
has comment: http://stackoverflow.com/comment/81233189
upvote count: 5
downvote count: 0
has body: I have a modelform in which I want to set required attribute to True for email validation field:-email class RegisterMyBuisinessForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_action = '/registermybuisness/' Field('email', type='email') self.helper.add_input(Submit('submit', 'Submit',css_class="btn c-theme-btn c-btn-square c-btn-bold c-btn-uppercase")) super(RegisterMyBuisinessForm, self).__init__(*args, **kwargs) class Meta: model = RegistermyBusiness fields = ['name','email', 'org_name', 'contact','business_description','store_address','message','store_landmark','business_type','city'] I tried self.fields['email'].required=True this resulted in class RegisterMyBuisinessForm doesnot have fields error
has answer: http://stackoverflow.com/a/47141693
tagged with: django
tagged with: django-crispy-forms
tagged with: python
accepted answer: http://stackoverflow.com/a/47141693
type: AnsweredQuestion

http://stackoverflow.com/q/47076050
has comment: http://stackoverflow.com/comment/81101160
has comment: http://stackoverflow.com/comment/81100549
has title: Merging and transposing columns in Python gives TypeError: '>' not supported between instances of 'int' and 'datetime.datetime'
has comment: http://stackoverflow.com/comment/81100378
has body: I will give a minimum sample of the two dataframe, Search_Exits and Page_Exits that I am trying to merge/transpose and the code I am using. Search_Exits Search_Term No._of_Searches_before %_Search_Exits_before hello 10 .070 goodbye 100 .030 Page_Exits Search_Term Exit_Pages_actual Ratios hello /store/car 0.30 hello /store/b2b 0.30 hello /store/catalog/product/12 0.40 goodbye /store/car 1.00 the result I would like to see here is: Search_Term No._of_Searches_before %_Search_Exits_before /store/car /store/catalog/product12 /store/catalog/product23 /store/b2b hello 10 .070 0.30 0.40 0.00 0.30 goodbye 100 .030 1.00 0.00 0.00 0.00 I have tried all 3 versions given in the answer from this stackoverflow question:How to merge two tables and transpose rows to columns but get the identical error message for all of them, I have attempted the following: version 1 df = Search_Exits.merge(Page_Exits.groupby('Search_Term')['Exit_Pages_actual'].apply(lambda x: x.reset_index(drop=True)).unstack().reset_index()) version 2 Search_Exits.merge(Page_Exits.pivot_table(index='Search_Term', values='Ratios',columns='Exit_Pages_actual' + Page_Exits.groupby(['Search_Term'])['Exit_Pages_actual'].cumcount().astype(str)).reset_index()) version 3 (Search_Exits.set_index('Search_Term').join(Page_Exits.groupby('Search_Term')['Ratios'].apply(lambda x: x.tolist()).apply(pd.Series)).reset_index()) All 3 of these give me the following error, so I don't know what to do, if anyone can help: TypeError: '&gt;' not supported between instances of 'int' and 'datetime.datetime' UPDATE: So I tried doing the same thing on a simulated dataset that I myself created and I no longer get the error message (so I guess I don't know what is causing that problem in the data) however I have 2 things that are currently occurring differently from how I want them to occur. Firstly, the newly generated columns are not being labeled with the corresponding "Exit_Pages_actual" that I wanted them to be labeled as. Secondly, each c…
type: Question
has comment: http://stackoverflow.com/comment/81100508
has comment: http://stackoverflow.com/comment/81101284
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81110797
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81100703
has comment: http://stackoverflow.com/comment/81100481
has comment: http://stackoverflow.com/comment/81100753
has comment: http://stackoverflow.com/comment/81101303
tagged with: transpose
tagged with: datetime
has comment: http://stackoverflow.com/comment/81100804
has comment: http://stackoverflow.com/comment/81101108
tagged with: python
linked to: http://stackoverflow.com/q/37787289
score: 0
has comment: http://stackoverflow.com/comment/81105793
has comment: http://stackoverflow.com/comment/81100619
has comment: http://stackoverflow.com/comment/81100898
tagged with: pandas
has comment: http://stackoverflow.com/comment/81100667
has comment: http://stackoverflow.com/comment/81100542
has answer: http://stackoverflow.com/a/47079635
answer count: 1

http://stackoverflow.com/q/47179188
has body: My Django model has a pricing_plan choice field. There are 12 fields whose value depends on the pricing_plan value. class Organisation(models.Model): PRICING_CHOICES = ( ('basic', 'Basic'), ('team', 'Team'), ('super', 'Super') ) # some fields... pricing_plan = models.CharField(max_length=50, default='basic') max_host_accounts = models.IntegerField(default=1) max_admin_accounts = models.IntegerField(default=1) max_guests = models.IntegerField(default=10) # more fields whose value depends on pricing_plan value For every different pricing_plan these fields get specific values. In code that could be described like: if pricing_plan == 'basic': max_host_accounts = 1 max_admin_accounts = 1 max_guests = 10 ... elif pricing_plan == 'team': max_host_accounts = 10 max_admin_accounts = 3 max_guests = 25 ... However, there might be more pricing plans in the future and more options and I am afraid that an if/elif/else statement will be huge and not-easily readable. What would be the best/idiomatic way to implement that in a Django model? Use more CHOICE tuples with constant values for every pricing plan? Use Enum classes with constant values for every pricing plan? Use Organisation as parent class and create subclasses like: . class BasicOrganisation(Organisation): max_host_accounts = models.IntegerField(default=1) max_admin_accounts = models.IntegerField(default=1) max_guests = models.IntegerField(default=10) class TeamOrganisation(Organisation): max_host_accounts = models.IntegerField(default=10) max_admin_accounts = models.IntegerField(default=3) max_guests = models.IntegerField(default=25) Anything else?
type: UnansweredQuestion
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81307774
has answer: http://stackoverflow.com/a/47179553
has comment: http://stackoverflow.com/comment/81307376
score: 1
tagged with: django-models
has comment: http://stackoverflow.com/comment/81307730
favorite count: 0
has comment: http://stackoverflow.com/comment/81307695
type: Question
has comment: http://stackoverflow.com/comment/81307540
answer count: 2
has answer: http://stackoverflow.com/a/47180406
has title: Multiple django model values depend on choice field value

http://stackoverflow.com/comment/81311676
type: QuestionComment
comment on: http://stackoverflow.com/q/47181187
score: 0
type: Comment
has text: Thanks will do (is it not obvious in the example?)

http://stackoverflow.com/comment/81328889
type: Comment
score: 0
type: AnswerComment
has text: this kind of question is difficult to solve because we don't have the hardware the OP has, so it's important to get the maximum of info from the OP. I tried, but forgot some points. Let's wait for his new comment/edit.
comment on: http://stackoverflow.com/a/47189220

http://stackoverflow.com/comment/81418412
has text: @JimDennis yes you are right. That got out of my mind. Thanks .
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47171774
score: 0

http://stackoverflow.com/comment/81182881
has text: I've just tried "\n".join(sets) and it's worked however it leaves a blank line between each string. Is there any way to keep them line after line?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47116328

http://stackoverflow.com/comment/81182299
has text: @OP: can you give a link to the similar question you've found?
comment on: http://stackoverflow.com/q/47116042
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47128044
accepted answer: http://stackoverflow.com/a/47134703
has body: I'm trying to run the PyTorch tutorial on CIFAR10 image classification here - http://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py I've made a small change and I'm using a different dataset. I have images from the Wikiart dataset that I want to classify by artist (label = artist name). Here is the code for the Net - class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16*5*5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16*5*5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x Then there is this section of the code where I start training the Net. for epoch in range(2): running_loss = 0.0 for i, data in enumerate(wiki_train_dataloader, 0): inputs, labels = data['image'], data['class'] print(inputs.shape) inputs, labels = Variable(inputs), Variable(labels) optimizer.zero_grad() # forward + backward + optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() # print statistics running_loss += loss.data[0] if i % 2000 == 1999: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0 This line print(inputs.shape) gives me torch.Size([4, 32, 32, 3]) with my Wikiart dataset whereas in the original example with CIFAR10, it prints torch.Size([4, 3, 32, 32]). Now, I'm not sure how to change the Conv2d in my Net to be compatible with torch.Size([4, 32, 32, 3]). I get this error: RuntimeError: Given input size: (3 x 32 x 3). Calculated output size: (6 x 28 x -1). Output size is too small at /opt/conda/conda-bld/pytorch_1503965122592/work/torch/lib/THNN/generic/SpatialConvolutionMM.c:45 While reading the images for the Wikiart dataset, I…
upvote count: 9
answer count: 5
tagged with: convolution
has title: Calculating input and output size for Conv2d in PyTorch for image classification
score: 7
tagged with: python
has answer: http://stackoverflow.com/a/59130038
possible better answer: http://stackoverflow.com/a/59130038
tagged with: image
has answer: http://stackoverflow.com/a/57319832
type: AnsweredQuestion
tagged with: tensor
tagged with: pytorch
has answer: http://stackoverflow.com/a/47142862
downvote count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/47134703
has answer: http://stackoverflow.com/a/60486320
type: Question

http://stackoverflow.com/comment/81128317
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47088928
has text: 2-year: 〖(1.08 × 1.0824)〗^(1/2) – 1 = 8.12% 3-year: 〖(1.08 × 1.0824 ×1.09)〗^(1/3) – 1 = 8.41% 4-year: 〖(1.08 × 1.0824 ×1.09 ×1.095)〗^(1/4) – 1 = 8.68%
score: 0

http://stackoverflow.com/a/47229103
has comment: http://stackoverflow.com/comment/81410878
has comment: http://stackoverflow.com/comment/81460429
has comment: http://stackoverflow.com/comment/81455498
has comment: http://stackoverflow.com/comment/81459395
has body: This script will include everything but folders tcl8.6 and tk8.6. You will need to copy those with your build folder manually. from cx_Freeze import setup, Executable import os files = {"include_files": ["&lt;Path to Python&gt;/Python36-32/DLLs/tcl86t.dll", "&lt;Path to Python&gt;/Python36-32/DLLs/tk86t.dll"], "packages": ["tkinter"]} os.environ['TCL_LIBRARY'] = "&lt;Path to Python&gt;/Python36-32/tcl/tk8.6" os.environ['TK_LIBRARY'] = "&lt;Path To Python&gt;/Python36-32/tcl/tk8.6" base = "Win32GUI" setup( name = "Name of app", version = "0.1", author = "The author", options = {'build_exe': files}, description = "Enter Description Here", executables = [Executable("tk_ex.py", base=base)]) EDIT: This script works without copying and pasting anything. from cx_Freeze import setup, Executable import os import sys import os.path PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__)) os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR,'tcl','tcl8.6') os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6') files = {"include_files": ["&lt;Location to Python&gt;/Python36-32/DLLs/tcl86t.dll", "&lt;Location to Python&gt;/Python36-32/DLLs/tk86t.dll"], "packages": ["tkinter"]} setup( name = "Name of app", version = "0.1", author = "The author", options = {'build_exe': files}, description = "Enter Description Here", executables = [Executable("tk_ex.py", base=base)])
has comment: http://stackoverflow.com/comment/81434903
type: Answer
answers question: http://stackoverflow.com/q/47107454
has comment: http://stackoverflow.com/comment/81458917
has comment: http://stackoverflow.com/comment/81446783
has comment: http://stackoverflow.com/comment/81408674
has comment: http://stackoverflow.com/comment/81454530
score: 0
has comment: http://stackoverflow.com/comment/81434857
upvote count: 1
has comment: http://stackoverflow.com/comment/81457342
has comment: http://stackoverflow.com/comment/81446689
has comment: http://stackoverflow.com/comment/81435476
has comment: http://stackoverflow.com/comment/81435889
downvote count: 1
has comment: http://stackoverflow.com/comment/81460258
has comment: http://stackoverflow.com/comment/81443325
has comment: http://stackoverflow.com/comment/81458772
has comment: http://stackoverflow.com/comment/81460416
has comment: http://stackoverflow.com/comment/81460477

http://stackoverflow.com/comment/81774643
has text: @SamyakJain Thank You. Can you tell me where I can find the tutorial or the study material?
comment on: http://stackoverflow.com/a/47067638
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47191477
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47191590
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47191590
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
has body: I need some help with my code. I want to find the data of program_start_date into the database as I would like to store the program_id in the same rows as the program_start_date data. When I try this: cur.execute("UPDATE programs SET program_id=? WHERE start_date=?",(program_start_date, program_id)) conn.commit() It will not let me to update the program_id in the same rows as the start_date data. Here is the full code: nextday_list = ['20171109224500', '20171109223000', '20171109224500', '20171109223500', '20171109220000', '20171109224000', '20171109230000'] program_id_list = ['3001', '3002', '3003', '3004', '3005', '3006', '3007', '3008', '3009', '3010', '3011', '3012', '3013', '3014', '3015', '3016', '3017', '3018', '3019', '3020', '3021', '3022', '3023', '3024', '3025', '3026', '3027', '3028', '3029', '3030', '3031', '3032', '3033', '3034', '3035', '3036', '3037', '3038', '3039', '3040', '3041', '3042', '3043', '3044', '3045', '3046', '3047', '3048', '3049', '3050', '3051', '3052', '3053', '3054', '3055', '3056', '3057', '3058', '3059', '3060', '3061', '3062', '3063', '3064', '3065', '3066', '3067', '3068', '3069', '3070'] for nextday, program_id in zip(nextday_list, program_id_list): cur.execute('SELECT start_date, program_id FROM programs WHERE start_date &gt;= ? LIMIT 10', [nextday,]) programs = cur.fetchall() for ind, row in enumerate(programs): program_start_date = str(row[0]) cur.execute("UPDATE programs SET program_id=? WHERE start_date=?",(program_start_date, program_id)) conn.commit() Here is the program_start_date data: 20171109224500 20171109234500 20171110004500 20171110005000 20171110060000 20171110091500 20171110100000 20171110110000 20171110114500 20171110121500 20171109223000 20171109224500 20171109234500 20171110004500 20171110005000 20171110060000 20171110091500 20171110100000 20171110110000 20171110114500 20171109224500 20171109234500 20171110004500 20171110005000 20171110060000 20171110091500 20171110100000 20171110110000 20171110114500 201711…
has title: Update the data in the same rows as the other data
score: 1

http://stackoverflow.com/a/47083027
type: Answer
answers question: http://stackoverflow.com/q/47082410
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: You need to have a function that will keep track of the highest scores for each player. It will add a player to the total if not already there, otherwise adding it if it's higher. Something like this: def addScores(scores, total): for player in scores: if player not in total or total[player] &lt; scores[player]: total[player] = scores[player]
accepted answer of: http://stackoverflow.com/q/47082410

http://stackoverflow.com/comment/81182316
type: QuestionComment
has text: That is true that it's ambiguous but I think one can disambiguate "destructively"
comment on: http://stackoverflow.com/q/47116042
score: 0
type: Comment

http://stackoverflow.com/a/47138995
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47136578
has comment: http://stackoverflow.com/comment/81234781
answers question: http://stackoverflow.com/q/47136578
has comment: http://stackoverflow.com/comment/81233759
type: Answer
has body: As I said in a comment, you seemingly misunterstood the semantics of xmin, xmax that should be fractions 0≤x≤1 of the x-axis. The correct way to use them, in your particular use case, is In [42]: N, n = 12, 12.0 # an integer and a float, so it works also in Python 2 In [43]: data = np.random.randint(50, 80, N) In [44]: for j in range(N): ...: k = j+1 ...: plt.axhline(data[j], xmin=j/n, xmax=k/n) To have a better appearance you can finish with In [45]: plt.xlim((2016-N,2016)); In [46]: plt.xticks(np.linspace(2016-N, 2016, N+1)); In [47]: plt.grid(); # of course gridding is optional In [48]: to obtain
has comment: http://stackoverflow.com/comment/81234592
score: 0

http://stackoverflow.com/comment/81246462
has text: Not possible. Why are you building this string in the first place?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47148068
type: QuestionComment

http://stackoverflow.com/q/47074691
has comment: http://stackoverflow.com/comment/81097802
linked to: http://stackoverflow.com/q/17936555
has title: Python Requests to cURL?
tagged with: python
has body: I have a python snippet for a posting a file onto an URL: import requests url = 'http://www.test.com/route' files = {'pdf': open('/path/to/file/abc.pdf', 'rb'), 'variable_1': '1', 'variable_2': '2'} r = requests.post(url, files=files) print(r.status_code) It works! And I am looking for the cURL equivalent for the same! I have tried this: curl -X POST http://www.test.com/route -H 'content-type: application/json' -F pdf=@/path/to/file/abc.pdf -F variable_1=1 -F variable_2=2 What would be the correct curl? Thanks!
has comment: http://stackoverflow.com/comment/81099461
has comment: http://stackoverflow.com/comment/81099629
tagged with: curl
upvote count: 4
answer count: 0
type: UnansweredQuestion
tagged with: python-requests
downvote count: 1
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/81110506

http://stackoverflow.com/comment/81109983
comment on: http://stackoverflow.com/q/47080272
type: Comment
has text: @Tomalak How do you save Unicode objects to a file without encoding them in some fashion?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81187430
comment on: http://stackoverflow.com/a/47118400
score: 0
type: Comment
has text: use `minkey, minvalue = min(dct.items(), key=lambda x:x[1])` you have to use minkey and minvalue variables in your print statement
type: AnswerComment

http://stackoverflow.com/comment/81257679
has text: Your answer was probably downvoted because your 2nd and 3rd solutions are exactly what the OP doesn't want to do. `List`s **are** fully stored in memory. Your 1st solution or at least the idea behind it would work though, if the OP could split in two the input generator, then this would solve the problem. But it's most likely not possible.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47147228

http://stackoverflow.com/a/47128434
has body: Use enumerate() in inner for-loop to retrieve index (say i), then use item[i] = float(n)
answers question: http://stackoverflow.com/q/47128389
type: Answer
downvote count: 0
score: 1
upvote count: 1

apache-spark
tags question: http://stackoverflow.com/q/47147830
tags question: http://stackoverflow.com/q/47083219
tags question: http://stackoverflow.com/q/47177669
tags question: http://stackoverflow.com/q/47100325
tags question: http://stackoverflow.com/q/47198678
tags question: http://stackoverflow.com/q/47213631
tags question: http://stackoverflow.com/q/47091529
tags question: http://stackoverflow.com/q/47221186
tags question: http://stackoverflow.com/q/47174686
tags question: http://stackoverflow.com/q/47099332
tags question: http://stackoverflow.com/q/47103730
tags question: http://stackoverflow.com/q/47176888
tags question: http://stackoverflow.com/q/47146275
tags question: http://stackoverflow.com/q/47222505
tags question: http://stackoverflow.com/q/47211002
tags question: http://stackoverflow.com/q/47177112
tags question: http://stackoverflow.com/q/47181025
tags question: http://stackoverflow.com/q/47150234
tags question: http://stackoverflow.com/q/47102378
type: Tag
tags question: http://stackoverflow.com/q/47090432
tags question: http://stackoverflow.com/q/47211837
tags question: http://stackoverflow.com/q/47164588
tag name: apache-spark
tags question: http://stackoverflow.com/q/47167891
tags question: http://stackoverflow.com/q/47073414
tags question: http://stackoverflow.com/q/47111737

http://stackoverflow.com/comment/81361916
has text: Thanks everyone for your advices, finally I'm able to get desired results using different solutions from both ctwheels and RomanPerekhrest.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47205335
type: Comment

http://stackoverflow.com/comment/81290008
comment on: http://stackoverflow.com/a/47170167
score: 0
type: Comment
has text: Can you explain ?
type: AnswerComment

http://stackoverflow.com/comment/136503739
has text: I get index Date contains duplicate values error. How to handle that?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/74190430

http://stackoverflow.com/comment/81277461
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47163874
type: QuestionComment
has text: Seems you're really close. Just need to make that ad_list function a method on your Node class. See the beginning of this article: https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods

http://stackoverflow.com/q/47141461
answer count: 1
score: -3
tagged with: selenium
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47141866
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/47141866
downvote count: 3
tagged with: python
favorite count: 0
has title: I am trying to webscrape to pycharm using selenium
type: Question
has body: This is the HTML text that gives the output -£0.03. I`d like to find this value by xpath and print the output to pycharm console. <mv-runner-pnl ng-repeat="(type, pnl) in ctrl.vm.data.pnl[runner.key] track by type" type="actual" values="pnl.values" separator="comma" formatter="::pnl.formatter"> -£0.03 I have tried the following: driver.find_element_by_xpath('//*[@id="main-wrapper"]/div/div[3]/div/div[2]/div/div[1]/div[3]/div/div[1]/div/bf-main-market/bf-main-marketview/div/div[2]/bf-marketview-runners-list[2]/div/div/div/table/tbody/tr[1]/td[1]/div/div[3]').get_attribute(pnl.value) print(pnl.value) My result is: :NameError: name 'pnl' is not defined Is this even possible? If not by xpath then by any other means? As I said I am totally new to this and trying to learn from YouTube tutorials.
tagged with: pycharm
upvote count: 0

http://stackoverflow.com/comment/81207486
comment on: http://stackoverflow.com/a/47127793
score: 0
type: AnswerComment
has text: https://repl.it/NkrV/3 I think I did what you said, but I'm still getting the error "Traceback (most recent call last): File "python", line 55, in <module> File "python", line 17, in main File "python", line 49, in division ZeroDivisionError: float division by zero"
type: Comment

http://stackoverflow.com/comment/81237225
has text: as an update when running it, we were about to get 10049 readings in 1 second. so this is much much faster than a point every millisecond like before. Thanks again!
type: Comment
comment on: http://stackoverflow.com/a/47103498
score: 0
type: AnswerComment

http://stackoverflow.com/a/47174285
has body: This is because in your example without classes the count variable is in a scope that is available to your update_txt function. In your class, the update_clock function does not have access to the countVar variable that you define in __init__. Two functions defined separately will not have access to each others variables. This is what you use your variable self for. The first argument passed to any of your functions in this class is a copy of the class, and you give it the name self. So if you set it as self.countVar it will be available in update_clock as self.countVar. You may be interested in doing a search for "python LEGB", which will show you a bit more about how scoping works in python :D
answers question: http://stackoverflow.com/q/47174160
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/81298002
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47174160

http://stackoverflow.com/q/47071256
tagged with: pip
has answer: http://stackoverflow.com/a/74641646
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/78136045
has title: How to update/upgrade a package using pip?
has answer: http://stackoverflow.com/a/77299399
upvote count: 854
accepted answer: http://stackoverflow.com/a/47071257
has answer: http://stackoverflow.com/a/50207498
has answer: http://stackoverflow.com/a/59011518
score: 850
tagged with: python
has answer: http://stackoverflow.com/a/47071257
has body: What is the way to update a package using pip? those do not work: pip update pip upgrade I know this is a simple question but it is needed as it is not so easy to find (pip documentation doesn't pop up and other questions from stack overflow are relevant but are not exactly about that)
possible better answer: http://stackoverflow.com/a/56798606
has answer: http://stackoverflow.com/a/71079694
has answer: http://stackoverflow.com/a/52469115
has answer: http://stackoverflow.com/a/76423887
linked to: http://stackoverflow.com/q/2861183
has answer: http://stackoverflow.com/a/71620568
has answer: http://stackoverflow.com/a/56798606
type: AnsweredQuestion
answer count: 12
downvote count: 4
has answer: http://stackoverflow.com/a/63169309
linked to: http://stackoverflow.com/q/15221473

http://stackoverflow.com/q/47075210
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: django
favorite count: 0
has comment: http://stackoverflow.com/comment/81126191
has body: I am new in django, i need to develop chart based application i am creating line chart using chart.js library Django Version: 1.10.8 &amp; Python Version: 3.6.3 i have install pip install django-chartjs INSTALLED_APPS settings: INSTALLED_APPS = ('chartjs',) Create the HTML file Create the view with labels and data definition and also add urls.py file and static files. when i run this application it returns only json data but i want to display chart if any mistake my code.its not navigate to html page. reference link http://django-chartjs.readthedocs.io/en/latest/ urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^line_chart/$', views.line_chart_json, name='line_chart_json'), ]
score: 1
has title: not navigate to template page in django chartjs?Django Version: 1.10.8 and Python Version: 3.6.3
tagged with: python
tagged with: chartjs-2.6.0
type: Question
has comment: http://stackoverflow.com/comment/81105280

http://stackoverflow.com/comment/81097636
comment on: http://stackoverflow.com/q/47074617
score: 0
type: Comment
type: QuestionComment
has text: appearently, I am using 3.6, your solution worked, thank you! @JonClements if you want to post an answer I can upvote, do so :)

http://stackoverflow.com/a/47146129
has body: I would implement a defaultdict from the collections module. Here is an example from the official docs: &gt;&gt;&gt; s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] &gt;&gt;&gt; d = defaultdict(list) &gt;&gt;&gt; for k, v in s: ... d[k].append(v) ... &gt;&gt;&gt; sorted(d.items()) [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47145305

http://stackoverflow.com/a/47086845
has comment: http://stackoverflow.com/comment/81126064
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47086497
has comment: http://stackoverflow.com/comment/81123739
has comment: http://stackoverflow.com/comment/81125388
answers question: http://stackoverflow.com/q/47086497
score: 0
has comment: http://stackoverflow.com/comment/81123722
type: Answer
has comment: http://stackoverflow.com/comment/81123810
has body: This is what I will do with isin t_df1.loc[~t_df1['contactId'].isin(t_df2['contactId']),:]

http://stackoverflow.com/q/47093661
type: AnsweredQuestion
has title: Print in terminal with colors using python but also want to save output in file but getting unreadable text
score: 0
has comment: http://stackoverflow.com/comment/81137318
has comment: http://stackoverflow.com/comment/81137107
answer count: 1
has body: I tried terminal color code using python. But I also want to save it in a file but when I tried to that file is having unreadable text. How can I do this both? BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) def cprint(text, color=WHITE): seq = "\x1b[1;%dm" % (30+color) + text + "\x1b[0m" sys.stdout.write(seq) cprint("String", RED) It will get a red color output in the terminal. But when I save it into a file it got with color code. Output in the file: ^[[1;31mstring^[[0m
has comment: http://stackoverflow.com/comment/81136793
type: Question
has comment: http://stackoverflow.com/comment/81137121
has comment: http://stackoverflow.com/comment/81137670
linked to: http://stackoverflow.com/q/27265322
accepted answer: http://stackoverflow.com/a/47094194
tagged with: python
has comment: http://stackoverflow.com/comment/81136888
has answer: http://stackoverflow.com/a/47094194

http://stackoverflow.com/comment/81307031
has text: I'm asking about the _python_ module you're using to read/write the excel spreadsheet.
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47179026

http://stackoverflow.com/q/47112972
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47113901
has body: I am trying to scrape twitter, and I am concerned only with the tweet text as off now. When I narrow my down to the 'p' tag that contains the text, there are unprecedented tags like 'strong' inside the text that I just can't get rid off. For example, this is what outputs when I print my tag text: &gt; &lt;selenium.webdriver.remote.webelement.WebElement &gt; (session="5dd609e4b0694f9c363007d68d5b698a", &gt; element="0.02910224956545071-1")&gt; &gt; &lt;selenium.webdriver.remote.webelement.WebElement &gt; (session="5dd609e4b0694f9c363007d68d5b698a", &gt; element="0.02910224956545071-2")&gt; Trevor Noah challenging Tomi Lahren &gt; and her stance on Black Lives Matter, her racist narratives, Donald &gt; Trump and more While the output I expect is as follows: &gt; Trevor Noah challenging Tomi Lahren and her stance on Black Lives &gt; Matter, her racist narratives, Donald Trump and more Another example is as follows: &gt; &lt;selenium.webdriver.remote.webelement.WebElement &gt; (session="5dd609e4b0694f9c363007d68d5b698a", &gt; element="0.18626949664745118-10")&gt; If the Cubs can win the World &gt; Series, Donald Trump can win the presidency, and the Cowboys can win &gt; 11-straight, then I can survive finals Here is what I expect: &gt; If the Cubs can win the World &gt; Series, Donald Trump can win the presidency, and the Cowboys can win &gt; 11-straight, then I can survive finals The number of occurrences and position of this webelement is different for every iteration, and hence I'm stuck. I have tried regex, but couldn't solve the issue. Any help would be appreciated. Thankyou!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81175884
tagged with: python
tagged with: selenium-chromedriver
has title: Selenium (Python): Remove all webelements from text
answer count: 2
has answer: http://stackoverflow.com/a/47113191
score: 0
tagged with: selenium
upvote count: 1

http://stackoverflow.com/a/47192907
answers question: http://stackoverflow.com/q/47192724
has body: You can open two files at once. Don't open one within the loop For example open(tweets_filename) as tweets_file, open(output, "a") as out_file: for line in tweets_file: # parse the line here out_file.write(line)
accepted answer of: http://stackoverflow.com/q/47192724
has comment: http://stackoverflow.com/comment/81396187
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/81394492
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47109289
accepted answer: http://stackoverflow.com/a/47109523
favorite count: 0
type: Question
has title: get list of NoneType values 'None'
tagged with: nonetype
upvote count: 0
linked to: http://stackoverflow.com/q/3459098
score: -3
tagged with: python
duplicate of: http://stackoverflow.com/q/11178061
has comment: http://stackoverflow.com/comment/81168864
tagged with: lambda
possible better answer: http://stackoverflow.com/a/47109983
has comment: http://stackoverflow.com/comment/81168744
has answer: http://stackoverflow.com/a/47109983
duplicate of: http://stackoverflow.com/q/3459098
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47109523
answer count: 3
tagged with: plotly
downvote count: 3
has body: I am new to Python. I'm trying to get a list of NoneType values to create a subplot (plotly library). The following setup is required to create subplots with different specs: fig = tools.make_subplots(rows=2, cols=3, specs=[ [{'colspan':3}, None, None], map(lambda x: {}, ew) ], shared_xaxes=False, shared_yaxes=False, start_cell='top-left', print_grid=False) So, based on the values in the list "ew", a list of Nonetype values is needed. The values in the list can vary and so should the list of Nonetypes. Solution: List of Strings, List comprehension: lst =', '.join([str(None) for ticker in ew]) Problem: Strings - convert to Nonetype possible? Solution: Lambda function that inserts None for each value in ew. map(lambda x: None, ew) Problem: Brackets of the list. Can't get rid of them. The Solution I am looking for: print(lst) None, None &lt;type 'NoneType'&gt; so that: fig = tools.make_subplots(rows=2, cols=3, specs=[ [{'colspan':3}, lst], map(lambda x: {}, ew) ], shared_xaxes=False, shared_yaxes=False, start_cell='top-left', print_grid=False) Is there a way to get such a list? or a better solution over a embedded function? EDIT since there is still an error by inserting the following 'lst' to fig: lst = print(*map(lambda x: None, ew), sep= ', ') #returns None, None print('{lst}'.format(**locals())) #returns only None -> is this a possible explanation?
has answer: http://stackoverflow.com/a/47111340

http://stackoverflow.com/comment/81319040
type: QuestionComment
has text: Possible duplicate of [How can I write a python method to compute all combinations of a dict of lists?](https://stackoverflow.com/questions/47175020/how-can-i-write-a-python-method-to-compute-all-combinations-of-a-dict-of-lists)
comment on: http://stackoverflow.com/q/47184806
score: 1
type: Comment

http://stackoverflow.com/comment/81154748
type: QuestionComment
type: Comment
score: 2
has text: This is also doing only `99999` simulations and throwing away the results of the first `99998`...
comment on: http://stackoverflow.com/q/47102190

http://stackoverflow.com/comment/81240407
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47145070
type: Comment
has text: Why are you going through the complication of saving a bunch of lists as a text file, using your own home-brewed format? If you are going to do that, why not use `pickle` or `json`? Have you tried printing the offending object? Any attempt to debug this yourself?

http://stackoverflow.com/comment/81192582
type: QuestionComment
comment on: http://stackoverflow.com/q/47120873
has text: @UlrichEckhardt yes, I'm connected to the machine through SSH. After I run the command, it hangs until the session is closed. So I'm sure I don't get the prompt back
type: Comment
score: 0

http://stackoverflow.com/comment/81389424
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47123747
has text: I think you need `days = pd.to_datetime(df['Time Stamp'].str.split().str[0]) df = df.groupby([days, 'Id','Latitude','Longitude'])` and then `['Id'].nunique().reset_index(name='count')`
score: 0

http://stackoverflow.com/comment/81248592
type: Comment
score: 0
has text: Have you tried any of the answers? It seems you don't even find it necessary to make any comment whether it solves your problem or not.
type: QuestionComment
comment on: http://stackoverflow.com/q/47138501

http://stackoverflow.com/comment/81315539
score: 1
type: QuestionComment
has text: Ok, so it sounds like you want the values from `list2`, along with everything in `list1` that's not in `list2`. Do you care about the order?
type: Comment
comment on: http://stackoverflow.com/q/47183095

http://stackoverflow.com/comment/81152119
type: AnswerComment
has text: @OzgurVatansever What's `0(n^2)`? And I think you confuse `x` and `l`...
comment on: http://stackoverflow.com/a/47100984
score: 0
type: Comment

http://stackoverflow.com/a/47104927
answers question: http://stackoverflow.com/q/47104318
type: AcceptedAnswer
has body: You can do the way you want if you import Main.py from within function_y(): functions.py def function_y(): import main dostuff... main.object.bye() #object from Main.py dostuff... main.function_x() #function from Main.py
has comment: http://stackoverflow.com/comment/81160636
has comment: http://stackoverflow.com/comment/81160847
has comment: http://stackoverflow.com/comment/81160573
type: Answer
accepted answer of: http://stackoverflow.com/q/47104318
has comment: http://stackoverflow.com/comment/81160698
score: 0

http://stackoverflow.com/comment/81240319
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47104627
has text: @ekhumoro Sorry for not responding. I've tried your answer and it worked. Mostly because I moved `init_queue()` out from `main` and import started working as i expected.

http://stackoverflow.com/q/47118267
has answer: http://stackoverflow.com/a/47118397
type: Question
tagged with: python
has body: When I use plt.waitforbuttonpress(), it behaves as expected, but any click to the plot is getting dispatched as this "button press", so using plot GUI tools like zooming tool is not possible. Is there an alternative to waitforbuttonpress that enables you to freeze a window in plt.ion() mode until certain input from user in received and not clear the plot in until explicit cla() or clf() call, and enables you to use these gui tools?
has title: How to use plt.waitforbuttonpress() with plot gui tools such as zoom?
type: AnsweredQuestion
score: 0
tagged with: matplotlib
answer count: 1
accepted answer: http://stackoverflow.com/a/47118397
tagged with: interactive

http://stackoverflow.com/a/47134159
has comment: http://stackoverflow.com/comment/81218279
has comment: http://stackoverflow.com/comment/81219137
downvote count: 1
has comment: http://stackoverflow.com/comment/81219036
score: 5
type: Answer
answers question: http://stackoverflow.com/q/47134083
upvote count: 6
has body: This should work from itertools import chain 1 in chain.from_iterable(chain.from_iterable(my_list))
accepted answer of: http://stackoverflow.com/q/47134083
type: AcceptedAnswer

http://stackoverflow.com/comment/81223168
score: 0
comment on: http://stackoverflow.com/q/47136904
has text: @timgeb thanks for saying it. The file is generated using `pickle.dump(storage.get(), open(COOKIE_FILENAME, "wb"))` where the `storage` is the content of the LocalStorage of a browser (I'm using Selenium).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81304404
comment on: http://stackoverflow.com/a/47176213
type: Comment
score: 0
type: AnswerComment
has text: sir, still blocking other api call when it running Program is

python-telegram-bot
tags question: http://stackoverflow.com/q/47167193
tag name: python-telegram-bot
tags question: http://stackoverflow.com/q/47163157
type: Tag
tags question: http://stackoverflow.com/q/47138143

http://stackoverflow.com/comment/81340767
score: 0
comment on: http://stackoverflow.com/q/47195785
type: Comment
type: QuestionComment
has text: @SethMMorton I agree with Julien that duplicate classification is incorrect. Please re-open this question.

http://stackoverflow.com/comment/81129447
type: QuestionComment
comment on: http://stackoverflow.com/q/47087919
type: Comment
score: 0
has text: i am getting error... global name csrf_token is not defined @Kalariya_M

http://stackoverflow.com/a/47096179
answers question: http://stackoverflow.com/q/47096034
type: Answer
score: 0
has body: self.cursor.execute("SELECT * FROM Book") dbFile = QFileDialog.getSaveFileName(parent=None,caption="Export DataFile a File",directory=".",filter="CSV File(*.csv)") if dbFile[0]: with open(dbFile[0] + ".csv", "wb") as csvFile: csvWriter = csv.writer(csvFile,delimiter=',', quotechar="\"",quoting=csv.QUOTE_MINIMAL) rows = self.cursor.fetchall() rowCount = len(rows) for row in rows: csvWriter.writerow(bytes(row,"UTF-8")) Error : Traceback (most recent call last): File "D:/Souerce/PyQT/Project/Library Management/main.py", line 303, in ExportFile csvWriter.writerow(bytes(row,"UTF-8")) TypeError: encoding or errors without a string argument

ngrok
tag name: ngrok
tags question: http://stackoverflow.com/q/47147492
type: Tag

http://stackoverflow.com/comment/81328384
comment on: http://stackoverflow.com/a/47185640
type: Comment
score: 0
type: AnswerComment
has text: Thanks, the only problem is the output file contains the literal header info instead of the values. Using python 2.7 btw.

http://stackoverflow.com/q/47200741
tagged with: python
has body: I'm trying to add object-persistence to my python app. I'm currently using python 3.4 on windows. The only module I found useful was shelve but on windows, it appears, it creates three different files rather than one: 'db.bak' ,'db.dat' and 'db.dir'. How can I force shelve to create only single file ? furthermore , whenever I need to open that db on read-only mode , 'db.dir' is being edited for some reason. Does anyone know how to fix those issues ? or maybe suggest other modules that would work considering the OS and python version?
has comment: http://stackoverflow.com/comment/81349956
tagged with: python-3.4
has comment: http://stackoverflow.com/comment/81351842
has title: shelve module on windows
answer count: 0
has comment: http://stackoverflow.com/comment/81351436
score: 0
has comment: http://stackoverflow.com/comment/81352104
tagged with: shelve
type: Question
has comment: http://stackoverflow.com/comment/81352221
type: UnansweredQuestion
tagged with: windows
tagged with: object-persistence

http://stackoverflow.com/comment/81337116
score: 0
type: Comment
type: AnswerComment
has text: you are right, I appreciate your help. I have updated the answer.
comment on: http://stackoverflow.com/a/47194043

http://stackoverflow.com/q/47161512
tagged with: python
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/59502599
has body: I am searching for password in a text file but it says password not found every time, although the passwords exist in the file. This is my current code: import pickle import time print "Do you already have a database created" y=raw_input("'yes' to continue") if y=='yes': #to search password in text file infile=open(r"C:\Users\pc\Desktop\itika study material\cs\password.txt", "r") Passwords = infile.readlines() while True: InputPassword = raw_input("Enter your password.") print "Searching for password." time.sleep(2) if InputPassword in Passwords: print "your password has been found, you can access your database" break else: print "your password has Not been found." #only prints this statement break
has answer: http://stackoverflow.com/a/47165172
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81329052
has answer: http://stackoverflow.com/a/47162460
score: 2
has comment: http://stackoverflow.com/comment/81279606
tagged with: python-2.7
has title: Searching for password in a text file
answer count: 3
downvote count: 0

http://stackoverflow.com/q/47156119
has comment: http://stackoverflow.com/comment/81263999
tagged with: python
type: UnansweredQuestion
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81267196
score: 0
tagged with: user-interface
has body: I'm developing a simple user interface with Tkinter. I have some checkbuttons, entries and I should setup a button to save them all in a file. This is the code: from tkinter import * import json, sys class Window(Frame): def load_config(self,obs,wav): d = json.load(open('config.txt','r')) self.conf_dict = d[obs][wav] def __init__(self,master,observatory,wavelength): Frame.__init__(self, master) self.master = master self.load_config(observatory,wavelength) r = 0 for k,v in self.conf_dict.items(): r += 1 self.l = Label(master, text=k+':') self.l.grid(row=r,column=0,padx=10, pady=5) if isinstance(v,bool): self.c = Checkbutton(master) self.c.grid(row=r,column=1,padx=10,pady=5) else: self.e = Entry(master) self.e.insert(END,str(v)) self.e.grid(row=r,column=1,padx=10, pady=5) self.b = Button(master,text='Save',command=save_callback) def save_callback(self): # save new config file with json if __name__ == '__main__': root = Tk() app = Window(root,sys.argv[1],sys.argv[2]) root.mainloop() Best idea would be to modify the values of conf_dict directly and save the dict in save_callback. How can I do this? I need some way to get the ID of the button or to link them to the dict. NOTE: I tried with self.c = Checkbutton(master,var=self.conf_dict[k])but it doesn't work.
tagged with: tk-toolkit
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47160811
tagged with: tkinter
has title: Getting the values of UI elements with Tkinter

http://stackoverflow.com/q/47174160
has title: Variable inside a method is not defined
has answer: http://stackoverflow.com/a/47174285
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47174263
has body: I'm trying to make a game with tkinter and for that I used classes to be the frames so I can change screens... My class Jogo is the game and I want to put a clock with a countdown in it. The code for the clock that I made just for test, without using classes works. However when I tried to put it on the game's code a problem appear NameError: name 'countVar' is not defined Here's the code that I want to fix: class Jogo(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.grid(row=0, column=0, sticky="nsew") countVar = tk.StringVar() self.after(1000, self.update_clock) clock = tk.Label(self, textvariable=countVar) clock.grid() def update_clock(self, event = None): for t in range(120, -1, -1): mins, secs = divmod(t,60) timeformat = "{:02d}:{:02d}".format(mins, secs) countVar.set(timeformat) clock.update_idletasks() sleep(1) And the code that I made without using classes: import tkinter from time import sleep main = tkinter.Tk() count = tkinter.StringVar() txt = tkinter.Label(main, textvariable=count) txt.grid() def update_txt(event = None): for t in range(120, -1, -1): mins, secs = divmod(t, 60) timeformat = '{:02d}:{:02d}'.format(mins, secs) count.set(timeformat) txt.update_idletasks() sleep(1) main.after(1000,update_txt) main.mainloop()
tagged with: python
score: -1
tagged with: tkinter
possible better answer: http://stackoverflow.com/a/47174263
type: AnsweredQuestion
upvote count: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/47174285

http://stackoverflow.com/q/47162413
accepted answer: http://stackoverflow.com/a/47162735
has answer: http://stackoverflow.com/a/47162735
has body: I'm trying to include an template and utilize it in two different views, where the first one gets one url param and the second gets the same plus another one. Inside my included template there is an iteration with a {% url %} tag that I need to pass both params, since the second view needs them, but doing this causes NoReverseMatch when trying to render my first view, probably because it only accepts one param. Is there any way to specifying the second param is optional? Here is my code: urls.py ... url(r'^portfolio/(?P&lt;category_slug&gt;[-\w]+)/$', views.category, name='category'), url(r'^portfolio/(?P&lt;category_slug&gt;[-\w]+)/(?P&lt;album_slug&gt;[-\w]+)/$', views.album, name='album'), ... models.py ... class Album(models.Model): cover = models.ImageField() title = models.CharField(max_length=200, unique=True) description = models.CharField(max_length=200, blank=True) posts = models.ManyToManyField(Post, blank=True) slug = models.SlugField(max_length=200) class Category(models.Model): cover = models.ImageField() title = models.CharField(max_length=200, unique=True) albums = models.ManyToManyField(Album, blank=True) slug = models.SlugField(max_length=200) @receiver(pre_save, sender=Album) @receiver(pre_save, sender=Category) def save_slug(sender, instance, *args, **kwargs): instance.slug = slugify(instance.title) ... views.py ... def index(request): main_categories = Category.objects.filter(...) return render(request, 'index.html', {'main_categories': main_categories}) def category(request, category_slug): try: category_selected = Category.objects.get(slug=category_slug) except Category.DoesNotExist: category_selected = None albums = category_selected.albums.all() return render(request, 'category.html', { 'category_selected': category_selected, 'albums': albums }) def album(request, category_slug, album_slug): try: category_selected = Category.objects.get(slug=category_slug) album_selected = Album.objects.get(slug=album_slug) except Category.DoesNotExist: cate…
type: Question
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: django-templates
has title: Django - multiple url params with included template
answer count: 1
tagged with: django-urls

django-admin
tags question: http://stackoverflow.com/q/47126208
tags question: http://stackoverflow.com/q/47113620
tags question: http://stackoverflow.com/q/47082765
tags question: http://stackoverflow.com/q/47162991
type: Tag
tag name: django-admin
tags question: http://stackoverflow.com/q/47126983
tags question: http://stackoverflow.com/q/47138660
tags question: http://stackoverflow.com/q/47163935
tags question: http://stackoverflow.com/q/47093195
tags question: http://stackoverflow.com/q/47105795

http://stackoverflow.com/comment/81399201
comment on: http://stackoverflow.com/a/47206856
type: Comment
has text: True, I didn't noticed that I need to convert the output to HEX to obtain the 0x10000000. Thanks
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81151156
comment on: http://stackoverflow.com/q/47100375
score: 2
has text: Result is correct. John is the oldest guy so he will come last. Maybe you should sort by grade first then age: `print sorted(student_objects, key=lambda student: (student.grade, student.age))`? So people with `A` will come first and the rest is sorted by their age.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81165435
type: Comment
type: QuestionComment
score: 0
has text: if you are using an API you have to use JWT to do that if that is what you mean
comment on: http://stackoverflow.com/q/47107549

http://stackoverflow.com/comment/81138193
type: Comment
type: QuestionComment
has text: Wait, why are you printing the p.communicate function?
comment on: http://stackoverflow.com/q/47094142
score: 0

http://stackoverflow.com/q/47203889
upvote count: 1
has title: Python : Get Largest number input from User
has comment: http://stackoverflow.com/comment/81356605
accepted answer: http://stackoverflow.com/a/47204169
has comment: http://stackoverflow.com/comment/81356324
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47204169
possible better answer: http://stackoverflow.com/a/47204008
score: 1
has answer: http://stackoverflow.com/a/47204008
tagged with: python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81356617
answer count: 2
has body: This is a issue with simple Max number identification which is input by User. When attempting to get the largest number passed as arguement in function-it works. But when dynamically i get 3 input numbers from User , the Output is not actually Larger number. Please correct. def maxof2nums(x,y): if (x&gt;y): return x return y a= input('Enter value for a=') b= input('Enter value for b=') c= input('Enter value for c=') def maxof3nums(a,b,c): return maxof2nums(a,maxof2nums(b,c)) print ("Maximum of 3 numbers=",maxof3nums(a,b,c))
downvote count: 0

multiplication
tags question: http://stackoverflow.com/q/47217135
tag name: multiplication
type: Tag

http://stackoverflow.com/comment/130839021
has text: I spent a lot of time on this issue, none of the proposed solutions worked for me. This was the one working in my case: https://stackoverflow.com/a/74104235/6713310
comment on: http://stackoverflow.com/a/47162390
type: Comment
score: 0
type: AnswerComment

loops
tags question: http://stackoverflow.com/q/47204256
tags question: http://stackoverflow.com/q/47087338
tags question: http://stackoverflow.com/q/47222004
tags question: http://stackoverflow.com/q/47119856
tags question: http://stackoverflow.com/q/47189414
tags question: http://stackoverflow.com/q/47144580
tags question: http://stackoverflow.com/q/47216177
tags question: http://stackoverflow.com/q/47134599
tags question: http://stackoverflow.com/q/47093829
tags question: http://stackoverflow.com/q/47202331
tags question: http://stackoverflow.com/q/47106855
tag name: loops
tags question: http://stackoverflow.com/q/47122770
tags question: http://stackoverflow.com/q/47142567
tags question: http://stackoverflow.com/q/47091703
tags question: http://stackoverflow.com/q/47129107
tags question: http://stackoverflow.com/q/47186264
tags question: http://stackoverflow.com/q/47213727
tags question: http://stackoverflow.com/q/47191296
tags question: http://stackoverflow.com/q/47180690
tags question: http://stackoverflow.com/q/47128671
tags question: http://stackoverflow.com/q/47113370
tags question: http://stackoverflow.com/q/47195973
tags question: http://stackoverflow.com/q/47117353
tags question: http://stackoverflow.com/q/47213852
tags question: http://stackoverflow.com/q/47218337
tags question: http://stackoverflow.com/q/47077854
tags question: http://stackoverflow.com/q/47084759
tags question: http://stackoverflow.com/q/47066552
tags question: http://stackoverflow.com/q/47162455
tags question: http://stackoverflow.com/q/47191492
tags question: http://stackoverflow.com/q/47128907
type: Tag
tags question: http://stackoverflow.com/q/47190488
tags question: http://stackoverflow.com/q/47207331
tags question: http://stackoverflow.com/q/47069054
tags question: http://stackoverflow.com/q/47075492
tags question: http://stackoverflow.com/q/47111701
tags question: http://stackoverflow.com/q/47124808
tags question: http://stackoverflow.com/q/47133105
tags question: http://stackoverflow.com/q/47187764
tags question: http://stackoverflow.com/q/47112874
tags question: http://stackoverflow.com/q/47086206
tags question: http://stackoverflow.com/q/47085958
tags question: http://stackoverflow.com/q/47110056
tags question: http://stackoverflow.com/q/47095695
tags question: http://stackoverflow.com/q/47143605
tags question: http://stackoverflow.com/q/47106956
tags question: http://stackoverflow.com/q/47130133
tags question: http://stackoverflow.com/q/47101865
tags question: http://stackoverflow.com/q/47215094
tags question: http://stackoverflow.com/q/47110352

http://stackoverflow.com/comment/108145148
comment on: http://stackoverflow.com/a/48069535
type: AnswerComment
has text: @Oscar, here is the link https://github.com/memsindustrygroup/Open-Source-Sensor-Fusion/tree/master/docs
score: 0
type: Comment

http://stackoverflow.com/a/57900471
answers question: http://stackoverflow.com/q/47207892
score: 0
has body: Please see if you have saved the file ex1.py properly.Check once. You may have saved the file name first and later typed in the notepad and forgot to save the file.
type: Answer

http://stackoverflow.com/comment/81139529
has text: Use pandas over openpyxl it is a lot easier and more documentation
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47094083

http://stackoverflow.com/q/47145175
tagged with: numpy
has comment: http://stackoverflow.com/comment/81240814
has comment: http://stackoverflow.com/comment/81240583
has comment: http://stackoverflow.com/comment/81241005
score: 0
has title: How to index items from higher dimensions in numpy?
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47145758
has body: I've done some search on this site but it seems there is no similar question (or my description is too bad to search). I'm facing a problem that I need to fetch some ndarray from a multi-dimensional ndarray in numpy. Suppose I have W = np.random.randn(2,2,3,8) which represents eight 2x2x3 filters in a convolutional layers in a CNN. I want to access the first filter, which is the first 2x2x3 in W. I tried print(W.shape) print(W[:,:,:,:c].shape) print(W[:,:,:,:c]) print(W[:,:,:,:c].flatten()) where c is in range 0 - 7. The result returned is always (2, 2, 3, 8) (2, 2, 3, 0) [] [] But I expect to see the 2x2x3 filter result from above indexing.. from the above 4 lines of code... Reproduction: W = np.random.randn(2,2,3,8) for c in range(0, 8): # print(W.shape) print(W[:,:,:,:c].shape) # print(W[:,:,:,:c]) # print(W[:,:,:,:c].flatten()) The result is: (2, 2, 3, 0) (2, 2, 3, 1) (2, 2, 3, 2) (2, 2, 3, 3) (2, 2, 3, 4) (2, 2, 3, 5) (2, 2, 3, 6) (2, 2, 3, 7) where I actually expect 8 (2, 2, 3). Please help!
type: Question
has comment: http://stackoverflow.com/comment/81241540
has comment: http://stackoverflow.com/comment/81240523
has comment: http://stackoverflow.com/comment/81240502
has comment: http://stackoverflow.com/comment/81240556
tagged with: python
has comment: http://stackoverflow.com/comment/81240611
has comment: http://stackoverflow.com/comment/81241110

http://stackoverflow.com/a/47218018
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47216564
has comment: http://stackoverflow.com/comment/81520875
has comment: http://stackoverflow.com/comment/81397287
has comment: http://stackoverflow.com/comment/81520857
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81398012
has comment: http://stackoverflow.com/comment/81445012
has comment: http://stackoverflow.com/comment/81397777
has comment: http://stackoverflow.com/comment/81445297
answers question: http://stackoverflow.com/q/47216564
has comment: http://stackoverflow.com/comment/81397759
score: 3
type: Answer
has body: For me working if output of apply is pandas DataFrame, so last if necessary convert to dask DataFrame: def f(x): trip = ((1,2,x) for x in range(3)) df = pd.DataFrame.from_records(trip) return df df1 = ddf.groupby('cars').apply(f, meta={'x': 'i8', 'y': 'i8', 'z': 'i8'}).compute() #only for remove MultiIndex df1 = df1.reset_index() print (df1) cars level_1 x y z 0 1 0 1 2 0 1 1 1 1 2 1 2 1 2 1 2 2 3 2 0 1 2 0 4 2 1 1 2 1 5 2 2 1 2 2 6 3 0 1 2 0 7 3 1 1 2 1 8 3 2 1 2 2 ddf1 = dd.from_pandas(df1,npartitions=1) print (ddf1) cars level_1 x y z npartitions=1 0 int64 int64 int64 int64 int64 8 ... ... ... ... ... Dask Name: from_pandas, 1 tasks EDIT: L = [] def f(x): trip = ((1,2,x) for x in range(3)) #append each L.append(da.from_array(np.array(list(trip)), chunks=(1,3))) ddf.groupby('cars').apply(f, meta={'x': 'i8', 'y': 'i8', 'z': 'i8'}).compute() dar = da.concatenate(L, axis=0) print (dar) dask.array&lt;concatenate, shape=(12, 3), dtype=int32, chunksize=(1, 3)&gt;
has comment: http://stackoverflow.com/comment/81396987
has comment: http://stackoverflow.com/comment/81445358
upvote count: 3

http://stackoverflow.com/comment/81160607
has text: How to stop when I need all the 0 stays together. I mean c is always the same, and the value of c is 0 for more than 30 times.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47104973
type: Comment

http://stackoverflow.com/q/47068353
has answer: http://stackoverflow.com/a/47068422
type: AnsweredQuestion
score: 0
answer count: 1
has title: Python send keystrokes to exe file
type: Question
has body: I need to send keystrokes to an exe using python. I can run the exe using python from subprocess as import subprocess subprocess.Popen('myfile.exe',stdout=subprocess.PIPE) but how can I keep the connection and keep sending keys. I don't want to read back from the exe just to send some keystrokes any suggestions
accepted answer: http://stackoverflow.com/a/47068422
tagged with: python

http://stackoverflow.com/a/47145751
score: 0
type: Answer
has body: You should try doing this: from netmiko import ConnectHandler r1 = {'ip': '10.1.1.1', 'device_type': 'juniper', 'username': 'test', 'password': 'test1'} r2 = {'ip': '10.1.1.2', 'device_type': 'juniper', 'username': 'test', 'password': 'test1'} If you say ConnectHandler class takes (*args, **kwargs) then your function should look like: def connect(*args, **cred): ssh_conn = ConnectHandler(*args, **cred) connect(**r1) *args are added optionally if sometime you'll want to add them. The thing is you are using **cred as kwargs signature but you don't pass keyword args to function, passing positional arguments instead.
has comment: http://stackoverflow.com/comment/81242372
answers question: http://stackoverflow.com/q/47145626

http://stackoverflow.com/a/47151552
has comment: http://stackoverflow.com/comment/81253168
has comment: http://stackoverflow.com/comment/81252946
type: Answer
has comment: http://stackoverflow.com/comment/81253063
score: 0
answers question: http://stackoverflow.com/q/47151375
has comment: http://stackoverflow.com/comment/81252944
has body: the easiest way that i found is as follows let the initial CSV file name be test.csv with open('test.csv','r') as f: with open('cleaned.csv','w') as ff: ff.write(f.readline()) ff.write(f.read().lower()) the above code will create a new csv with all lower case

http://stackoverflow.com/q/47159735
tagged with: dictionary
downvote count: 1
has body: I have a dictionary with three keys, but each key has multiple values. mydictionary = {'wave': [14.26661, 14.3583, 14.45, 14.54169, 14.63338, etc], 'flux': [2.092778, 1.188152, 2.130176, 3.201674, 2.043295, etc], 'unc': [0.7566527, 0.7157381, 0.7030209, 0.6992941, etc]} I would like to save the dictionary to a csv in the following format. wave, flux, unc 14.2666, 2.0927, 0.756 14.35, 1.18, 0.715 With each key being a column header with each value in it's own row. Final csv should have 3 columns and 116/117 rows. This is the closest I have gotten, but the csv is only writing the first column, and is skipping lines. with open(n + '_sp.csv', 'w') as f: w = csv.writer(f) w.writerow(['wavelength','flux', 'unc']) for key, values in mydictionary.items(): for value in values: w.writerow([value])
has comment: http://stackoverflow.com/comment/81269664
has answer: http://stackoverflow.com/a/47159829
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
has comment: http://stackoverflow.com/comment/81269068
has comment: http://stackoverflow.com/comment/81269046
favorite count: 0
type: Question
score: 0
type: UnansweredQuestion
has title: Converting Dictionary to CSV File - multiple values per key
upvote count: 1
tagged with: python

http://stackoverflow.com/q/47208473
has body: I am attempting to find the log slope of a ton of short series using sklearn.LinearRegression. The data is being pulled from rows of a pandas dataframe and looks like: bp01 1.12 bp02 1.12 bp03 1.08 bp04 0.99 bp05 1.08 bp06 1.19 bp07 1.17 bp08 1.05 bp09 0.8 bp10 0.96 bp11 0.97 bp12 1.12 bp13 0.91 bp14 0.96 bp15 1.05 bp16 0.93 bp17 0.97 bp18 0.92 bp19 0.89 bp20 0 Name: 42029, dtype: object However, when I attempt to use np.log10, on the series I get the following error: In[27]: test.apply(np.log10) Traceback (most recent call last): File "&lt;ipython-input-27-bccff3ed525b&gt;", line 1, in &lt;module&gt; test.apply(np.log10) File "C:\location", line 2348, in apply return f(self) AttributeError: 'numpy.float64' object has no attribute 'log10' I am not sure why this error is being raised, np.log10 should work with numpy.float64 from what I am seeing. Ideas?
upvote count: 11
favorite count: 0
accepted answer: http://stackoverflow.com/a/47208873
tagged with: numpy
has title: AttributeError: 'numpy.float64' object has no attribute 'log10'
has answer: http://stackoverflow.com/a/47208873
linked to: http://stackoverflow.com/q/46995041
has comment: http://stackoverflow.com/comment/81366370
answer count: 2
has comment: http://stackoverflow.com/comment/81366143
downvote count: 0
possible better answer: http://stackoverflow.com/a/56140465
tagged with: python
has comment: http://stackoverflow.com/comment/81366117
has answer: http://stackoverflow.com/a/56140465
has comment: http://stackoverflow.com/comment/81366300
score: 11
type: Question
tagged with: pandas
type: AnsweredQuestion

http://stackoverflow.com/q/47100903
tagged with: python
has title: Deleting every 3rd element of a tensor in tensorflow
accepted answer: http://stackoverflow.com/a/47253840
has body: I am looking for the analogous of np.delete in tensorflow - so I have batches of tensors - each batch has shape (batch_size, variable_length) and I want to get a tensor of shape (batch_size, 2 * variable_length / 3). As seen each batch has a different length which is stored and read from the tfrecord. I am a bit at a loss here on what API I should use for that. Related (for numpy): Python removing every nth element in array where the solution would simply be np.delete(x, slice(2, None, 3)) (after performing a reshape to cater for batch_size) As requested in the comments I post the code for parsing a single example proto - although I am interested in deleting the nth (3rd) element of a tensor as a standalone question. @classmethod def parse_single_example(cls, example_proto): instance = cls() features_dict = cls._get_features_dict(example_proto) instance.path_length = features_dict['path_length'] ... instance.coords = tf.decode_raw(features_dict['coords'], DATA_TYPE) # the tensor ... return instance.coords, ... @classmethod def _get_features_dict(cls, value): features_dict = tf.parse_single_example(value, features={'coords': tf.FixedLenFeature([], tf.string), ... 'path_length': tf.FixedLenFeature([], tf.int64)}) return features_dict
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81173422
has comment: http://stackoverflow.com/comment/81205839
downvote count: 0
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/21922314
favorite count: 0
has answer: http://stackoverflow.com/a/47253840
linked to: http://stackoverflow.com/q/38987
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/81170892
type: Question
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/47137142
has comment: http://stackoverflow.com/comment/81171254
has comment: http://stackoverflow.com/comment/81172549
has comment: http://stackoverflow.com/comment/81160499
has answer: http://stackoverflow.com/a/47137142

http://stackoverflow.com/comment/81226809
type: AnswerComment
has text: I'll keep the question unaccepted until someone writes it that way. Good day to you too!
type: Comment
comment on: http://stackoverflow.com/a/47118728
score: 0

http://stackoverflow.com/a/47148786
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47148553
has body: You can break up the logic of the overloading like this: a1 + (a2 + a3) separate instance You can implement this like so: class A: def __init__(self, val): self.val = val self.cummulative = [val] def flatten(self, val): if isinstance(val, int): yield val else: for i in val: for b in self.flatten(i): yield b def __add__(self, instance): self.cummulative.append(instance.cummulative) return A(self.cummulative) def __str__(self): return repr(list(self.flatten(self.cummulative))) a1 = A(40) a2 = A(50) a3 = A(60) val = a1+a2+a3 print(val) Output: [40, 50, 60]

http://stackoverflow.com/comment/81163431
comment on: http://stackoverflow.com/a/47106411
has text: This answer in its current conversational style would work best as a comment.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81475771
score: 0
has text: If you try the code of the question I have linked, you will see that the scrollbar does work. Just replace the labels by whatever widgets you want to.
type: Comment
comment on: http://stackoverflow.com/q/47152542
type: QuestionComment

http://stackoverflow.com/q/47106964
has comment: http://stackoverflow.com/comment/81164636
has answer: http://stackoverflow.com/a/47106983
has body: I wrote the following code: def bigger(a,b): if a&gt;b: return a else: return b print(bigger(1,3)) I saved the code as a file named bigger.py. Then I executed the file using the following code in the Python interpreter (Python 3.6): exec(open('e:\py\bigger.py').read()) Python returns the following error message: &gt;&gt;&gt; exec(open('e:\py\bigger.py').read()) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; OSError: [Errno 22] Invalid argument: 'e:Vipy\x08igger.py' As you can see, it says the file name is x08igger.py, while what I entered in the code is bigger.py. This is so weird!
type: Question
tagged with: python-3.x
has title: Getting unexpected OSError
tagged with: python
accepted answer: http://stackoverflow.com/a/47106983
has comment: http://stackoverflow.com/comment/81164540
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/comment/81373146
type: Comment
type: QuestionComment
has text: Yeah you are right. I got confused with having single quotes for %s. This works too.
comment on: http://stackoverflow.com/q/47210833
score: 0

http://stackoverflow.com/q/47189319
has answer: http://stackoverflow.com/a/47189514
type: UnansweredQuestion
has body: I'm trying to read in a text file and format it correctly in a numpy array. The Input.txt file contains: point_load, 3, -300 point_load, 6.5, 500 point_moment, 6.5, 3000 I want to produce this array: point_load = [3, -300, 65, 500] My code is: a = [] for line in open("Input.txt"): li=line.strip() if li.startswith("point_load") a.append(li.split(",")) #np.flatten(a) My code prints: [['point_load', ' 3', ' -300'], ['point_load', ' 6.5', ' 500']] Any help would be appreciated. Thank you.
has answer: http://stackoverflow.com/a/47189638
tagged with: python
has title: Fixing numpy array after reading in text file
answer count: 3
has answer: http://stackoverflow.com/a/47189443
score: 0
linked to: http://stackoverflow.com/q/509211
type: Question

http://stackoverflow.com/comment/120887003
has text: @Hack_Hut my server also hangs.. can you suggest some way to resolve this? I have asked a question regarding this: [Requests to localhost from within a view cause the server to stop responding](https://stackoverflow.com/questions/68401321/requests-to-localhost-from-within-a-view-cause-the-server-to-stop-responding)
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47159919
type: Comment

http://stackoverflow.com/a/47117608
has body: Yes, you can append only the first element of the tuple returned by the integration method: integrals.append(quad(integrand, 0 , i, args=(ps, rs))[0]) The error will not be included in your results
type: Answer
answers question: http://stackoverflow.com/q/47117525
score: 0

http://stackoverflow.com/q/47186425
answer count: 1
downvote count: 0
has title: How to cast a python function to std::function with pybind11
accepted answer: http://stackoverflow.com/a/47188943
tagged with: c++11
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/47188943
tagged with: pybind11
tagged with: python
tagged with: c++
type: AnsweredQuestion
upvote count: 3
has body: I have a c++ type Foo which contains a std::function&lt;void()&gt; funcs, which has been successfully bound to python. My aim is to define functions in python and add them to this type, then return an instance. In c++ I use pybind to get an instance of this type which works. However when I attempt to call one of the functions my program seg-faults. class Foo { void addFunc(std::function&lt;void()&gt; _func) { funcs.push_back(_func); } void call(int _index) { funcs[_index](); } private: std::vector&lt;std::function&lt;void()&gt;&gt; funcs; } namespace py = pybind11; PYBIND11_MODULE(foo, m) { py::class_&lt;Foo&gt;(m, "foo") .def(py::init&lt;int, int&gt;()) .def("addFunc", &amp;Foo::addFunc) .def("call", &amp;Foo::call); } And later in c++ py::scoped_interpreter python; auto module = py::module::import("foo_module"); auto func = module.attr("create_foo"); auto result = func(); //This works! result.attr("call")(0); Foo* blah = result.cast&lt;Foo*&gt;(); //This seg-faults! blah-&gt;call(0); My python module has this: def newFunc(): print "working!" def create_foo(): temp = foo.Foo(0, 100) temp.addFunc(newFunc) return temp I'm not sure why the functions aren't being cast back to c++ correctly?

http://stackoverflow.com/q/47160601
tagged with: cairo
tagged with: python
tagged with: pycairo
has answer: http://stackoverflow.com/a/47200028
has title: pyCairo Stack images
type: UnansweredQuestion
answer count: 1
type: Question
has body: I'm using pycairo to compose images. Currently I am creating my ImageSurface from a base image and setting a Context from this Surface. surface = cairo.ImageSurface.create_from_png("base.png") ctx = cairo.Context (surface) Then I can for example add text on top: # draw text ctx.select_font_face('Sans') ctx.set_font_size(20) ctx.move_to(10, 90) ctx.set_source_rgb(1.00, 0.83, 0.00) # yellow ctx.show_text('Hello World') And finally stroking and saving ctx.stroke() surface.write_to_png('hello_world.png') # write to file Apart from text, I also need to load other images and put then on top of my base image at specific locations. Should I create another surface from a new image and then stack the surfaces, or can I directly load the new image into the context at an specific location as I do with text?
score: 0

http://stackoverflow.com/q/47069829
tagged with: pymysql
downvote count: 0
upvote count: 1
tagged with: python
has body: This may be a repeated question of attempting to run a mysql query on a remote machine using python. Im using pymysql and SSHTunnelForwarder for this. The mysqldb is located on different server (192.168.10.13 and port 5555). Im trying to use the following snippet: with SSHTunnelForwarder( (host, ssh_port), ssh_username = ssh_user, ssh_password = ssh_pass, remote_bind_address=('127.0.0.1', 5555)) as server: with pymysql.connect("192.168.10.13", user, password, port=server.local_bind_port) as connection: cursor = connection.cursor() output = cursor.execute("select * from billing_cdr limit 1") print output Is this the correct approach ? I see the following error: sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway Also is there any other recommended library to use ?
tagged with: python-2.7
score: 1
has answer: http://stackoverflow.com/a/47070611
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47070793
answer count: 2
has title: MYSQL and Python (via ssh)
type: UnansweredQuestion

http://stackoverflow.com/comment/81234941
comment on: http://stackoverflow.com/q/47142327
type: QuestionComment
has text: You could indicate in the images where it is observed that "the space in between the horizontal layout and the QFrame line is still random"
type: Comment
score: 0

http://stackoverflow.com/comment/81387470
has text: Thanks but installing environment_kernels package has helped to achieve this.
comment on: http://stackoverflow.com/q/47191297
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47099385
has comment: http://stackoverflow.com/comment/81266165
has body: The content of the description element is HTML. There are various ways of parsing it, one of them being html from lxml. &gt;&gt;&gt; description.text '&lt;img src="https://www.example.com/image.jpg" alt="image" height="42" width="42"&gt;' &gt;&gt;&gt; from lxml import html &gt;&gt;&gt; img = html.fromstring(description.text) &gt;&gt;&gt; img.attrib['src'] 'https://www.example.com/image.jpg' Edit, in response to comment: &gt;&gt;&gt; from lxml import etree, html &gt;&gt;&gt; tree = etree.parse('temp.xml') &gt;&gt;&gt; for guide in tree.xpath('guide'): ... '---', guide.xpath('id')[0].text ... for pages in guide.xpath('.//pages'): ... for page in pages: ... '------', page.xpath('id')[0].text ... for description in page.xpath('.//asset/description'): ... '---------', html.fromstring(description.text).attrib['src'] ... ('---', 'guide 1') ('------', 'page 1') ('---------', 'https://www.example.com/image.jpg') Edit: Handling exception. Replace '---------', html.fromstring(description.text).attrib['src'] with try: '---------', html.fromstring(description.text).attrib['src'] except KeyError: '--------- No image URL present' Edit, responding to 9 Nov comment: from lxml import etree, html tree = etree.parse('guides.xml') for guide in tree.xpath('guide'): print('---', guide.xpath('id')[0].text) for pages in guide.xpath('.//pages'): for page in pages: print('------', page.xpath('id')[0].text) for description in page.xpath('.//asset/description'): try: print('---------', html.fromstring(description.text).attrib['src']) except TypeError: print('--------- no src identifiable') except KeyError: print('--------- no src identifiable') Output for xml file where 2nd guide element contains no HTML at all, and 3rd contains HTML without a src attribute. --- guide 1 ------ page 1 --------- https://www.example.com/image.jpg --- guide 2 ------ page 1 --------- no src identifiable --- guide 3 ------ page 1 --------- no src identifiable --- guide 4 ------ page 1 --------- https://www.example.co…
has comment: http://stackoverflow.com/comment/81321039
has comment: http://stackoverflow.com/comment/81228926
answers question: http://stackoverflow.com/q/47093335
has comment: http://stackoverflow.com/comment/81221871
has comment: http://stackoverflow.com/comment/81348265
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81524489
has comment: http://stackoverflow.com/comment/81275920
has comment: http://stackoverflow.com/comment/81274708
has comment: http://stackoverflow.com/comment/81302619
has comment: http://stackoverflow.com/comment/81530387
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47093335
has comment: http://stackoverflow.com/comment/81148775

http://stackoverflow.com/q/47071235
favorite count: 0
type: Question
tagged with: numpy
has title: Efficient way of checking if value within boundaries defined in 2d array
answer count: 2
has comment: http://stackoverflow.com/comment/81101961
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47071517
tagged with: arrays
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81101646
has answer: http://stackoverflow.com/a/47071607
score: 2
has body: I am trying to write a Python program that uses input data from an eye tracking device and checks if it is within a given range. The input is a normalized value and corresponds to the x position of gaze. The ranges are always sorted beforehand. I need to check if this position x is within boundaries in any pair of elements in a 2D array and run a function if that's the case. Something like: x = 0.23 # input variable boundaries = [[0.0, 0.025], [0.025, 0.1], [0.1, 0.14], [0.15, 0.25]] for i, pair in enumerate(boundaries): if x &gt;= pair[0] and x &lt;= pair[1]: print(i) # some function Now, the catch is that the input x is realtime data emitted at 60Hz and the boundaries can be sometimes long lists (1000 elements), so there will be hundreds of thousands of checks per second with this approach. What would be the most efficient way to do this calculation? I imagine that perhaps there's a good vectorised version of this in numpy but I'm rather bad at calculus. I have run a test to determine if the solution posted by @Meitham in the answers gives me a noticeable difference, I obtain however, using a Python approach: import numpy as np n = 10000 b1 = np.linspace(0.0, 1.0, n) boundaries = [[b1[i], b1[i] + 0.01] for i in range(n)] x = 0.23 final = [] for i, pair in enumerate(boundaries): if x &gt;= pair[0] and x &lt;= pair[1]: final.append(pair) 100000000 loops, best of 3: 0.0121 usec per loop And the numpy approach: import numpy as np n = 10000 b1 = np.linspace(0.0, 1.0, n) boundaries = [[b1[i], b1[i] + 0.01] for i in range(n)] x = 0.23 a = np.array(boundaries) final = a[(a[...,0] &lt; x) &amp; (a[...,1] &gt; x)] 100000000 loops, best of 3: 0.0122 usec per loop So I see no meaningful difference between this two approaches. Maybe I'm testing it in the wrong way?
has comment: http://stackoverflow.com/comment/81090928
has comment: http://stackoverflow.com/comment/81101492
has comment: http://stackoverflow.com/comment/81093153

http://stackoverflow.com/a/47129930
has comment: http://stackoverflow.com/comment/81210020
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/81209876
has comment: http://stackoverflow.com/comment/81209837
has comment: http://stackoverflow.com/comment/81209960
answers question: http://stackoverflow.com/q/47129866
upvote count: 0
has comment: http://stackoverflow.com/comment/81209780
has comment: http://stackoverflow.com/comment/81209933
has comment: http://stackoverflow.com/comment/81209940
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/81209765
accepted answer of: http://stackoverflow.com/q/47129866
has body: This should work fine: txt = "hello world" l = len(txt) for n in range(1, l//2+1): print txt[-n:][::-1] + txt[n:-n] + txt[:n][::-1] # reversed end + middle + reversed start you can also use this (but I find it less readable): print txt[l-1:-n-1:-1] + txt[n:-n] + txt[n-1:None:-1]

http://stackoverflow.com/a/47188275
has comment: http://stackoverflow.com/comment/81326815
answers question: http://stackoverflow.com/q/47187764
downvote count: 0
upvote count: 1
has body: This is how I would write your program, using collections.Counter and the new-fangled f-strings: from collections import Counter word = input("What is your word? ") letter_counts = Counter(word.lower()) sorted_letter_counts = sorted(letter_counts.items()) for letter, count in sorted_letter_counts: print(f"'{letter}' = {count}")
has comment: http://stackoverflow.com/comment/81326061
has comment: http://stackoverflow.com/comment/81326730
score: 1
has comment: http://stackoverflow.com/comment/81326974
type: Answer

http://stackoverflow.com/q/47173762
score: 2
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
has body: I want to use RSA in my python web, and I used the pycrypto. But I have some questions in it. this is my code: from Crypto import Random from Crypto.Cipher import PKCS1_v1_5 from Crypto.PublicKey import RSA import base64 random_generator = Random.new().read def decrypt_rsa(secret): with open('/home/ubuntu/project/all/all_test/all_python/util/private_rsa.pem') as file: private_key = RSA.importKey(file.read()) cipher = PKCS1_v1_5.new(private_key) text = cipher.decrypt(base64.b64decode(secret), random_generator) print(str(text)) return text.decode('utf-8') But when I run a application, I break down with an error like: Traceback (most recent call last): File "/home/ubuntu/project/all/venv/lib/python3.5/site-packages/flask/app.py", line1982, in wsgi_app response = self.full_dispatch_request() File "/home/ubuntu/project/all/venv/lib/python3.5/site-packages/flask/app.py", line1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/ubuntu/project/all/venv/lib/python3.5/site-packages/flask/app.py", line1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/ubuntu/project/all/venv/lib/python3.5/sitepackages/flask/app.py", line1612, in full_dispatch_request rv = self.dispatch_request() File "/home/ubuntu/project/all/venv/lib/python3.5/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/ubuntu/project/all/all_test/all_python/v3/v3_main.py", line 192, in v3_set_article_love if check_secret(secret): File "/home/ubuntu/project/all/all_test/all_python/v3/v3_main.py", line 18, in check_secret t = int(secret_util.decrypt_rsa(secret)) File "/home/ubuntu/project/all/all_test/all_python/util/secret_util.py", line14, in decrypt_rsa return text.decode('utf-8') AttributeError: 'function' object has no attribute 'decode' my server os is ubuntu 16.04, with python3.*, and the secret is encode by base64, just like FRw3kfdpHKD4Ms2O3hmaEoD4Gqp5onwF/OUkkp5zSVDsYnJ9Bej8f6kRewoZ…
has title: PyCrypto: function returned by the decrypt() method
tagged with: pkcs#1
tagged with: python
tagged with: pycrypto
has answer: http://stackoverflow.com/a/50188324
favorite count: 0
type: Question

http://stackoverflow.com/comment/81171650
comment on: http://stackoverflow.com/q/47110317
type: QuestionComment
has text: I mean - do you run the program in Linux terminal, Windows cmd or some IDE?
type: Comment
score: 0

http://stackoverflow.com/comment/81132056
type: AnswerComment
score: 0
has text: @Mersper In the version of PyQt that I have the conversion is not necessary (to me it works correctly), but of all my idea is correct, please if my answer will help you the usual is mark it as correct.
type: Comment
comment on: http://stackoverflow.com/a/47087838

http://stackoverflow.com/q/47184177
has comment: http://stackoverflow.com/comment/81317592
has comment: http://stackoverflow.com/comment/81317869
has comment: http://stackoverflow.com/comment/81317755
downvote count: 0
tagged with: python
has body: I have a text file with the names parsed with commas that looks like this: Ann Marie,Smith,ams@companyname.com The list could have over 100+ names in it. I left out the code that generates all the other GUI components to focus on loading the combobox and the items. Problem: How do I implement asyncio to read the text file without blocking the main thread to load the other GUI components. This is the best I could come up with: import wx import asyncio class Mywin(wx.Frame): def __init__(self, parent, title): super(Mywin, self).__init__(parent, title=title, size=(300, 200)) self.panel = wx.Panel(self) box = wx.BoxSizer(wx.VERTICAL) self.eventloop() box.Add(self.combo, 1, wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 5) box.AddStretchSpacer() self.panel.SetSizer(box) self.Centre() self.Show() #code to display and position GUI components left out async def readlist(self): filename = 'employees.txt' empList = [] with open(filename) as f_obj: for line in f_obj: empList.append(line) return empList async def managecombobox(self, loop): task = loop.create_task(self.readlist()) return_value = await task self.combo = wx.ComboBox(self.panel, choices=return_value) def eventloop(self): event_loop = asyncio.get_event_loop() try: event_loop.run_until_complete(self.managecombobox(event_loop)) finally: event_loop.close() def OnCombo(self, event): self.label.SetLabel("You selected" + self.combo.GetValue() + " from Combobox") app = wx.App() Mywin(None, 'ComboBox Demo') app.MainLoop()
has comment: http://stackoverflow.com/comment/81317973
accepted answer: http://stackoverflow.com/a/47191190
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81317713
score: 3
has comment: http://stackoverflow.com/comment/81317989
has comment: http://stackoverflow.com/comment/81318035
tagged with: python-asyncio
has answer: http://stackoverflow.com/a/47191190
upvote count: 3
has title: How do I use Asyncio and GUI to read a file.
answer count: 1
has comment: http://stackoverflow.com/comment/81317655
linked to: http://stackoverflow.com/q/54282226
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81317626
has comment: http://stackoverflow.com/comment/81318005
has comment: http://stackoverflow.com/comment/81317819

http://stackoverflow.com/a/47122827
has body: Use numpy.concatenate to join the arrays: import numpy as np a = np.array([[1, 2, 3, 4]]) b = np.array([[5, 6, 7, 8]]) arr = np.concatenate((a, b), axis=0) print(arr) # [[1 2 3 4] # [5 6 7 8]] Edit1: To do it inside the array (as mentioned in the comment) you can use numpy.vstack: import numpy as np for i in range(0, 3): a = np.random.randint(0, 10, size=4) if i == 0: arr = a else: arr = np.vstack((arr, a)) print(arr) # [[1 1 8 7] # [2 4 9 1] # [8 4 7 5]] Edit2: Citing Iguananaut from the comments: That said, using concatenate repeatedly can be costly. If you know the size of the output in advance it's better to pre-allocate an array and fill it as you go.
has comment: http://stackoverflow.com/comment/81196828
answers question: http://stackoverflow.com/q/47122770
has comment: http://stackoverflow.com/comment/81195501
type: Answer
has comment: http://stackoverflow.com/comment/81196671
score: 2
has comment: http://stackoverflow.com/comment/81195537
upvote count: 3
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/81196220
has comment: http://stackoverflow.com/comment/81195788
accepted answer of: http://stackoverflow.com/q/47122770

http://stackoverflow.com/comment/81323438
type: Comment
type: AnswerComment
has text: here it's line numbers. It's in principle not a problem to find the index with the line number.
comment on: http://stackoverflow.com/a/47186961
score: 0

http://stackoverflow.com/a/63949891
answers question: http://stackoverflow.com/q/47125961
has body: This script takes all the PDF files and converts the first page to png. In the current execution directory #pip install pdf2image import os import tempfile from pdf2image import convert_from_path output_folder=os.getcwd() #current work directory def pdf_to_png(pdf_name,source,destino): with tempfile.TemporaryDirectory() as path: images_from_path = convert_from_path(pdf_path=source+"/"+pdf_name, dpi=100, output_folder=destino, fmt="png", output_file=pdf_name[:-4], single_file=True) for filename in os.listdir(output_folder): if filename.endswith(".pdf"): pdf_to_png(filename,output_folder,output_folder) print("ok!")
downvote count: 1
type: Answer
score: -1
upvote count: 0

http://stackoverflow.com/comment/81295203
has text: there you go, the nested output. Cheers!
type: Comment
comment on: http://stackoverflow.com/a/47172990
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81373745
comment on: http://stackoverflow.com/a/47211933
score: 0
type: Comment
type: AnswerComment
has text: When I try to do that I get TypeError: can't pickle CompiledFFI objects

http://stackoverflow.com/q/47150229
upvote count: 1
linked to: http://stackoverflow.com/q/54867
favorite count: 0
score: 1
tagged with: python
has title: How do I pass a reference from one property to another in a Python class?
type: Question
has answer: http://stackoverflow.com/a/47151808
has comment: http://stackoverflow.com/comment/81250495
has comment: http://stackoverflow.com/comment/81250347
has body: I have a class that has instances of other classes as its properties: from ctypes import * class C(): A = propA() B = propB() def __init__(self): class c_struct(Structure): _fields_ = [('_A', c_int), ('_B', c_int)] self._c_struct = c_struct() I need to somehow "connect" the propA and propB classes to the internal structure _c_struct created in C to eventually get the behavior like so: c = C() c.A.val = 12 c.B.val = 13 c._c_struct._A == c.A.val == 12 Where C.A is able to manipulate C._c_struct._A. I've attempted to do something like this: from ctypes import * class propParent(): def set_ref(self, ext_ref): self._val = ext_ref @property def val(self): return self._val @val.setter def val(self, val): self._val = val class propA(propParent): # Further definitions here pass class propB(propParent): # Further definitions here pass class C(): A = propA() B = propB() def __init__(self): class c_struct(Structure): _fields_ = [('_A', c_int), ('_B', c_int)] self._c_struct = c_struct() self.A.set_ref(self._c_struct._A) self.B.set_ref(self._c_struct._B) But it appears that self._c_struct._A returns a Python integer object and not the reference to the _A internal c_int object of the structure. How do I connect a property to a sub property of another property in the same class?
type: UnansweredQuestion
downvote count: 0
answer count: 1

http://stackoverflow.com/a/47145843
has body: re.findall might be a solution if you want to use regular expressions instead of splitting. findall returns a list of all occurrences of a pattern. re.findall(r":(?:(\w+)(?=:))", r"theSTART:param1:param2:paramN:theEND") returns the list ['param1', 'param2', 'paramN']. You probably won't (or can't) find a pattern to match any number of parameters. According to the Python re module documentation is only the last match accessible, if a group matches multiple times.
accepted answer of: http://stackoverflow.com/q/47128060
answers question: http://stackoverflow.com/q/47128060
type: AcceptedAnswer
type: Answer
score: 0

http://stackoverflow.com/comment/81107986
comment on: http://stackoverflow.com/a/47070431
type: Comment
type: AnswerComment
has text: Ok, I think I need to stick with MySQL, unitl I figured out how to deal with it. The problem is need to automated the test. If I terminate the backend, then the django development server will fail.
score: 0

alert
tags question: http://stackoverflow.com/q/47074558
tag name: alert
type: Tag

http://stackoverflow.com/q/47166419
has comment: http://stackoverflow.com/comment/86534090
type: Question
has body: Inspired by sentdex's tutorial I wanted to try another game. In the tutorial, Harrison takes key presses and one-hot encodes them (code here), then trains a Neural Net with X being the image/pixel data and Y being the desired key press. Capturing clicks and their locations is easy, but how can I convert the data to something that I can feed to the NN? Sample click data format, tuple: (100, 300, "left_click", True) (x, y, mouse button, press click=True / unpress click=False)
has comment: http://stackoverflow.com/comment/87557367
has title: Encoding clicks and keyboard presses in mutual format to feed the to a Neural Net
type: UnansweredQuestion
tagged with: neural-network
tagged with: python
has comment: http://stackoverflow.com/comment/87557209
score: 0
answer count: 0

http://stackoverflow.com/q/47179707
favorite count: 0
has body: I know there is a UDP stream being sent from an ip xxx.xxx.xxx.xxx on port xxxx, how do I receive that data in python.
type: Question
tagged with: network-programming
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
has title: How to receive data through udp (in python) known the source IP address and port?
tagged with: udp
has answer: http://stackoverflow.com/a/47179813
answer count: 1
downvote count: 1

http://stackoverflow.com/a/47148118
has comment: http://stackoverflow.com/comment/81254542
has body: Best solution: Use python3. Fixing the problem: At the top of your code add this line # -*- coding: utf-8 -*-
answers question: http://stackoverflow.com/q/47147087
type: Answer
score: 0

http://stackoverflow.com/q/47080410
accepted answer: http://stackoverflow.com/a/47080806
type: Question
upvote count: 2
tagged with: numpy
has title: 3 Dimensional Combination of One-hot Vectors
tagged with: one-hot-encoding
has body: I need to create a 3-dimensional list of all pairs of 3x1 one-hot vectors in python, but I'm having trouble generating the array. I'm trying to do it using np.arange, but I haven't quite been able to get that working. For example, my one-hot vectors are: A=[1,0,0] B=[0,1,0] and C=[0,0,1]. The output I need is the three dimensional array [[A,A],[A,B],[A,C],[B,A],[B,B],[B,C],[C,A],[C,B],[C,C]] That is, a 9x2x3 array consisting of all combinations of pairs of one-hot vectors.
possible better answer: http://stackoverflow.com/a/47080713
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/47080806
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/47080809
has answer: http://stackoverflow.com/a/47080744
has answer: http://stackoverflow.com/a/47080713
answer count: 4

http://stackoverflow.com/comment/81080231
score: 0
comment on: http://stackoverflow.com/q/47065693
type: Comment
type: QuestionComment
has text: Also see [Other languages have variables, Python has names](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables)

http://stackoverflow.com/a/47106512
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47106105
has body: df.N=df.N.replace({0:np.nan}) df.N=df.N.ffill() df.N=(df.groupby('Name').cumcount()*2).replace({0:1})*df.N df Out[363]: Name Range N 0 Name1 0.11 0.9 1 Name1 0.20 1.8 2 Name1 0.30 3.6 3 Name2 0.40 0.3 4 Name2 0.50 0.6 5 Name3 0.60 0.5 5 Name3 0.70 1.0 6 Name3 0.80 2.0
type: Answer
has comment: http://stackoverflow.com/comment/81166355

http://stackoverflow.com/comment/81188796
type: Comment
type: AnswerComment
has text: You need use other delimeter for next after 8th element like ";" "Hello,World, 100005940,wordlh1,98,99,97,86;0001;0002;0003" After you need to resplit return for ";" delimiter and you got all yours 0001, 0002, etc datas
comment on: http://stackoverflow.com/a/47118112
score: 0

http://stackoverflow.com/a/47172020
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47171900
has comment: http://stackoverflow.com/comment/81294257
upvote count: 2
has comment: http://stackoverflow.com/comment/81294253
type: Answer
has body: Bear with me but I'm going to cite a bit here (emphasis mine): dir([object]) Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object. (Python 3.6.3 Documentation source) The above notation for the Python documentation implies that the parameter, object, is optional and supplying it affects the behavior of the method (as described in dir()'s description). As for your example of complex([real[, imag]]), the syntax indicates that it is valid for you to supply none, only real, or both of the arguments. The behaviors of the method under those circumstances are also listed in the method's description (emphasis also mine): ...If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like int and float. If both arguments are omitted, returns 0j. (PyDocs source) However, be careful as this is not the same as complex([real, imag]). complex([real, imag]) only implies that you can supply either none or both of the arguments, not any single one of them. Hope this helped!
accepted answer of: http://stackoverflow.com/q/47171900
score: 2

http://stackoverflow.com/q/47112666
has answer: http://stackoverflow.com/a/47112696
answer count: 2
tagged with: pandas
has body: How to get this effect? Input data: val1 val2 val3 val4 0 A1.1 A2.1 A3.1 A4.1 1 A1.2 A2.2 A3.2 A4.2 2 A1.3 A2.3 A3.3 A4.3 And output data: new_column A1.1 A1.2 A1.3 0 val2 A2.1 A2.2 A2.3 1 val3 A3.1 A3.2 A3.3 2 val4 A4.1 A4.2 A4.3 Where A1.1, A1.2, A1.3 are the columns name. I tried pivot, unpivot, unstack, but I can't get the intended effect.
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/81175663
has title: New column created with column headers
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81175191
tagged with: python
score: -1
possible better answer: http://stackoverflow.com/a/47112698
accepted answer: http://stackoverflow.com/a/47112696
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47112698

http://stackoverflow.com/a/47083805
score: 2
downvote count: 0
has body: This works like a charm: dict1 = {"a": 6, "z": 4, "g": 1, "hh": 50, "ggg": 1} dict2 = {"a": 3, "g": 5, "d": 2, "hh": 50} for key in dict1: if key not in dict2 or dict1[key] &gt; dict2[key]: dict2[key] = dict1[key] print (dict1) print (dict2) dict3 = {**dict1, **dict2} print (dict3) Now I can compare dict3 with other dicts and so on.
answers question: http://stackoverflow.com/q/47082410
upvote count: 2
type: Answer

http://stackoverflow.com/q/47101572
accepted answer: http://stackoverflow.com/a/47101774
has comment: http://stackoverflow.com/comment/81153206
has title: Input multiple string values and convert 1 to float
has body: In the following code: a, b, c = input("A, B, C: ").split() float(a) print(a) a should be a float, b is a string and c is an integer. Now if I try to convert a from a string to a float number, e.g. 0.9, I get this message: ValueError: could not convert string to float: '0.9,' What am I doing wrong? Or am I missing something?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47101774
has answer: http://stackoverflow.com/a/47101718
possible better answer: http://stackoverflow.com/a/47101718
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81153601
tagged with: type-conversion
upvote count: 2
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/47101760
downvote count: 3

http://stackoverflow.com/comment/81201625
has text: M % 100 gives a number between 0 and 99. alphabet has only 72 characters.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47125655
type: QuestionComment

http://stackoverflow.com/a/47216593
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: you can do something like this from subprocess import Popen outputPath ='C:\...\folder1\folder2' inputpath = 'D:\...\folder1\folder2' command='ruunable.exe' + outputPath + inputpath proc=Popen(command)
accepted answer of: http://stackoverflow.com/q/47205292
answers question: http://stackoverflow.com/q/47205292
type: Answer
score: 1

http://stackoverflow.com/q/47141287
upvote count: 1
type: UnansweredQuestion
has body: Does anyone with a lot of experience know the fastest package for solving linear programs in Python? Or can point me in the right direction? I have built some code that takes in hourly records for market prices from a number of different source and chooses which market to participate in given a big list (10-20) of constraints based on timing and combination.
favorite count: 0
score: 0
downvote count: 1
tagged with: python
tagged with: linear-programming
tagged with: glpk
has comment: http://stackoverflow.com/comment/81235418
has comment: http://stackoverflow.com/comment/81233636
type: Question
answer count: 0
has title: Fastest Python GLPK linear program solver

http://stackoverflow.com/comment/81422946
has text: No - I don't mean the include path for gcc. I mean the module search path at runtime https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47216437
score: 0

http://stackoverflow.com/comment/81433531
has text: TypeError: 'str' object does not support item assignment
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47216961
score: 0

logistic-regression
tags question: http://stackoverflow.com/q/47185586
tags question: http://stackoverflow.com/q/47204919
tag name: logistic-regression
tags question: http://stackoverflow.com/q/47121953
tags question: http://stackoverflow.com/q/47140803
type: Tag

http://stackoverflow.com/a/47106544
has body: Assuming you are happy to replace the value 'na' with None, or more generally, any non-float looking text with None, then you could do something like: def converter(x): try: return float(x) except ValueError: return None alist = [converter(x) for x in alist] This will convert anything to float that it can. So, as it stands, this will also convert existing numbers to float: &gt;&gt;&gt; [converter(x) for x in ('1.1', 2, 'na')] [1.1, 2.0, None]
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47106490
score: 1
accepted answer of: http://stackoverflow.com/q/47106490
type: Answer

input
tags question: http://stackoverflow.com/q/47208285
tags question: http://stackoverflow.com/q/47129866
tags question: http://stackoverflow.com/q/47169556
tags question: http://stackoverflow.com/q/47191225
tag name: input
tags question: http://stackoverflow.com/q/47187615
type: Tag
tags question: http://stackoverflow.com/q/47192096
tags question: http://stackoverflow.com/q/47179167
tags question: http://stackoverflow.com/q/47114862

http://stackoverflow.com/q/47126987
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81204913
answer count: 2
has comment: http://stackoverflow.com/comment/81204301
has comment: http://stackoverflow.com/comment/81204335
accepted answer: http://stackoverflow.com/a/47132180
downvote count: 0
tagged with: python
tagged with: optimization
type: AnsweredQuestion
has body: the problem is to find total number of sub-lists from a given list that doesn't contain numbers greater than a specified upper bound number say right and sub lists max number should be greater than a lower bound say left .Suppose my list is: x=[2, 0, 11, 3, 0] and upper bound for sub-list elements is 10 and lower bound is 1 then my sub-lists can be [[2],[2,0],[3],[3,0]] as sub lists are always continuous .My script runs well and produces correct output but needs some optimization def query(sliced,left,right): end_index=0 count=0 leng=len(sliced) for i in range(leng): stack=[] end_index=i while(end_index&lt;leng and sliced[end_index]&lt;=right): stack.append(sliced[end_index]) if max(stack)&gt;=left: count+=1 end_index+=1 print (count) origin=[2,0,11,3,0] left=1 right=10 query(origin,left,right) output:4 for a list say x=[2,0,0,1,11,14,3,5] valid sub-lists can be [[2],[2,0],[2,0,0],[2,0,0,1],[0,0,1],[0,1],[1],[3],[5],[3,5]] total being 10
has comment: http://stackoverflow.com/comment/81204890
has comment: http://stackoverflow.com/comment/81204415
tagged with: algorithm
upvote count: 3
score: 3
has title: Optimization of list's sublist
possible better answer: http://stackoverflow.com/a/47127454
has comment: http://stackoverflow.com/comment/81204480
has answer: http://stackoverflow.com/a/47132180
has comment: http://stackoverflow.com/comment/81204229
has comment: http://stackoverflow.com/comment/81204518
has answer: http://stackoverflow.com/a/47127454
has comment: http://stackoverflow.com/comment/81204629
has comment: http://stackoverflow.com/comment/81204439
has comment: http://stackoverflow.com/comment/81205112
has comment: http://stackoverflow.com/comment/81204459

http://stackoverflow.com/comment/81351226
type: QuestionComment
has text: Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken)
score: 3
comment on: http://stackoverflow.com/q/47200953
type: Comment

sql-server
tags question: http://stackoverflow.com/q/47212289
tags question: http://stackoverflow.com/q/47077649
type: Tag
tags question: http://stackoverflow.com/q/47076992
tags question: http://stackoverflow.com/q/47159033
tags question: http://stackoverflow.com/q/47196391
tags question: http://stackoverflow.com/q/47142549
tag name: sql-server
tags question: http://stackoverflow.com/q/47188976

http://stackoverflow.com/q/47108125
type: Question
has answer: http://stackoverflow.com/a/47108361
has title: Forbidden access 403 for some url using urllib2 python
tagged with: python
type: UnansweredQuestion
tagged with: urllib2
has body: I am trying to download the data from NSE India website. Data to be download is the zip file which I process after it downloaded. I have sample code which downloads the files for dates after year 2016. def start_download(): directory = 'data' hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) ' 'Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive'} try: #req = urllib2.Request("https://www.nseindia.com/content/historical/EQUITIES//2000/JAN/cm01JAN2000bhav.csv.zip", headers=hdr) import ipdb;ipdb.set_trace() req = urllib2.Request("https://www.nseindia.com/content/historical/EQUITIES//2017/NOV/cm03NOV2017bhav.csv.zip", headers=hdr) file_url = urllib2.urlopen(req) try: if not os.path.exists(directory): os.makedirs(directory) file_name_obj = open(os.path.join(directory, "hello.zip"), 'wb') file_name_obj.write(file_url.read()) file_name_obj.close() except IOError, e: print e except Exception, e: print e In the above code, when I use the url "https://www.nseindia.com/content/historical/EQUITIES//2017/NOV/cm03NOV2017bhav.csv.zip",it downloads the data. I also tried using Postman client, it downloads too. When I use following url:https://www.nseindia.com/content/historical/EQUITIES//2000/JAN/cm01JAN2000bhav.csv.zip, I get forbidden access 403 error in code as well as in Postman. When I paste this link in the chrome browser, then also issue exists. But when go through link from this page "https://www.nseindia.com/products/content/equities/equities/archieve_eq.htm" and put Report as Bhavcopy and date as January 01, 2000, it successfully downloads the file *.csv.zip. How do I fix this 403 forbidden error for commented url in sample code?
tagged with: cookies
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/81175415
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47112714
has text: That answer hasn't been updated in a year, `set_value` is depreciated as stated in the answer, `ix` is also depreciated. The pandas doc say that `.at` is similar to `.loc`

http://stackoverflow.com/comment/81220668
comment on: http://stackoverflow.com/a/47135665
has text: Great, thanks! :-) I'm gonna upvote you as soon as I'm allowed!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47145314
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47145341
tagged with: list
has title: How do i extract a specific string in a list
downvote count: 2
has body: I need to extract a the first string in my list alone then I need to extract the second string in my list in another variable. username_password = ["wil15","password"] i have tried: username = username_password[0]
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81240845

http://stackoverflow.com/q/47146190
has comment: http://stackoverflow.com/comment/81243236
tagged with: unicode
duplicate of: http://stackoverflow.com/q/33001373
type: Question
has comment: http://stackoverflow.com/comment/81243074
score: 0
tagged with: python
has title: how to np.genfromtxt a utf-8 file? python3 numpy
tagged with: numpy
linked to: http://stackoverflow.com/q/33001373
answer count: 0
tagged with: genfromtxt
type: UnansweredQuestion
has body: I have a txt file with these characters: á é í ó ú ñ and I want to make it a numpy array with np.genfromtxt and when doing it, it displays this error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 34: ordinal not in range(128) If I open the file manually with a text editor and search and replace these characters á é í ó ú ñ with this ones a e i o u n, It works perfectly. But, I cannot mess with the data, the array has to be exact with the correct characters. Any ideas will help thanks. mydata = np.genfromtxt("data.txt",delimiter=[4,2,2,2,2,2,2,2,2,236],dtype=[np.int16,np.int8,np.int8,np.int8,np.int8,np.int8,np.int8,np.int8,np.int8,(np.str_,236)],names=["a","b","c","d","e","f","g","h","i","j"]) It seems np.genfromtxt uses 'ascii' but I need it to use utf-8 for it to be compatible with the tilde symbols.
tagged with: arrays

http://stackoverflow.com/comment/81131084
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47090958
has text: timedelta(0) would mean 0 days, 0 seconds, so you would want 00:00
type: Comment

http://stackoverflow.com/q/47191535
tagged with: python
has answer: http://stackoverflow.com/a/47193586
type: AnsweredQuestion
score: 0
tagged with: selenium
has answer: http://stackoverflow.com/a/47195398
type: Question
has title: Can't access some content on page using selenium and python
has body: I am using selenium in a python script to login into a website where I can get an authorization key to access their API. I am able to login and navigate to the page where the authorization key is provided, I am using chrome driver for testing so I can see what's going on. When I get to the final page where the key is displayed, I can't find a way to access it. I can't see it in the page source, and when I try to access via the page element outer html, it doesn't print the value shown on the page. Here is a screenshot of what I see in the browser (I'm interested in accessing the content shown in response body): this is the code snippet I am using to try to access the content: auth_key = WebDriverWait(sel_browser, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="responseBodyContent"]'))) print auth_key.get_attribute("outerHTML") and this is what the print statement returns: &lt;pre id="responseBodyContent"&gt;&lt;/pre&gt; I've also tried: print auth_key.text which returns nothing. Is there way I can extract this key from the page?
answer count: 2
accepted answer: http://stackoverflow.com/a/47195398
possible better answer: http://stackoverflow.com/a/47193586

http://stackoverflow.com/comment/81180426
has text: Why would you call `str()` when the result is already a `str`?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47115281

http://stackoverflow.com/comment/81375908
score: 0
has text: I have done the code I have it generating the list i just cant figure out how to add it together
type: Comment
comment on: http://stackoverflow.com/q/47213130
type: QuestionComment

http://stackoverflow.com/q/47086380
tagged with: scikit-image
tagged with: python
has comment: http://stackoverflow.com/comment/81126548
has comment: http://stackoverflow.com/comment/81122615
score: 4
has comment: http://stackoverflow.com/comment/81126512
tagged with: image
upvote count: 4
tagged with: imagemagick
has title: fastest Python native way to manipulate images?
has comment: http://stackoverflow.com/comment/81173587
has answer: http://stackoverflow.com/a/47088695
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81126357
has body: I'm creating a process that iterates over an image and does x/y transformations and zooms. The original images are very large. My current process involves making a bash script (using python) to creates rows and rows with the all-famous Imagemagick Convert. The major upside of using convert is the fact that you can load the image into memory once, then write out each frame. However, this bash script workflow is not sustainable, and I need something more native. So this begs the question: What is the FASTEST python processing library for image manipulations? Considering how larger the images can be, speed is the goal. Here is where my research (and some tinkering) has led me: Wand (Imagemagick wrapper) - Theoretically, Wand would be great! But I have found no mention of being able to read the image from memory, which makes it VERY slow. Skimage - I'd love to use Skimage for the depth of the operations (though overkill for my needs), but I've found the API/Documentation very difficult to work with. However, the fact that you can load an image into a numpy array and get breakneck speeds (for Python, anyways), seems like a compelling argument. PIL - Pil can be very tricky to install, which has caused a lot of trouble on a few systems I'm trying to deploy. The API, though, it's pretty darn easy. I've heard generally to stay away from PIL due to it's ongoing development woes. Pillow - Similar to above, I've had some trouble getting Pillow working. I think I read that Pillow can conflict with PIL... maybe that's the problem? I would love some input.
favorite count: 0
has comment: http://stackoverflow.com/comment/81122583
type: Question
has comment: http://stackoverflow.com/comment/81126758
tagged with: python-imaging-library
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81122458

http://stackoverflow.com/comment/81283169
has text: Are you sure that the number of 1's and 2's is changing, and not just their positions? The order of the keys may not be deterministic, but you are correct in that it shouldn't matter for the counts themselves.
score: 0
comment on: http://stackoverflow.com/q/47166428
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47090524
downvote count: 0
has comment: http://stackoverflow.com/comment/81220887
answers question: http://stackoverflow.com/q/47089700
type: Answer
has comment: http://stackoverflow.com/comment/81227878
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47089700
score: 2
has body: you have almost done. But there is a small mistake in if condition. Your required condition should be like below: if (chk == 'y' and sw1 == '1'): That means you should keep 1 in single quotes '1' because it's a string

http://stackoverflow.com/a/47202962
has comment: http://stackoverflow.com/comment/81356025
has comment: http://stackoverflow.com/comment/81356165
has comment: http://stackoverflow.com/comment/81355242
accepted answer of: http://stackoverflow.com/q/47201578
type: Answer
has comment: http://stackoverflow.com/comment/81355044
has comment: http://stackoverflow.com/comment/81354986
has comment: http://stackoverflow.com/comment/81355308
has comment: http://stackoverflow.com/comment/81358093
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/81356136
has comment: http://stackoverflow.com/comment/81355935
has comment: http://stackoverflow.com/comment/81358176
has body: First filter only english rows and create default index: df1 = df.loc['english'].reset_index(drop=True) print (df1) allergy 0 'MAY CONTAIN: prawn' 1 'MAY CONTAIN: peanuts' 2 'MAY CONTAIN: milk' Then concat twice, sorting and last remove second level: df = (pd.concat([df1, df1], keys=('french','dutch')) .sort_index(level=1) .reset_index(level=1, drop=True) ) print (df) allergy french 'MAY CONTAIN: prawn' dutch 'MAY CONTAIN: prawn' french 'MAY CONTAIN: peanuts' dutch 'MAY CONTAIN: peanuts' french 'MAY CONTAIN: milk' dutch 'MAY CONTAIN: milk'
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47201578

http://stackoverflow.com/q/47133147
type: Question
upvote count: 2
has body: I use to get Information from google, I know that I will block after a few requests, that's why I tried to get through Proxies. For the Proxies I use the ProxyBroker from this link: The Link However, if I use proxies, google returns 503. If I click on the error, google shows me my IP and not the Proxy IP. Here is what I've tried with: usedProxy = self.getProxy() if usedProxy is not None: proxies = {"http": "http://%s" % usedProxy[0]} headers = {'User-agent': 'Mozilla/5.0'} proxy_support = urlrequest.ProxyHandler(proxies) opener = urlrequest.build_opener(proxy_support, urlrequest.HTTPHandler(debuglevel=1)) urlrequest.install_opener(opener) req = urlrequest.Request(search_url, None, headers) with contextlib.closing(urlrequest.urlopen(req)) as url: htmltext = url.read() I tried with http and https. Even if the requests is going well, I get a 503 with this the following Message: send: b'GET http://www.google.co.in/search?q=Test/ HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.google.co.in\r\nUser-Agent: Mozilla/5.0\r\nConnection: close\r\n\r\n' reply: 'HTTP/1.1 302 Found\r\n' header: Date header: Server header: Location header: Pragma header: Expires header: Cache-Control header: Content-Type header: Content-Length header: X-XSS-Protection header: X-Frame-Options header: &gt;Connection send: b'GET http://ipv4.google.com/sorry/index?continue=http://www.google.co.in/search%3Fq%3DTest/&amp;q=EgTCDs9XGMbOgNAFIhkA8aeDS0dE8uXKu31DEbfj5mCVdhpUO598MgFy HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: ipv4.google.com\r\nUser-Agent: Mozilla/5.0\r\n &gt;Connection: close\r\n\r\n' reply: 'HTTP/1.1 503 Service Unavailable\r\n' If the above error doesn't happen, I finally get the following Error: &gt;[Errno 54] Connection reset by peer My Questions are: Is the Ip from the error Link every time my IP and not the Proxy IP? Google Error Link And if it´s every time the Host IP what is shown in the error Message from google and the Problem is from the Proxies, how to bypass the error?
tagged with: web-scraping
tagged with: python
score: 2
tagged with: proxy
type: AnsweredQuestion
has title: python - Service Unavailable - urllib proxy not working
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47156476
favorite count: 0
accepted answer: http://stackoverflow.com/a/47156476

http://stackoverflow.com/a/57687339
has body: You have to import the LoginView in your urls.py: from django.contrib.auth.views import LoginView and change auth_view.login to LoginView.as_view()
score: 7
answers question: http://stackoverflow.com/q/47065438
type: Answer
downvote count: 0
upvote count: 7

http://stackoverflow.com/comment/81190931
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47120539
score: 0
has text: that is the exception method of logging library not exactly a exceptional handler. i may replace that with `info` method or `error` than that should have worked at least right .for example `logging.info()`

http://stackoverflow.com/comment/81171264
comment on: http://stackoverflow.com/q/47110284
type: Comment
score: 1
has text: You might want to edit the question as it states : `v is a sparse scipy matrix`.
type: QuestionComment

http://stackoverflow.com/a/64410841
has comment: http://stackoverflow.com/comment/113895210
answers question: http://stackoverflow.com/q/47123188
has body: I had this issue kinda.... I had been editing my excel workbook. I ended up accidentally pasting a space into an almost infinite amount of rows. ya know... like a lot. I selected all empty cells and hit delete, saved workbook, problem gone.
score: 0
type: Answer

http://stackoverflow.com/a/47130343
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47129901
answers question: http://stackoverflow.com/q/47129901
type: Answer
has body: You can get your desired result using groupby and apply, you don't need to create df.check ahead of time: def filterer(x): y = x.FG.eq('Y') n = x.FG.eq('N') if 'N' in x.FG.values: if x.loc[y, 'Date'].values &gt; x.loc[n, 'Date'].values + timedelta(60): return x.loc[y] elif 'Y' in x.FG.values: return x (df.groupby(['Name','Program']) .apply(filterer) .sort_values(["Name","Date"]) .reset_index(drop=True) ) Output: Name FG Program Date 0 A Y Eval 2017-10-01 1 C Y PO 2017-10-01 2 D Y Info 2017-06-03 3 D Y IB 2017-10-01 4 D Y PO 2017-10-01 5 G Y Info 2017-10-21 6 H Y PO 2017-04-01

argparse
tags question: http://stackoverflow.com/q/47203240
tags question: http://stackoverflow.com/q/47088766
tags question: http://stackoverflow.com/q/47119468
tags question: http://stackoverflow.com/q/47119114
tags question: http://stackoverflow.com/q/47200268
tags question: http://stackoverflow.com/q/47103242
tags question: http://stackoverflow.com/q/47205477
type: Tag
tags question: http://stackoverflow.com/q/47222276
tags question: http://stackoverflow.com/q/47113138
tags question: http://stackoverflow.com/q/47219662
tags question: http://stackoverflow.com/q/47118098
tag name: argparse

http://stackoverflow.com/q/47195075
has comment: http://stackoverflow.com/comment/81339861
accepted answer: http://stackoverflow.com/a/47263399
answer count: 2
has answer: http://stackoverflow.com/a/47263399
has comment: http://stackoverflow.com/comment/81339307
has body: I'm using pyfpdf in python to generate pdf files. I have a Base64 which I want to insert into a pdf file without having to save it as an image in my file system. But the pyfpdf image function only accepts file path. fpdf.image(name, x = None, y = None, w = 0, h = 0, type = '', link = '') Is there a way (hack) to directly insert base64 or buffered image from memory, without having to save into the file system beforehand? I even checked their source code on github and couldn't figure. link : https://github.com/reingart/pyfpdf/tree/master/fpdf
tagged with: python
has title: Insert Base64 image to pdf using pyfpdf
score: 4
possible better answer: http://stackoverflow.com/a/61086746
has comment: http://stackoverflow.com/comment/81339780
has answer: http://stackoverflow.com/a/61086746
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81339565
has comment: http://stackoverflow.com/comment/81339527
tagged with: fpdf
favorite count: 0
type: Question
upvote count: 4

http://stackoverflow.com/comment/81391759
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47220556
has text: No, there isn't a way to format the box other than completely rewriting the widget, which is possible but a silly idea. Instead you can produce your own `Toplevel()` widget.
type: Comment

tiff
tags question: http://stackoverflow.com/q/47182125
tag name: tiff
tags question: http://stackoverflow.com/q/47178272
type: Tag

http://stackoverflow.com/q/47163732
tagged with: numpy
tagged with: list
accepted answer: http://stackoverflow.com/a/47163803
score: 0
has title: Extract values before and after position in a python list
answer count: 2
has comment: http://stackoverflow.com/comment/81277318
has answer: http://stackoverflow.com/a/47163803
possible better answer: http://stackoverflow.com/a/47167975
has body: I want to conditionally extract values from a python list based on following logic: ll = [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015] I want to extract 3 values before and after a given value. e.g. if input is 2007, then 3 values before it will be: 2004, 2005, 2006 and after will be: 2008, 2009, 2010. If input is 2014, then I want to extract 5 values before and 1 value after (for a total of 6 values). I can do this using for loops but is there a more pythonic solution?
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81277257
tagged with: python
has answer: http://stackoverflow.com/a/47167975

http://stackoverflow.com/a/47194666
downvote count: 1
has body: from print('My 1st corner is at: ',lawrence.xcor().format(),',',lawrence.ycor(), 'and my heading is',lawrence.heading()) to print_str = 'My 1st corner is at: ({}, {}), and my heading is {}'.format(lawrence.xcor(), lawrence.ycor(), lawrence.heading()) print(print_str)
answers question: http://stackoverflow.com/q/47194539
type: Answer
score: -1
upvote count: 0

http://stackoverflow.com/comment/81114465
type: QuestionComment
score: 0
has text: Why do you need them sorted in that order? Is it possible that this is an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)?
comment on: http://stackoverflow.com/q/47082391
type: Comment

http://stackoverflow.com/q/47189031
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/47189317
accepted answer: http://stackoverflow.com/a/47189104
has title: Initialize empty vector with 3 dimensions
has answer: http://stackoverflow.com/a/47189317
has comment: http://stackoverflow.com/comment/81327466
has answer: http://stackoverflow.com/a/47189104
type: Question
tagged with: numpy
answer count: 2
tagged with: arrays
has body: I want to initialize an empty vector with 3 columns that I can add to. I need to perform some l2 norm distance calculations on the rows after I have added to it, and I'm having the following problem. I start with an initial empty array: accepted_clusters = np.array([]) Then I add my first 1x3 set of values to this: accepted_clusters = np.append(accepted_clusters, X_1) returning: [ 0.47843416 0.50829221 0.51484499] Then I add a second set of 1x3 values in the same way, and I get the following: [ 0.47843416 0.50829221 0.51484499 0.89505277 0.8359252 0.21434642] However, what I want is something like this: [ 0.47843416 0.50829221 0.51484499] [ 0.89505277 0.8359252 0.21434642] .. and so on This would enable me to calculate distances between the rows. Ideally, the initial empty vector would be of undefined length, but something like a 10x3 of zeros would also work if the code for that is easy.
tagged with: python

http://stackoverflow.com/q/47081747
has comment: http://stackoverflow.com/comment/81113210
tagged with: python
type: UnansweredQuestion
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81113027
linked to: http://stackoverflow.com/q/41970789
has title: How to dm person who used command in discord
has comment: http://stackoverflow.com/comment/81113496
tagged with: discord
has comment: http://stackoverflow.com/comment/81112695
favorite count: 0
score: -1
has body: This is my code to dm the person doing the command: @client.command() async def test(pass_context=True): await message.author.sendMessage("test") what my code is supposed to do is when someone does (this is an example) !test then they would receive a Direct Message saying something. When I try this it tells me: NameError: name 'message' is not defined. And I have no idea what to do about it.
type: Question
has answer: http://stackoverflow.com/a/47263455
upvote count: 0

http://stackoverflow.com/q/47117592
upvote count: 1
favorite count: 0
tagged with: multiprocessing
type: Question
tagged with: proxy
score: 1
has answer: http://stackoverflow.com/a/47126748
has title: Python Manager access dict through registry
tagged with: python
has body: I have a manager with one dict proxy. I want to access it from a different process. For brevity sample code only uses one process but assume we don't have a direct reference to it (as if the other process was created from the first one). I register dict proxy dict1 under typeName 'd1' so I can access it remotely. I check the manager's registry and see the dict proxy there. But when I try to access it by calling d1 I get a KeyError from the remote. I know I could create a method to access my dict, but there must be a direct way to access the dict proxy according to the documentation (python 2, chapter 16.6). from multiprocessing.managers import SyncManager from sys import stderr proxy = SyncManager() proxy.start() dict1 = proxy.dict({'k1': 'blah'}) proxy.register('d1', dict1) # next line shows that d1 is bound method of manager print &gt;&gt;stderr, 'd1 is', proxy.d1 # next line produces a KeyError print 'The value of d1 is', proxy.d1() Run output d1 is &lt;bound method SyncManager.d1 of &lt;multiprocessing.managers.SyncManager object at 0x10925dd10&gt;&gt; Traceback (most recent call last): File "/Users/adriancepleanu/PycharmProjects/AFX/UIproxy.py", line 32, in &lt;module&gt; print 'The value of d1 is', proxy.d1() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/managers.py", line 667, in temp token, exp = self._create(typeid, *args, **kwds) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/managers.py", line 567, in _create id, exposed = dispatch(conn, None, 'create', (typeid,)+args, kwds) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/managers.py", line 105, in dispatch raise convert_to_error(kind, result) multiprocessing.managers.RemoteError: --------------------------------------------------------------------------- Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/mult…
tagged with: dictionary
type: UnansweredQuestion
answer count: 1
downvote count: 0

http://stackoverflow.com/a/47210989
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47210790
has body: This should work fine: newlist = [100 if x == 0 else x for x in listzero]
type: Answer

http://stackoverflow.com/q/47143435
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81236948
tagged with: python
has title: Invalid syntax inside dateutil when importing tensorflow. Why?
has body: Here is the transcript: dims@calculon:~$ pip install tensorflow-gpu Collecting tensorflow-gpu Downloading tensorflow_gpu-1.4.0-cp35-cp35m-manylinux1_x86_64.whl (170.1MB) 100% |████████████████████████████████| 170.1MB 10kB/s Requirement already satisfied: numpy&gt;=1.12.1 in ./.local/lib/python3.5/site-packages (from tensorflow-gpu) Requirement already satisfied: protobuf&gt;=3.3.0 in ./.local/lib/python3.5/site-packages (from tensorflow-gpu) Requirement already satisfied: wheel&gt;=0.26 in ./.local/lib/python3.5/site-packages (from tensorflow-gpu) Collecting tensorflow-tensorboard&lt;0.5.0,&gt;=0.4.0rc1 (from tensorflow-gpu) Downloading tensorflow_tensorboard-0.4.0rc2-py3-none-any.whl (1.7MB) 100% |████████████████████████████████| 1.7MB 844kB/s Requirement already satisfied: six&gt;=1.10.0 in ./.local/lib/python3.5/site-packages (from tensorflow-gpu) Collecting enum34&gt;=1.1.6 (from tensorflow-gpu) Downloading enum34-1.1.6-py3-none-any.whl Requirement already satisfied: setuptools in ./.local/lib/python3.5/site-packages (from protobuf&gt;=3.3.0-&gt;tensorflow-gpu) Requirement already satisfied: bleach==1.5.0 in ./.local/lib/python3.5/site-packages (from tensorflow-tensorboard&lt;0.5.0,&gt;=0.4.0rc1-&gt;tensorflow-gpu) Requirement already satisfied: markdown&gt;=2.6.8 in ./.local/lib/python3.5/site-packages (from tensorflow-tensorboard&lt;0.5.0,&gt;=0.4.0rc1-&gt;tensorflow-gpu) Requirement already satisfied: werkzeug&gt;=0.11.10 in ./.local/lib/python3.5/site-packages (from tensorflow-tensorboard&lt;0.5.0,&gt;=0.4.0rc1-&gt;tensorflow-gpu) Requirement already satisfied: html5lib==0.9999999 in ./.local/lib/python3.5/site-packages (from tensorflow-tensorboard&lt;0.5.0,&gt;=0.4.0rc1-&gt;tensorflow-gpu) Installing collected packages: tensorflow-tensorboard, enum34, tensorflow-gpu Found existing installation: tensorflow-tensorboard 0.1.8 Uninstalling tensorflow-tensorboard-0.1.8: Successfully uninstalled tensorflow-tensorboard-0.1.8 Successfully installed enum34-1.1.6 t…
has answer: http://stackoverflow.com/a/47144432
score: 0
tagged with: python-dateutil
answer count: 1
has comment: http://stackoverflow.com/comment/81238713
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/81236886
type: Question

http://stackoverflow.com/comment/81095673
has text: @hansTheFranz This one ('emp.csv', 'a',newline=' ') works but I want to display the header (Employee id,Employee name,Department,Age) only once that is the beginning.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47073072

http://stackoverflow.com/a/47065794
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47065677
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81080456
type: Answer
answers question: http://stackoverflow.com/q/47065677
has body: Based on @COLDSPEED comment. Changed conversion of ID_potential to numpy array: &gt;&gt;&gt; np.flatnonzero(np.asarray(ID_potential) == ID_target).tolist() [2, 5, 7] Another version: &gt;&gt;&gt; np.where(np.equal(ID_potential, ID_target))[0].tolist() If this does not work in your actual code, then most likely there is a type mismatch between ID_potential and ID_target in your actual code/data or some of the data are floating point and therefore strict equality may not hold. In that case use numpy.isclose(). Just to make the code more resilient to mistakes, try this version: np.where(np.equal(np.asarray(ID_potential, dtype=np.int), np.int(ID_target)))[0].tolist() or, if the values are actually float - replace np.int above with np.float and np.equal with np.isclose(): np.where(np.isclose(np.asarray(ID_potential, dtype=np.float), np.float(ID_target)))[0].tolist()
downvote count: 0

http://stackoverflow.com/comment/81115393
has text: Could you explain what this question is about? It is rather unclear right now without a sample text and expected output. You cannot *revert* a `re.sub` operation. Nor change the direction the `re` engine matches in a string (though you may with `regex`).
comment on: http://stackoverflow.com/q/47082599
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47142887
tagged with: matplotlib
has title: How to create a heatmap with discrete color legend for my DataFrame?
tagged with: python
duplicate of: http://stackoverflow.com/q/12286607
type: Question
linked to: http://stackoverflow.com/q/12286607
linked to: http://stackoverflow.com/q/40662475
answer count: 2
has answer: http://stackoverflow.com/a/47142981
accepted answer: http://stackoverflow.com/a/47143142
tagged with: seaborn
has answer: http://stackoverflow.com/a/47143142
has body: I have this DataFrame df: df = pd.DataFrame(columns=["System","F1", "F2", "F3", "F4"], data=[["System1",0,1,0,0], ["System2",0,1,0,0]]) I want to create a "heatmap" of seaborn: plt.figure(figsize=(12,6)) ax = sns.heatmap(df, annot=False, linewidths=.5, cmap="Set3") plt.ylabel('Features', fontsize=12) plt.xlabel('Systems', fontsize=12) plt.xticks(rotation='vertical') plt.yticks(rotation='horizontal') plt.show() In the X axis I want to have Systems, while in the Y axis I want to have Features. If the System-Feature value is 0, then the color is dark blue, otherwise it's light blue. How can I do it?
possible better answer: http://stackoverflow.com/a/47142981
type: AnsweredQuestion
score: 0
tagged with: pandas

http://stackoverflow.com/q/47191297
has answer: http://stackoverflow.com/a/47276896
has comment: http://stackoverflow.com/comment/81387470
downvote count: 0
has answer: http://stackoverflow.com/a/47191558
tagged with: jupyter
has title: How to switch environment on Jupyter notebook for new notebook?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/60784116
has body: I have an instance with various environment and some notebooks are compatible with different environment for e.g. notebook1 is for MXNet and notebook2 is for Tensorflow. How do I jump to new environment when I move from notebook1 to notebook2? I tried doing that but this doesn't quite work with Jupyter notebook? Any suggestion? So I need to do it from conda environment but looks like jupyter notebook UI doesn't respect (calls right activation function) to set the path.
has answer: http://stackoverflow.com/a/47262847
tagged with: anaconda
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/64810375
tagged with: python
score: 11
has comment: http://stackoverflow.com/comment/81332280
tagged with: conda
upvote count: 11
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/81332105

http://stackoverflow.com/q/47188543
linked to: http://stackoverflow.com/q/21320585
has answer: http://stackoverflow.com/a/47193067
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/81326584
tagged with: python
has title: Creating Python scrapy project yields: File "<stdin>", line 1 error
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47193067
has body: Windows 10, Command Line Terminal, Python 3.6.3 |Anaconda, Inc.| (default, Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)] on win32 New to Python &amp; following tutorial instructions here: https://docs.scrapy.org/en/latest/intro/tutorial.html Steps: Downloaded Anaconda Installed scrapy package through Anaconda Navigator Opened terminal cd c:\Anaconda python scrapy startproject tutorial Yields this error: File "&lt;stdin&gt;", line 1 scrapy startproject tutorial Syntax Invalid Syntax See screenshot: https://www.dropbox.com/s/17d3r1hzt02pp2k/Screenshot%202017-11-08%2013.41.06.png?dl=0 I've run globals() to see that Scrapy appears to be running correctly. I've also try running this command from c:\Anaconda directory. python scrapy startproject tutorial Which yielded this error: python.exe: can't find '__main__' module in 'scrapy' There may also be an issue with Anaconda &amp; Scrapy (Cannot Set Up a Scrapy Project) though, to my knowledge, I installed correctly using the recommended method from scrapy.org.
answer count: 1

http://stackoverflow.com/q/47210332
has answer: http://stackoverflow.com/a/47210364
linked to: http://stackoverflow.com/q/26091689
has comment: http://stackoverflow.com/comment/81369928
answer count: 1
type: Question
duplicate of: http://stackoverflow.com/q/26091689
has body: I write below program but My program cannot check the two number is equal or not. There is no error, I would be appreciate for any help. import math def IsCollinding(ball1,ball2): distance=math.sqrt((((ball2[0]-ball1[0])**2)+((ball2[1]-ball1[1])**2))) print(type(distance)) print(type(ball1[2]+ball2[2])) if(distance==ball1[2]+ball2[2]): print("Is Coliding") else: print("Not Coliding") print(distance) print(ball1[2]+ball2[2]) ball1=[2,2,3] ball2=[11,11,9.7279220614] IsCollinding(ball1,ball2) output: &lt;type 'float'&gt; &lt;type 'float'&gt; Not Coliding 12.7279220614 12.7279220614
type: UnansweredQuestion
tagged with: python
has title: How can I check two float is exactly equal?
score: 0

http://stackoverflow.com/comment/81415443
score: 0
comment on: http://stackoverflow.com/a/47223451
type: Comment
type: AnswerComment
has text: You will keep everything the same, just change the `cbar.ax.set_yticklabels(otherticks)`, where otherticks includes some string at the first or last position.

http://stackoverflow.com/q/47099527
score: 3
answer count: 2
tagged with: odoo-10
upvote count: 3
has body: I'm using Odoo 10. After a new user sign up (through localhost:8069/web/signup) i want him to be automatically allocated inside a group i created on my very own custom module (the user will need authentication from an admin later on so he can be converted to a regular portal user; after signup he will receive restricted access). I have tried many things. My latest effort looks like this: class RestrictAccessOnSignup(auth_signup_controller.AuthSignupHome): def do_signup(self, *args): super(RestrictAccessOnSignup, self).do_signup(*args) request.env['res.groups'].sudo().write({'groups_id': 'group_unuser'}) Note that I have import odoo.addons.auth_signup.controllers.main as auth_signup_controller so that I can override the auth_signup controller. I have located that method as the responsible for doing the signup. So I call it in my new method and then try to change the newly created user's group_id. What i miss is a fundamental understanding of how to overwrite a field's value from another model inside a controller method context. I'm using the 'request' object although i'm not sure of it. I have seen people using 'self.pool['res.users'] (e.g.) for such purposes but i don't understand how to apply it inside my problem's context. I believe, also, that there is a way to change the default group for a user after it is created (i would like to know), but i also want to understand how to solve the general problem (accessing and overwriting a field's value from another module). Another weird thing is that the field groups_id does exist in 'res.users' model, but it does not appear as a column in my pgAdmin interface when i click to see the 'res.users' table... Any idea why? Thanks a lot!
downvote count: 0
has title: Odoo - Changing user group id just right after signup (ecommerce)
favorite count: 0
has answer: http://stackoverflow.com/a/47104764
type: Question
type: UnansweredQuestion
tagged with: odoo
has answer: http://stackoverflow.com/a/47121114
tagged with: overriding
tagged with: python
tagged with: controllers

http://stackoverflow.com/comment/81282806
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47165683
has text: your code is written only for the 2 sample lines that I mentioned. I have a file with 100 such lines

http://stackoverflow.com/comment/81276138
has text: "What you tried to do" is not a python code. Is that meant to be pseudo-code?? Please append the whole code you tried, as it can't be much for this simple example...
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47163056
type: Comment

http://stackoverflow.com/q/47131110
has title: HTML/Django/Jinja/Python : How to post a fixed value back
has body: This is a HTML template that displays all of the proposals in a database (passed through views.py as a list in the dictionary parameter). I then use a jinja for-loop to go through all the proposals in the database and display their attributes. How can I Post-request the {{ proposal.id }} back to my python code when the "Learn more" button is clicked? I need this to allow me to display the corresponding values in my other html template. Sorry if this is a basic question, i'm a high school student and extremely new to django! Thanks alot in advance! {% block body %} {% for proposal in proposals %} Proposal : {{ proposal.title }} Status : {{ proposal.status }} Out of --- Votes: 35% Complete (success) {{ proposal.votes_for }}% For 10% Complete (danger) {{ proposal.votes_against }}% Against Learn more
score: 0
answer count: 1
type: Question
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/47133340
tagged with: django
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47181850
tagged with: matplotlib-basemap
has answer: http://stackoverflow.com/a/47200574
has comment: http://stackoverflow.com/comment/81317001
type: Question
linked to: http://stackoverflow.com/q/13306519
tagged with: python
has body: After several days trying to figure this out, I thought I would ask for help... I have 3 lists, lon, lat and pop all the same length. With lon[1],lat[1] corresponding to pop[1]. What I want to do, is after having plotted them out, to 'hover over the map' and then (ultimately plot a time series of population for each point) but for now, I just want to know what the corresponding population value is... i have been using this below, but I don't know how to a) make it to the nearest lat,lon point, as currently it produces a list of possible options b) with the figure zoom in then click, because the click zoom in button seems to stop any further points being recorded... #Import modules import netCDF4 as nc4 from netCDF4 import Dataset import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.basemap import Basemap from matplotlib import cm as cm from matplotlib import mlab as ml import matplotlib as mpl from matplotlib.pyplot import figure, show def extractdata(nc_filename,column_data): dataset=Dataset(nc_filename) #Reads the data into a column format output= dataset.variables[column_data][:] dataset.close() return(output) #Start of program inputfile='reference_pop.nc' dataset = Dataset(inputfile) print(dataset.variables.keys()) time=extractdata(inputfile,'time') lon=extractdata(inputfile,'lon') lat=extractdata(inputfile,'lat') pop=extractdata(inputfile,'pop') index=np.arange(len(lat)) #Reverse the time order (So that 0 is 120,000 years ago aka from past to present time=time[::-1] #Reverse population order pop=pop[::-1] #Population is a 2d matrix, of dimensions pop and len(lon/lat) def onpick3(event): ind = event.ind #print 'onpick3 scatter:', ind, npy.take(lon, ind), npy.take(lat, ind) print 'ind', ind #Example output: [2513 2673 2843 3022 3023 3024 3025 3203] print 'npy.take(lon, ind)',npy.take(lon, ind) #Example output [ 21398764. 21459962. 21520490. 21391092. 21454742. 21517902. 21580542. 21577006.] print 'npy.take(lat, ind)',npy.take(lat, ind) #Example ou…
tagged with: scatter-plot
accepted answer: http://stackoverflow.com/a/47200574
type: AnsweredQuestion
score: 0
has title: Onpick3 Hover nearest data point rather than list
tagged with: matplotlib
answer count: 1
linked to: http://stackoverflow.com/q/7908636
has comment: http://stackoverflow.com/comment/81317628

http://stackoverflow.com/comment/81152751
has text: @Lazza87 you may also prefer the `mystic` package (on PyPI) for constrained optimization, its setup is a bit better for more complicated constraints.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47100961
type: Comment

http://stackoverflow.com/comment/81179008
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47112782
has text: Thanx a lot! it works perfectly but again if x_1 y_1 are also 2d and i use it as np.vstack([np.asarray(a).T, np.asarray(x_1).T, np.asarray(y_1).T]).. then it doesn't work. It should work like x_1 is (3,2) y_1 is (3,2) and a is also (3,2) then after joining it should be (3,6) matrix. How will this work now.
type: Comment

http://stackoverflow.com/q/47159215
answer count: 1
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has body: I have successfully built a model using Tensorflow in Python in IBM Data Science Experience. It works to evaluate test data using this model. However, when I invoke it to do a prediction on records, I cannot consume the result that evaluate returns. I follow the description from https://www.tensorflow.org/get_started/input_fn and use list(): predict_input_fn = tf.estimator.inputs.pandas_input_fn( x={"x": x_pandas_predict_data}, num_epochs=1, shuffle=False) y = m.predict(input_fn=predict_input_fn) predictions = list(p["predictions"] for p in itertools.islice(y, 6)) print("Predictions: {}".format(str(predictions))) The error I get is as follows: TypeErrorTraceback (most recent call last) &lt;ipython-input-49-49a72bc2fad0&gt; in &lt;module&gt;() 15 # .predict() returns an iterator of dicts; convert to a list and print 16 # predictions ---&gt; 17 predictions = list(p["predictions"] for p in itertools.islice(y, 6)) 18 print("Predictions: {}".format(str(predictions))) TypeError: 'list' object is not callable How can I fix this? Many thanks. Johannes
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47159294
tagged with: python
has title: Tensorflow in DSX: Consuming prediction results fails due to list()
score: 2
tagged with: data-science-experience
upvote count: 3

http://stackoverflow.com/q/47197637
score: 2
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/509211
accepted answer: http://stackoverflow.com/a/47197822
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47197822
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/81344073
duplicate of: http://stackoverflow.com/q/509211
has comment: http://stackoverflow.com/comment/81344171
tagged with: python
type: AnsweredQuestion
has title: Why string reversing is not happening?
has body: s="Python" print(s[0:6:-1]) print(s[::-1]) Output '' # for first print function 'nohtyP' #for second print function Both have the same meaning but gives different output, I don't understand this why?

http://stackoverflow.com/q/47201586
type: Question
has comment: http://stackoverflow.com/comment/81358690
has comment: http://stackoverflow.com/comment/81360228
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81355705
tagged with: python
has comment: http://stackoverflow.com/comment/81355572
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/81353900
has comment: http://stackoverflow.com/comment/81351830
answer count: 0
has comment: http://stackoverflow.com/comment/81355622
type: UnansweredQuestion
has title: How to increase the width of subplots in Basemap?
has comment: http://stackoverflow.com/comment/81391351
has body: I am having a problem with subplots when using Basemap. I am plotting relative humidity (RH) measured in six pressure levels by a satellite. In the first image (Figure 1) I have plotted RH measured over the satellite's entire trajectory (encircling the globe). Each subplot corresponds to one pressure level. This figure is fine. However, to study a certain measured event (here: the tropical cyclone seen east of Madagascar) I want to zoom in on the figure. Zooming in (in terms of limiting the latitudinal and longitudinal range) also seems to work fine (Figure 2). BUT, in Figure 2 the subplots don't make use of the entire figure space at their disposal. I imagine that all components seen in Figure 2 (i.e., the map and measured RH) would be enlarged if the subplots made use of the entire width of the figure. In other words, I want my subplots in Figure 2 to be just as wide as the subplots in Figure 1. Please, how can I do this? Here is my code: First I load my file and my variables Then comes the plotting: import numpy as np from netCDF4 import Dataset import matplotlib.pyplot as plt import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.basemap import Basemap from matplotlib import gridspec # Generate variables lat_use = np.arange(29.5, 30.5, 1) lon_use = np.arange(179.5, 180.5, 1) RH = np.random.random((60, 360, 6)) plt.subplot(611) m = Basemap(projection='cyl', llcrnrlon=-180, urcrnrlon=180, llcrnrlat=-29.5, urcrnrlat=29.5, resolution='c') m.drawcoastlines(color='k') lons, lats = np.meshgrid(lon_use,lat_use) x, y = m(lons,lats) m.contourf(x, y, RH[:,:,5], cmap='RdYlBu') plt.xlim(-179.5, 179.5) plt.xticks([-180, -120, -60, 0, 60, 120, 180], ['180W', '120W', '60W', '0E', '60E', '120E', '180E'], fontsize=10) plt.ylim(-29.5, 29.5) plt.yticks([-30, -20, -10, 0, 10, 20, 30], ['30S', '20S', '10S', '0', '10N', '20N', '30N'], fontsize=10) plt.ylabel('6th') plt.title('RH in 6 levels') #plt.show() plt.subplot(612) m = Basemap(projection='cyl', llcrnr…
tagged with: matplotlib-basemap

http://stackoverflow.com/q/47117179
score: 0
tagged with: scikit-image
tagged with: python
tagged with: image-processing
accepted answer: http://stackoverflow.com/a/47117326
tagged with: rgb
has answer: http://stackoverflow.com/a/47117326
has title: histogram equalization skimage
answer count: 1
has body: I'm tryng to get some statics from some images, and when I tryed to perform histogram equalization I get confused. Because I tryed this: img = io.imread(file); img = exposure.equalize_hist(img); And I get the warning warn("This might be a color image. The histogram will be " Then I tryed to perform the equalization in each channel like this: img = io.imread(file); #img = exposure.equalize_hist(img); height, width = len(img), len(img[0]); r1 = []; g1 = []; b1 = []; for i in range(height): for j in range(width): pixel = img[i, j]; r1.append(pixel[0]); g1.append(pixel[1]); b1.append(pixel[2]); r = exposure.equalize_hist(r1); g = exposure.equalize_hist(g1); b = exposure.equalize_hist(b1); And I get the error AttributeError: 'list' object has no attribute 'shape' So how should I do histogram equalization in an image with color, and if I wanna do it in an image in HSV, or CIELAB, is it the same way?! histogram equalization
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/47076266
answers question: http://stackoverflow.com/q/47075718
type: Answer
has comment: http://stackoverflow.com/comment/81101455
has body: You could simply use set intersections. It doesn't require any if or loops and should be very efficient: &gt;&gt;&gt; set('try to find a substring') &amp; set('acdf') {'a', 'f', 'd'} &gt;&gt;&gt; set('no substring') &amp; set('acdf') set() If you really want to use pandas, look at @Coldspeed's solution.
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47115173
downvote count: 0
answers question: http://stackoverflow.com/q/47110263
type: Answer
upvote count: 2
score: 2
has body: As you haven't shown your code how you have written to parse the tabular data, I gave a demo here to give you an idea how you can parse the selective data from a table. Just twitch the selectors in your code like i did here: from bs4 import BeautifulSoup import requests link = "http://applications.slbfe.lk/jobbank/jsearchdisplay_an_m.asp?an=1712" res = requests.get(link).text soup = BeautifulSoup(res,"lxml") table = soup.select("table")[3] for items in table.select('tr'): item_name = [' '.join(item.text.split()) for item in items.select('td')[:3]] #this is where you change the index which column to parse print(' '.join(item_name)) Partial results: Details Approved Vacancies Available Vacancies Kuwait House Boy 10 10 House Boy 10 8 House Cook - Male 10 10 House Cook - Male 10 8

http://stackoverflow.com/comment/81388663
score: 0
type: AnswerComment
has text: But inheritance is about inheriting attributes as well as methods isn't it? e.g. a player could inherit the attributes of score, such as current_score or health. Isn't having a score property if that property is an attribute of another class, also an example of inheritance. That is how several tutorials seem to teach it.
type: Comment
comment on: http://stackoverflow.com/a/47219490

http://stackoverflow.com/comment/131903031
type: Comment
has text: @Thomas did you manage to solve it yet? Ideally there would be an option to supply a custom ping message when creating the instance (EG heartbeat_message={"message"="PING"}, I'm at the point of thinking to just fork the project and add it in myself
comment on: http://stackoverflow.com/a/47119476
score: 0
type: AnswerComment

http://stackoverflow.com/a/47147058
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/47146728
has body: No. Playing an audio file doesn't modify the file. Unless your car stereo writes some sort of log to the flash drive of what it's played -- which is unlikely; I've never seen or heard of a stereo that did that -- there's no way to determine which files have been played.
type: Answer
has comment: http://stackoverflow.com/comment/81244616
answers question: http://stackoverflow.com/q/47146728

http://stackoverflow.com/comment/81331100
score: 0
comment on: http://stackoverflow.com/a/47188975
has text: Well, actually commas are what define a tuple: `x = 1, 2` if you print `x`, you'll get `(1, 2)`, but if you don't include parentheses in the function call, it will think that you're trying to pass multiple arguments. The outer parenthesis belong to the `.append()` call.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47241610
has comment: http://stackoverflow.com/comment/82025974
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47219727
has comment: http://stackoverflow.com/comment/81461171
has body: The problem (at least as far as I can tell without having your test file) is that your code fails to check the value of ret, after testvid.read(). When this call returns False, then there are no more frames to display, so not surprisingly, imshow() will fail.
score: 1

http://stackoverflow.com/q/47134108
answer count: 0
type: UnansweredQuestion
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/81219035
has comment: http://stackoverflow.com/comment/81255683
has comment: http://stackoverflow.com/comment/81245830
has body: I am new in NLP subject. I am working on Turkish so it is hard to find a proper corpus. I read a lot and found this https://radimrehurek.com/gensim/wiki.html#preparing-the-corpus it tells to use Wikipedia data but even if I use it will not give me the stems of words because of the structure of the language(agglutinative language). My aim is to put my texts into some categories. Result must be like text1 related to subject1 20% and subject2 50% and subject3 30% I thought that what if I try to do it without a corpus but first wanted to ask here if my idea is possible or utopic. Also, I will need categories and words related with them. If someone can show me a path to go on that will be great I am drifting inside this topic. Thanks.
tagged with: nlp
has title: How to work with languages without explicit tokens, e.g. Turkish?
type: Question

http://stackoverflow.com/comment/81208733
has text: Thanks for the solution. Is there any way of finding same pair using same way. I tried to look for equal or same function but didn't find it
score: 0
comment on: http://stackoverflow.com/a/47120072
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81103541
has text: Sorry, I simplified my code somewhat for this post. My input data is actually a list of dicts which I convert into a dict of lists. In order to pass this to `from_tensor_slices`, I have to convert the values in the dict to tensors.
score: 0
comment on: http://stackoverflow.com/q/47077183
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81186628
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47118093
has text: check my edited answer with code for the function
score: 0

http://stackoverflow.com/comment/81140170
type: QuestionComment
has text: I think `MaxU` answer ;)
comment on: http://stackoverflow.com/q/47095375
type: Comment
score: 0

http://stackoverflow.com/a/47139415
type: Answer
has body: There are a number of different ways to start a process in CentOS, chose yourself which one solves the problem in the way you prefer. Open a terminal, run python 1.py and forget about it until you shut the machine down Open a terminal, run nohup python 1.py &amp; and close the terminal. Nohup keeps the program alive even though the session ended. If you need to kill it, you need to find it in the process list with ps -ax and kill it with kill &lt;process_id&gt; Read the documentation on the deamon function and call your script with it I am sure there are many more
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47139180

http://stackoverflow.com/a/47110499
downvote count: 0
has body: Just initialize an empty array of xmap and ymap and then try to append in that. A sample code would look like: xmap = [] xmap.append(str(x)) Similarly for y. ymap = [] ymap.append(str(arctan(x,100))) Don't forget to initialize the xmap and ymap outside of the loop. If you want me to modify the whole of your code then let me know. Update Complete code in 1D array. import math xmap = [] ymap = [] for x in range(1,10,1): def arctan(x, n): arctang=0 inv_x=1/x for i in range(n): sign=(-1)**i arctang = arctang + ((inv_x**(2.0*i+1))/(2.0*i+1))*sign if x&gt;0: arc_tan=(math.pi/2)-arctang else: arc_tan=-(math.pi/2)-arctang return arc_tan xmap.append(str(x)) ymap.append(str(arctan(x,100))) x = xmap y = ymap print "x= ",x print "y= ",y
score: 3
answers question: http://stackoverflow.com/q/47110381
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/81171661
has comment: http://stackoverflow.com/comment/81171116
has comment: http://stackoverflow.com/comment/81246356

http://stackoverflow.com/q/47084949
has answer: http://stackoverflow.com/a/47085105
type: Question
upvote count: 2
score: 2
answer count: 2
downvote count: 0
type: UnansweredQuestion
has body: Below is the code that I have been working with to replace some values with np.NaN. My issue is how to replace'47614750_h' at index 111 with np.NaN. I can do this directly with drop_list, however, I need to iterate this with different values ending in '_h' over many files and would like to do this automatically. I have tried some searches on regex as it seems the way to go, but could not find what i needed. drop_list = ['dash_code', 'SONIC WELD'] df_clean.replace(drop_list, np.NaN).tail(10) DASH_CODE Name Quantity 107 1011567 .156 MALE BULLET TERM INSUL 1.0 108 102066901 .032 X .187 FEMALE Q.D. TERM. 1.0 109 105137901 TERM,RING,10-12AWG,INSULATED 1.0 110 101919701 1/4 RING TERM INSUL 2.0 111 47614750001_h HARNESS, MAIN, AC, LIO 1.0 112 NaN NaN 19.0 113 7685 5/16 RING TERM INSUL. 1.0 114 102521601 CLIP,HARNESS 2.0 115 47614808001 CAP, RESISTOR, TERMINATION 1.0 116 103749801 RECPT, DEUTSCH, DTM04-4P 1.0
favorite count: 0
has title: Replacing a pandas DataFrame value with np.nan when the values ends with '_h'
has answer: http://stackoverflow.com/a/47085006
has comment: http://stackoverflow.com/comment/81119282
tagged with: pandas
has comment: http://stackoverflow.com/comment/81141942
tagged with: python

http://stackoverflow.com/comment/81325176
type: Comment
has text: @SebastianWozny Are you hinting at something?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47187838

http://stackoverflow.com/q/47119468
tagged with: python
has comment: http://stackoverflow.com/comment/81189000
tagged with: module
tagged with: import
has comment: http://stackoverflow.com/comment/81196440
has comment: http://stackoverflow.com/comment/81188819
type: Question
linked to: http://stackoverflow.com/q/47118098
has comment: http://stackoverflow.com/comment/81188676
upvote count: 1
type: UnansweredQuestion
has title: importing custom python modules.. why do only some elements carry over?
has comment: http://stackoverflow.com/comment/81188860
downvote count: 1
favorite count: 0
tagged with: class
has comment: http://stackoverflow.com/comment/81188677
has body: I need to create a python module that many scripts need to ultimately import from: Custom arg parsing to set format and constant args (i.e. my verbose and help args, and everything visually pleasing/consistent across scripts) My custom module is currently working independently and I'm satisfied enough to move forward for now, but I can't seem to import it into another script properly. THAT module imports another module (ver.py) defining a simple variable constant with no issues (a version code I want to exist in only one location). But when I try to import that file into another (e.g. myexecutable.py) and add code for parsing additional arguments, it fails. Also, I have _ _init__.py in the dir which contains all of the files I'm working with right now. This code has changed so much and I can't get it back to a "partially working" state, but I can get it to have no errors. Here's what's not throwing errors: #!/usr/bin/env python import argparse import par as pp ##par.py is my working parsing code pp.preq.add_argument('input', metavar=" INPUT.ext", type=argparse.FileType('rt')) pp.preq.add_argument('output', metavar=" OUTPUT.ext", type=argparse.FileType('wt')) Of note, I am hoping to define the 'description' and 'usage' in the executed file, not the imported file. Here's a subset of what the imported file (par.py) has: class USAGEformat(argparse.RawTextHelpFormatter): def add_usage(self, usage, actions, groups, prefix=None): if prefix is None: prefix = 'nameconstant '+v.VERSION+'\n\nUSAGE: '+prog super(USAGEformat, self).add_usage(usage, actions, groups, prefix) parse = argparse.ArgumentParser(add_help=False, formatter_class=USAGEformat) preq = parse.add_argument_group("___________________\n++ COMPULSORY ARGS") When I try to add in anything more with ArgumentParser, it doesn't recognize my USAGEformat class. At some point I got my script to recognize it partially, and take my defined usage but not my defined description or compulsory arguments. Can't figure out what I…
score: 0
has comment: http://stackoverflow.com/comment/81189786
has comment: http://stackoverflow.com/comment/81198417
tagged with: argparse
has answer: http://stackoverflow.com/a/47124352
answer count: 1

http://stackoverflow.com/comment/109316594
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52309010
has text: doesn't iterrows slow down processing by a lot?
score: 3

http://stackoverflow.com/comment/81099574
comment on: http://stackoverflow.com/a/47075301
has text: Thank you it's working. But I need only correlation between one row vs all the rest. Your solution calculates all row pairs correlations.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/117166085
comment on: http://stackoverflow.com/q/47096120
type: Comment
type: QuestionComment
has text: Does this answer your question? [How do I protect Python code?](https://stackoverflow.com/questions/261638/how-do-i-protect-python-code)
score: 0

http://stackoverflow.com/comment/81187665
score: 1
type: Comment
type: QuestionComment
has text: You should use the `a` mode, otherwise you re-write your file each time. Also, write your headers just once...
comment on: http://stackoverflow.com/q/47118937

http://stackoverflow.com/comment/81300933
type: AnswerComment
has text: I see it now. first column is not count, because index, so need `df = df.drop_duplicates(subset=[df.columns[2]], keep=False)` - check 3.rd column.
comment on: http://stackoverflow.com/a/47175265
type: Comment
score: 0

http://stackoverflow.com/comment/81224046
score: 0
comment on: http://stackoverflow.com/a/47137233
type: Comment
type: AnswerComment
has text: No problem, I add more possible solutions. Good luck!

http://stackoverflow.com/comment/81292134
type: Comment
comment on: http://stackoverflow.com/q/47170523
type: QuestionComment
score: 0
has text: It means you are unpacking the arrary values with the asterisk (*) unpack means use all the values at once.

http://stackoverflow.com/a/47157304
has comment: http://stackoverflow.com/comment/81263775
type: Answer
has comment: http://stackoverflow.com/comment/81263963
answers question: http://stackoverflow.com/q/47156680
has comment: http://stackoverflow.com/comment/81264682
has comment: http://stackoverflow.com/comment/81264641
downvote count: 0
type: AcceptedAnswer
has body: You may use \b((?:\d+|\d{1,3}(?:[,.\s]\d{3})*)(?:[,.\s]*\d+)?)\s(?:euros?|€) See the regex demo Details \b - a word boundary ((?:\d+|\d{1,3}(?:[,.\s]\d{3})*)(?:[,.\s]*\d+)?) - Group 1 (?: - an alternation group start \d+ - 1+ digits | - or \d{1,3} - 1 to 3 digits (?:[,.\s]\d{3})* - 0+ sequences of [,.\s] - 1 whitespace, , or . \d{3} - 3 digits ) - end of the alternation group (?:[,.\s]*\d+)? - an optional group of [,.\s]* - 0+ whitespaces, , or . \d+ - 1 or more digits \s - a whitespace (?:euros?|€) - either euro, euros or €
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47156680

http://stackoverflow.com/a/47194569
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47193373
upvote count: 1
type: Answer
has body: Here is how to make your approach work. First, why does the list comp work in-place, whereas the in1d doesn't? The list comp operates on individual rows of arr_first, each such row is a "view", i.e. a reference into arr_first. By contrast, the in1d soln creates a mask which is then applied to the array. Using masks is one form of "fancy" or "advanced" indexing. Since the subset of the orig array fancy indexing refers to will typically not be representable by offsets and strides this forces a copy and whatever you do afterwards will not affect the orig array. One easy fix is to not apply the mask. Instead convert it to a vector of row indices and use random.choice directly on this vector: import numpy as np import random arr_first = np.array([[0,0,0,0],[0,0,0,0],[1,1,1,0],[1,1,1,0],[1,1,1,0],[1,1,2,0],[1,1,2,0],[2,2,2,0]]) arr_second = np.array([[0,0,0],[1,1,1],[1,1,2],[2,2,2]]) for i in range(len(arr_second)): filtered_idx = np.where(np.in1d(arr_first[:, 0], arr_second[i][0]) &amp; np.in1d(arr_first[:, 1], arr_second[i][1]) &amp; np.in1d(arr_first[:, 2], arr_second[i][2]))[0] choosen_block = random.choice(filtered_idx) arr_first[choosen_block, 3] += 32 print(arr_first) Sample output: [[ 0 0 0 0] [ 0 0 0 32] [ 1 1 1 32] [ 1 1 1 0] [ 1 1 1 0] [ 1 1 2 0] [ 1 1 2 32] [ 2 2 2 32]]

http://stackoverflow.com/q/47123353
has comment: http://stackoverflow.com/comment/81198122
type: Question
has comment: http://stackoverflow.com/comment/81197894
has comment: http://stackoverflow.com/comment/81198010
tagged with: anaconda
has comment: http://stackoverflow.com/comment/81197942
has comment: http://stackoverflow.com/comment/81197162
accepted answer: http://stackoverflow.com/a/49828092
tagged with: python
has title: Python- error in importing rllab
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/16069816
score: 0
has body: I installed rllab successfully: $ source activate rllab3 (rllab3) $ Python 3.5.2 :: Continuum Analytics, Inc. (rllab3) $ import rllab (rllab3) $ but when I try to import other libraries: (rllab3) $ from rllab.algos.trpo import TRPO from: can't read /var/mail/rllab.algos.trpo (rllab3) $ from rllab import rllab from: can't read /var/mail/rllab I can understand why this happens. I defined the environment variable export PYTHONPATH="${PYTHONPATH}:/home/b**/rllab3" when I am trying to load it from spyder: [] import rllab Traceback (most recent call last): File "&lt;ipython-input-1-6bfd29d10263&gt;", line 1, in &lt;module&gt; import rllab ModuleNotFoundError: No module named 'rllab' I can't figure the problem. If the problem is with environment variable, can anyone help me to fix it? I can not find where were rllab is installed on my system (I installed it with anaconda)
has comment: http://stackoverflow.com/comment/81200635
has comment: http://stackoverflow.com/comment/81198187
has comment: http://stackoverflow.com/comment/128240526
answer count: 1
has answer: http://stackoverflow.com/a/49828092

http://stackoverflow.com/a/47096124
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47091028
downvote count: 0
has body: In a parameterized query, parameters can only be used to supply column values, not column names. Therefore, you need to use string manipulation to insert the column name and then use a parameter to specify the value. For example, with Python3: column_name = 'param1' column_value = 'param2' cursor.execute(f"UPDATE ttt SET status = 'Good' WHERE [{column_name}] = %s", (column_value,)) In Python2 column_name = 'param1' column_value = 'param2' sql = "UPDATE ttt SET status = 'Good' WHERE [{}] = %s".format(column_name) cursor.execute(sql, (column_value,))
accepted answer of: http://stackoverflow.com/q/47091028
has comment: http://stackoverflow.com/comment/81144261
has comment: http://stackoverflow.com/comment/81142478
type: Answer
has comment: http://stackoverflow.com/comment/124363255
score: 2
has comment: http://stackoverflow.com/comment/81145608

http://stackoverflow.com/comment/82887807
type: AnswerComment
comment on: http://stackoverflow.com/a/47084451
score: 0
has text: I am wishing you a Merry Christmas! And thank you for all support, so small present for you (3+). Good luck!
type: Comment

http://stackoverflow.com/q/47072224
has title: Django ORM get jobs with top 3 scores for each model_used
tagged with: django-rest-framework
answer count: 1
downvote count: 1
favorite count: 0
tagged with: postgresql
type: Question
has body: Models.py: class ScoringModel(models.Model): title = models.CharField(max_length=64) class PredictedScore(models.Model): job = models.ForeignKey('Job') candidate = models.ForeignKey('Candidate') model_used = models.ForeignKey('ScoringModel') score = models.FloatField() created_at = models.DateField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) serializers.py: class MatchingJobsSerializer(serializers.ModelSerializer): job_title = serializers.CharField(source='job.title', read_only=True) class Meta: model = PredictedScore fields = ('job', 'job_title', 'score', 'model_used', 'candidate') To fetch the top 3 jobs, I tried the following code: queryset = PredictedScore.objects.filter(candidate=candidate) jobs_serializer = MatchingJobsSerializer(queryset, many=True) jobs = jobs_serializer.data top_3_jobs = heapq.nlargest(3, jobs, key=lambda item: item['score']) Its giving me top 3 jobs for the whole set which contains all the models. I want to fetch the jobs with top 3 scores for a given candidate for each model used. So, it should return the top 3 matching jobs with each ML model for the given candidate. I followed this answer https://stackoverflow.com/a/2076665/2256258 . Its giving the latest entry of cake for each bakery, but I need the top 3. I read about annotations in django ORM but couldn't get much about this issue. I want to use DRF serializers for this operations. This is a read only operation. I am using Postgres as database. What should be the Django ORM query to perform this operation?
accepted answer: http://stackoverflow.com/a/47079417
tagged with: python
has comment: http://stackoverflow.com/comment/81102192
has answer: http://stackoverflow.com/a/47079417
has comment: http://stackoverflow.com/comment/81097471
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/13076822
linked to: http://stackoverflow.com/q/2074514
tagged with: django
upvote count: 1

http://stackoverflow.com/comment/81155953
type: Comment
comment on: http://stackoverflow.com/q/47094680
type: QuestionComment
score: 0
has text: please join chatroom

http://stackoverflow.com/comment/81237381
type: AnswerComment
comment on: http://stackoverflow.com/a/47142981
score: 0
type: Comment
has text: Now the color bar simply disappeared.

http://stackoverflow.com/comment/81247813
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47128013
has text: yes, it can show the content on the browser, but I need to save the image and importantly get the latest image from the updated timestamp
type: Comment

http://stackoverflow.com/q/47144326
has comment: http://stackoverflow.com/comment/81241425
answer count: 0
has comment: http://stackoverflow.com/comment/81241128
tagged with: pyqt
has comment: http://stackoverflow.com/comment/81240379
upvote count: 3
has comment: http://stackoverflow.com/comment/81240610
downvote count: 0
has title: PYQT Drawing on top of QGraphicsPixmapItem picture
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/81238944
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81241013
has comment: http://stackoverflow.com/comment/81241238
tagged with: python-3.x
has body: Hello I'm having some trouble getting QPainter to draw on top of a photo that has been loaded into a QGraphicsPixmapItem Goal I would like to be able to draw a circle on top of a picture that has been loaded into QGraphicsPixmapItem everytime the mouse is clicked. Also, I would like to be able to keep track of the circles so that if the user wishes to delete or move one or all of them later they can. I was thinking a list or directory. I don't know which would be more appropriate. Any help will be greatly appreciated! Current GraphicsArea.py file import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from GraphicsArea_GUI import * from QGraphicsView import * class LogObject(QObject): MousePixmapSignal = pyqtSignal(QPoint, QColor) pointDraw = pyqtSignal(QPoint) class PictureItem(QGraphicsPixmapItem): def __init__(self, log,*args, **kwargs): QGraphicsPixmapItem.__init__(self,*args, **kwargs) self.setAcceptHoverEvents(True) self.log = log def hoverMoveEvent(self, event): point = event.pos().toPoint() color = QColor(self.pixmap().toImage().pixel(point.x(), point.y())) self.log.MousePixmapSignal.emit(point, color) QGraphicsPixmapItem.hoverMoveEvent(self, event) def hoverEnterEvent(self, event): QApplication.setOverrideCursor(Qt.CrossCursor) QGraphicsPixmapItem.hoverMoveEvent(self, event) def hoverLeaveEvent(self, event): QApplication.setOverrideCursor(Qt.ArrowCursor) QGraphicsPixmapItem.hoverLeaveEvent(self, event) def mousePressEvent(self,event): point = event.pos().toPoint() self.log.pointDraw.emit(point) QGraphicsPixmapItem.mousePressEvent(self, event) class LoadPicture(QWidget, Ui_GraphicsArea): def __init__(self, pixmap, parent=None): QWidget.__init__(self, parent) self.setupUi(self) self.pixmap = pixmap self.log = LogObject(self) self.scene = self.PictureArea.setScene(QGraphicsScene()) self.item = PictureItem(self.log,pixmap) self.PictureArea.scene().addItem(self.item) self.resize(pixmap.size()) self.log.pointDraw.connect(self…
score: 3
tagged with: qgraphicsitem
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81242464

http://stackoverflow.com/comment/81115508
type: QuestionComment
comment on: http://stackoverflow.com/q/47082410
has text: @mrjlp i was mistaken, i dont want to úp' the scores if a player has multplie score becuz he was in several contests. that player keeps only his highest score.
score: 0
type: Comment

http://stackoverflow.com/q/47084509
has answer: http://stackoverflow.com/a/70940536
accepted answer: http://stackoverflow.com/a/47084774
upvote count: 1
has comment: http://stackoverflow.com/comment/81119252
favorite count: 0
has answer: http://stackoverflow.com/a/47084774
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81118327
answer count: 3
score: 1
has answer: http://stackoverflow.com/a/59536169
has body: I have the following problem: Given a year and a month, determine the week numbers that are contained in that particular month, i.e., October 2017 contains week numbers 39,40,41,42,43,44. Caveat: As a rule, week starts in Monday and ends in Sunday. I have a cumbersome code that does the trick but I would like to know if there is a more elegant or Pythonistic way of doing this. from datetime import datetime import calendar def get_week_numbers_in_month(year,month): list_of_weeks = [] initial_day = 1 ending_day = calendar.monthrange(int(year),int(month))[1] #get the last day of month initial_week = int(datetime(year,month,initial_day).isocalendar()[1]) ending_week = int(datetime(year,month,ending_day).isocalendar()[1]) counter = initial_week while(counter &lt;= ending_week): list_of_weeks.append(counter) counter += 1 return list_of_weeks print("Your month contains the following weeks:\n"+str(get_week_numbers_in_month(2017,10))) # result: Your month contains the following weeks: # [39, 40, 41, 42, 43, 44]
tagged with: python
has comment: http://stackoverflow.com/comment/81118926
has comment: http://stackoverflow.com/comment/81150862
type: Question
possible better answer: http://stackoverflow.com/a/70940536
has comment: http://stackoverflow.com/comment/81133855
has comment: http://stackoverflow.com/comment/81119150
has comment: http://stackoverflow.com/comment/81118377
has title: How to determine all the week numbers in a month with Python?
downvote count: 0

http://stackoverflow.com/q/47107328
answer count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/47107760
has title: regarding the usage of np.all along with axis
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/81165032
has comment: http://stackoverflow.com/comment/81165308
has answer: http://stackoverflow.com/a/47107760
accepted answer: http://stackoverflow.com/a/47107524
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47107524
has body: I tried to test the usage of np.all, the test array a is a=array([[[ 0, 0, 0], [ 0, 0, 0], [ 0, 0, 0], [ 0, 0, 0]], [[ 0, 0, 255], [255, 255, 255], [ 0, 0, 0], [255, 0, 0]]]) b = [255,0,255] c = np.all(a==b,axis=1) I got c= array([[False, True, False], [False, False, False]], dtype=bool) I don't understand how was TRUE in c obtained from running np.all(a==b,axis=1).
downvote count: 0
tagged with: scipy
favorite count: 0
tagged with: numpy
tagged with: python-3.x
type: Question

http://stackoverflow.com/comment/81190090
has text: @UpmostScarab yes
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47120159

http://stackoverflow.com/q/47178793
has body: I don't know why this probelm , all the time the varaiable of parameters out of range , and now also the problem is for code and give me this eroor object of type 'Bounds' has no len(): (I hope i can find the error in my code or find other good code for using bounds of variabels) Traceback (most recent call last): File "./trigger_SLQ.py", line 160, in &lt;module&gt; main() File "./trigger_SLQ.py", line 156, in main opt(x0) File "./trigger_SLQ.py", line 148, in opt res = basinhopping(rmse, x0, minimizer_kwargs=minimizer_kwargs, T=10000.0, stepsize=1.0, niter=100, niter_success=200, accept_test=bounds) File "/usr/lib/python3/dist-packages/scipy/optimize/_basinhopping.py", line 611, in basinhopping accept_tests, disp=disp) File "/usr/lib/python3/dist-packages/scipy/optimize/_basinhopping.py", line 72, in __init__ minres = minimizer(self.x) File "/usr/lib/python3/dist-packages/scipy/optimize/_basinhopping.py", line 280, in __call__ return self.minimizer(self.func, x0, **self.kwargs) File "/usr/lib/python3/dist-packages/scipy/optimize/_minimize.py", line 455, in minimize constraints, callback=callback, **options) File "/usr/lib/python3/dist-packages/scipy/optimize/slsqp.py", line 329, in _minimize_slsqp if bounds is None or len(bounds) == 0: TypeError: object of type 'Bounds' has no len() I use this code b0 = (5, 95) b1 = (0.10, 0.95) b2= (2, 8) bounds=((5, 95), (0.10, 0.95), (2, 8)) class Bounds(object): def __init__(self, xmax=[0,0,2], xmin=[100,0.100,8], stepsize=0.01): self.xmax = np.array(xmax) self.xmin = np.array(xmin) self.stepsize = stepsize def __call__(self, x): min_step = np.maximum(self.xmin - x, -self.stepsize) max_step = np.minimum(self.xmax - x, self.stepsize) random_step = np.random.uniform(low=min_step, high=max_step, size=x.shape) xnew = x + random_step return xnew bounded_step = Bounds(np.array([b[0] for b in bounds]), np.array([b[1] for b in bounds]), np.array([b[2] for b in bounds])) def opt(x0): bounds = Bounds() minimizer_kwargs = {'method':'SLSQP…
has comment: http://stackoverflow.com/comment/81308506
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81310043
linked to: http://stackoverflow.com/q/47055970
has comment: http://stackoverflow.com/comment/81311462
has comment: http://stackoverflow.com/comment/81309330
has comment: http://stackoverflow.com/comment/81310247
tagged with: python
has comment: http://stackoverflow.com/comment/81309746
tagged with: optimization
has comment: http://stackoverflow.com/comment/81311400
answer count: 0
has title: i have error in code when i use basin hopping scipy
has comment: http://stackoverflow.com/comment/81311750
score: 0
has comment: http://stackoverflow.com/comment/81310057
has comment: http://stackoverflow.com/comment/81307927
has comment: http://stackoverflow.com/comment/81311808
has comment: http://stackoverflow.com/comment/81309729
tagged with: scipy
has comment: http://stackoverflow.com/comment/81308475
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81309335

http://stackoverflow.com/q/47084844
has body: when trying to save my map i get the following error 'KeyError Traceback (most recent call last) &lt;ipython-input-31-65c9bba51b6f&gt; in &lt;module&gt;() 7 # Create Folium plot 8 #map.save('plot_data.html') ----&gt; 9 map.save(outfile= "test.html") KeyError: 'ATA' this is my code, here i am trying to bind the pandas data frame and the json geometries to create an overlay for visualisation of data import folium import pandas as pd country_geo = './world-development-indicators/world-countries.json' data = pd.read_csv('world-development-indicators/Indicators.csv') hist_indicator = 'CO2 emissions \(metric' hist_year = 2011 mask1 = data['IndicatorName'].str.contains(hist_indicator) mask2 = data['Year'].isin([hist_year]) stage = data[mask1 &amp; mask2] plot_data = stage'CountryCode','Value' hist_indicator = stage.iloc[0]['IndicatorName'] map = folium.Map(location=[100, 0], zoom_start=1) map.choropleth(geo_path=country_geo, data=plot_data, columns=['CountryCode', 'Value'], key_on='feature.id', fill_color='YlGnBu', fill_opacity=0.7, line_opacity=0.2, legend_name=hist_indicator) map.save('plot_data.html')
has comment: http://stackoverflow.com/comment/81143367
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81140609
tagged with: python
tagged with: folium
linked to: http://stackoverflow.com/q/38014480
has comment: http://stackoverflow.com/comment/81119981
score: 0
tagged with: visualization
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/81144552
has comment: http://stackoverflow.com/comment/82152972
tagged with: data-science
type: Question
has comment: http://stackoverflow.com/comment/81192978
has comment: http://stackoverflow.com/comment/81142562
has title: Folium map KeyError ATA while saving

http://stackoverflow.com/comment/81289292
has text: Thank you for your help I have fixed that issue now its just the issue of the list not appending....
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47169711

http://stackoverflow.com/a/47134728
answers question: http://stackoverflow.com/q/47133737
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82068556
has comment: http://stackoverflow.com/comment/81304189
accepted answer of: http://stackoverflow.com/q/47133737
has body: Give this a shot and tell me this is not what you wanted: from bs4 import BeautifulSoup import requests incl_page_url = "https://www.triodos.com/en/investment-management/socially-responsible-investment/sustainable-investment-universe/companies-atmf1/" page = requests.get(incl_page_url).text soup = BeautifulSoup(page, "lxml") for items in soup.select(".splitColumn p"): title = '\n'.join([item for item in items.strings]) print(title) Result: 3iGroup 8point3 Energy Partners A ABN AMRO Accell Group Accsys Technologies Achmea Acuity Brands Adecco Adidas Adobe Systems
has comment: http://stackoverflow.com/comment/81304033
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81311481
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47069516
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81086906
has answer: http://stackoverflow.com/a/47069677
answer count: 2
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81086903
accepted answer: http://stackoverflow.com/a/47069795
linked to: http://stackoverflow.com/q/42820548
type: Question
has answer: http://stackoverflow.com/a/47069795
has comment: http://stackoverflow.com/comment/81086847
has title: comparing the values of a dictionary
tagged with: python
tagged with: dictionary
score: -3
downvote count: 4
has body: I have two dictionaries dic_1 and dic_2. dic_1={"HI":"HELLO" , "NAME":"XYZ"} dic_2={"HI" : "HELLO" , "NAME" : "XYZ" , "AGE" : "YY"} I want to compare the key ,value pairs of these two dictionaries.If the values are same then output should print "YES" else "NO". It should check the values of the common keys in both dictionaries.
possible better answer: http://stackoverflow.com/a/47069677
has comment: http://stackoverflow.com/comment/81087174

http://stackoverflow.com/q/47143233
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/81250722
downvote count: 0
has comment: http://stackoverflow.com/comment/81249397
has title: Footer string not showing on view - Odoo v8
has comment: http://stackoverflow.com/comment/81250694
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47150678
accepted answer: http://stackoverflow.com/a/47150678
has comment: http://stackoverflow.com/comment/81249865
tagged with: odoo
tagged with: odoo-8
tagged with: python
has body: I'm having an issue trying to show the field string on my view, I'm trying to add two fields, to the footer of my view, and the fields are showing up, but not the strings. Here's my view: worksheet.form mrp.worksheet.contract form As You can see, I've put the string flag even on view, they have those strings on .py file as well, but they won't show up either. Any ideas?
has answer: http://stackoverflow.com/a/47150028
possible better answer: http://stackoverflow.com/a/47150028
has comment: http://stackoverflow.com/comment/81250749

http://stackoverflow.com/comment/81239105
type: QuestionComment
has text: Where do these strings come from? If you wrote `'No\xebl'` in your source code, stick a `u` there in your source code. If you're getting these strings from some external source, like a file or a web page, you will need to determine the source's encoding and decode it.
comment on: http://stackoverflow.com/q/47144509
score: 0
type: Comment

http://stackoverflow.com/a/47113860
answers question: http://stackoverflow.com/q/47111880
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Use systemd on Ubuntu, /etc/systemd/system, for a simple setup (probably not ideal for a production setup though). I do this sometimes for Python Flask app that I'm prototyping. First, put your application code in /opt/my-app. I usually just cd /opt and git clone a repo there. Then, create a file called /etc/systemd/system/my-app.service. In that file, add the following: [Unit] Description=My App daemon After=network.target postgresql.service Wants=postgresql.service [Service] EnvironmentFile=/etc/sysconfig/my-app WorkingDirectory=/opt/my-app/ # &lt;- this is where your app lives User=root Group=root Type=simple ExecStart=/usr/bin/python server.py # &lt;- this starts your app Restart=always RestartSec=5s [Install] WantedBy=multi-user.target Next, paste any environment variables you have into a file called /etc/sysconfig/my-app like: DB_HOST=localhost DB_USER=postgres DB_PASSWORD=postgres DB_NAME=postgres Then you can do: service my-app start service my-app stop service my-app restart and then you can hit the app running on the servers IP and port (just like if you ran python app.py or python server.py. To check the logs for your daemon process, if it doesn't seem to work out, you can run: journalctl -u my-app -e In production, I'm not sure this is the best setup, probably better to look into something like ngnix. But I do this for prototypes all the time and it's pretty great.
type: Answer
accepted answer of: http://stackoverflow.com/q/47111880
has comment: http://stackoverflow.com/comment/81181178

http://stackoverflow.com/a/47118317
answers question: http://stackoverflow.com/q/47118098
has body: import argparse version = "1.0" class USAGEformat(argparse.RawDescriptionHelpFormatter): def add_usage(self, usage, actions, groups, prefix=None): if prefix is None: prefix = 'nameconstant version '+ version+' USAGE: ' return super(USAGEformat, self).add_usage( usage, actions, groups, prefix) parser = argparse.ArgumentParser(add_help=False, formatter_class=USAGEformat, description=\ '''several lines of text describing my program.. because it will be necessary''') gp1 = parser.add_argument_group('___________________\nCOMPULSORY ARGS') gp1.add_argument('input', metavar="input.ext", type=argparse.FileType('rt')) gp1.add_argument('output', metavar="output.ext", type=argparse.FileType('wt')) gp2 = parser.add_argument_group('___________________\nOPTIONAL ARGS') gp2.add_argument('-v', '--verbose', action='store_true', default=False, help='print debugging messages to terminal') gp2.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS) parser.print_help() produces 2156:~/mypy$ python stack47118098.py nameconstant version 1.0 USAGE: stack47118098.py [-v] [-h] input.ext output.ext several lines of text describing my program.. because it will be necessary ___________________ COMPULSORY ARGS: input.ext output.ext ___________________ OPTIONAL ARGS: -v, --verbose print debugging messages to terminal -h, --help RawDescriptionHelpFormatter preserves the formatting of the description. I used the '''...''' for the description just to make the code look nicer; that's not important. I substituted argument_groups for your renaming of the existing groups. Your way works fine, but I think mine is what the developers intended. HelpFormatter formats the various pieces, with a generous use of \n between them, and then ends up stripping out duplicates (including the end). So we'd have to identify and modify the relevant method (format_help). You've made some changes on the usage line since I started my answer. I agree with the comment that required arguments are shown, by conv…
type: Answer
has comment: http://stackoverflow.com/comment/81186651
score: 0

http://stackoverflow.com/q/47068395
tagged with: python
tagged with: pyodbc
favorite count: 0
has comment: http://stackoverflow.com/comment/81086452
score: 0
has comment: http://stackoverflow.com/comment/81084798
has body: I'm here trying to parse JSON string that comes from a sql table, but while parsing it is giving the error TypeError: string indices must be integers at line result = json_normalize(json_st,'results') here is the code snippet from pandas.io.json import json_normalize import pyodbc cnxn = pyodbc.connect('connection string') cursor = cnxn.cursor() cursor.execute("select TOP 1 GEOCODE_ID, JSON from GEOCODE_TBL where GEOCODE_ID = 20") ID=[] JSON=[] for row in cursor.fetchall(): ID.append(row[0]) JSON.append(row[1]) json_st1 = json.dumps(JSON) json_st=json.loads(json_st1) result = json_normalize(json_st,'results') Any suggestion on this will be helpful. Thanks Domnick.
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47070031
type: Question
has title: Python Error:"TypeError: string indices must be integers"
upvote count: 1
type: UnansweredQuestion
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/81418567
has text: Since this was mentioned: `splprep` doesn't allow repeating points, throwing an exception. Also, I answered the question as it was stated but frankly, interpreting "clamped" as zero derivative of a parametric curve doesn't make much sense. Clamping would mean the derivative should be set to some nonzero vector which specifies the initial direction of spline curve. (In non-parametric case, we often want horizontal direction, which means zero dy/dx derivative; but the parametric case is different). In any case, this is also possible with the `bc_type` parameter described below.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47089749

http://stackoverflow.com/q/47105208
has comment: http://stackoverflow.com/comment/81226538
has comment: http://stackoverflow.com/comment/81160986
has title: 'GeneratorContextManager' Object does not support indexing
score: -1
type: Question
tagged with: python-2.7
has body: I am trying to load .p12 certificate by converting it into pem cert and key as found through this github source My code looks like this @contextlib.contextmanager def pfx_to_pem(pfx_path, pfx_password): ''' Decrypts the .pfx file to be used with requests. ''' with tempfile.NamedTemporaryFile(suffix='.pem') as t_pem: f_pem = open(t_pem.name, 'wb') pfx = open(pfx_path, 'rb').read() p12 = OpenSSL.crypto.load_pkcs12(pfx, pfx_password) f_pem.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, p12.get_privatekey())) f_pem.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, p12.get_certificate())) ca = p12.get_ca_certificates() if ca is not None: for cert in ca: f_pem.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)) f_pem.close() yield t_pem.name cert = pfx_to_pem(clientCert,password) when I execute this, I keep getting an error that says File "F:\code\InforSTS\scripts\loadDefaultDataV2.py", line 87, in &lt;module&gt; res4 = requests.get(gridEndpoint,headers = headers, cert=cert, verify=False) File "C:\Python27\lib\site-packages\requests\api.py", line 72, in get return request('get', url, params=params, **kwargs) File "C:\Python27\lib\site-packages\requests\api.py", line 58, in request return session.request(method=method, url=url, **kwargs) File "C:\Python27\lib\site-packages\requests\sessions.py", line 518, in request resp = self.send(prep, **send_kwargs) File "C:\Python27\lib\site-packages\requests\sessions.py", line 639, in send r = adapter.send(request, **kwargs) File "C:\Python27\lib\site-packages\requests\adapters.py", line 405, in send self.cert_verify(conn, request.url, verify, cert) File "C:\Python27\lib\site-packages\requests\adapters.py", line 240, in cert_verify conn.cert_file = cert[0] TypeError: 'GeneratorContextManager' object does not support indexing How do I get a certificate from this cert object? It is clear that it is not an array.
downvote count: 2
answer count: 1
upvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: object
accepted answer: http://stackoverflow.com/a/47218575
has answer: http://stackoverflow.com/a/47218575
tagged with: python

http://stackoverflow.com/a/47117972
has comment: http://stackoverflow.com/comment/98737837
has comment: http://stackoverflow.com/comment/95846404
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/95844802
has comment: http://stackoverflow.com/comment/97057899
answers question: http://stackoverflow.com/q/47117758
score: 2
downvote count: 0
has body: Because you are executing a command ( other than env or something similar) to get those config variables it means that most likely they are NOT in your normal environment, meaning you can't get them through os.environ.get(). What you can do would be to extract them from the output of that very command (the example - python 2.7 - assumes they come out on stdout, if they're not also check stderr in the same way): from subprocess import Popen, PIPE graphenedb_url = graphenedb_user = graphenedb_pass = None stdout, stderr = Popen(['heroku', 'config'], stdout=PIPE, stderr=PIPE).communicate() for line in stdout.split('\n'): split = line.split(':') if len(split) == 2: if split[0] == 'GRAPHENEDB_BOLT_URL': graphenedb_url = split[1].strip() elif split[0] == 'GRAPHENEDB_BOLT_USER': graphenedb_user = split[1].strip() elif split[0] == 'GRAPHENEDB_BOLT_PASSWORD': graphenedb_pass = split[1].strip() print graphenedb_url print graphenedb_user print graphenedb_pass Notes: the example is python 2.7 it assumes the info comes out on stdout, if not check stderr as well, in the same way you may need to use the full path for the heroku executable, not sure.
has comment: http://stackoverflow.com/comment/97060013
has comment: http://stackoverflow.com/comment/95878525

http://stackoverflow.com/q/47128166
has title: python matplotlib 2.x axis autolimit
has body: I've got a problem with matplotlib 2.x code not reproducing 1.x behaviour, when it comes to choosing the auto-limits on the axes. According to https://matplotlib.org/users/dflt_style_changes.html , version 1.x axis rounding should be reproduced by the using the commands: mpl.rcParams['axes.autolimit_mode'] = 'round_numbers' mpl.rcParams['axes.xmargin'] = 0 mpl.rcParams['axes.ymargin'] = 0 But it doesn't. See the code below. My y values range from just above 5 to just below 50. When I run the code: with classic (version 1.x) behaviour (sys.argv[1]=="1"), the y axis ticks are 5 and 50. with version 2.x behaviour (sys.argv[1]=="2") the y axis ticks are 0 and 60. Version 2.x rounding appears to be coarser. How do I reproduce version 1.x rounding? import sys import matplotlib.pyplot as plt import matplotlib as mpl if sys.argv[1]=="1": import matplotlib.style matplotlib.style.use('classic') elif sys.argv[1]=="2": mpl.rcParams['axes.autolimit_mode'] = 'round_numbers' mpl.rcParams['axes.xmargin'] = 0 mpl.rcParams['axes.ymargin'] = 0 else: raise Exception("param must be 1 or 2") z = [49.0, 14.5, 6.0, 5.8] steps = len(z) plt.clf() plt.figure(figsize=(8,6)) # Matplotlib 1.x default plt.subplot(311) plt.plot(range(steps), z) plt.xlim(xmin=0, xmax=steps-1) plt.xticks(range(steps)) ymin, ymax = plt.ylim() plt.yticks([ymin, ymax]) plt.savefig("mpltest%s.pdf" % sys.argv[1])
has comment: http://stackoverflow.com/comment/81217230
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81206453
tagged with: matplotlib
tagged with: axis-labels
tagged with: python
accepted answer: http://stackoverflow.com/a/47139048
type: Question
score: 0
has answer: http://stackoverflow.com/a/47139048
answer count: 1

http://stackoverflow.com/q/47067985
tagged with: python
tagged with: comparison
has answer: http://stackoverflow.com/a/47068058
score: 0
has answer: http://stackoverflow.com/a/47068241
has title: Python: how to check if one string in a list is part of any strings in anther list
tagged with: string
has answer: http://stackoverflow.com/a/47068615
has body: my code works like this if listOne = ['hello','hi','bye'] listTwo = ['goodbye','bye'] for x in range(0,len(listOne)) listOne[x] in listTwo &gt;&gt;&gt;True but consider this situation: listOne = ['hello','hi','bye'] listTwo = ['goodbye','by'] for x in range(0,len(listOne): listOne[x] in listTwo &gt;&gt;&gt;False My need is to find if strings in listTwo are part of strings in listOne. However, I need to have each loop checking one item in listOne to all in listTwo on each instance Thanks!!
type: Question
has answer: http://stackoverflow.com/a/47068045
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47068348

http://stackoverflow.com/q/47198319
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: google-app-engine-python
tagged with: python
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/81598465
downvote count: 0
has comment: http://stackoverflow.com/comment/81345251
has title: Got ModuleNotFoundError: No module named 'google.appengine' even after install google app engine SDK
has body: I installed the latest Google-App engine and everything is set up. I still cannot use app engine library. Google docs are not helpful on this part. Here is the command I used in jupyter notebook. Python version is 3.6. Command used and the trace-back error (print-screen): from google.appengine.api import images ModuleNotFoundError Traceback (most recent call last) in () ----> 1 from google.appengine.api import images ModuleNotFoundError: No module named 'google.appengine' Can anyone help me to fix this issue? Thank you!
favorite count: 0
tagged with: jupyter-notebook
type: Question
has comment: http://stackoverflow.com/comment/81534526
answer count: 0

http://stackoverflow.com/comment/81092187
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47071931
has text: Or instead of testing for odd numbers use i += 2 in the loop (i.e. `while i <= num: s+= i`). Works also.

http://stackoverflow.com/comment/81288388
type: Comment
type: AnswerComment
has text: Actually if you're using Numpy you should probably use Numpy to do this. You might want to hold off on that green tick and see if juanpa.arrivallaga comes through.
score: 0
comment on: http://stackoverflow.com/a/47169076

http://stackoverflow.com/comment/81137318
comment on: http://stackoverflow.com/q/47093661
type: Comment
has text: @MaheshKaria But the problem is both processes are in same way first it will print and save it to a log file.
score: 0
type: QuestionComment

ide
tags question: http://stackoverflow.com/q/47102651
tag name: ide
type: Tag

del
tag name: del
tags question: http://stackoverflow.com/q/47080385
tags question: http://stackoverflow.com/q/47222099
type: Tag

http://stackoverflow.com/comment/112280513
type: Comment
comment on: http://stackoverflow.com/a/47093979
has text: Different context: But the 'xpath=//img/@src' worked for me to locate the element.
type: AnswerComment
score: 0

http://stackoverflow.com/q/47072702
has comment: http://stackoverflow.com/comment/81098182
has body: I am using scrapy 1.4,the version of twisted is 17.5.0,python is 3.6.3. html is like this： 20 when I run the spider,there is an error: item['number'] = response.xpath('//span[@class="number"]/text()').extract_first().strip() AttributeError: 'NoneType' object has no attribute 'strip' what should I do?
score: 0
answer count: 1
tagged with: scrapy
type: Question
has answer: http://stackoverflow.com/a/47072866
has title: Scrapy error : 'NoneType' object has no attribute 'strip'
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/81295963
comment on: http://stackoverflow.com/a/47172477
type: Comment
score: 0
has text: @AndyHayden I don't have a reference, but when you think about it, it is a direct result of point #2. If calling `keys()` and then `values()` preservers order, and calling `values()` and then `keys()` preserves order, it follows that calling `keys()` and then `keys`() preserves order. It is easy to give a formal proof for that.
type: AnswerComment

http://stackoverflow.com/comment/81414062
has text: @BorisSerebrov it definitely closes some of them, as you can see in the question though, there are still abut 28 open connections left after running this task. I suspect it has something to do with getting the Lock, but I'm not sure.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47106592
type: QuestionComment

http://stackoverflow.com/q/47173483
tagged with: authentication
linked to: http://stackoverflow.com/q/20424521
has title: Django REST framework custom format for all out responses
upvote count: 10
has answer: http://stackoverflow.com/a/63780771
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47324306
answer count: 2
tagged with: angularjs
has answer: http://stackoverflow.com/a/47324306
downvote count: 0
score: 10
has comment: http://stackoverflow.com/comment/81298330
tagged with: django
tagged with: python
has body: In my project I use DRF as backend and Angular as frontend. Django==1.10 djangorestframework==3.7.1 I need all responses from DRF to be in the following format. { "status": "", // 200,400,.....etc "error": "", // True, False "data": [], // data "message": "" // Success messages } Currently it is in [ { "id": 1, "name": "" }, { "id": 2, "name": "" } ] it should be { "status": "200", "error": "False", "data": [ { "id": 1, "name": "" }, { "id": 2, "name": "" } ], "message": "Success" } for this i have written a custom viewset and overridden the functions list, detail, create, update class ResponseModelViewSet(viewsets.ModelViewSet): def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) custom_data = { "status": True, "error": False, "message": 'message', "data": serializer.data } return Response(custom_data) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) custom_data = { "status": True, "error": False, "message": 'message', "data": serializer.data } return Response(custom_data, status=status.HTTP_201_CREATED, headers=headers) def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) custom_data = { "status": True, "error": False, "message": 'message', "data": serializer.data } return Response(custom_data) def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, …
tagged with: django-rest-framework
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/63780771

http://stackoverflow.com/a/47122525
answers question: http://stackoverflow.com/q/47122459
has comment: http://stackoverflow.com/comment/81195015
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47122459
has comment: http://stackoverflow.com/comment/81194790
has comment: http://stackoverflow.com/comment/81194973
score: 2
downvote count: 0
type: Answer
has body: You can use the pd.TimeGrouper + ngroup to group by time frequency. df['time'] = pd.to_datetime(df.time) df['group'] = df.set_index('time').groupby(['sensor_id', pd.TimeGrouper(freq='1H')], sort=False).ngroup().values So far, we have what we want, but we'll need to reset the group value for each sensor_id, so another groupby call is in order. df['group'] = df.groupby('sensor_id').group.apply(lambda x: x - x.min() + 1) df sensor_id event_id time group 0 A e1 2017-02-14 05:30:00 1 1 A e2 2017-02-14 05:45:00 1 2 A e3 2017-02-14 08:30:00 2 3 B e3 2017-02-14 05:20:00 1 4 B e4 2017-02-14 05:30:00 1 5 B e6 2017-02-14 05:45:00 1 6 C e1 2017-02-14 05:30:00 1 7 C e3 2017-02-14 07:30:00 2 8 C e7 2017-02-14 09:35:00 3
upvote count: 2

http://stackoverflow.com/q/47094142
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81137787
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81137751
favorite count: 0
has body: I have created a Subprocess object. The subprocess invokes a shell, I need to send the shell command provided below to it. The code I've tried: from subprocess import Popen, PIPE p = Popen(["code.exe","25"],stdin=PIPE,stdout=PIPE,stderr=PIPE) print p.communicate(input='ping 8.8.8.8') The command doesn't execute, nothing is being input into the shell. Thanks in advance.
has comment: http://stackoverflow.com/comment/81137975
tagged with: popen
has answer: http://stackoverflow.com/a/47109927
tagged with: pipe
score: 1
has comment: http://stackoverflow.com/comment/81138232
has comment: http://stackoverflow.com/comment/81138152
type: Question
has title: Send input (command) with communicate to created Subprocess Python
tagged with: subprocess
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81138193

http://stackoverflow.com/q/47122799
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47130018
accepted answer: http://stackoverflow.com/a/47130018
has title: Regex matches in regexr but not in pythex nor in the python script
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81209879
tagged with: python
tagged with: regex
has body: I am trying to match find out all possible instances of -- between two Arabic sentences. Here is my pattern for it: [\u0600-\u06FF]+--[\u0600-\u06FF]+ Here is an example text: قَنَاتِيْ--وَ الْمُحَامِيْ It matches on regexr.com but not on pythex. Can anyone please help and let me know my mistake?
has comment: http://stackoverflow.com/comment/81198819

http://stackoverflow.com/comment/81379822
has text: Instead of `open('data.txt')` can you provide full path to file `/home/user/dir/file`
type: Comment
comment on: http://stackoverflow.com/q/47215168
score: 0
type: QuestionComment

http://stackoverflow.com/q/47194539
score: 0
has answer: http://stackoverflow.com/a/47194677
answer count: 4
has answer: http://stackoverflow.com/a/47194666
type: Question
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47194659
has comment: http://stackoverflow.com/comment/81338231
has title: trying to format x and y coordinates using .format() function
has body: So I have an assignment where I have the user input a few numbers and it draws a shape based on the number and length input. As the turtle draws the picture it is supposed to report the X and Y coordinates and heading after each turn; however the X and Y coordinates need to be formatted as integers so that they display a whole number instead of a decimal. I'm supposed to use the .format() function to do so but I have no idea where and how to use it. Here is my code so far: import turtle lawrence = tur tle.Turtle() lawrence.goto(-150,0) lawrence.pencolor('white') lawrence.speed(2) #setup of window that final image will be displayed on window = turtle.Screen() window.setup(1000,1000) window.title("Homework 3") window.bgcolor('black') user_shape = int(input('What do you want me to draw? (1 = square, 2 = triangle): ')) if user_shape == 1: print('I will draw a square') else: print('I will draw an equilateral triangle') user_length = int(input('How long do you want the sides of your square to be? Please enter the number of pixels (e.g. 100): ')) for num in range(user_shape): lawrence.forward(user_length) lawrence.left(90) print('My 1st corner is at: ',lawrence.xcor().format(),',',lawrence.ycor(), 'and my heading is',lawrence.heading()) lawrence.forward(user_length) lawrence.left(90) print('My 2nd corner is at: ',lawrence.xcor(),',',lawrence.ycor(), 'and my heading is',lawrence.heading()) lawrence.forward(user_length) lawrence.left(90) print('My 3rd corner is at: ',lawrence.xcor(),',',lawrence.ycor(), 'and my heading is',lawrence.heading()) lawrence.forward(user_length) lawrence.left(90) print('My 4th corner is at: ',lawrence.xcor(),',',lawrence.ycor(), 'and my heading is',lawrence.heading()) window.exitonclick() I'm only in a basic python programming class and just need to know how to use the .format() function and where so any help would be great EDIT--------------------------------------------------------------------------- that first part of my code works great but I h…
has answer: http://stackoverflow.com/a/47195221

http://stackoverflow.com/q/47101750
has comment: http://stackoverflow.com/comment/81153795
has title: Changing instance variable in Python also changes original list
tagged with: python-3.x
answer count: 2
tagged with: instance
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81153516
upvote count: 1
linked to: http://stackoverflow.com/q/986006
favorite count: 0
has comment: http://stackoverflow.com/comment/81153554
has answer: http://stackoverflow.com/a/47101803
type: Question
tagged with: object
has answer: http://stackoverflow.com/a/47101804
has body: Here is my code: class Foo(object): def __init__(self, x, y): self.x = x self.y = y def func(self): self.x[0] -= 1 self.y -= 1 x = [10] y = 10 a = Foo(x, y) a.func() print(x, y) Output is ([9], 10). Why does passing a list to an instance variable and then changing the instance variable also change the original list, but not the original integer? How do you pass a list to an instance variable in Python, and then change the instance variable without affecting the original list?
score: 1
duplicate of: http://stackoverflow.com/q/986006
tagged with: python
tagged with: instance-variables

http://stackoverflow.com/comment/81125153
has text: @knitti Yes, I think my input for both user_ID and Category ID are strings, but this worked perfectly fine using sqlite as they got automapped into name column, I have updated the post with more information, and wonder if there is a way to fix it without breaking most of the code..(changing input of user_ID and Category ID to integer will break most of my code )
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47065679

http://stackoverflow.com/comment/81125436
comment on: http://stackoverflow.com/q/47087927
type: QuestionComment
type: Comment
score: 0
has text: The django context is just a bunch of variables that the template has access to.

http://stackoverflow.com/comment/81120693
comment on: http://stackoverflow.com/q/47074590
has text: If you are only modifying Python code for experimental purposes, one possibility would be to build the PIP package using Bazel, install it into a virtualenv, and then modify the installed version of the library (in `lib/site-packages/pythonX.X/tensorflow`).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47113421
has comment: http://stackoverflow.com/comment/81176703
tagged with: python
score: 0
answer count: 1
tagged with: file
has body: I have a file full of sentences and I want to do a unigram with that: This is my code and is only getting one letter and I want it to get the word old_lines = open("f.final",'r').readlines() new_lines = [] for line in old_lines: words = line.split() new_lines.append(words) print new_lines for lines in new_lines: c = Counter(str(lines)) with open("final.final", 'w') as f: for k,v in c.items(): f.write("{} {}\n".format(k,v))
has title: Python Taking information from a Counter to a file
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47113444
tagged with: counter

http://stackoverflow.com/a/47122060
type: AcceptedAnswer
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/47122028
type: Answer
accepted answer of: http://stackoverflow.com/q/47122028
has body: chunk1 is overwritten in every iteration. Instead, you should store the values in a list. You also don't need all of these string concatenations output = [] for i in range(0, 4): # Choose randomly whether the next character will be a letter or digit uld = randint(0, 1) if uld == 0: character = 'letters' # Randomly choose a letter from all upper- and lowercase letters selector = randint(0, 51) elif uld == 1: character = 'digits' # Randomly choose a digit from 0-9 selector = randint(0, 9) output.append(charset[character][selector]) print(''.join(output))
upvote count: 2

http://stackoverflow.com/comment/81266194
score: 0
has text: I want to sort it according to the special rules outlined in the question.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47158267

http://stackoverflow.com/comment/81086448
type: Comment
type: QuestionComment
has text: could you please leave a link on the github page and also get the error of the application, if not we cannot really do much.
comment on: http://stackoverflow.com/q/47069054
score: 0

http://stackoverflow.com/comment/81240437
score: 1
has text: Look at [subprocess](https://docs.python.org/2/library/subprocess.html) - it offers far more control over subprocesses than `os.system`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47145139

http://stackoverflow.com/a/72383624
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47094705
has body: Starting with SciPy 1.7 you have a Sobol' and Halton low discrepancy sequences in SciPy. There is also a convenient function scale that can be used to scale the values to given bounds. https://scipy.github.io/devdocs/reference/stats.qmc.html
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47151250
has comment: http://stackoverflow.com/comment/81261116
has answer: http://stackoverflow.com/a/47155881
has comment: http://stackoverflow.com/comment/81252248
accepted answer: http://stackoverflow.com/a/47155881
type: Question
has comment: http://stackoverflow.com/comment/81261139
tagged with: odoo
tagged with: python
has title: Posbox - scan decode incorrect
tagged with: barcode-scanner
type: AnsweredQuestion
score: 0
has body: I can't scan correctly a barcode when my scanner is plugged to Posbox. For example, when I scan the barcode (EAN13) 3288190200005, I've got "#@**!()@))))%" The log of posbox is : DEBUG ? openerp.addons.hw_scanner.controllers.main: pushing barcode #@**!()@))))% from device /dev/input/by-id/usb-Honeywell_Scanning_and_Mobility_Honeywell_Scanning_and_Mobility_Scanner-event-kbd, name "Honeywell Scanning and Mobility Honeywell Scanning and Mobility Scanner", phys "usb-3f980000.usb-1.3/input0 But when I plugged my scanner directly to my computer, it works without problem. IP posbox is correctly set; I have a popup error : "Barcode unknown". I have already reinstall posbox version 15 or version 16, nothing change. What should I do ?
answer count: 1

http://stackoverflow.com/q/47117911
type: Question
has comment: http://stackoverflow.com/comment/81186052
tagged with: python-3.x
tagged with: tkinter
has body: Basically what I'm trying to figure out is, how do I make my menu bar "buttons" change the page? I've already made the dropdown menu, and the classes with each page. The thing is it works if I create a separate button to change the page, but not when i'm trying to do it through the menu bar? every tutorial I find is through the buttons, and only the buttons.. I am using python 3.6, with tkinter. import tkinter as tk class MyApp(tk.Tk): def __init__(self, *args, **kwargs, ): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} menu = tk.Menu(container) betting = tk.Menu(menu, tearoff=0) menu.add_cascade(menu=betting, label="Pages") betting.add_command(label="PageOne", command=lambda: controller.show_frame(PageOne)) betting.add_command(label="PageTwo", command=lambda: controller.show_frame(PageTwo)) tk.Tk.config(self, menu=menu) for F in (Startpage, PageOne, PageTwo): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(Startpage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class Startpage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Home") label.pack(pady=10, padx=10) button1 = tk.Button(self, text="page 1", command=lambda: controller.show_frame(PageOne)) button1.pack() button2 = tk.Button(self, text="Page Two", command=lambda: controller.show_frame(PageTwo)) button2.pack() # ***** PAGES ***** class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Back to Home") label.pack(pady=10, padx=10) button1 = tk.Button(self, text="Back to Home", command=lambda: controller.show_frame(Startpage)) button1.pack() button2 = tk.Button(self, text="Page Two", command=lambda: controller.show_frame(PageTwo…
has answer: http://stackoverflow.com/a/47120773
has comment: http://stackoverflow.com/comment/81185859
tagged with: python
type: AnsweredQuestion
has title: How to change page through my menu bar methods in tkinter?
accepted answer: http://stackoverflow.com/a/47120773
has comment: http://stackoverflow.com/comment/81185821
score: 0
tagged with: menubar
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81185799
tagged with: menu
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81237529
has text: Relevant: https://stackoverflow.com/a/1266082/1959808
comment on: http://stackoverflow.com/q/47124810
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47138276
has comment: http://stackoverflow.com/comment/81225834
has comment: http://stackoverflow.com/comment/81226711
answer count: 1
has comment: http://stackoverflow.com/comment/81226584
has comment: http://stackoverflow.com/comment/81226135
type: Question
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/9622163
has title: Plotting a dataframe python
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81226165
has answer: http://stackoverflow.com/a/47138404
score: 0
has body: The original dataframe,df I had was: date name count 0 2017-08-07 ABC 12 1 2017-08-08 ABC 5 2 2017-08-08 TTT 6 3 2017-08-09 TAC 5 4 2017-08-09 ABC 10 Then the following code was used to transform to the new dataframe,df2 below: df = pd.DataFrame({"date":["2017-08-07","2017-08-08","2017-08-08","2017-08-09","2017-08-09"],"name":["ABC","ABC","TTT","TAC","ABC"], "count": ["12","5","6","5","10"]}) df = df.pivot(index='date', columns='name', values='count').reset_index().fillna(0) Now dataframe,df2 is transformed to: date ABC TTT TAC 0 2017-08-07 12 0 0 1 2017-08-08 5 6 0 2 2017-08-09 10 0 5 Now I tried to plot the dataframe,df2 in order to show each day on the x -axis vs the values in the column names/day on y-axis:( ABC,TTT,TAC ) but I keep getting two straight lines. Here is the code: fig=pyplot.figure() ax=fig.add_subplot(1,1,1) ax.set_title('Plot') ax.plot(df2)
tagged with: pandas

http://stackoverflow.com/q/47118337
tagged with: boolean
has title: Why does boolean indexing of a 2D NumPy array produces 1d array?
score: 5
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81186564
accepted answer: http://stackoverflow.com/a/47118408
has comment: http://stackoverflow.com/comment/81186763
has body: I was experimenting with boolean indexing in NumPy and came across this which is confusing me: import numpy as np np.random.seed(0) Created a 7 x 4 array: data = np.random.rand(7, 4) [[ 0.5488 0.7152 0.6028 0.5449] [ 0.4237 0.6459 0.4376 0.8918] [ 0.9637 0.3834 0.7917 0.5289] [ 0.568 0.9256 0.071 0.0871] [ 0.0202 0.8326 0.7782 0.87 ] [ 0.9786 0.7992 0.4615 0.7805] [ 0.1183 0.6399 0.1434 0.9447]] Created a boolean array also 7 x 4: bool_array = ([[True,False,False,True], [True,False,False,True], [True,False,False,True], [True,False,False,True], [True,False,False,True], [True,False,False,True], [True,False,False,True]]) bool_array = np.array(bool_array) data[bool_array] Output: [ 0.5488 0.5449 0.4237 0.8918 0.9637 0.5289 0.568 0.0871 0.0202 0.87 0.9786 0.7805 0.1183 0.9447] How can this be explained? I reasoned it as follows: the number of rows is the same (i.e. 7). For each row, True is found at positions 0 and 3 (i.e. 2 values). Thus I end up getting a 1 x 14 matrix. I was expecting a 7 x 2 matrix though. Could someone please clarify how this is evaluated to give a 1 x 14 matrix?
type: Question
type: AnsweredQuestion
upvote count: 5
has answer: http://stackoverflow.com/a/47118408
tagged with: python
has comment: http://stackoverflow.com/comment/81186563
favorite count: 0
tagged with: numpy

eval
tag name: eval
tags question: http://stackoverflow.com/q/47163401
tags question: http://stackoverflow.com/q/47103057
tags question: http://stackoverflow.com/q/47161939
type: Tag

http://stackoverflow.com/comment/81144917
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47097584
has text: No errors but it creates a bizarre result reducing file size and data looks now like this https://ibb.co/if2rJG for filename = ('BAAC.xlsx') pd.read_excel(filename).dropna(how='any').to_excel(filename, index=False)
score: 0

http://stackoverflow.com/a/47172471
has comment: http://stackoverflow.com/comment/139706590
has body: I need to make two unrelated HTTP requests in parallel. What's the simplest way to do that? import asyncio import aiohttp async def request(url): async with aiohttp.ClientSession() as session: async with session.get(url) as resp: return await resp.text() async def main(): results = await asyncio.gather( request('http://httpbin.org/delay/1'), request('http://httpbin.org/delay/1'), ) print(len(results)) loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) loop.run_until_complete(loop.shutdown_asyncgens()) finally: loop.close() Yes, you may achieve concurrency with asyncio.gather or creating task with asyncio.ensure_future. Next, I want to have some complex dependency structure? I want to start operations when I have all prerequisites for them and get results when I need the results. While code you provided will do job, it would be nicer to split concurrent flows on different coroutines and again use asyncio.gather: import asyncio import aiohttp async def request(url): async with aiohttp.ClientSession() as session: async with session.get(url) as resp: return await resp.text() async def get_ip(): return await request('http://httpbin.org/ip') async def post_from_get(): async with aiohttp.ClientSession() as session: async with session.get('http://httpbin.org/get') as resp: get_res = await resp.text() async with session.post('http://httpbin.org/post', data=get_res) as resp: return await resp.text() async def main(): results = await asyncio.gather( get_ip(), post_from_get(), ) print(len(results)) loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) loop.run_until_complete(loop.shutdown_asyncgens()) finally: loop.close() Is it true that normally developers have to think what coroutines should become separate tasks and use aforementioned functions to gain optimal performance? Since you use asyncio you probably want to run some jobs concurrently to gain performance, right? asyncio.gather is a way to say - "run these jobs concurrently to get thei…
type: Answer
has comment: http://stackoverflow.com/comment/81299001
upvote count: 30
score: 30
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47169474
answers question: http://stackoverflow.com/q/47169474

http://stackoverflow.com/q/47169556
tagged with: input
tagged with: python
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/47183117
has comment: http://stackoverflow.com/comment/81289054
has answer: http://stackoverflow.com/a/47183117
has comment: http://stackoverflow.com/comment/81288951
has comment: http://stackoverflow.com/comment/81289011
type: Question
has comment: http://stackoverflow.com/comment/81289039
accepted answer: http://stackoverflow.com/a/47169605
score: 0
has comment: http://stackoverflow.com/comment/81289077
has body: I'm new to Python and just learning the basics. Can you please correct this for me and tell me how and why I was wrong? age = input('Please enter your age:') ten = 10 agePlusTen= age + ten print('You will be', agePlusTen, 'in 10 years' Traceback (most recent call last): File "C:/Users/Admin/Documents/Python/6.2 fixed.py", line 3, in &lt;module&gt; print('You will be', age + ten, 'in 10 years') TypeError: must be str, not int
has answer: http://stackoverflow.com/a/47169605
has title: TypeError: must be str, not int (basic user)
has comment: http://stackoverflow.com/comment/81289028

http://stackoverflow.com/comment/81219035
score: 2
has text: Have you tried a web search for "Turkish NLP"? Because when I did, I found a couple of pages with links to resources – including corpora and a morphological analyser. Have you seen Deniz Yuret's homepage?
comment on: http://stackoverflow.com/q/47134108
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81334882
score: 0
has text: @oezeadi. This is the only answer that will work in any locale. The replace answer is a quick and dirty hack by comparison, that will only really work in the US. You can always change your selection.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47192212

http://stackoverflow.com/comment/81403149
score: 0
comment on: http://stackoverflow.com/a/47216938
type: Comment
type: AnswerComment
has text: Interesting, what about `pd.DataFrame(np.concatenate(df.col.values).tolist())` ? I think it should be faster.

http://stackoverflow.com/comment/81301978
score: 0
type: Comment
type: QuestionComment
has text: Look at `pd.Series.map` and `fillna`.
comment on: http://stackoverflow.com/q/47176420

http://stackoverflow.com/a/47212267
answers question: http://stackoverflow.com/q/47203492
type: Answer
accepted answer of: http://stackoverflow.com/q/47203492
has comment: http://stackoverflow.com/comment/81460336
has comment: http://stackoverflow.com/comment/82024348
has body: You can do this. >>> from lxml import etree >>> mediawiki = etree.iterparse('mediawiki.xml') >>> page_content = {} >>> for ev, el in mediawiki: ... if el.tag=='page': ... if page_content['ns']=='2': ... print (page_content) ... page_content = {} ... else: ... page_content[el.tag.replace('{http://www.mediawiki.org/xml/export-0.10/}', '')] = \ ... el.text.strip() if el.text else None ... >>> page_content {'mediawiki': '', 'revision': '', 'timestamp': '2017-07-27T00:59:41Z', 'title': 'User:Wonychifans', 'page': '', 'text': 'blah blah', 'ns': '2'} Because the structure of the output xml is quite simple there should be no difficulty in constructing it from the dictionary. Edit: Although this approach requires two passes through the xml file it could be faster and it does recover the required xml. First, look for the starting lines of the page elements. >>> from lxml import etree >>> mediawiki = etree.iterparse('mediawiki.xml', events=("start", "end")) >>> for ev, el in mediawiki: ... tag = el.tag[1+el.tag.rfind('}'):] ... if ev=='start' and tag=='page': ... keep=False ... if ev=='start' and tag=='ns' and el.text=='2': ... keep=True ... if ev=='end' and tag=='page' and keep: ... print (el.sourceline) ... 10 The go through the xml again to find the complete page entries using the starting points. >>> with open('mediawiki.xml') as mediawiki: ... for _ in range(9): ... r = next(mediawiki) ... for line in mediawiki: ... print (line.strip()) ... if ' ' in line: ... break ... User:Wonychifans 2 blah blah
has comment: http://stackoverflow.com/comment/81530213
score: 1
has comment: http://stackoverflow.com/comment/81493068
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47102302
score: 0
has body: In case other users come to this, here's what I did to solve it (but it's not the most ideal). I essentially faked the django_migrations table since none of the the migrations actually needed to be made in the new database. First I looked in the "default" database's django_migrations table to see what the first migration was and then ran that via the command line to create the initial table in the new database. For me that was this: python manage.py migrate --database new_database --fake contenttypes 0001_initial After I had the first initial value and the table created I essentially copied over the rest using an SQL statement. I made sure to retain the order from the "default" database in case that had any importance. Statement looked like this: INSERT INTO django_migrations (app, name, applied) VALUES ('auth', '0001_initial', NOW()), ('users', '0001_initial', NOW()), ... Then just to make sure everything was good I ran: python manage.py migrate --database new_database python manage.py migrate
type: Answer
answers question: http://stackoverflow.com/q/47097812

http://stackoverflow.com/comment/81124545
has text: Just to make sure, the error occurs in `player_weapon = inventory.Inv[what]`?
type: QuestionComment
comment on: http://stackoverflow.com/q/47087236
type: Comment
score: 1

http://stackoverflow.com/q/47121531
tagged with: python
linked to: http://stackoverflow.com/q/35366854
score: 2
has comment: http://stackoverflow.com/comment/81199299
has body: I have made my custom config settings in Odoo using models.TransientModel with implementing the get_default and the set function. The way I do it is the same like is shown in the answer for this question Set and get store data Odoo with TransientModel When the module installed, the settings is empty. How to have a default value of that config settings on install? I've tried using the init function. def init(self, cr): config = self.pool.get("ir.config.parameter") config_value = { "value": "randomaddress@gmail.com", "key": "myapplication.email_address" } config.create(cr, uid, config_value, context=None) It didn't work.
upvote count: 2
tagged with: odoo
tagged with: odoo-8
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81199381
favorite count: 0
has title: Set Odoo's config settings on module installation
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/117046977
has answer: http://stackoverflow.com/a/47129718

http://stackoverflow.com/q/47185315
downvote count: 0
tagged with: repeat
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47185548
possible better answer: http://stackoverflow.com/a/47185548
tagged with: pandas
score: 1
tagged with: python
has body: Suppose I have a list of data. For eg [1,2,3,4,5] and I have 1704 rows in my DataFrame. Now I want to add new column with this values only but it should be repeated till the last row as shown below: 1 2 3 4 5 1 2 3 4 5 .. and so on till the last record. I tried df['New Column']=pd.Series([1,2,3,4,5]) but it inserts record only in first 5 rows but I want this series to be repeated till the last. I referred many posts on SO but didn't found any relevant post. I am a newbie to pandas framework. Please help me with this. Thanks in advance.
linked to: http://stackoverflow.com/q/21068971
tagged with: list
favorite count: 0
has title: Assign column of repeating values from a list
type: Question
has answer: http://stackoverflow.com/a/47185435
accepted answer: http://stackoverflow.com/a/47185435
answer count: 2

http://stackoverflow.com/q/47138248
has body: I have just installed anaconda on my Mac and any time I execute a conda command or start a python instance I get the following odd error message: ianashpole $ conda info --envs Vendor: continuum Product: anaconda Message: trial mode expires in 27 days OR ianashpole $ python Vendor: continuum Product: anaconda Message: trial mode expires in 27 days Python 2.7.3 |Anaconda custom (64-bit)| (default, Dec 20 2012,09:57:39) To clarify, I haven't installed any additional packages or anything after the initial download from https://www.anaconda.com/download/#macos Does anybody know a) how to stop this message from appearing; and b) whether anaconda really will stop working for me in 27 days? Thanks!
has title: Anaconda "trial mode expires in x days" error message
tagged with: conda
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/47138835
tagged with: anaconda
downvote count: 0
answer count: 1
tagged with: macos
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47138835
tagged with: python

http://stackoverflow.com/a/47216514
answers question: http://stackoverflow.com/q/47204711
has body: As pointed out by ryachza the answer was to use an openpyxl utility, however the utility to use is get_column_letter and not column_index_from_string as I want to convert number to letter and not visa versa. Here is the working code from openpyxl.utils import get_column_letter # Start changing width from column C onwards column = 3 while column &lt; 601: i = get_column_letter(column) ws.column_dimensions[i].width = 4 column += 1
downvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47204711
upvote count: 13
score: 12

http://stackoverflow.com/q/47071120
has answer: http://stackoverflow.com/a/47264809
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
has body: def custom_scrape(e1, master): session = requests.Session() # selectWikiPage = input("Please enter the Wikipedia page you wish to scrape from") selectWikiPage = e1.get() if "wikipedia" in selectWikiPage: #turn this into a regular expression html = session.post(selectWikiPage) bsObj = BeautifulSoup(html.text, "html.parser") findReferences = bsObj.find('ol', {'class': 'references'}) # isolate refereces section of page href = BeautifulSoup(str(findReferences), "html.parser") links = [a["href"] for a in href.find_all("a", href=True)] for link in links: print("Link: " + link) else: print("Error: Please enter a valid Wikipedia URL") As you can see, I am able to isolate the references section of the Wikipedia page, but I am unsure as how to make it enter the isolated links, and then carry out the actions aforementioned in the title.
has title: Creating a scraper that isolates a part of a page, and then scrapes the title and first paragraph from every link
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 1
tagged with: web-scraping

http://stackoverflow.com/q/47186526
upvote count: 1
tagged with: django-rest-framework
favorite count: 0
type: Question
tagged with: rest
has body: I am using Django filter backend on few fields which is working very good. But i want to filter fields when i get specific condition Like if user_type is basic get filter query otherwise get all objects from model. Mine code for filters is here: http_method_names = ['get'] serializer_class = SearchSerializer pagination_class = LargeResultsSetPagination filter_backends = (DjangoFilterBackend,) filter_fields = ('property_zipcode', 'property_state', 'property_county',) The thing i need is: def get_queryset(self): if self.request.query_params.get('basic',None): filter_backends = (DjangoFilterBackend,) filter_fields = ('property_zipcode', 'property_state', 'property_county',) return filtered_query # I want to return filter query from here. queryset = property.objects.all(); return queryset I am new to Django rest framework and django filter backend. If anyone tried do to this thing please help me out.
accepted answer: http://stackoverflow.com/a/47192531
downvote count: 0
tagged with: django
tagged with: python
tagged with: django-filter
has answer: http://stackoverflow.com/a/47192531
has title: Conditions on django filter backend in django rest framework?
type: AnsweredQuestion
score: 1
answer count: 1

http://stackoverflow.com/comment/81226822
comment on: http://stackoverflow.com/a/47137989
type: AnswerComment
score: 1
type: Comment
has text: @JohnSmith As I said, inheritance/composition only makes sense if the classes are *functionally similar*. Your classes do very different things.

http://stackoverflow.com/q/47096930
has comment: http://stackoverflow.com/comment/81144267
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81146142
has comment: http://stackoverflow.com/comment/81144134
has title: Is it possible to do my own Tkinter custom tracking variable type?
has answer: http://stackoverflow.com/a/47098656
tagged with: tkinter
downvote count: 0
has body: I was wondering if it may be possible to create a MyValueVar type, equivalent to those like StringVar, BooleanVar, DoubleVar... I've read Learning Python, I'm half the way of Programming Python and have almost finished Tkinter GUI Application Development Blueprints. I also google on the internet and haven't found any info about how to create such a data type. My desire would be to create a class (it may be a mixin class) that could be attached to my visual component, and every time the visual component changes, its internal value, which is a custom class object instance, also changes. It would be ideal to have some king of MyValueVar type of variable which would be synced with the visual component. It would be enough to me to know which class and which methods or interface I have to implement and, overall, some documentation to stick to. Thanks in advance
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81145204
tagged with: user-interface
answer count: 1

http://stackoverflow.com/comment/81333249
comment on: http://stackoverflow.com/a/47191527
type: AnswerComment
score: 0
has text: In the future, it helps to fill out the edit comment accurately: Changing the OP's code is not "fixing indentation" and should be explained if you want your edit approved. I only noticed my mistake (and that your edit was correct) because I was going to comment about it being incorrect after the review. That being said, sorry.
type: Comment

http://stackoverflow.com/comment/81110122
type: AnswerComment
comment on: http://stackoverflow.com/a/47077135
type: Comment
has text: thank you for your (fast) answer. You are right, I made a mistake, I wanted to say cross-entropy, not softmax (I do not know why I put softmax btw). I corrected it in the question. Well,for f(x) it was just an example of a differentiable function, I do not actually want to minimize that function
score: 0

http://stackoverflow.com/q/47214610
has answer: http://stackoverflow.com/a/47214624
has answer: http://stackoverflow.com/a/47214635
linked to: http://stackoverflow.com/q/1185524
has answer: http://stackoverflow.com/a/47214623
has body: I've tried if string[0] == "\n": string = string[1:] I don't think strip() and rtrim() is what I want because they'd either remove all occurrences of \n or only at the end of the string.
type: UnansweredQuestion
tagged with: string
duplicate of: http://stackoverflow.com/q/1185524
score: 0
answer count: 3
tagged with: python
tagged with: regex
has title: Removing new lines only at the beginning of a string
tagged with: substring
type: Question

http://stackoverflow.com/q/47223129
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81397354
has comment: http://stackoverflow.com/comment/81396001
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/81396723
answer count: 0
has comment: http://stackoverflow.com/comment/81396114
has comment: http://stackoverflow.com/comment/81396109
has body: My code compare actual file type to extension and return a result. I had to adjust it to return the results and reuse other function but I'm stuck and I don't know why my script appends only one item to a list and generates no error whatsoever. I would get a result like ['asd', 'fgh', etc..]. What I'm doing wrong? import os, sys sys.argv.append("C:/temp/ver_files/") dirct = set(os.listdir(sys.argv[1])) file_sigs = { b'\xff\xd8\xff': ( '.jpg', '.jpeg', '.JPG', '.JPEG' ), b'\x47\x49\x46': ( '.gif', '.GIF' ), b'\x89\x50\x4e': ( '.png', '.PNG' ), b'\x50\x4b\x03': ( '.docx', '.DOCX' ), b'\x42\x4d': ( '.bmp', '.BMP' ) } for i in dirct: inf = [] file = open(sys.argv[1]+i, "rb") sig = file.read(3) file.close() ext = os.path.splitext(i)[1] if len(inf) &gt;= 0: if sig in file_sigs.keys(): if ext in file_sigs[sig]: inf.append('Matching extension: '+ ext+ ' for file: '+i) else: inf.append('No matching extension for file: '+i+" it's a "+ file_sigs[sig][0]+ ' file') else: inf.append('No such signature in database') print(inf)
type: Question
has title: Adding items to a list with for loop in Python

http://stackoverflow.com/a/47110791
answers question: http://stackoverflow.com/q/47110630
score: -1
upvote count: 0
type: Answer
has body: Two tips: When you calculate something, save the result in a variable so you can use it later; and to calculate the number of left-over people, find out how many people your tables can sit (at 10 people per table) and compare it to the number of guests. More help than this would not help you solve the problem, but to avoid solving it.
downvote count: 1

http://stackoverflow.com/q/47110766
has answer: http://stackoverflow.com/a/47111083
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47111083
has comment: http://stackoverflow.com/comment/81172079
downvote count: 0
has comment: http://stackoverflow.com/comment/81171918
score: 1
answer count: 1
tagged with: python
type: Question
tagged with: python-3.x
has body: I'm trying to create a revision guide on Tkinter, The basics are working fine , however when i tried to put a frame within a frame ( Pressing Physics will show two more buttons , which each show a frame themselves) My Python code , is showing an error, so i created a new file where Physics itself is the start page , yet i'm getting this error when running it , i don't understand what's wrong, i've checked other answers and questions , yet i still don't understand what i'm doing wrong (widgetName, self._w) + extra + self._options(cnf)) _tkinter.TclError: unknown option "-parent" Here is my code class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller button1 = tk.Button(self, text="Physics Equations", command=lambda: controller.show_frame("PhysicsEquations"),bg="blue",fg="white",font=(None, 23, "bold"), height=2, width=11).grid(row=0,column=0,padx=5,pady=5) button2 = tk.Button(self, text="Physics Definitions", command=lambda: controller.show_frame("PhysicsDefinitions"),bg="green",fg="white",font=(None, 23, "bold"), height=2, width=11).grid(row=0,column=1,padx=5,pady=5) button = tk.Button(self, text="Go to the start page",command=lambda: controller.show_frame("StartPage"),fg="white",bg="blue",width=10,font=(None,20,"bold")) button.grid() class PhysicsEquations(tk.Frame): def clickPhysicsEquations(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="This is Physics", font=controller.title_font,fg="white", bg="blue") label.pack(side="top", fill="x", pady=10) label1 = tk.Label(self, text=' ',bg="blue") label1.pack() try: file=open("physics_EQUATIONS.txt","r") data=file.read() file.close() except IOError: file=open("physics_EQUATIONS.txt","w+") file.write("Distance = Speed x Time,") data=file.read() file.close() physics_equations=data.split(',') temp=random.choice(physics_equations) used=[] used.append(temp) physics_equations.remove(temp) …
tagged with: tkinter
upvote count: 1
has comment: http://stackoverflow.com/comment/81171891
has title: (widgetName, self._w) + extra + self._options(cnf)) _tkinter.TclError: unknown option "-parent"
favorite count: 0
has comment: http://stackoverflow.com/comment/81172064

http://stackoverflow.com/a/47088853
type: Answer
has comment: http://stackoverflow.com/comment/81127254
has comment: http://stackoverflow.com/comment/81127374
has body: The problem is caused because QMessageBox.about() requires as a first parameter a widget but self, that is Ui_MainWindow, is not a widget. Qt Designer does not generate a widget but creates a class that fills a widget. It is also not recommended to modify the class generated by Qt Designer, it is appropriate to create a class that inherits from the appropriate widget and use the design class class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self, *args, **kwargs): QtWidgets.QMainWindow.__init__(self, *args, **kwargs) self.setupUi(self) self.Button.clicked.connect(self.btn_clicked) self.RButton.clicked.connect(self.btn_clicked) def btn_clicked(self): QMessageBox.about(self,"창","안녕") if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) w = MainWindow() w.show() sys.exit(app.exec_())
has comment: http://stackoverflow.com/comment/81127519
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47088724
answers question: http://stackoverflow.com/q/47088724

http://stackoverflow.com/q/47190372
has answer: http://stackoverflow.com/a/47191431
tagged with: python
has body: Let's say I have the following picture: And the following "reference" colours which are static and not determined from the images (in RGB) [90, 160, 155] [245, 210, 110] [20, 20, 20] [150, 150, 120] How do I get a return object that tells me, per reference colour, the percentage of colours in the image that are "closest" to the reference colour with a return value like such: { "colour1": 0.25, // These aren't the actual distributions, but the answer "colour2": 0.1, // this is trying to represent is that 25% of the colour "colour3": 0.6, // in the image is closest to "colour1", 10% of the "colour4": 0.05 // image is closest to "colour2", etc. } Is there a performant way to do this, so that a result could be returned for a large image within a couple of seconds and with a dozen reference colours? The answer doesn't need to be an exact, an approximation within 10% would be ok, so if reducing the size of the picture dramatically is the way to speed it up then that's ok. My first (and awful - it was just for a quick proof of concept) pass solution was: Loop through all of the pixels in the picture Loop through all of the reference colours Calculate the Euclidian distance between the pixel colour and reference colour Return the reference colour with the closest Euclidian distance Count the occurrences of each reference colour in the result and divide by total number of pixels to get percentage Of course, this is slow My next steps, I've been thinking of trying a couple of different options: Use opencv to generate a colour histogram and somehow use the result of that to get to the percentage of each reference colour Use K-means clustering, setting the reference colours as the centroids, and use the result of that But I thought I would ask on here first before diving in to see if anybody has recommendations on where to go, or even better, if there's a simple library that could solve this problem without much effort.
has answer: http://stackoverflow.com/a/47190991
score: 0
answer count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81330467
has title: What is the distribution of colour in an image relative to defined centroids
has answer: http://stackoverflow.com/a/47192707
tagged with: image-processing
has comment: http://stackoverflow.com/comment/81334502
type: Question
has comment: http://stackoverflow.com/comment/81330527
has comment: http://stackoverflow.com/comment/81330132
tagged with: opencv
has comment: http://stackoverflow.com/comment/81330838
has comment: http://stackoverflow.com/comment/81330477

http://stackoverflow.com/q/47084010
tagged with: web-scraping
has body: I am a noob in Python and am currently in the process of trying to write some code that when I run it, will give me the price of bitcoin from Coinbase. Whenever I run the code, it says none instead of the price of Bitcoin. Below is my code: import requests from bs4 import BeautifulSoup page = requests.get('https://www.coinbase.com/dashboard') soup = BeautifulSoup(page.content, 'lxml') price = soup.find(id='id root') assert isinstance(price, object) bitcoin = soup.find('span',{'class':'BigAmount__AmountSuper-jnVzGG jdlzFZ'}) print(bitcoin)
type: Question
has answer: http://stackoverflow.com/a/47084229
has title: Webpage (Coinbase) data Scraping using Python
tagged with: coinbase-api
tagged with: bitcoin
tagged with: python
score: 0
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/81149040
has text: this doesn't break at the end, it just returns to asking for A0
type: AnswerComment
comment on: http://stackoverflow.com/a/47087015
type: Comment
score: 0

int
tags question: http://stackoverflow.com/q/47103377
tag name: int
tags question: http://stackoverflow.com/q/47073294
type: Tag
tags question: http://stackoverflow.com/q/47113652
tags question: http://stackoverflow.com/q/47165189

http://stackoverflow.com/comment/81175615
comment on: http://stackoverflow.com/a/47112076
has text: Thank you so much! Once you suggested using vectors, I studied a bit of it and I was trying to make it work. I'm happy seeing your code now: I was quite close!
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81185355
score: 0
type: AnswerComment
has text: I mean this line avgs.append(float(sum(mark)/(len(mark)))) has a division by zero error for some reason
comment on: http://stackoverflow.com/a/47116869
type: Comment

http://stackoverflow.com/comment/81155814
has text: What exactly is your problem? Can you show code as well as the data structures?
comment on: http://stackoverflow.com/q/47102808
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81298839
has text: @n.m. I have reduced the code to exactly what I have and the expected behaviour. Le t me know if this you have solution for this. Thanks!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47161318
type: Comment

http://stackoverflow.com/q/47149884
tagged with: http://stackoverflow.com/tag/r
score: 0
duplicate of: http://stackoverflow.com/q/24142576
linked to: http://stackoverflow.com/q/42790891
has comment: http://stackoverflow.com/comment/83406833
downvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/42790891
has body: I am wondering if there is a built in command in R that would replicate the pd.get_dummies() function in python. What this does is, for example I have a data set T Chris Male Mary Female Bob Male John Male I want it to convert these unique categories (Male and Female) into binary data, such as having it show as Male Female Chris 1 0 Mary 0 1 Bob 1 0 John 1 0 Would anyone be able to shine some light on this? I would like to know the function and package that would need to be applied. If there does not exist one, how would you convert it?
has answer: http://stackoverflow.com/a/47150272
has title: Converting category labels into binary in R
type: Question
has comment: http://stackoverflow.com/comment/81249727
upvote count: 1
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81249638
favorite count: 0
linked to: http://stackoverflow.com/q/24142576

http://stackoverflow.com/q/47169287
type: AnsweredQuestion
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/47169610
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47169610
tagged with: jupyter-notebook
favorite count: 0
type: Question
has title: Plot a column from a data frame as a function of another column in pandas
has body: I have a pandas data frame: Name A B C a1 2.0 1.1 2.5 a2 2.2 3.4 8.7 a3 4.3 4.4 2.3 I would like to plot C as a function of Name (Name is the index) the graph should look like: y | | -------------&gt;X Where X should be the strings 'a1','a2','a3'..etc.. and the Y are the values of column C.
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/81197537
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47123677
type: Comment
has text: I had added that -- let me look into it a bit more.

http://stackoverflow.com/q/47174294
type: AnsweredQuestion
tagged with: algorithm
accepted answer: http://stackoverflow.com/a/47174460
has comment: http://stackoverflow.com/comment/81298242
has answer: http://stackoverflow.com/a/47174398
possible better answer: http://stackoverflow.com/a/47174398
downvote count: 3
tagged with: python
favorite count: 0
type: Question
has body: Suppose two lists, a,b,c,d are int. l1 = [[a,b],[c,d],...[x,y]] # len(l1) = 1 million l2 = [[a,b],[c,d],...[x,y]) # len(l2) = 10k Want l3 = [[c,d],...[x,y]] # items [c,d] in l1 but not l2 Usage: l1 is my testing pairwise result, and l2 is the false positive. I want to remove false positive so I have true positive. My attempt 1: double loops, slow ~30mins-ish My attempt 3: set does not work My attempt 2: double loops, but inner loop: when matching a item, remove it from both l2, so next iteration, will search less one item in l2, still slow 28min-ish Any better performance is welcome.
has comment: http://stackoverflow.com/comment/81298468
answer count: 2
has answer: http://stackoverflow.com/a/47174460
has comment: http://stackoverflow.com/comment/81297749
has title: Efficient algorithm for Intersecting of two large lists
score: -2
has comment: http://stackoverflow.com/comment/81297738
upvote count: 1
has comment: http://stackoverflow.com/comment/81297988

http://stackoverflow.com/q/47117011
type: Question
has comment: http://stackoverflow.com/comment/81206731
type: UnansweredQuestion
has title: Python Bounding a 3D Projection Cut Off by the Z-Axis
has comment: http://stackoverflow.com/comment/81206654
has comment: http://stackoverflow.com/comment/81206317
tagged with: python
tagged with: numpy
tagged with: projection
score: 0
has comment: http://stackoverflow.com/comment/81184085
answer count: 0
has body: So... I'm trying to project a 3D surface onto the screen. I've already written code to handle rotations and perspective and everything, and my projection code works exactly as intended when I use it on a numpy array of points. What I am wondering about is how to apply this to projecting 3D surfaces. Specifically, how exactly should I handle if part of a surface is behind the viewpoint, and part of it is in front of the viewpoint? Would I need to calculate a new surface that represents only the visible portion of the surface I am trying to project? For example, say I am trying to depict a square with vertices at ([10, 0, 10], [-10, 0, 10], [10, 0, -10], [-10, 0, -10]). Would I need to calculate a new surface with vertices at ([10, 0, 10], [-10, 0, 10], [10, 0, 0], [-10, 0, 0]), and then display that on the screen, or is there a different way to handle planes being cut off by the viewpoint? With a square, that calculation is trivial, but with an arbitrary surface, the calculation sounds rather inefficient. I feel like there should be a better way to do this. Along the X and Y axes, there is no problem with drawing things off-screen, but along the Z axis, I am struggling to think of an efficient algorithm that doesn't simply neglect to draw a surface that is partially behind the viewpoint.

http://stackoverflow.com/a/47145341
has body: If you know that your list always contains two items, you can do this: var1, var2 = ["wil15", "password"] That will assign "wil15" to var1 and "password" to var2.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47145314

http://stackoverflow.com/comment/81294066
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47172288
has text: I think you need to enable access to less secure apps from your gmail settings.
score: 1

http://stackoverflow.com/q/47066357
has answer: http://stackoverflow.com/a/47066483
has answer: http://stackoverflow.com/a/47066553
has answer: http://stackoverflow.com/a/47066474
possible better answer: http://stackoverflow.com/a/47066474
has comment: http://stackoverflow.com/comment/81080912
upvote count: 2
has comment: http://stackoverflow.com/comment/81080906
has comment: http://stackoverflow.com/comment/81081008
has comment: http://stackoverflow.com/comment/81081086
has comment: http://stackoverflow.com/comment/81081025
has answer: http://stackoverflow.com/a/47066607
accepted answer: http://stackoverflow.com/a/47066607
downvote count: 1
has answer: http://stackoverflow.com/a/47066789
has title: Search two consecutive words and combine them in python
answer count: 7
has body: I have list of lists as follows. mycookbook= [["i", "love", "tim", "tam", "and", "ice", "cream"], ["cooking", "fresh", "vegetables", "is", "easy"], ["fresh", "vegetables", "are", "good", "for", "health"]] I also have a list as follows. mylist = ["tim tam", "ice cream", "fresh vegetables"] Now, I want to find the consecutive words in mylist and combine them to update mycookbook. I am currently doing it as follows. for sentence in mycookbook: for sub in sentence: if sub is (mylist[0].split(" ")[0]): But I am not sure how to detect the next word as there is no command next(). Please help me.
has answer: http://stackoverflow.com/a/47067841
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47066561
has comment: http://stackoverflow.com/comment/81080914
type: AnsweredQuestion
score: 1
tagged with: python

http://stackoverflow.com/comment/81131164
comment on: http://stackoverflow.com/q/47090886
score: 3
has text: `reflect` should probably be a non-member function. It doesn't seem a natural property or behaviour of a `Point`. You don't want it to be a dumping ground for all your transformations. (hint - maybe create a `Transformer` object)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47196220
has body: Sessions must be a dictionary where you store values as (key,value) pairs. So, in this case: session['fred'] = 'yes' 'Fred' is the key and 'Yes' is the value. Learn more about python dictionaries, here: https://www.tutorialspoint.com/python/python_dictionary.htm session["abc"] = 123 print (session["abc"]) this will get you 123
has comment: http://stackoverflow.com/comment/81342660
score: 0
has comment: http://stackoverflow.com/comment/81345066
has comment: http://stackoverflow.com/comment/81342797
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47195772
has comment: http://stackoverflow.com/comment/81342245
accepted answer of: http://stackoverflow.com/q/47195772
has comment: http://stackoverflow.com/comment/81342303
type: Answer
has comment: http://stackoverflow.com/comment/81342423
has comment: http://stackoverflow.com/comment/81342466

http://stackoverflow.com/q/47182539
has title: PyQt4: printing Code 128 barcode fonts
has comment: http://stackoverflow.com/comment/81316793
downvote count: 0
accepted answer: http://stackoverflow.com/a/47270814
has comment: http://stackoverflow.com/comment/81332046
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81492493
has answer: http://stackoverflow.com/a/47270814
answer count: 1
has comment: http://stackoverflow.com/comment/81317132
tagged with: qt
tagged with: printing
type: Question
tagged with: pyqt
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81483108
score: 1
tagged with: code128
favorite count: 0
has body: I'm trying to write a text in code128 and a printer also ends in a picture, but it does not work in either of the two ways, I looked at the official documentation and other forum questions but it does not print in code128 from PyQt4.QtGui import QApplication,QImage,QFont from PyQt4.QtCore import QSizeF import sys,time app = QApplication(sys.argv) image = QImage(640,100,QImage.Format_Mono) image.fill(1) font = QFont('code128',32,QFont.Normal) painter = QPainter() painter.begin(image) painter.setFont(font) text = "\xccasdfsf\xce" painter.drawText(10,90,text) painter.end() image.save('test.png') and also in my thermal printer from PyQt4.QtGui import QApplication,QImage,QFont,QPrinter from PyQt4.QtCore import QSizeF import sys,time app = QApplication(sys.argv) printer = QPrinter('POS-58(copy of 1)') font = QFont('code128',32,QFont.Normal) painter = QPainter() painter.begin(printer) painter.setFont(font) text = "\xccasdfsf\xce" painter.drawText(10,90,text) painter.end() Neither of these two works for me and I find a solution for this, what could be happening? The actual output is this I am using PyQt4 in windows 10 with python 2.7

http://stackoverflow.com/q/47200617
tagged with: echarts
has comment: http://stackoverflow.com/comment/81350921
has comment: http://stackoverflow.com/comment/81351693
tagged with: textfield
has comment: http://stackoverflow.com/comment/81351353
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/81350569
tagged with: django
tagged with: javascript
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81350984
has comment: http://stackoverflow.com/comment/81350923
has body: How to add/use javascript code in Django textfield in the condition that safe filter is used? Will django textfield filter out all the ? I want to add/use some interactive charts plugin in my blog post, which uses javascript API, namely I need to use in my blog post, but all the content of my blog post is in the TextField() of Django models. The chart can not be shown in the post of the frontend, but it can be shown outside the post/TextField() in the web page if I put the js code outside the. body = models.TextField(). What's reason for that? Please help me.
has title: How to add/use javascript code in Django textfield in the condition that safe filter is used?
has comment: http://stackoverflow.com/comment/81352036
score: 0

http://stackoverflow.com/comment/81131971
type: QuestionComment
has text: I would recommend using a recursive function.
score: 0
comment on: http://stackoverflow.com/q/47089645
type: Comment

http://stackoverflow.com/q/47218038
downvote count: 0
tagged with: python
tagged with: jquery
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47218338
accepted answer: http://stackoverflow.com/a/47218338
tagged with: ansible
tagged with: api
upvote count: 1
has comment: http://stackoverflow.com/comment/81385558
score: 1
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has body: Jquery in Ansible is not working well for me. Here is the scenario. I am trying to make GET call to satellite api. It brings me the following output: "parameters": [ { "name": "sports", "value": "soccer" }, { "name": "color", "value": "blue" }, ], Now I want to grep the value of sports. here is my playbook - name: Make GET api calls from ansible uri: url: https://example/api/xyz method: GET user: administrator password: space@L42 force_basic_auth: yes validate_certs: no register: getoutput - name: grep the value of sports debug: msg="" It is throwing error for question mark.. `FAILED! => {"msg": "template error while templating string: unexpected char u'?' i am following documentation here http://docs.ansible.com/ansible/latest/playbooks_filters.html#json-query-filter http://jmespath.org/tutorial.html ----Filter Projections section On the other side if i replace the debug line with the line mentioned below. it works but it displays it via array and i don't want to grep anything with array ID. debug: msg="" Can any one of you please help please .
favorite count: 0
type: Question
has title: GET API Call from Ansible using Jquery (jmespath)

http://stackoverflow.com/a/55746347
has comment: http://stackoverflow.com/comment/98171564
score: 5
downvote count: 0
upvote count: 5
type: Answer
has body: Suggest to go here: https://id.atlassian.com/manage/api-tokens and create an API token. (The link is for JIRA Cloud. Go to your own instance if using DataCenter) To connect with the Python JIRA client, use your email address as the username, and the token value as the password.
answers question: http://stackoverflow.com/q/47146942

http://stackoverflow.com/a/47168804
answers question: http://stackoverflow.com/q/47168721
type: AcceptedAnswer
has body: You probably should consult some code examples on the web for reading a file. You need something like: fp = open(fname, "r") lines = fp.readlines() for line in lines: do_something_with_the_lines fp.close()
type: Answer
accepted answer of: http://stackoverflow.com/q/47168721
score: 0

http://stackoverflow.com/a/47111963
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/81174696
has comment: http://stackoverflow.com/comment/81180067
has comment: http://stackoverflow.com/comment/81180081
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47106862
type: Answer
accepted answer of: http://stackoverflow.com/q/47106862
has body: Looking at the sourcecode, this is in the flask's jsonify.py: # Use the same json implementation as itsdangerous on which we # depend anyways. from itsdangerous import json as _json and in the itstangerous.py there is: try: import simplejson as json except ImportError: import json The simplejson library has an option namedtuple_as_object which is enabled by default. So when the 3rd party simplejson is installed, the app uses it and serializes a namedtuple to a JSON object (a dict in Python). On systems where that library is not installed, the app falls back to standard json and serializes a namedtuple to an array (list). But if the simplejson is installed and imported by flask, the test program imports directly the standard json overwriting it and thus changing the behaviour between running and testing.

http://stackoverflow.com/comment/81330025
type: Comment
score: 1
has text: Also, apart from removing [] from list comprehension, if you use list instead of set, you will gain a little performance boost
type: QuestionComment
comment on: http://stackoverflow.com/q/47190055

http://stackoverflow.com/comment/81237038
has text: Only 6 of the 24 items have a `z-nvg-cognac_infoContainer-MvytX` class. You could select items by `'.z-nvg-cognac_infoContainer-MvytX'`, then find brand, article, price, new price ( or None)
type: Comment
comment on: http://stackoverflow.com/q/47124761
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81184853
has text: Please post the Traceback, formatted as code.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47117359
type: Comment

http://stackoverflow.com/comment/81352999
score: 0
type: Comment
has text: Version installed from pip3: dbus-python-1.2.4, and from the package manager: 1.2.4-1+b4.
type: QuestionComment
comment on: http://stackoverflow.com/q/47200971

http://stackoverflow.com/comment/81322666
score: 0
comment on: http://stackoverflow.com/a/47186441
type: Comment
has text: Note that I believe it is referring to order between groups, not within groups.
type: AnswerComment

http://stackoverflow.com/comment/81173354
type: AnswerComment
score: 1
has text: Thanks bla, your code output looks good. However, instead of just dumping your function into my program, could you please explain what's going on? Or even better -- for the benefits of future solution-seekers -- simplify the solution to match the original problem in it's form?
comment on: http://stackoverflow.com/a/47110178
type: Comment

http://stackoverflow.com/a/47187536
score: 2
type: Answer
answers question: http://stackoverflow.com/q/47184099
upvote count: 2
downvote count: 0
has body: c = [[i,j] for i in (a) for j in (b)]
has comment: http://stackoverflow.com/comment/81326081

http://stackoverflow.com/comment/81372996
type: AnswerComment
comment on: http://stackoverflow.com/a/47211514
has text: This actually worked thank you so much. Before $$ solution I used named places holders(https://pyformat.info)
type: Comment
score: 0

http://stackoverflow.com/q/47202965
has comment: http://stackoverflow.com/comment/81354435
tagged with: encryption
tagged with: python
has answer: http://stackoverflow.com/a/47203101
score: 0
answer count: 2
has title: How do I perform a simple substitution encryption in python?
has answer: http://stackoverflow.com/a/47203377
type: Question
has body: Sorry if this is a really simple question but I'm very new to python and I'm confused as to where to even start with this. What I need to do is substitute at least 5 letters from a sentence to produce a new encrypted sentence i.e "Hello my name is TGMezza" could be encrypted using ('H':'1', 'e':'2', 'l':'3', 'o':'4', 'm':'5') so it would instead read "12334 5y n15e is TGM2zza". I know this is probably a really simple question but I'd appreciate as much explanation of how to do this as possible because I'm such a newbie to this and all I've been able to find on my searches are much more complicated forms of encryption like a caesar cipher.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81354310

http://stackoverflow.com/a/47074545
answers question: http://stackoverflow.com/q/47072859
type: Answer
has comment: http://stackoverflow.com/comment/101916336
has comment: http://stackoverflow.com/comment/122110407
has body: I have found a solution that seems to work! Have a look at this: incremental writes to hdf5 with h5py! In order to append data to a specific dataset it is necessary to first resize the specific dataset in the corresponding axis and subsequently append the new data at the end of the "old" nparray. Thus, the solution looks like this: with h5py.File('.\PreprocessedData.h5', 'a') as hf: hf["X_train"].resize((hf["X_train"].shape[0] + X_train_data.shape[0]), axis = 0) hf["X_train"][-X_train_data.shape[0]:] = X_train_data hf["X_test"].resize((hf["X_test"].shape[0] + X_test_data.shape[0]), axis = 0) hf["X_test"][-X_test_data.shape[0]:] = X_test_data hf["Y_train"].resize((hf["Y_train"].shape[0] + Y_train_data.shape[0]), axis = 0) hf["Y_train"][-Y_train_data.shape[0]:] = Y_train_data hf["Y_test"].resize((hf["Y_test"].shape[0] + Y_test_data.shape[0]), axis = 0) hf["Y_test"][-Y_test_data.shape[0]:] = Y_test_data However, note that you should create the dataset with maxshape=(None,), for example h5f.create_dataset('X_train', data=orig_data, compression="gzip", chunks=True, maxshape=(None,)) otherwise the dataset cannot be extended.
has comment: http://stackoverflow.com/comment/84875656
accepted answer of: http://stackoverflow.com/q/47072859
upvote count: 74
has comment: http://stackoverflow.com/comment/107147625
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/94925577
score: 74

http://stackoverflow.com/comment/117018888
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47160440
has text: @LeonardoRick It’s not perfectly clear to me what it is you’re trying to say.

http://stackoverflow.com/q/47169313
favorite count: 0
type: Question
has body: I have created a custom op using the tutorial, and modified it a bit. I want to use this op as input for the compute_gradients method. My op expects three inputs: target values, predicted values, and another matrix. It returns a new matrix with the same shape as the target values. However, when I use @ops.RegisterGradient for this method, it expects strange return values, giving this message in one script: ValueError: Num gradients 1 generated for op name: "SoftDtwJacobianSqEuc" op: "SoftDtwJacobianSqEuc" input: "targets" input: "mul" input: "strided_slice" do not match num inputs 3 And this in another script: ValueError: Num gradients 1 generated for op name: "SoftDtwJacobianSqEuc" op: "SoftDtwJacobianSqEuc" input: "decoder_targets" input: "Reshape" input: "strided_slice_8" do not match num inputs 3 A snippet of the code I am running (full example below): # Calling the op backwards = soft_dtw_jacobian_sq_euc_module.soft_dtw_jacobian_sq_euc(decoder_targets, decoder_predictions, alignment_matrix[1:-1,1:-1]) # Need to register, other wise get error: No gradient defined for operation... @ops.RegisterGradient("SoftDtwJacobianSqEuc") def _soft_dtw_jacobian_sq_euc_grad(op, grad): # To generate the error which mentions the expected return values: return(None) # This kind of works in the first script, as I can 'mul'tiply the gradient with the output of the op #return(None, soft_dtw_jacobian_sq_euc_module.soft_dtw_jacobian_sq_euc(decoder_targets, decoder_predictions, alignment_matrix[1:-1,1:-1]), None) optimizer = tf.train.AdamOptimizer(0.02) params = tf.trainable_variables() gradients = optimizer.compute_gradients(backwards, params) train_op = optimizer.apply_gradients(gradients) Why is RegisterGradients expecting different return values? How does RegisterGradients determine these? Preferably I would just return the output of the op (since that's what I made it for), but if I do not use RegisterGradient I get a "No gradient defined for operation..." error. I have a complete…
type: UnansweredQuestion
has title: TensorFlow strange (random?) output expected for RegisterGradient
tagged with: python
has answer: http://stackoverflow.com/a/47383277
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: tensorflow

http://stackoverflow.com/q/47170925
tagged with: python
tagged with: python-3.6
tagged with: ipython
upvote count: 4
score: 4
answer count: 2
has answer: http://stackoverflow.com/a/47176626
has answer: http://stackoverflow.com/a/47171152
downvote count: 0
has comment: http://stackoverflow.com/comment/81291677
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I am getting error on the following python code. I'm running from a script. Im using python 3.6.2. import matplotlib matplotlib.use('Agg') import pandas as pd import numpy as np import matplotlib.pyplot as plt from IPython import get_ipython get_ipython().magic(u'matplotlib inline') I have tried using both py and jpy extensions. Tried to change the syntax for importing matplotlib but nothing works. The error from running with python shows. Traceback (most recent call last): File "example01.py", line 11, in &lt;module&gt; get_ipython().magic(u'matplotlib inline') AttributeError: 'NoneType' object has no attribute 'magic' Error from running with iPython shows /usr/local/lib/python3.6/site-packages/IPython/core/history.py:226: UserWarning: IPython History requires SQLite, your history will not be saved warn("IPython History requires SQLite, your history will not be saved") --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) ~/python/week1/example01.py in &lt;module&gt;() 9 from IPython import get_ipython 10 ---&gt; 11 get_ipython().magic(u'matplotlib inline') 12 /usr/local/lib/python3.6/site-packages/IPython/core/interactiveshell.py in magic(self, arg_s) 2172 magic_name, _, magic_arg_s = arg_s.partition(' ') 2173 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) -&gt; 2174 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2) 2175 2176 #------------------------------------------------------------------------- /usr/local/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth) 2093 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals 2094 with self.builtin_trap: -&gt; 2095 result = fn(*args,**kwargs) 2096 return result 2097 &lt;decorator-gen-107&gt; in matplotlib(self, line) /usr/local/lib/python3.6/site-packages/IPython/core/magic.py in &lt;lambda&gt;(f, *a, **k) 185 # but it's overkill for just that one bit of st…
has title: AttributeError: 'NoneType' object has no attribute 'magic'
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81291497

http://stackoverflow.com/comment/81353923
comment on: http://stackoverflow.com/a/47200367
type: Comment
has text: what is your code doing? compares two files if they are dups? finds dups in a directory? something else?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81130730
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47090630
has text: @ankitpandey that should have been `f.read()` I'll correct code. Sorry, I was rushing.
type: Comment

http://stackoverflow.com/comment/81373557
comment on: http://stackoverflow.com/a/47162390
score: 1
has text: Thanks Maxim. Apparently I can't rate your answer yet.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47177533
has answer: http://stackoverflow.com/a/49508723
has body: I am having a python script like below in a file git.py #!/usr/bin/env python # -*- coding:utf-8 -*- from git import Repo git_path = "test" repo = Repo(git_path) assert not repo.bare Python version is : Python 2.7.12 OS : Description: Ubuntu 16.04.1 LTS Gitpython - 2.1.7 I am getting the below error when i run python git.py Traceback (most recent call last): File "git.py", line 4, in &lt;module&gt; from git import Repo File "/home/user/demo_files/git.py", line 4, in &lt;module&gt; from git import Repo ImportError: cannot import name Repo I have checked most of the links ,available not able to resolve my issue. Please help me.
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81305375
answer count: 1
tagged with: git
favorite count: 0
has title: GitPython not able to import Repo from Git
type: Question
has comment: http://stackoverflow.com/comment/81305660
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81304449
tagged with: python

http://stackoverflow.com/comment/81316817
comment on: http://stackoverflow.com/q/47183342
has text: This is what I have currently. It only does half a diamond?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81386186
type: Comment
has text: I found this on the keras tutotial, I guess you might have skipped the +1, embedding_matrix = np.zeros((len(word_index) + 1, EMBEDDING_DIM))
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47215195

http://stackoverflow.com/q/47172110
tagged with: python
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/47172161
has body: import sys import os mac = 0 def mac_list(): global mac if sys.platform == 'win32': for line in os.popen("ipconfig /all"): if line.lstrip().startswith('Physical Address'): mac = line.split(':')[1].strip().replace(':','-') break else: for line in os.popen("/sbin/ifconfig"): if line.find('Ether') &gt; -1: mac = line.split()[4] break return mac I got this code from StackOverflow only. This works really good as my requirement to get MAC ID of Windows machine. -My Problem is When machine is connected to both Wlan and Ethernet this code fetching both activated MACids. I want to get only one active MAC(preferaly ethernet 1st and then if it's not available then wlan) can anyone recommend proper condition to filter the appropriate mac.
answer count: 1
linked to: http://stackoverflow.com/q/159137
tagged with: nic
has title: How to get Windows MacID using python script
type: Question
type: UnansweredQuestion
tagged with: windows

http://stackoverflow.com/comment/135384301
type: AnswerComment
comment on: http://stackoverflow.com/a/59288726
type: Comment
has text: why is tensorflow_datasets necessary?
score: 0

http://stackoverflow.com/a/47127882
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/81205963
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47127856
has comment: http://stackoverflow.com/comment/81206497
has body: For user's environment variables, use this: [Environment]::GetEnvironmentVariables("User") Use either of the following for system's environment variables: gci env:* ls Env: [Environment]::GetEnvironmentVariables("Machine") For a particular variable: [Environment]::GetEnvironmentVariable("PATH","Machine")
accepted answer of: http://stackoverflow.com/q/47127856
type: Answer

http://stackoverflow.com/q/47114939
has answer: http://stackoverflow.com/a/47114979
score: 0
answer count: 2
tagged with: random
upvote count: 3
has answer: http://stackoverflow.com/a/47115126
downvote count: 3
has title: Python - randomint() should be equal to C - rand()
has comment: http://stackoverflow.com/comment/81179709
has comment: http://stackoverflow.com/comment/81179906
favorite count: 0
type: Question
has body: I have the following C - Program: #include &lt;stdio.h&gt; #include &lt;time.h&gt; int main(int argc, char *argv[]){ srand(time(NULL)); printf("%d", rand()); } And this Python script: import random import time random.seed(int(time.time())) print (random.randint(0, 2147483647)) RAND_MAX in the C-program is defined as 2147483647. If I start both programs in the same second, they should print the same "random" number but this is not the case? Any ideas why? Are there different methods implemented to get a pseudo-random number? The seed is definitely the same.
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/81179688

http://stackoverflow.com/comment/81207655
score: 0
type: Comment
type: AnswerComment
has text: Yes I am using 3.x. Try raising ZeroDivisonError not ValueError
comment on: http://stackoverflow.com/a/47127793

http://stackoverflow.com/a/47070500
upvote count: 2
answers question: http://stackoverflow.com/q/47066584
downvote count: 0
type: Answer
score: 2
has body: In your case, simply print [[x, y**2, z] for x, y, z in l] would do the job and says more explicitly what is going on. In general, do from itertools import izip p = (1, 2, 1) # element 0 power 1 # # element 1 power 2 # # element 2 power 1 # ... print [[x**power for x, power in izip(row, p)] for row in l]
has comment: http://stackoverflow.com/comment/81089099

http://stackoverflow.com/a/47174563
answers question: http://stackoverflow.com/q/47171154
has comment: http://stackoverflow.com/comment/81301407
has comment: http://stackoverflow.com/comment/81300710
has body: PDF file is binary mode, you should read it as its format with its headers and footers. you can not read bianry files as raw string. 1) If you have ANY spaces in your file name, then PyPDF 2 decrypt function will ultimately fail despite returning a success code. Try to stick to underscores when naming your PDFs before you run them through PyPDF2. For example, Rather than "my pdf.pdf" do something like "my_pdf.pdf". 2) Try to decrypt it using an empty string as password and it works. Try This : import requests, PyPDF2 url = 'http://www.asx.com.au/asxpdf/20171103/pdf/43nyyw9r820c6r.pdf' response = requests.get(url) my_raw_data = response.content with open("my_pdf.pdf", 'wb') as my_data: my_data.write(my_raw_data) open_pdf_file = open("my_pdf.pdf", 'rb') read_pdf = PyPDF2.PdfFileReader(open_pdf_file) if read_pdf.isEncrypted: read_pdf.decrypt("") print(read_pdf.getPage(0).extractText()) else: print(read_pdf.getPage(0).extractText())
has comment: http://stackoverflow.com/comment/133677907
type: Answer
has comment: http://stackoverflow.com/comment/81303692
has comment: http://stackoverflow.com/comment/81303112
score: 11
upvote count: 11
has comment: http://stackoverflow.com/comment/81300222
has comment: http://stackoverflow.com/comment/81300047
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47171154
has comment: http://stackoverflow.com/comment/81300951

http://stackoverflow.com/q/47175165
type: UnansweredQuestion
tagged with: wget
has body: I have below code to download a file inside a loop, import wget try: wget.download(url) except: pass But if the Internet goes down, it doesn't return! So my whole loop is stuck. I want to repeat the same download if internet goes down. So I wanna know does any error happen. How can i mitigate this?
tagged with: python
has title: python wget library not returning if internet goes down for some times. How can I return with error if Internet is down?
has comment: http://stackoverflow.com/comment/81300960
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81299534
has comment: http://stackoverflow.com/comment/81299739
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47176398
has comment: http://stackoverflow.com/comment/81300681

http://stackoverflow.com/a/47183928
has body: In my experience with openpyxl, formatting functions like what you want require the worksheet to be passed in as an argument as well. wb = openpyxl.load_workbook('/New.xlsx') ws = wb.active ws = wb.get_sheet_by_name(u'И') redFill = PatternFill(start_color='FFFF00',end_color='FFFF00',fill_type='solid')#желтый redFill2 = PatternFill(start_color='FF4500',end_color='FF4500',fill_type='solid')#красный redFill3 = PatternFill(start_color='FFA500',end_color='FFA500',fill_type='solid')#оранжевый redFill4 = PatternFill(start_color='228B22',end_color='228B22',fill_type='solid')#зеленый def ws_f(wks, row, column): if wks.cell(row=row, column=column).value=='50,0%': wks.cell(row=row,column=column).fill = redFill2 elif wks.cell(row=row, column=column).value=='75,0%': wks.cell(row=row,column=column).fill = redFill3 elif wks.cell(row=row, column=column).value=='100,0%': wks.cell(row=row,column=column).fill = redFill4 wsf(ws, 3, 4) wb.save("File_out.xlsx") It's also better to have the variable not shadow the outer scoped ws that you have above so I named it wks. You don't want to call return in the function either as the output will expect a value passed back while this formatting simply operates on the cell itself. I tested it and it worked for me. Hope this helped!
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/47182872
accepted answer of: http://stackoverflow.com/q/47182872
type: Answer

web3py
tags question: http://stackoverflow.com/q/47129837
type: Tag
tag name: web3py

http://stackoverflow.com/a/47183687
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47183377
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47183377
has body: First, group keys that have the same value in a second dictionary. Then, use a dictionary comprehension to get the minimum key for all values that have duplicate keys. &gt;&gt;&gt; import collections &gt;&gt;&gt; my_data = {5:1,2:2,3:2,4:2,1:1} &gt;&gt;&gt; d = collections.defaultdict(list) &gt;&gt;&gt; for k, v in my_data.items(): ... d[v].append(k) &gt;&gt;&gt; {min(keys): value for value, keys in d.items() if len(keys) &gt; 1} {1: 1, 2: 2} (Not sure about the if len(key) &gt; 1. If that's not what you meant with "among the duplicated values", then just remove that part.)

http://stackoverflow.com/a/47071610
has comment: http://stackoverflow.com/comment/81091493
has body: you may want to use map and filter , and the globals().items() feature: concat_list = map ( lambda list_var : list_var[1] , filter ( lambda list_var : list_var[0].startswith("list"), globals().items())) your concat_list is the list of all items from all lists
downvote count: 0
has comment: http://stackoverflow.com/comment/81091218
has comment: http://stackoverflow.com/comment/81091984
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81091677
has comment: http://stackoverflow.com/comment/81091808
has comment: http://stackoverflow.com/comment/81091399
has comment: http://stackoverflow.com/comment/81091452
has comment: http://stackoverflow.com/comment/81091548
type: Answer
answers question: http://stackoverflow.com/q/47071450

http://stackoverflow.com/q/47149230
accepted answer: http://stackoverflow.com/a/47149347
has answer: http://stackoverflow.com/a/47149347
tagged with: tk-toolkit
tagged with: python
type: Question
tagged with: tkinter
has body: I am writing a time clock program. I have built the code, but have had trouble creating a GUI around it. I have entries that takes input and sends them to an outside function with a button event handling for calculation. Running the program, I do not get a label updating the time. I wonder if it has to do with my textvariables. from tkinter import * import time import os def show_entry_fields(): hr= hrvar.get() mn = minvar.get() sc = secvar.get() counter = int(hr)*3600+int(mn)*60+ int(sc) mins = int(counter/60) hours = int(mins/60) hours = IntVar() mins = IntVar() secs = IntVar() while counter &gt; 0: counter -= 1 hours, sec = divmod(counter, 3600) mins, sec = divmod(sec, 60) printv = StringVar() printv = (" %d Hr:, %d Min: %d Sec" % (hours, mins, sec)) win1 = Tk() timeLabel = Label(win1, textvariable= printv).grid(row=7) mins= int(counter/60) hours = int(mins/60) time.sleep(1) os.system('cls') return else: finishedLabel = Label(master, text="Time is Up").grid(row=7) return master = Tk() Label(master, text="Enter Hour(s)").grid(row=0) Label(master, text="Enter Mins(s)").grid(row=1) Label(master, text="Enter Second(s)").grid(row=2) hrvar = IntVar() minvar = IntVar() secvar = IntVar() e1 = Entry(master, textvariable = hrvar) e2 = Entry(master, textvariable = minvar) e3 = Entry(master, textvariable = secvar) e1.grid(row=0, column=1) e2.grid(row=1, column=1) e3.grid(row=2, column=1) Button(master, text='Quit', command=master.quit).grid(row=3, column=0, sticky=W, pady=4) Button(master, text='Show', command=show_entry_fields).grid(row=3, column=1, sticky=W, pady=4) mainloop( ) Updated code. class Timer: def __init__(self, master): #self.seconds = 0 self.time = StringVar() self.hr = StringVar() self.mins = StringVar() self.secs = StringVar() self.hr_label = Label(master, text='Enter Hours').pack() self.entry_hr = Entry(master, textvariable = self.hr ) self.entry_hr.pack() self.min_label = Label(master, text='Enter Minutes').pack() self.entry_min = Entry(master, textvariabl…
answer count: 1
has title: Why is my label not updating variable from different function? Tkinter
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47180983
score: 20
has comment: http://stackoverflow.com/comment/81311054
upvote count: 20
accepted answer: http://stackoverflow.com/a/47181183
has answer: http://stackoverflow.com/a/68147285
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/69052960
has comment: http://stackoverflow.com/comment/108302938
type: AnsweredQuestion
tagged with: pandas
tagged with: duplicates
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81310941
has answer: http://stackoverflow.com/a/47181183
has body: I am trying to find duplicate rows in a pandas dataframe, but keep track of the index of the original duplicate. df=pd.DataFrame(data=[[1,2],[3,4],[1,2],[1,4],[1,2]],columns=['col1','col2']) df Out[15]: col1 col2 0 1 2 1 3 4 2 1 2 3 1 4 4 1 2 duplicate_bool = df.duplicated(subset=['col1','col2'], keep='first') duplicate = df.loc[duplicate_bool == True] duplicate Out[16]: col1 col2 2 1 2 4 1 2 Is there a way to add a column referring to the index of the first duplicate (the one kept) duplicate Out[16]: col1 col2 index_original 2 1 2 0 4 1 2 0 Note: df could be very very big in my case....
has comment: http://stackoverflow.com/comment/81310856
answer count: 3
possible better answer: http://stackoverflow.com/a/68147285
has title: Keep duplicate rows after the first but save the index of the first

http://stackoverflow.com/q/47131615
downvote count: 2
has body: I am a noob in Python/Django and want to know what additional benefits Django forms offer compared to html forms? From what I have seen in a few tutorials, Django forms are mostly used for front-end validation only, which can also be done by html/JavaScript, so why should I use Django forms?
tagged with: django
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/81212958
has comment: http://stackoverflow.com/comment/81212963
has comment: http://stackoverflow.com/comment/81212754
upvote count: 0
has title: What is the need for forms in Django?
answer count: 1
tagged with: django-forms
has comment: http://stackoverflow.com/comment/81212925
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47137588
type: UnansweredQuestion
score: -2

http://stackoverflow.com/comment/81271252
comment on: http://stackoverflow.com/q/47160523
type: Comment
type: QuestionComment
has text: What is wrong with this code? I tested it and it works, when you double click it changes the coordinates, and when you press a it appends it to physNodes... and when 'esc' key is pressed it exits and closes all windows. I did not tested in Jupyter though.... what is actually doing in your case? could it be a jupyter problem perhaps?
score: 0

http://stackoverflow.com/a/47131995
has comment: http://stackoverflow.com/comment/81307264
has comment: http://stackoverflow.com/comment/81252057
type: Answer
score: 4
answers question: http://stackoverflow.com/q/47131771
has comment: http://stackoverflow.com/comment/81307402
has comment: http://stackoverflow.com/comment/81237677
accepted answer of: http://stackoverflow.com/q/47131771
type: AcceptedAnswer
downvote count: 0
has body: Python's int objects can grow as big as necessary (subject only to how much memory is available), so they can be used for calculations involving huge numbers. In Python 2, there were 2 integer types, int and long, with int being used for values that fit into machine integers, but in Python 3 they've been amalgamated into a single int type. Python doesn't have a built-in BigFloat type, but the standard library does have the decimal module which can do basic arithmetic, including square roots, to any desired precision. If you need to do arbitrary precision mathematics with more functions, please see the excellent 3rd-party library, mpmath. You can safely use // floor division when computing binomial coefficients, since the terms in the denominator are guaranteed to divide the numerator. Eg from math import factorial a = (factorial(500) // factorial(490)) // factorial(10) print(a) output 245810588801891098700 However, it may be more efficient to calculate the binomial coefficient with a simple loop, rather than calculating those huge factorials. def binomial(n, r): ''' Binomial coefficients ''' if not 0 &lt;= r &lt;= n: return 0 p = 1 r = min(r, n - r) for i in range(1, r+1): p *= n p //= i n -= 1 return p # Test print(binomial(500, 10), '\n') for i in range(10): print([binomial(i, j) for j in range(i+1)]) output 245810588801891098700 [1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] [1, 7, 21, 35, 35, 21, 7, 1] [1, 8, 28, 56, 70, 56, 28, 8, 1] [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
upvote count: 4

http://stackoverflow.com/q/47116080
tagged with: range
tagged with: python
has comment: http://stackoverflow.com/comment/81182314
has comment: http://stackoverflow.com/comment/81182174
tagged with: for-loop
has comment: http://stackoverflow.com/comment/81182632
tagged with: function
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/81182237
answer count: 1
has comment: http://stackoverflow.com/comment/81182145
favorite count: 0
has answer: http://stackoverflow.com/a/47116447
type: Question
accepted answer: http://stackoverflow.com/a/47116447
has comment: http://stackoverflow.com/comment/81182344
type: AnsweredQuestion
has title: Trying to make loop for a function that stops after the result is lower than a certain value
score: -2
has body: I'm taking a beginner python class and part of an exercise we were given was this: The point x with the property x= sin(x)−ax+ 30 is called a fixed point of the function f(x) = sin(x)−ax+ 30. It can be computed with the so-called fixed point iteration: x(i+1)= sin(x(i))−ax(i)+ 30, where the superscript (i) denotes an iteration counter. Here you find a piece of Python code which performs the first 200 steps of this x=0.5 a=0.5 for i in range(200): x = sin(x) - a*x + 30 print('The result after {num} iterations is {res}.'.format(num=i, res=x)) Modify the code in such a way that it stops iterating as soon as |x(i+1)−x(i)| &lt; 10−8. Furthermore it should print a little message if this condition was not met within 200 iteration steps. Test your code with a= 0.5 and a= 8 I've tried to do this but am not getting anywhere with it. This is what I have so far, any help would be much appreciated. x = 0.5 a = 8 iterations = 0 for i in range(y): x = sin(x) - a*x + 30 if abs(x**(i+1) - x**i) &lt; 1.e-8: break elif i &gt; 200: iterations += 1 print('The result after {num} iterations is {res}.'.format(num=i, res=x)) if iterations &gt; 0: print('The condition was not met within 200 iteration steps.')

http://stackoverflow.com/q/47180602
has comment: http://stackoverflow.com/comment/81329069
has answer: http://stackoverflow.com/a/47286100
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81322829
score: 0
has comment: http://stackoverflow.com/comment/81320176
has comment: http://stackoverflow.com/comment/81326391
has title: Flask-Admin | How to fix route to the image
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/81321705
has comment: http://stackoverflow.com/comment/81324129
has comment: http://stackoverflow.com/comment/81406376
tagged with: flask-admin
has comment: http://stackoverflow.com/comment/81330064
has body: I have a question according to image path in Flask. I have a DB model Image, that contains all necessary info about image, including path - '/animals/sometype/image.jpg'. I'm using Flask-admin module, and the problem is the wrong path to the image in editing mode. Here's a code: class ImageView(ModelView): edit_template = 'image_edit.html' def _list_thumbnail(view, context, model, name): if not model.path: return '' return Markup('&lt;img src="%s"&gt;' % url_for('static', filename=('images' + model.path))) column_formatters = { 'path': _list_thumbnail } form_extra_fields = { 'path': form.ImageUploadField('Image', base_path='static/images', url_relative_path='images/') } For column formatters path is correct, but for the extra fields is wrong, resulting in 404 error: http://127.0.0.1:5000/static//animals/birds/the_bird-wallpaper-1366x768.jpg How can I solve this? Also, I was thinking about passing an image to the custom edit template, but I don't understand, how to do it in Flask-Admin.
tagged with: python
tagged with: flask
accepted answer: http://stackoverflow.com/a/47286100

http://stackoverflow.com/comment/81190980
score: 2
comment on: http://stackoverflow.com/q/47120642
has text: It's too early to ask this question. Keep learning.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47197960
tagged with: runtime-error
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/47197982
answer count: 1
favorite count: 0
type: Question
has body: i'm a beginner in python, i'm using python 3x, i'm getting an 'attribute error' : 'NoneType' object has no attribute 'isdigit' on line 4 of my program. Q: Use a "forever" while loop to get user input of integers to add to sum, until a non-digit is entered, then break the loop and print sum .Here is the program : sum = 0 num="" while True: num=print("input no. :") if num.isdigit(): sum=sum+int(num) else: break print("sum is :",sum) what must be the modification to be done to modify the program. thanks
tagged with: python-3.x
type: UnansweredQuestion
score: -2
tagged with: python
has title: Attribute error using python3x

http://stackoverflow.com/a/47104987
type: Answer
has body: You have a recursive function so you need to pass in an initial Current_Pal and keep passing that variable to the subsequent calls; you can also do the same for Longest_Pal, like below: def isPal(s, Current_Pal='', Longest_Pal=''): if len(s) &lt;= 1: return Current_Pal + s else: if s[0] == s[-1]: Current_Pal = Current_Pal + s[0] else: if Current_Pal &gt; Longest_Pal: Longest_Pal = Current_Pal Current_Pal = '' return isPal(s[1:-1], Current_Pal, Longest_Pal) This way it's set to '' and then the additional changes are continually passed into the method, retaining its previous value. On a side note, you should probably rewrite your else statements: def isPal(s, Current_Pal='', Longest_Pal=''): if len(s) &lt;= 1: return Current_Pal + s elif s[0] == s[-1]: Current_Pal = Current_Pal + s[0] elif Current_Pal &gt; Longest_Pal: Longest_Pal = Current_Pal Current_Pal = '' return isPal(s[1:-1], Current_Pal, Longest_Pal)
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47104717
answers question: http://stackoverflow.com/q/47104717

http://stackoverflow.com/q/47096120
type: UnansweredQuestion
downvote count: 2
linked to: http://stackoverflow.com/q/261638
has answer: http://stackoverflow.com/a/51919783
has comment: http://stackoverflow.com/comment/90789341
favorite count: 0
tagged with: dll
answer count: 5
has answer: http://stackoverflow.com/a/53860462
has answer: http://stackoverflow.com/a/47096336
tagged with: python
tagged with: source-code-protection
score: 1
has answer: http://stackoverflow.com/a/47096534
has body: I have written a python code which takes an input data file, performs some processing on the data and writes another data file as output. I should distribute my code now but the users should not see the source code but be able to just giving the input and getting the output! I have never done this before. I would appreciate any advice on how to achieve this in the easiest way. Thanks a lot in advance
type: Question
has comment: http://stackoverflow.com/comment/117166085
has answer: http://stackoverflow.com/a/73302562
has title: How to protect my Python code before distribution?
upvote count: 3

http://stackoverflow.com/comment/81132096
has text: @jonatan: Yes the shebang of `ipython` is correct...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47091061

http://stackoverflow.com/comment/81094056
score: 0
comment on: http://stackoverflow.com/q/47072916
has text: it depends on what `Get_Y` does and is implemented, can you post that code
type: Comment
type: QuestionComment

http://stackoverflow.com/a/55520971
has body: I had the same problem and found the solution at https://github.com/scrapy/scrapy/issues/3447 conda update -n base conda And as it turns out, the error occured only within PyCharm and the solution was to install OpenSSL according to https://github.com/conda/conda/issues/8046#issuecomment-450515815
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47164238
downvote count: 0

http://stackoverflow.com/comment/81209031
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47126957
has text: It seems that `a[:,None]-b` also gives the same result as `a[:,None,:]-b` for two 2D arrays that I tried. How exactly does `a[:,None,:]` work?
score: 0

http://stackoverflow.com/comment/81246537
has text: So, is it work for you ? I can not realize it ? The images doesn't appear, with your last update !
type: Comment
comment on: http://stackoverflow.com/a/47147865
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81084995
comment on: http://stackoverflow.com/a/47067760
type: Comment
score: 0
type: AnswerComment
has text: This does what I want. Thanks. Would you know how to extend groupby with other aggregation functions in one step? Say if I need the sum and the mean?

http://stackoverflow.com/comment/81327466
has text: Just use a list and convert to an array. It's likely going to be more performant.
type: QuestionComment
comment on: http://stackoverflow.com/q/47189031
type: Comment
score: 0

http://stackoverflow.com/comment/81399454
has text: Ah great thanks, it was the `to_frame` piece I was missng!
comment on: http://stackoverflow.com/a/47215106
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81219819
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47131587
has text: pandas version is '0.19.2' , I did filledna() but it affects in other ways

http://stackoverflow.com/a/47214624
score: 0
answers question: http://stackoverflow.com/q/47214610
has body: You want str.lstrip(). Exact same as strip() except it strips from the left only, not both directions. &gt;&gt;&gt; s = '\n\nhi\n' &gt;&gt;&gt; s.lstrip('\n') 'hi\n'
type: Answer

http://stackoverflow.com/q/47166077
type: AnsweredQuestion
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81282141
tagged with: python
has comment: http://stackoverflow.com/comment/81282096
favorite count: 0
tagged with: bash
type: Question
score: 3
has body: I'm trying to use Curl to perform a call with the DUO API. I tried reviewed their docs here: https://duo.com/docs/adminapi#authentication The docs says to pass the creds as HMAC key for the request but now sure how to get that going. This is what I got so far: curl --request GET \ --header 'Authorization: Basic 'Integration key:Secret key'' \ --header "Content-Type: application/x-www-form-urlencoded" \ "https://api-12345678.duosecurity.com/auth/v2/check" Which returns {"code": 40101, "message": "Missing request credentials", "stat": "FAIL"} Can one point me to the right direction for an example in Bash. If not in Python.
tagged with: shell
has title: Duo API Bash Call
accepted answer: http://stackoverflow.com/a/47166217
possible better answer: http://stackoverflow.com/a/52844449
tagged with: curl
has answer: http://stackoverflow.com/a/47166217
has answer: http://stackoverflow.com/a/52844449
has comment: http://stackoverflow.com/comment/81281906
answer count: 2
tagged with: api

http://stackoverflow.com/comment/81359782
type: AnswerComment
has text: you're right @D.Everhard it is (too) long on purpose ;)
comment on: http://stackoverflow.com/a/47203887
type: Comment
score: 0

http://stackoverflow.com/comment/81347059
type: Comment
has text: @Alfe good point, but OP chose a very poor separator. Updated. It would be much better to choose `:`
type: AnswerComment
comment on: http://stackoverflow.com/a/47199085
score: 0

http://stackoverflow.com/q/47166043
score: 1
has title: Flask 404 response from AJAX request
tagged with: python
has answer: http://stackoverflow.com/a/67244626
favorite count: 0
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/19627195
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81281909
has comment: http://stackoverflow.com/comment/81281802
has body: I am trying to get a simple AJAX request to be handled by Flask, but am having issues getting the request sent to the correct address. I am using this simple route and function withing the app.py file to define how to handle a request to URL/HelloWorld: @app.route('/HelloWorld', methods=['GET', 'POST']) def HelloWorldRouted(): return "Hello World!" I am using this jQuery function to attempt to send a request to URL/HelloWorld: $.ajax({ type: "POST", url: "/HelloWorld", headers: {"Content-Type": "application/json"}, success: function(response) { console.log('Response:\t', response) } }); When I start the Flask server and send a request via my browser to URL:5000/HelloWorld, I can see the expected "Hello World" message, as well as a log of the request in the server output: "GET /HelloWorld HTTP/1.1" 200 However, when I attempt to submit the request via that webpage, I get the following error in the console: POST URL/HelloWorld 404 (Not Found) So my question is what do I need to do for the app to handle requests from URL/ instead of URL:5000/. I am hosting the webpage and server on an AWS EC2 Amazon Linux instance if that matters at all.
tagged with: jquery
has comment: http://stackoverflow.com/comment/81281956
tagged with: flask
tagged with: ajax
has answer: http://stackoverflow.com/a/47167456
downvote count: 0
upvote count: 1

jupyter-notebook
tags question: http://stackoverflow.com/q/47158370
tags question: http://stackoverflow.com/q/47118935
tags question: http://stackoverflow.com/q/47137370
tags question: http://stackoverflow.com/q/47121093
tags question: http://stackoverflow.com/q/47211324
tags question: http://stackoverflow.com/q/47071709
tags question: http://stackoverflow.com/q/47147749
tags question: http://stackoverflow.com/q/47086510
tags question: http://stackoverflow.com/q/47102564
tags question: http://stackoverflow.com/q/47145648
tags question: http://stackoverflow.com/q/47212852
tags question: http://stackoverflow.com/q/47124387
tags question: http://stackoverflow.com/q/47201227
tags question: http://stackoverflow.com/q/47194815
tags question: http://stackoverflow.com/q/47213631
tags question: http://stackoverflow.com/q/47155472
tags question: http://stackoverflow.com/q/47109960
tags question: http://stackoverflow.com/q/47117876
tags question: http://stackoverflow.com/q/47192545
tags question: http://stackoverflow.com/q/47165346
tags question: http://stackoverflow.com/q/47077433
tags question: http://stackoverflow.com/q/47100854
tags question: http://stackoverflow.com/q/47145233
tags question: http://stackoverflow.com/q/47194211
tags question: http://stackoverflow.com/q/47198319
tags question: http://stackoverflow.com/q/47146358
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/47169287
tags question: http://stackoverflow.com/q/47101046
tags question: http://stackoverflow.com/q/47124683
tags question: http://stackoverflow.com/q/47075946
type: Tag
tags question: http://stackoverflow.com/q/47147106
tags question: http://stackoverflow.com/q/47185277
tags question: http://stackoverflow.com/q/47192144
tags question: http://stackoverflow.com/q/47169539
tags question: http://stackoverflow.com/q/47114998
tags question: http://stackoverflow.com/q/47181602
tags question: http://stackoverflow.com/q/47082416
tags question: http://stackoverflow.com/q/47191192
tags question: http://stackoverflow.com/q/47191297
tags question: http://stackoverflow.com/q/47167659
tags question: http://stackoverflow.com/q/47113934

http://stackoverflow.com/comment/81341853
type: Comment
has text: I added 10 cols as an example. Actual number of cols are about 10000. I want to apply the function on these 10000 cols in parallelized fashion
type: AnswerComment
comment on: http://stackoverflow.com/a/47189270
score: 0

http://stackoverflow.com/comment/112486138
has text: You will want to add `import shutil` to the imports in your answer
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/59178861
score: 1

http://stackoverflow.com/comment/81283021
has text: hey guys why answering a triplicate?
type: Comment
comment on: http://stackoverflow.com/a/47166576
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81244086
type: QuestionComment
comment on: http://stackoverflow.com/q/47145741
has text: The problem, it seems, it that when I request a subset of items via boolean index, the call doesn't know what I'm going to do with the results. It would be convenient if python/numpy has a way specifying for what the result of the `__getitem__` will be used, e.g., `tested.multi_index([~mask],[selected]) = True`
score: 0
type: Comment

http://stackoverflow.com/q/47192804
accepted answer: http://stackoverflow.com/a/47476106
tagged with: python
has answer: http://stackoverflow.com/a/49790784
tagged with: tkinter
has body: I see that Tkinter for qpython is available ( https://github.com/qpython-android/qpython3-core/blob/master/python3-src/Doc/library/tkinter.rst ) but it is not installed by default with Qpython app on android. How can I install Tkinter on Qpython on android device? I could not get the answer from website. Thanks for your help.
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47476106
answer count: 2
has title: Installing Tkinter on Qpython
type: Question
tagged with: qpython
tagged with: android
possible better answer: http://stackoverflow.com/a/49790784

http://stackoverflow.com/comment/81350318
type: QuestionComment
score: 1
has text: `Memory errors` are very bad handled, if large data, because obviously help add RAM, but very often it is impossible :(
type: Comment
comment on: http://stackoverflow.com/q/47200853

http://stackoverflow.com/a/47097428
has comment: http://stackoverflow.com/comment/81155139
has comment: http://stackoverflow.com/comment/81145651
score: 1
has comment: http://stackoverflow.com/comment/81145735
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47096859
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81145484
accepted answer of: http://stackoverflow.com/q/47096859
type: Answer
has comment: http://stackoverflow.com/comment/81147582
has comment: http://stackoverflow.com/comment/81149273
has comment: http://stackoverflow.com/comment/81144924
has body: Note: I'm using Python 3, and my image_raw is a byte object, so the results will be different (probably due to the difference between things like byte, unicode and str), but the explanation should be applicable. It helps to print out a part of the actual res.content. In the first case: &gt;&gt;&gt; res.content[:200] b'{\n "args": {}, \n "data": "", \n "files": {}, \n "form": {\n "pic": "\\ufffdPNG\\r\\n\\u001a\\n\\u0000\\u0000\\u0000\\rIHDR\\u0000\\u0000\\u0001\\u000f\\u0000\\u0000\\u0000\\u0019\\b\\u0002\\u0000\\u0000\\u0000\\ufffd\\uf' In the second case: &gt;&gt;&gt; res.content[:200] b'{\n "args": {}, \n "data": "", \n "files": {}, \n "form": {\n "name": "1.png", \n "pic": "iVBORw0KGgoAAAANSUhEUgAAAQ8AAAAZCAIAAACgtTxbAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAc' As you can see, res.content, the string returned by http://httpbin.org/post, is actually a human-readable representation of the POST data. In the first case, the POST data contains many non-ASCII characters, which are encoded in an even more inefficient encoding than base64 -- \uxxxx escape sequences. This is why the length of res.content is longer in the first case.

http://stackoverflow.com/comment/81126068
comment on: http://stackoverflow.com/q/47088045
type: Comment
type: QuestionComment
has text: That is true, however, i'm failing to understand how can i incorporate the instanceid inside the function, could you shed some light? Thanks!
score: 0

http://stackoverflow.com/a/48344733
type: AcceptedAnswer
downvote count: 0
score: 16
upvote count: 16
answers question: http://stackoverflow.com/q/47137370
has body: If you want to use Text instead of Textarea you can connect a callback via the on_submit method. This gets executed once Enter is hit in the text field. from ipywidgets import interact, widgets from IPython.display import display text = widgets.Text( value='last', placeholder='Paste ticket description here!', description='String:', disabled=False ) display(text) def callback(wdgt): # replace by something useful display(wdgt.value) text.on_submit(callback)
type: Answer
accepted answer of: http://stackoverflow.com/q/47137370

http://stackoverflow.com/q/47074132
downvote count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81097179
has comment: http://stackoverflow.com/comment/81098601
tagged with: django-shell
score: 2
answer count: 0
has title: Function Call in another function not working in django shell
has comment: http://stackoverflow.com/comment/81101287
has comment: http://stackoverflow.com/comment/81098675
favorite count: 0
type: Question
has body: I have a file : def fetchArticles(topic): testing() def testing(): print("testing") print("starting") fetchArticles("World") It is present in a app in django and when i run it as a standalone file using python3 xyz.py it runs perfectly fine but when i run it in django shell using python3 manage.py shell &lt; xyz.py it is not able to locate the testing function. It shows this error : starting Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/shell.py", line 101, in handle exec(sys.stdin.read()) File "&lt;string&gt;", line 12, in &lt;module&gt; File "&lt;string&gt;", line 4, in fetchArticles NameError: name 'testing' is not defined Can anyone help me to resolve this issue ?
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/81098771
type: UnansweredQuestion

http://stackoverflow.com/comment/81235129
comment on: http://stackoverflow.com/q/47141916
score: 3
has text: I think that the fact that pandas 20.0.0 happens to have `df.melt` is besides the point. Perhaps if the OP had not given specific examples then people would be more likely to answer the actual question asked, which is "Why were some operations in pandas implemented as DataFrame methods while others were implemented as functions that accept a DataFrame?" I think there is an interesting history lesson there if someone happens to know the answer.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47166702
has title: Scrapy how to define custom ItemExporters
answer count: 0
duplicate of: http://stackoverflow.com/q/33290876
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81296305
score: 0
has comment: http://stackoverflow.com/comment/81305978
has body: I want to export scraped data into the google sheets. I know I can write own pipeline to export need info, but from scrapy documentation pipelines aren't intended to use in that way. They suggested to use Item Exporters, but it's not clear for me the usage of it: Where I should define the custom exporter? What kind of changes I need to do in settings.py to enable custom exporter?
linked to: http://stackoverflow.com/q/33290876
tagged with: scrapy
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/47188143
has comment: http://stackoverflow.com/comment/81325772
has comment: http://stackoverflow.com/comment/81327381
score: 1
possible better answer: http://stackoverflow.com/a/47188478
favorite count: 0
type: Question
tagged with: split
has body: I am very new to python and getting stuck in list splitting even referring to many examples in stackoverflow. What can I do if I want to split a list with the following conditions? Task 1. Split the list like this once the items in "wordlist" were found in "datalist" collected. Wordlist = ["Time", "date", "place",....] output = ["A","B"]["Time","C","D","E"]["Date",.....] Task 2. Once a specific item was found, the list would be split following by the specific word and n items included, then continue to loop over the dlist. e.g. word, n = no. of item followed Time, 1 Date, 2 place, 1 .... input: datalist = ["A","B", "N", "K" , "R", "Time", "2230" , "C" , "Date" , '12/05', "E" , "F", "R", "F", "K" ,"Place", "XXXXXX", "H", "I" , "J" ] wordlist = ["Time", "Date", "Place"] n = [1,2,1] output: newlist = [["A","B", "N", "K" , "R"] ,["Time", "2230"],[ "C"], [ "Date" , '12/05',"E"][ "F", "R", "F", "K" ], ["Place", "XXXXXX"], ["H", "I","J"] ] This is my referred example solving task-1 partially while not for task-2: Python spliting a list based on a delimiter word
has title: Python split list by multiple elements and conditions
downvote count: 0
has comment: http://stackoverflow.com/comment/81325784
has answer: http://stackoverflow.com/a/47188478
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81325867
has answer: http://stackoverflow.com/a/47188644
accepted answer: http://stackoverflow.com/a/47188644
linked to: http://stackoverflow.com/q/15357830
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81326909
has answer: http://stackoverflow.com/a/47188612
tagged with: conditional-statements
tagged with: list
answer count: 3

http://stackoverflow.com/comment/81353242
has text: OK, then need `df.groupby(['name','geoid']).name.count().sort_values(ascending=False)‌​.iloc[50:]`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47201262
type: Comment

http://stackoverflow.com/comment/81164071
type: AnswerComment
comment on: http://stackoverflow.com/a/47106786
score: 0
has text: Thanks @ReblochonMasque
type: Comment

http://stackoverflow.com/comment/81344096
type: AnswerComment
has text: Hi i casted them to an integer and it worked. Many thanks
type: Comment
comment on: http://stackoverflow.com/a/47194021
score: 0

ascii
tags question: http://stackoverflow.com/q/47221611
tags question: http://stackoverflow.com/q/47176548
tags question: http://stackoverflow.com/q/47075856
type: Tag
tag name: ascii

http://stackoverflow.com/a/47101499
type: Answer
has comment: http://stackoverflow.com/comment/81156012
score: 0
answers question: http://stackoverflow.com/q/47101428
has body: In Python, () indicates that you want to call or execute something, a function for example. You were trying to call numbers by numbers() in the last line, which is a list, not a function. Change it to numbers to get the length of the list numbers. with open('Numbers.txt') as f: numbers = f.readlines() numbers = [int(x.strip()) for x in numbers] print(numbers[0]) print(len(numbers))

http://stackoverflow.com/q/47175195
tagged with: python
has answer: http://stackoverflow.com/a/47175995
has title: how to append to a list from input data, and print the list
score: 0
has answer: http://stackoverflow.com/a/47175561
has answer: http://stackoverflow.com/a/47175307
has answer: http://stackoverflow.com/a/47175293
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81299678
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81300269
has comment: http://stackoverflow.com/comment/81308316
has answer: http://stackoverflow.com/a/47175318
has body: All I would like to do is to enter three scores for player1, and have them appended to the list please: player1=[0,0,0] player2=[0,0,0] print('please enter your score for player 1, round 1') player1.append=int(input([0])) print('please enter your score for player 1, round 2') player1.append=int(input([1])) print('please enter your score for player 1, round 3') player1.append=int(input([2])) print(player1)
answer count: 5
type: UnansweredQuestion

http://stackoverflow.com/comment/81397632
has text: Suggestion: do a quick test with `nc` listening in localhost in a given port (adjusting host and port in `header` variable, of course) in order to see which exact HTTP message is your program sending on the wire.
score: 0
comment on: http://stackoverflow.com/q/47202065
type: Comment
type: QuestionComment

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/47211869

http://stackoverflow.com/a/47106908
downvote count: 0
score: 5
has comment: http://stackoverflow.com/comment/81164327
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47106751
has body: Just another way of doing in case you like using itertools.chain and collections.Counter: from itertools import chain from collections import Counter dict(Counter(chain.from_iterable(foods.values()))) #or Simply dict(Counter(chain(*foods.values()))) #Output: #{'apple': 3, 'banana': 4, 'grapes': 1, 'orange': 1}

http://stackoverflow.com/comment/81370472
has text: I'm not talking about performance, which is rarely a concern. I'm talking about "idiomatic" code that's easy to understand and change.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47210551

http://stackoverflow.com/q/47103246
has body: I have 2 lists and ready built pass and print of a function. I can replace each element of 1st list with each element of 2nd list separately but I am not sure how to do it all together in a function. I have searched for answers here on stackoverflow for hours now, but all the python stuff here on this subject is so old and not compatible with python 3.6. I hope you can give me a hint what to use without the use of any imported methods (e.g. if/elif or something else). Here is what I have so far: def goodbadString(string): for (a,b) in zip(strings, expectedResults): string = string.replace(strings[0],expectedResults[0]) return string strings = ['It has been a good and bad day', 'bad company', 'good is as good does!', 'Clovis is a big city.'] expectedResults = ['I am confused', 'goodbye', 'hello', 'hello and goodbye'] for string, expectedResult in zip(strings, expectedResults): print('Sample string = ', string) print('Expected result =', expectedResult) print('Actual result =', goodbadString(string)) print() This is expected result (not the whole result though) you can see that my function did show the right result for a first "Sample string" but now I should continue for the rest of the elements (actual result for a second sample "goodbye" and so on).
has answer: http://stackoverflow.com/a/47104095
tagged with: python
tagged with: python-3.6
has title: How to replace all elements in list 1 with all elements from list 2 in defined function Python3
tagged with: replace
has comment: http://stackoverflow.com/comment/81159184
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/81159278
has comment: http://stackoverflow.com/comment/81158050
accepted answer: http://stackoverflow.com/a/47104095
score: 1
has comment: http://stackoverflow.com/comment/81158355
tagged with: function
has comment: http://stackoverflow.com/comment/81158321
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81158659
has comment: http://stackoverflow.com/comment/81158319
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81158433

http://stackoverflow.com/q/47168721
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/47168845
answer count: 3
has answer: http://stackoverflow.com/a/47168845
score: -5
has answer: http://stackoverflow.com/a/47168803
has comment: http://stackoverflow.com/comment/81375813
has comment: http://stackoverflow.com/comment/81287481
has comment: http://stackoverflow.com/comment/81288233
favorite count: 0
has title: File to string conversion in python
type: Question
has comment: http://stackoverflow.com/comment/81287474
accepted answer: http://stackoverflow.com/a/47168804
upvote count: 0
has body: dictionary = file . read() I'm currently creating a cipher solver for the 2017 cipher challenge I have a word document of fifty eight thousand words but i cannot get the file as a string in python 2.7.9 I have tried many thing i have read online such as the above code but to no avail. I also need this to be easy to understand as i am new to python Thanks!Don't be negative be constructive! The word are from: http://www.mieliestronk.com/corncob_lowercase.txt
has answer: http://stackoverflow.com/a/47168804
linked to: http://stackoverflow.com/q/12453580
linked to: http://stackoverflow.com/q/3277503
downvote count: 5

http://stackoverflow.com/comment/81102049
has text: I see. Thank you for your quick answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47076820
type: Comment

http://stackoverflow.com/comment/81156832
type: Comment
score: 0
has text: Dear, I have edited my output, full script and expected output description, please check
type: AnswerComment
comment on: http://stackoverflow.com/a/47102020

http://stackoverflow.com/a/49324304
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47175398
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47175398
type: Answer
has body: It took me awhile, but I finally solved this using Datashader. If using a notebook, the plots can be embedded into interactive Bokeh plots, which looks really nice. Anyhow, here is the code for static images, in case someone else is in need of something similar: # coding: utf-8 import time import numpy as np from numpy.polynomial import polynomial import pandas as pd import matplotlib.pyplot as plt import datashader as ds import datashader.transfer_functions as tf plt.style.use("seaborn-whitegrid") def create_data(): # ... # Each column is one data sample df = create_data() # Following will append a nan-row and reshape the dataframe into two columns, with each sample stacked on top of each other # THIS IS CRUCIAL TO OPTIMIZE SPEED: https://github.com/bokeh/datashader/issues/286 # Append row with nan-values df = df.append(pd.DataFrame([np.array([np.nan] * len(df.columns))], columns=df.columns, index=[np.nan])) # Reshape x, y = df.shape arr = df.as_matrix().reshape((x * y, 1), order='F') df_reshaped = pd.DataFrame(arr, columns=list('y'), index=np.tile(df.index.values, y)) df_reshaped = df_reshaped.reset_index() df_reshaped.columns.values[0] = 'x' # Plotting parameters x_range = (min(df.index.values), max(df.index.values)) y_range = (df.min().min(), df.max().max()) w = 1000 h = 750 dpi = 150 cvs = ds.Canvas(x_range=x_range, y_range=y_range, plot_height=h, plot_width=w) # Aggregate data t0 = time.time() aggs = cvs.line(df_reshaped, 'x', 'y', ds.count()) print("Time to aggregate line data: {}".format(time.time()-t0)) # One colored plot t1 = time.time() stacked_img = tf.Image(tf.shade(aggs, cmap=["darkblue", "darkblue"])) print("Time to create stacked image: {}".format(time.time() - t1)) # Save f0 = plt.figure(figsize=(w / dpi, h / dpi), dpi=dpi) ax0 = f0.add_subplot(111) ax0.imshow(stacked_img.to_pil()) ax0.grid(False) f0.savefig("stacked.png", bbox_inches="tight", dpi=dpi) # Heat map - This uses a equalized histogram (built-in default), there are other options, though. …
upvote count: 12
score: 12

http://stackoverflow.com/comment/81280103
score: 1
has text: `float(data_splitted)` is obviously wrong..
comment on: http://stackoverflow.com/q/47165189
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47168382
downvote count: 1
answer count: 1
tagged with: nested
has answer: http://stackoverflow.com/a/61576396
has body: I have output from python networkX code: flow_value, flow_dict = nx.maximum_flow(T, 'O', 'T') print(flow_dict) #Output as followesenter #{'O': {'A': 4, 'B': 6, 'C': 4}, 'A': {'B': 1, 'D': 3}, 'B': {'C': 0, 'E': 3,'D': 4}, 'C': {'E': 4}, 'E': {'D': 1, 'T': 6}, 'D': {'T': 8}, 'T': {}} I want to extract all the data in the form looks like: #('O','A',4),('O','B','6'),('O','C','4'),('A','B',1),......,('D','T',8) Any ways can I traverse thru the nested dict and get the data I need?
favorite count: 0
tagged with: networkx
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81289392
has comment: http://stackoverflow.com/comment/81286806
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81286904
upvote count: 2
has title: Python How to Extract data from Nested Dict
score: 1

http://stackoverflow.com/q/47186962
has comment: http://stackoverflow.com/comment/81327199
has title: Plotting a histogram using argparse
tagged with: matplotlib
score: 1
favorite count: 0
tagged with: numpy
tagged with: python-3.x
type: Question
has body: I am new to using argparse and in this instance I have to use it as the code will be ran through a terminal. I want the user to be able to enter a bin size in the terminal and then the program will plot the histogram. The code works fine if I use input statements however I am having problems getting it to work with argparse. Here is the code at the moment. from matplotlib import pyplot as plt import numpy as np import argparse import sys fh = open('dummy2.pepmasses') values = [] for line in fh: data = line.split() protname, pep, mz, z, p, sequence = data mz = float(mz) #print(mz) values.append(mz) parser = argparse.ArgumentParser() parser.add_argument('-s', '--Bin_size', type=int, metavar='', required=True, help='Size of bin, multiple of 100 between 100-1000') args = parser.parse_args() def Histogram(Bin_size): if Bin_size ==100: bins = [0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000, 2100, 2200, 2300, 2400, 2500, 2600, 2700, 2800, 2900, 3000, 3100, 3200, 3300, 3400, 3500, 3600, 3700, 3800, 3900, 4000, 4100, 4200, 4300, 4400, 4500, 4600, 4700, 4800, 4900, 5000, 5100, 5200, 5300, 5400, 5500, 5600, 5700, 5800, 5900, 6000, 6100] elif Bin_size ==200: bins = [0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400, 2600, 2800, 3000, 3200, 3400, 3600, 3800, 4000, 4200, 4400, 4600, 4800, 5000, 5200, 5400, 5600, 5800, 6000, 6200] elif Bin_size ==300: bins = [0, 300, 600, 900, 1200, 1500, 1800, 2100, 2400, 2700, 3000, 3300, 3600, 3900, 4200, 4500, 4800, 5100, 5400, 5700, 6000, 6300] elif Bin_size ==400: bins= [0, 400, 800, 1200, 1600, 2000, 2400, 2800, 3200, 3600, 4000, 4400, 4800, 5200, 5600, 6000, 6400] elif Bin_size ==500: bins = [0, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000, 6500] elif Bin_size ==600: bins = [0, 600, 1200, 1800, 2400, 3000, 3600, 4200, 4800, 5400, 6000, 6600] elif Bin_size ==700: bins = [0, 700, 1400, 2100, 2800, 3500, 4100, 4900, 5600, 6300] elif …
has comment: http://stackoverflow.com/comment/81324995
has comment: http://stackoverflow.com/comment/81323627
answer count: 0
downvote count: 0
tagged with: histogram
has comment: http://stackoverflow.com/comment/81325344
upvote count: 1
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47200754
has body: I'm a newbie for python and SQL. My database contain a field which stored path to images. I want to assign each path to a variable in python. I can only store only the path of first row. This is my code import pymysql from arcpy import env env.workspace = "D:/year 4 semester 1/Python/Data/" conn= pymysql.connect(host='localhost',user='root',password='',db='research') cursor = conn.cursor () cursor.execute ("select Path from sourcedata") data = cursor.fetchmany() for row in data : a= row[0] print a But when I try following way including all other relevant text for row in data : a= row[0] b = row[1] c = row[2] print a Following error appear IndexError: tuple index out of range
has answer: http://stackoverflow.com/a/47200869
tagged with: python
downvote count: 1
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has title: Retrieve data from sql database using python
accepted answer: http://stackoverflow.com/a/47200869
tagged with: sql
answer count: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: data-retrieval

http://stackoverflow.com/a/62198061
score: 1
has body: I encountered the same issue. The nested table has to be inside a table cell e.g.: ...
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47145898
type: Answer

http://stackoverflow.com/q/47135852
has answer: http://stackoverflow.com/a/47135959
answer count: 1
favorite count: 0
has body: I am currently working on extracting latitude and longitude values of "point" field from json . I want to store each field value in two new columns. The JSON in pandas dataframe is as follows: user_id timestamp point 0 58d3ac2de04bd5249b4f6600 14567410 {'lon': 2.9546, 'lat': 41.5486} 1 58d3ac2de04bd5249b4f6600 14567410 {'lon': 2.9546, 'lat': 41.5486} 2 58d3ac2de04bd5249b4f6600 14567410 {'lon': 2.9546, 'lat': 41.5486} 3 58d3ac2de04bd5249b4f6600 14567410 {'lon': 2.9546, 'lat': 41.5486} 4 58d3ac2de04bd5249b4f6600 14567410 {'lon': 2.9546, 'lat': 41.5486} I tried in the following function and works: row = test["point"][0] type(row) row["lat"] But now I want to extract with the another function and I get the new columns with: &lt;function getLat at 0x0000000006AE2950&gt; &lt;function getLon at 0x0000000006A58BF8&gt; The function is: def getLat(point): return point["lat"] def getLon(point): return point["lon"] test["lat"] = test["point"].apply(lambda row: getLat) test["lon"] = test["point"].apply(lambda row: getLon) And I get the following table: user_id timestamp point lat lon 0 58d3ac2de04bd5249b4f6600 14567410 {'lon': 2.9546, 'lat': 41.5486} &lt;function getLat at 0x0000000006AE2950&gt; &lt;function getLon at 0x0000000006A58BF8&gt; 1 58d3ac2de04bd5249b4f6600 14567410 {'lon': 2.9546, 'lat': 41.5486} &lt;function getLat at 0x0000000006AE2950&gt; &lt;function getLon at 0x0000000006A58BF8&gt; 2 58d3ac2de04bd5249b4f6600 14567410 {'lon': 2.9546, 'lat': 41.5486} &lt;function getLat at 0x0000000006AE2950&gt; &lt;function getLon at 0x0000000006A58BF8&gt; 3 58d3ac2de04bd5249b4f6600 14567410 {'lon': 2.9546, 'lat': 41.5486} &lt;function getLat at 0x0000000006AE2950&gt; &lt;function getLon at 0x0000000006A58BF8&gt; 4 58d3ac2de04bd5249b4f6600 14567410 {'lon': 2.9546, 'lat': 41.5486} &lt;function getLat at 0x0000000006AE2950&gt; &lt;function getLon at 0x0000000006A58BF8&gt; Where is my code incorrect? Thanks
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81220928
type: Question
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: pandas
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
has title: How to get a latitude and longitude fields particular value of JSON in python 3?
score: 1

http://stackoverflow.com/q/47213443
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/47213647
type: AnsweredQuestion
score: 1
upvote count: 1
has body: I'm encountering really strange reproducible behaviour for the boxcox function of scipy that I cannot quite explain. Apologies for the long example but it seems to be specifically this data that causes the issue: data = [1710, 1262, 1786, 1717, 2198, 1362, 1694, 2090, 1774, 1077, 1040, 2324, 912, 1494, 1253, 854, 1004, 1296, 1114, 1339, 2376, 1108, 1795, 1060, 1060, 1600, 900, 1704, 1600, 520, 1317, 1228, 1234, 1700, 1561, 2452, 1097, 1297, 1057, 1152, 1324, 1328, 884, 938, 1150, 1752, 2149, 1656, 1452, 955, 1470, 1176, 816, 1842, 1360, 1425, 1739, 1720, 2945, 780, 1158, 1111, 1370, 1710, 2034, 2473, 2207, 1479, 747, 2287, 2223, 845, 1718, 1086, 1605, 988, 952, 1285, 1768, 1230, 2142, 1337, 1563, 1065, 1474, 2417, 1560, 1224, 1526, 990, 1040, 1235, 964, 2291, 1786, 1470, 1588, 960, 835, 1225, 1610, 1732, 1535, 1226, 1818, 1992, 1047, 789, 1517, 1844, 1855, 1430, 2696, 2259, 2320, 1458, 1092, 1125, 3222, 1456, 988, 1123, 1080, 1199, 1586, 754, 958, 840, 1348, 1053, 2157, 2054, 1327, 1296, 1721, 1682, 1214, 1959, 1852, 1764, 864, 1734, 1385, 1501, 1728, 1709, 875, 2035, 1080, 1344, 969, 1710, 1993, 1252, 1200, 1096, 1040, 1968, 1947, 2462, 1232, 2668, 1541, 882, 1616, 1355, 1867, 2161, 1720, 1707, 1382, 1656, 1767, 1362, 1651, 2158, 2060, 1920, 2234, 968, 1525, 1802, 1340, 2082, 1252, 3608, 1217, 1656, 1224, 1593, 2727, 1479, 1431, 1709, 864, 1456, 1726, 3112, 2229, 1713, 1121, 1279, 1310, 848, 1284, 1442, 1696, 1100, 2062, 1092, 864, 1212, 1852, 990, 1392, 1236, 1436, 1328, 1954, 1248, 1498, 2267, 1552, 864, 2392, 1302, 2520, 987, 912, 1555, 1194, 2794, 987, 894, 1960, 987, 1414, 1744, 1694, 1487, 1566, 866, 1440, 1217, 2110, 1872, 1928, 1375, 1668, 2144, 1306, 1625, 1640, 1302, 1314, 2291, 1728, 1604, 1792, 882, 1382, 2574, 1212, 1316, 764, 1422, 1511, 2192, 778, 1113, 1939, 1363, 2270, 1632, 816, 1548, 1560, 864, 2121, 2022, 1982, 1262, 1314, 1468, 1575, 1250, 1734, 858, 900, 1396, 1919, 1716, 1716, 2263, 1644, 1003, 1558, 1950, 1743, 1152, 1336, 2452, 1541, 894, 3…
answer count: 1
downvote count: 0
has title: divide by zero encountered in log scipy.stats.boxcox
tagged with: scipy
has answer: http://stackoverflow.com/a/47213647

http://stackoverflow.com/a/47099710
has body: As @OzgurVatansever stated in the comment you can simply split on "_": import os, csv mylist = os.listdir("M:/") with open("output.csv", 'w') as myfile: wr = csv.writer(myfile, lineterminator='\n') wr.writerows(row.split("_") for row in mylist) Hope that helps. Thanks @OzgurVatansever.
type: Answer
answers question: http://stackoverflow.com/q/47099567
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/47070119
has comment: http://stackoverflow.com/comment/81088128
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47070272
upvote count: 1
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81088154
tagged with: generator
score: 0
has comment: http://stackoverflow.com/comment/81088169
answer count: 1
has body: When I am using a generator, even I modify the dictionary passed to it, the generator still gives me a result with the old data structure. How could I fix that? def min_key_order(adict:dict): for key, value in sorted(adict.items()): yield (key, value) d = {1:'a', 2:'x', 4:'m', 8:'d', 16:'f'} i = min_key_order(d) print(next(i)) d.pop(2) print(next(i)) And it gives me (1,'a'), (2,'x'), even I have pop key 2 from the dictionary.
downvote count: 1
has title: How to keep the dictionary up to date when using a generator?
favorite count: 0
type: Question

http://stackoverflow.com/comment/81135975
type: AnswerComment
type: Comment
has text: I seem to get: indexes = [index for index in range(get_options_length)] TypeError: 'function' object cannot be interpreted as an integer
comment on: http://stackoverflow.com/a/47092339
score: 0

http://stackoverflow.com/q/47131902
has title: Draw Arc Between Two Points with Python Turtle
answer count: 1
has comment: http://stackoverflow.com/comment/81215870
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I want to use Python Turtle to draw an arc between two points. The turtle module allows something like turtle.circle(200, 180) but this is very limited, as I want to control the orientation of the arc as well. I see that Tkinter has something that does this: from Tkinter import * canvas = Canvas(width=300, height=300, bg='white') canvas.pack(expand=YES, fill=BOTH) canvas.create_arc(200, 200, 300, 100) widget = Label(canvas, text='AAA', fg='white', bg='black') widget.pack() canvas.create_window(100, 100, window=widget) mainloop() but I can't work out how to get this to work with just Turtle. I expect there are several possible solutions. Any help much appreciated.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81214791
tagged with: python
has comment: http://stackoverflow.com/comment/81236478
score: 0
has answer: http://stackoverflow.com/a/47145789
tagged with: turtle-graphics

http://stackoverflow.com/a/66397584
answers question: http://stackoverflow.com/q/47199348
score: 0
type: Answer
has body: If lang="es" meta is not Declared in the html you can to use (langdetect, requests, html2text) Modules with the following function to convert your website html to text then autodetect language : Let's install the Modules First : pip install langdetect && pip install requests && pip install html2text from langdetect import detect import requests import html2text def Detect_Lang(url): response = requests.get(url) # Requests to get url html rep = response.text # html txt=html2text.html2text(rep) # converting html to text response.close() # Close your Request return detect(txt) # Return language value Exp: (en, ar, pl, es) ... linklang=Detect_Lang("https://stackoverflow.com/questions/47199348/how-can-i-get-page-language-of-web-site-with-python") # Run Your Function print(linklang) # Print Language

http://stackoverflow.com/q/47130274
has comment: http://stackoverflow.com/comment/81215952
answer count: 1
has comment: http://stackoverflow.com/comment/81215882
has comment: http://stackoverflow.com/comment/81215714
has title: How to store values using onchange in odoo?
has comment: http://stackoverflow.com/comment/81215767
favorite count: 0
type: Question
has body: If I save the amount_total value changes to prior position because it is readonly. i want that field to be readonly. discount = fields.Selection([('fixed', 'fixed Price'), ('percentage', 'Percentage')], string="Discount") amount = fields.Float("Amount") total = fields.Float("Discounted Amount", store=True, compute='discount_amount') amount_total = fields.Monetary(string='Total', store=True,readonly=True, compute='_amount_all') @api.onchange('total') def totalamount(self): if self.total: self.amount_total -= self.total How to deal with this
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/47134676
upvote count: 1
tagged with: python
tagged with: odoo-10
tagged with: onchange
tagged with: odoo
score: 1

http://stackoverflow.com/comment/81259343
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47153241
type: Comment
has text: It giving any error or what ?? can you share the code how you reading CSV File

http://stackoverflow.com/comment/92299961
type: AnswerComment
comment on: http://stackoverflow.com/a/47393161
score: 0
type: Comment
has text: I am also creating a package with some command line args. Can you tell me how to make it ?

http://stackoverflow.com/comment/81570260
comment on: http://stackoverflow.com/q/47086718
has text: No and I think that is why, I will update it and let you know, thanks. Please check out my other post: https://stackoverflow.com/questions/47305550/python-for-android-in-app-purchase-kivy
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47127777
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81205735
score: -1
answer count: 4
has body: My start of the code goes like that: complementDNA = originalDNA.replace('a' , 't' , 't' , 'a') and it says on the running complementDNA = originalDNA.replace('a' , 't' , 't' , 'a') TypeError: replace() takes at most 3 arguments (4 given)
has answer: http://stackoverflow.com/a/47127889
has answer: http://stackoverflow.com/a/47127897
downvote count: 3
has comment: http://stackoverflow.com/comment/81205719
has answer: http://stackoverflow.com/a/47127885
favorite count: 0
has answer: http://stackoverflow.com/a/47128072
type: Question
upvote count: 2
has title: I want to write code to replace some arguments
tagged with: python

http://stackoverflow.com/q/47196883
has comment: http://stackoverflow.com/comment/81342724
has comment: http://stackoverflow.com/comment/81342809
downvote count: 0
possible better answer: http://stackoverflow.com/a/47197357
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81342967
has answer: http://stackoverflow.com/a/47197357
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81342984
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81342499
accepted answer: http://stackoverflow.com/a/47197661
has title: How can I output the file name with its word content in such format in python?
tagged with: python
has answer: http://stackoverflow.com/a/47197661
has body: Say I have a file test.txt containing : 1:text1.txt 2:text2.txt text1.txt contains: I am a good person text2.txt contains: Bla bla I would like to output : I 1 Bla 2 am 1 bla 2 good 1 a 1 person 1 As in I want to output the file index with each word in the file. I would post my code but it is so ugly and far from the solution. I'm new to python so please be nice. There is no specified order of the output, the sample output I mentioned is utterly random just to get you to have an idea of what I'm looking for. This is my code `with open("text.txt", "r") as f: text=f.readlines() for line in text: splitted=line.split(":") splitsplit=splitted[1].split("\n") files=splitsplit[0] splittedindicies=splitted[0].split("\n") indicies=splittedindicies[0] print indicies[0] files_list=list(files) files_l=files.split(" ") for x in files_l: fileshandle=open(x,"r") read=fileshandle.readlines() for y in read: words=y.split(" ") words.sort() for j in words: print j ` My output is: 1 I am a good person 2 Bla bla Again, please be nice, I'm an R programmer first time dealing with python.
has comment: http://stackoverflow.com/comment/81342555
has comment: http://stackoverflow.com/comment/81342419
has comment: http://stackoverflow.com/comment/81342613
answer count: 2
has comment: http://stackoverflow.com/comment/81342773

http://stackoverflow.com/a/47122592
has comment: http://stackoverflow.com/comment/81195241
score: 3
answers question: http://stackoverflow.com/q/47122494
upvote count: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can pass sharey=True to plt.subplots see the following docs for more info: https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.subplots.html For your second question on putting the subplots into a loop, you could use enumerate to loop over a list of your columns with an increasing index: for index,name in enumerate(['OWOCE','WARZYWA','NASIONA']): gg = sns.barplot(x="DANE", y=name, palette=sns.color_palette(flatui),data=x4,ci=None, ax=ax[index]) gg.set_xlabel(name,size = 15,color="g",alpha=0.5) gg.set_ylabel("",size = 20,color="r",alpha=0.5) plt.setp(gg.get_xticklabels(), rotation=-45) if index==1: gg.axes.set_title('Wpływ procentu marży na wielkosć sprzedaży', fontsize=15,color="b",alpha=0.3)
accepted answer of: http://stackoverflow.com/q/47122494

http://stackoverflow.com/comment/81326695
has text: Is this a fixed width file? Also, what code have you tried that isn't working?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47188698
score: 0

http://stackoverflow.com/q/47157129
tagged with: http://stackoverflow.com/tag/html
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47164476
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
tagged with: python
tagged with: web.py
has title: File Download and Directory Access Python(web.py) + HTML
type: AnsweredQuestion
has body: I need it when it is a file it downloads and when it is a directory it accesses the directory, could anyone help me? because when I go to a folder it gets /Python/Python/directory and does not access, like leaving it only /python/directory Thanks #!/usr/bin/python import web import os urls = ( '/(.*)', 'hello' ) app = web.application(urls, globals()) class hello: def GET(self, path): path = '/Python/'+path lista = ' ' caminhos = [os.path.join(path, nome) for nome in os.listdir(path)] diretorios = [dire for dire in caminhos if os.path.isdir(dire)] for dire in diretorios: # lista = lista+dire+' ' lista = lista+''+dire+' ' arquivos = [arq for arq in caminhos if os.path.isfile(arq)] for arq in arquivos: lista = lista+''+arq+' ' # lista = lista+arq+' ' lista = lista+' Voltar ' return lista if __name__ == "__main__": app.run()
score: 2
tagged with: operating-system
accepted answer: http://stackoverflow.com/a/47164476

http://stackoverflow.com/a/47151024
score: 1
type: AcceptedAnswer
downvote count: 0
has body: As I had mentioned earlier, the datatypes didn't match. So, the input array had to be converted into dtype of double. code: image = Image.open('1.jpg') data = array(image,dtype="double") print pad(data,data.shape[0])
type: Answer
accepted answer of: http://stackoverflow.com/q/47142114
answers question: http://stackoverflow.com/q/47142114
upvote count: 1

http://stackoverflow.com/q/47141980
score: 1
has answer: http://stackoverflow.com/a/47142498
has body: I have data A = np.array([1,2,3,4,5,6,7,8,9,10]) ind = np.array([0,1,4]) beg = 3 Typical size of A and ind is few millions. What I want to do is modify data in A with index ind+beg. for i in range(0,ind.size): A[ind[i]+beg] += 1 Since the operation on A (+1) is almost the same as adding beg to ind[i], I want to avoid this. In C-code, I usually do this by using pointer. int* ptA = A-beg; for(int i=0; i&lt;indsize; i++) ptA[ind[i]]++; Is it possible to do in python in a similar way, or should I stick to the first code?
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/23905817
has answer: http://stackoverflow.com/a/47142707
tagged with: python
duplicate of: http://stackoverflow.com/q/23905817
answer count: 2
has title: Accessing a segment of a numpy array

http://stackoverflow.com/comment/81235273
type: QuestionComment
has text: I have posted a simple working example.
score: 0
comment on: http://stackoverflow.com/q/47079461
type: Comment

http://stackoverflow.com/comment/81236691
comment on: http://stackoverflow.com/q/47142968
score: 0
type: Comment
type: QuestionComment
has text: I don't. I have to guess based on the information I have. Both encode `ç` as `\xe7`. The server should tell you what it uses with `Content-Type` and I would expect a decent Python library to use that header.

string
tags question: http://stackoverflow.com/q/47148641
tags question: http://stackoverflow.com/q/47113652
tags question: http://stackoverflow.com/q/47067043
tags question: http://stackoverflow.com/q/47170100
tags question: http://stackoverflow.com/q/47101982
tags question: http://stackoverflow.com/q/47191492
type: Tag
tags question: http://stackoverflow.com/q/47199314
tags question: http://stackoverflow.com/q/47188054
tags question: http://stackoverflow.com/q/47198703
tags question: http://stackoverflow.com/q/47107851
tags question: http://stackoverflow.com/q/47081741
tags question: http://stackoverflow.com/q/47191365
tags question: http://stackoverflow.com/q/47082106
tags question: http://stackoverflow.com/q/47144509
tags question: http://stackoverflow.com/q/47138573
tags question: http://stackoverflow.com/q/47099802
tags question: http://stackoverflow.com/q/47216834
tags question: http://stackoverflow.com/q/47118470
tags question: http://stackoverflow.com/q/47192228
tags question: http://stackoverflow.com/q/47180942
tags question: http://stackoverflow.com/q/47082021
tags question: http://stackoverflow.com/q/47160355
tags question: http://stackoverflow.com/q/47165189
tags question: http://stackoverflow.com/q/47130133
tags question: http://stackoverflow.com/q/47162399
tags question: http://stackoverflow.com/q/47214610
tags question: http://stackoverflow.com/q/47187105
tags question: http://stackoverflow.com/q/47088629
tags question: http://stackoverflow.com/q/47215275
tags question: http://stackoverflow.com/q/47141710
tags question: http://stackoverflow.com/q/47103377
tags question: http://stackoverflow.com/q/47091727
tags question: http://stackoverflow.com/q/47126257
tags question: http://stackoverflow.com/q/47119793
tags question: http://stackoverflow.com/q/47180633
tags question: http://stackoverflow.com/q/47188590
tags question: http://stackoverflow.com/q/47190553
tags question: http://stackoverflow.com/q/47213335
tags question: http://stackoverflow.com/q/47096806
tags question: http://stackoverflow.com/q/47078837
tags question: http://stackoverflow.com/q/47077275
tags question: http://stackoverflow.com/q/47131096
tags question: http://stackoverflow.com/q/47075718
tags question: http://stackoverflow.com/q/47121478
tags question: http://stackoverflow.com/q/47105893
tags question: http://stackoverflow.com/q/47161308
tags question: http://stackoverflow.com/q/47148204
tags question: http://stackoverflow.com/q/47206672
tags question: http://stackoverflow.com/q/47113787
tags question: http://stackoverflow.com/q/47204134
tags question: http://stackoverflow.com/q/47214374
tags question: http://stackoverflow.com/q/47067985
tags question: http://stackoverflow.com/q/47087801
tags question: http://stackoverflow.com/q/47179002
tags question: http://stackoverflow.com/q/47085958
tags question: http://stackoverflow.com/q/47168609
tags question: http://stackoverflow.com/q/47214402
tags question: http://stackoverflow.com/q/47185093
tag name: string
tags question: http://stackoverflow.com/q/47217927
tags question: http://stackoverflow.com/q/47072491
tags question: http://stackoverflow.com/q/47214992
tags question: http://stackoverflow.com/q/47168821
tags question: http://stackoverflow.com/q/47119450
tags question: http://stackoverflow.com/q/47185380
tags question: http://stackoverflow.com/q/47147563
tags question: http://stackoverflow.com/q/47169033
tags question: http://stackoverflow.com/q/47143165
tags question: http://stackoverflow.com/q/47214245
tags question: http://stackoverflow.com/q/47129866
tags question: http://stackoverflow.com/q/47102441
tags question: http://stackoverflow.com/q/47193230
tags question: http://stackoverflow.com/q/47129380

http://stackoverflow.com/comment/81307859
has text: So, please provide a [mcve] with _actual_ pandas data structures, not lists.
comment on: http://stackoverflow.com/q/47179215
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81187140
has text: none, just blank...
comment on: http://stackoverflow.com/a/47118632
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81155075
has text: Now that I have tested it, looks like Divakar's suggestion worked like a wonder.
score: 0
comment on: http://stackoverflow.com/q/47102190
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81280051
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47164979
score: 0
has text: What is the actual specific error you get? Include it in the question

http://stackoverflow.com/a/47143116
has comment: http://stackoverflow.com/comment/81241274
type: Answer
has comment: http://stackoverflow.com/comment/81237386
answers question: http://stackoverflow.com/q/47142536
has comment: http://stackoverflow.com/comment/81242382
accepted answer of: http://stackoverflow.com/q/47142536
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: What I would absolutely suggest is to use the curses module for fine-grain control over the terminal. You can find many examples of Snake programmed using this module, such as this one. To approach it without curses, I've written some sample code below. Note that you can't use print as-is, because it outputs a newline character \n after every call. (In Python 3, you can write print("hello",end="",flush=True) to get around this). So, in lei of print, I'm using sys.stdout.write(). Remember to use Ctrl+C to end a running Terminal program. import time from sys import stdout as s # Let's break this function down: # After writing a line to stdout, any additional # writing will happen at the end of this line. # Use \r (the carriage return) to reset to the beginning of # the line. Add 40 spaces to clear any characters on that line. # Then, go back to the beginning of the line again. def clear(): s.write("\r" + " "*40 + "\r") x = 0 x_max = 20 while True: clear() time.sleep(0.2) # Move the snake (*****) by increasing spaces s.write(" "*x+"*****") # Calling write puts characters into a 'buffer' # Calling flush() will write that buffer to the screen s.flush() x += 1 # Increase the x position # If the snake moves too far right, # reset him if (x &gt; x_max): x = 0

http://stackoverflow.com/a/47130456
type: Answer
score: -1
has body: If you want to print every step then you can use recursive approach: The beauty of Recursion : string_='stack' def recursion_reverse(string_1): if not string_1: return "" else: front_part=recursion_reverse(string_1[1:]) back_part=string_1[0] print(front_part+back_part + string_[:-len(string_1)]) return front_part+back_part[0] print(recursion_reverse(string_)) output: kstac kcsta kcast kcats kcats kcats
answers question: http://stackoverflow.com/q/47129866
upvote count: 0
downvote count: 1

http://stackoverflow.com/comment/81359065
type: AnswerComment
has text: @yinnonsanders better use `enumerate(lst)` if you want both the items and their indices.
comment on: http://stackoverflow.com/a/47205091
score: 1
type: Comment

http://stackoverflow.com/comment/81334276
has text: @Ankita Das, Given that both uid and iid are columns, direct indexing won't work as it assumes the first value to be the row index. You have to use df.loc[df['userID']==Uid, Iid]
score: 0
comment on: http://stackoverflow.com/q/47191956
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47144382
type: UnansweredQuestion
has title: Compiled version of OpenCV is unable to read video metadata (frame count)
has comment: http://stackoverflow.com/comment/81244547
tagged with: compilation
tagged with: python
has comment: http://stackoverflow.com/comment/81244618
tagged with: opencv
tagged with: video
score: 0
tagged with: metadata
has comment: http://stackoverflow.com/comment/81257948
has comment: http://stackoverflow.com/comment/81243321
linked to: http://stackoverflow.com/q/47112642
has comment: http://stackoverflow.com/comment/81245020
type: Question
has body: I have compiled OpenCV according to https://docs.opencv.org/master/d7/d9f/tutorial_linux_install.html Used sources for 2.4.13.4. Used the following cmake command: cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local -D PYTHON3_EXECUTABLE=/opt/anaconda3/bin/python PYTHON_INCLUDE_DIR=/opt/anaconda3/include/python3.5m PYTHON_INCLUDE_DIR2=/usr/include/python3.5 PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.5m.so PYTHON3_NUMPY_INCLUDE_DIRS=/opt/anaconda3/lib/python3.5/site-packages/numpy/core/include .. Tests ran ok. sudo make install ran ok. Unfortunately, in Python: video = cv.VideoCapture(filename) frame_count = int(video.get(cv.CAP_PROP_FRAME_COUNT)) returns zero. Suspect that cv2 package I use in python is just something separate. How to ensure cv2 uses the same OpenCV i compiled? UPDATE dims@calculon:~$ python -c "import cv2; print(cv2.__version__)" 3.3.0 dims@calculon:~$ pkg-config opencv --modversion 2.4.13.4
answer count: 0
has comment: http://stackoverflow.com/comment/81245335

pymongo
tags question: http://stackoverflow.com/q/47105525
tags question: http://stackoverflow.com/q/47139067
tags question: http://stackoverflow.com/q/47124481
tags question: http://stackoverflow.com/q/47133829
tags question: http://stackoverflow.com/q/47073925
tags question: http://stackoverflow.com/q/47086666
tags question: http://stackoverflow.com/q/47096633
type: Tag
tag name: pymongo
tags question: http://stackoverflow.com/q/47100989
tags question: http://stackoverflow.com/q/47075722
tags question: http://stackoverflow.com/q/47188727
tags question: http://stackoverflow.com/q/47148516

http://stackoverflow.com/q/47068715
type: Question
has answer: http://stackoverflow.com/a/47069000
type: UnansweredQuestion
tagged with: user-interface
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47068925
answer count: 3
has title: Cross Platform Python GUI Application
has answer: http://stackoverflow.com/a/47069416
downvote count: 3
tagged with: cross-platform
tagged with: python
score: -2
has body: Using python I am going to develop a cross-platform GUI application with following constraints Support all platform Desktop application with one click installation Also, have a tool for creating GUI (Drag and Drop) Can some guide me to find out best python modules or packages to satisfy all my constraints Thanks in advance....

http://stackoverflow.com/comment/81277568
type: Comment
score: 0
type: AnswerComment
has text: Oh, you are right. I kept thinking at what was wrong without thinking about the deploy. Thank you Scott!
comment on: http://stackoverflow.com/a/47163748

http://stackoverflow.com/comment/81150419
type: QuestionComment
comment on: http://stackoverflow.com/q/47100107
score: 1
has text: Someone just voted to close the question as "too broad". Why is it too broad and how could it be rephrased to be specific enough?
type: Comment

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/47206168

http://stackoverflow.com/a/57698343
answers question: http://stackoverflow.com/q/47115946
score: 4
has comment: http://stackoverflow.com/comment/102619284
has comment: http://stackoverflow.com/comment/102559897
has comment: http://stackoverflow.com/comment/138376983
type: Answer
has comment: http://stackoverflow.com/comment/102740075
has comment: http://stackoverflow.com/comment/102664919
upvote count: 4
has comment: http://stackoverflow.com/comment/102566318
downvote count: 0
has body: If you are calling the python function that calls Tensorflow from an external module, make sure that you the model isn't being loaded as a global variable or else it may not be loaded in time for usage. This happened to me calling a Tensorflow model from the Flask server.

http://stackoverflow.com/comment/81112695
comment on: http://stackoverflow.com/q/47081747
type: Comment
has text: What is wrong with your code? What does it do? What is your expected result vs the actual result? Do you get any errors? What have you tried?
score: 1
type: QuestionComment

http://stackoverflow.com/q/47078033
has body: Below are the output of the models.py from django.db import models from django.core.urlresolvers import reverse #from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Registration(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(max_length = 250) password = models.CharField(max_length = 250) email = models.CharField(max_length = 250) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Registration.objects.create(username=instance) instance.registration.save() Below is the output of the views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm from .forms import SignUpForm from django.views import generic class IndexView(generic.View): templet_name = 'user_info/index.html' def signupview(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('registration_form.html') else: form = SignUpForm() return render(request,'user_info/registration_form.html', {'form': form}) I have two questions: 1) In my models.py I have 4 fields, 'user','username','password','email'. In my first field "user", I guess, I shouldn't be using "models.OneToOneField(User, on_delete=models.CASCADE)", because, as per my understanding, it's used when we have a primary key and foreign key in working. Please correct me if I am wrong. 2) in my views.py, the function "signupview", I am saving the form in the database through form.save(), and then cleaned the data. have I done the right thing, as my models.py has 4 fields, but in view.p…
answer count: 1
has comment: http://stackoverflow.com/comment/81105250
accepted answer: http://stackoverflow.com/a/47079842
has answer: http://stackoverflow.com/a/47079842
has comment: http://stackoverflow.com/comment/81107002
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81106836
score: 0
has comment: http://stackoverflow.com/comment/81108207
has comment: http://stackoverflow.com/comment/81106218
has comment: http://stackoverflow.com/comment/81105040
has comment: http://stackoverflow.com/comment/81105207
has comment: http://stackoverflow.com/comment/81106918
type: Question
has comment: http://stackoverflow.com/comment/81104680
tagged with: django
tagged with: python
has title: models.py and views.py may be conflicting

http://stackoverflow.com/a/47140706
answers question: http://stackoverflow.com/q/47140166
downvote count: 4
has comment: http://stackoverflow.com/comment/81231234
upvote count: 0
score: -4
type: Answer
has body: The best way to install some package is to use pip install. So at first u need to PATH python and scripts: Hold Win and press Pause. Click Advanced System Settings. Click Environment Variables. Append C:\Users(your username)\AppData\Local\Programs\Python\Python36-32 C:\Users(your username)\AppData\Local\Programs\Python\Python36-32\Scripts to the Path variable. Restart Command Prompt. After that u can use pip install stratum in cmd

http://stackoverflow.com/comment/81242661
has text: Use `hasattr()`
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47146157

http://stackoverflow.com/comment/81519173
comment on: http://stackoverflow.com/a/47280363
type: Comment
score: 0
has text: lol a got new error that standard_init_linux.go:195: exec user process caused "exec format error"...
type: AnswerComment

http://stackoverflow.com/a/47135119
accepted answer of: http://stackoverflow.com/q/47102261
has comment: http://stackoverflow.com/comment/114328919
type: Answer
answers question: http://stackoverflow.com/q/47102261
score: 2
upvote count: 2
has body: As @Colin suggested in the comments, the problem happens when the input function returns an empty list. This is the case here when contrasts_dict[wildcards.contrast_type] is an empty list, a condition indicating that there is actually no point in trying to generate the output of the rule make_contrast_lfc_boxplots. I avoided the situation by modifying the input section of the rule all as follows: Old version: rule all: input: # [...] expand(OPJ(output_dir, "figures", "all_{contrast_type}", "{contrast_type}_{small_type}_{fold_type}_{gene_list}_boxplots.{fig_format}"), contrast_type=["ip"], small_type=IP_TYPES, fold_type=["mean_log2_RPKM_fold"], gene_list=BOXPLOT_GENE_LISTS, fig_format=FIG_FORMATS), # [...] New version: if contrasts_dict["ip"]: ip_fold_boxplots = expand(OPJ(output_dir, "figures", "all_{contrast_type}", "{contrast_type}_{small_type}_{fold_type}_{gene_list}_boxplots.{fig_format}"), contrast_type=["ip"], small_type=IP_TYPES, fold_type=["mean_log2_RPKM_fold"], gene_list=BOXPLOT_GENE_LISTS, fig_format=FIG_FORMATS) else: ip_fold_boxplots = [] rule all: input: # [...] ip_fold_boxplots, # [...] Some tinkering with snakemake/rules.py show that, at some point, the data attribute exist for the input attribute of the Rule object named make_contrast_lfc_boxplots, and that this attribute is still the source_fold_data function. I suppose this is later evaluated and removed when it is an empty list, but I haven't been able to find where. I suppose the empty input is not a problem when snakemake constructs the dependency graph between rules. The problem therefore only occurs during the execution of a rule.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/114255163

http://stackoverflow.com/q/47148777
tagged with: api
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: python
score: 2
tagged with: google-analytics
has body: I'm having trouble getting data on 30-day active users when I query Google Analytics in python. My code is below. My problem is that I need to specify a date or day as dimension. "At least one of ga:nthDay, ga:date, or ga:day must be specified as a dimension to query this metric." I'm just not sure what the proper syntax is for this. from oauth2client.service_account import ServiceAccountCredentials from apiclient.discovery import build import httplib2 #create service credentials #this is where you'll need your json key #replace "keys/key.json" with the path to your own json key key_file_location = 'maypath' credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file_location, ['https://www.googleapis.com/auth/analytics.readonly']) # create a service object you'll later on to create reports http = credentials.authorize(httplib2.Http()) service = build('analytics', 'v4', http=http, discoveryServiceUrl= ('https://analyticsreporting.googleapis.com/$discovery/rest')) response = service.reports().batchGet( body={ 'reportRequests': [ { 'viewId': 'ga:thisismyid', 'dateRanges': [{'startDate': '2017-10-01', 'endDate': '2017-10-01'}], 'metrics': [{'expression': 'ga:sessions'}, {'expression': 'ga:bounceRate'}, {'expression': 'ga:avgSessionDuration'}, {'expression': 'ga:users'}, {'expression': 'ga:newUsers'}, {'expression': 'ga:sessionsPerUser'}, {'expression': 'ga:30dayUsers'}], 'dimensions': [{"name": "ga:pagePath"}, {"name": "ga:city"}], 'orderBys': [{"fieldName": "ga:sessions", "sortOrder": "DESCENDING"}], 'pageSize': 10 }] } ).execute() So, in this example I am asking for a bunch of metrics on one date, including 30-day active users. As is, I hit this error: "Selected dimensions and metrics cannot be queried together," which is presumably because I am not specifying ga:date or ga:day as one of my dimensions. I've tried doing this a couple ways, but my syntax must be off. So how would I specify ga:day as a dimension to get the number of 30-day users ending on th…
tagged with: active-users
has answer: http://stackoverflow.com/a/48474209
has title: Querying Google Analytics API for 30-day active users
favorite count: 0
type: Question

http://stackoverflow.com/comment/81174702
comment on: http://stackoverflow.com/q/47111801
has text: Thank you. I will make changes to my code.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81365421
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47208139
has text: This is the correct answer, but it is very human unreadable! (not your fault Roman!)

http://stackoverflow.com/a/47103498
answers question: http://stackoverflow.com/q/47102432
has comment: http://stackoverflow.com/comment/81159405
has comment: http://stackoverflow.com/comment/81236182
has comment: http://stackoverflow.com/comment/81237225
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: For the most part, looks like you had the right idea. I changed your getADC function based on my understanding of the spec, I wasn't sure what you were doing with the "start of a new bit assignment" section. I don't have anything to test with, so I'm not sure that this works but it saves a few clock cycles removing that and cleaning up some more of the function to read the data. Another thing you can do, shown below, is wait to convert the raw ADC reading to float (float math typically takes a lot of time/processing power). So just read for some amount of time, store the data off, then format and output it later. I'm not sure if that will work for your application, but it's an idea. Hopefully this helps a little, at a minimum you should try waiting to convert to float and output. import time import os import RPi.GPIO as GPIO PIN_CLK = 11 PIN_DO = 9 PIN_DI = 10 PIN_CS = 8 def init_gpio(): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(PIN_DI, GPIO.OUT) GPIO.setup(PIN_DO, GPIO.IN) GPIO.setup(PIN_CLK, GPIO.OUT) GPIO.setup(PIN_CS, GPIO.OUT) def getADC(channel): # A falling CS signal initiates the conversion and data transfer GPIO.output(PIN_CS, False) # After the fifth falling DCLOCK edge # DOUT is enabled and outputs a LOW value for one clock period # So after 6 clock periods, we have data for i in range(0, 6): GPIO.output(PIN_CLK, True) GPIO.output(PIN_CLK, False) # For the next 16 DCLOCK periods, # DOUT outputs the conversion result, most significant bit first ad = 0 for i in range(0, 16): # Get next data bit ad &lt;&lt;= 1 # Get to next bit by advancing clock GPIO.output(PIN_CLK, True) GPIO.output(PIN_CLK, False) GPIO.output(PIN_CS, True) # reset return ad if __name__ == "__main__": init_gpio() start = time.time() results = [] # Run for 60 seconds while ((time.time() - start) &lt; 60): results.append(getADC(0)) for result in results: # This was slowing you down # You could capture data and then output it like this Data = float(result / 65535.0 * 3.3) getT…
accepted answer of: http://stackoverflow.com/q/47102432
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81280715

http://stackoverflow.com/comment/81807396
comment on: http://stackoverflow.com/a/47190578
type: Comment
has text: This should be a comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81113806
type: AnswerComment
score: 0
type: Comment
has text: Ok, thanks. I just needed it as my teacher asked if I could put all my programs in a menu system.
comment on: http://stackoverflow.com/a/47082230

http://stackoverflow.com/a/47101843
score: 3
has body: You are looking for isin df1.loc[df1.n.isin(df2.n),:]
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47101815
downvote count: 0
has comment: http://stackoverflow.com/comment/81153691
answers question: http://stackoverflow.com/q/47101815
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81154896
has comment: http://stackoverflow.com/comment/81153737
type: Answer

http://stackoverflow.com/a/47130973
answers question: http://stackoverflow.com/q/47130739
type: AcceptedAnswer
has body: It's not necessary to add status_code in DRF api because it's already included in the Response class. Check this for detail: http://www.django-rest-framework.org/api-guide/responses/#response. And the api above is called browsable API which generating human-friendly HTML output, status_code and msg you want is already there(HTTP 200 OK), 200 is the status_code, ok is the msg. Hope this answer your question.
accepted answer of: http://stackoverflow.com/q/47130739
downvote count: 0
score: 1
type: Answer
upvote count: 1

http://stackoverflow.com/comment/85977589
comment on: http://stackoverflow.com/q/47132741
has text: @SarweshSuman Nope. Hand-coded the cosine similarity based on the algorithm, that ended up being accurate. Still no solution for the doc2vec implementation.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47146215
downvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/81243132
has comment: http://stackoverflow.com/comment/81243442
upvote count: 3
answers question: http://stackoverflow.com/q/47145872
score: 1
has body: This leaves the original list as is and prints each number on its own: jail = [res for res in range(200,300)if res % 2 ==0 ] for number in jail: if all(int(digit)%2 == 0 for digit in str(number)): print(number) If you want only these special numbers in the jail list, simply put the condition into the creation of the list: jail = [res for res in range(200,300) if all(int(digit)%2 == 0 for digit in str(res))] These solutions rely on the fact that each digit can be obtained by iteration over the str representation of the integers.
has comment: http://stackoverflow.com/comment/81243850

http://stackoverflow.com/a/47114316
has body: You can't pass user name to print ctypes.windll.shell32.IsUserAnAdmin() it will just let you know whether logged in user is admin or not To get whether given user is admin you can refer this Check if an arbitrary user is in Administrator Group with Python
downvote count: 0
answers question: http://stackoverflow.com/q/47114257
upvote count: 1
has comment: http://stackoverflow.com/comment/81383167
score: 1
type: Answer

http://stackoverflow.com/comment/81238648
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47131099
has text: I think I nearly understand the concept but I have an additional question: 1. What do you mean by b1b1 and b2b2 and 2. You are using a z test, is it also possible to use a t test? --> For my unterstanding: A t test is normally used to compare the means of two data sets but here we simply interchange the means by the slopes of the data?
type: Comment

http://stackoverflow.com/comment/81245020
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47144382
has text: @MartinBeckett okay, and how to force it to use one I am building?

http://stackoverflow.com/a/47158770
upvote count: 1
has comment: http://stackoverflow.com/comment/82144859
type: Answer
has comment: http://stackoverflow.com/comment/82144060
has body: First of all, I'm not very much into Python, so I'm not really sure, but having experience in other languages I think that this answer is correct. What you did is... wrong. You don't want to raise an exception every time. Looking at the documentation of the readline function, readlines() depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly. This means that a timeout does not raise exceptions. You can test if the buffer is empty: try: print ("Message from arduino: ") buff = arduino.readline() print buff if not buff: raise except: print ("Fail to send!") Even if you may just skip the exception: print ("Message from arduino: ") buff = arduino.readline() print buff if not buff: print ("Fail to send!") If you prefer another behavior, write your own function (for instance this answer has something which looks like a reading function; you'll just have to add the exception raising. As for the type of exception, usually it is best to use just one type of exception, in order to avoid catching everything. For instance: class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) try: raise MyError(2*2) except MyError as e: print 'My exception occurred, value:', e.value
accepted answer of: http://stackoverflow.com/q/47158220
has comment: http://stackoverflow.com/comment/82144147
answers question: http://stackoverflow.com/q/47158220
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82167207

http://stackoverflow.com/a/47168272
answers question: http://stackoverflow.com/q/47167768
type: Answer
has body: a = [] b= {1:'one', 2:'two} a.append(b.copy()) print(a) --&gt; [{1: 'one', 2: 'two'}] print(type(a)) --&gt; &lt;class 'list'&gt;
score: 0
has comment: http://stackoverflow.com/comment/81289580

http://stackoverflow.com/q/47084226
has title: Copy files of certain extension from subdirectories and place them in new subdirectories of same structure
has body: I am going through a list of computers and searching a certain directory and subdirs for anything with a file extension of .exe.config I want to take those files ending in .exe.config and place them in a backup directory of the same structure. So this would be done recursively. For example, "main" is the main directory. There are several subdirs within "main" called "1", "2", "3", etc main \ \----------- \ \ \ 1 2 3 In each of the numbered directories, there would be a file with the extension of .exe.config I want to grab the main directory name, sub directory names, and *.exe.config files. Then place them in a backup "main" directory with the same structure. There are other files in those numbered directories but I want to ignore those. I'm not able to copy everything recursively. Here is the code I have been testing. A list of computers is placed in the serverlist.txt import os import shutil import fileinput def copy_names(servername): source = r'//' + servername + '/c$/Program Files (x86)/Main/' dest = r'//' + servername + '/c$/' + servername + '/Main/' for root, dirs, files in os.walk(source): for file in files: if file.endswith('.exe.config'): try: os.makedirs(dest, exist_ok=True) shutil.copyfile(os.path.join(source, file), os.path.join(dest, file)) print ("\n" + servername + " " + file + " : Copy Complete") except: print (" Directory you are copying to does not exist.") def start(): os.system('cls' if os.name == 'nt' else 'clear') array = [] with open("serverlist.txt", "r") as f: for servername in f: copy_names(servername.strip()) # start program start()
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47084572
downvote count: 0
upvote count: 1
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47084572
score: 1
tagged with: python

http://stackoverflow.com/q/47082785
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/81116277
has comment: http://stackoverflow.com/comment/81114886
has comment: http://stackoverflow.com/comment/81115877
has comment: http://stackoverflow.com/comment/81115016
has title: ValueError: could not convert string to float: C
answer count: 1
has body: I'm doing a CSV I/O program and there is something wrong with it. import csv filename1 = "sheets2.csv" filename2 = "newsheet.csv" fields = ['A','B','C','D','E'] average = 0 total = 0 row_count = 1 with open(filename1,'rU') as csvfile1: csvreader = csv.reader(csvfile1) with open(filename2,'w') as csvfile2: csvwriter = csv.writer(csvfile2) for col in csvreader: csvwriter.writerow(['stas']) if len (col[2])&gt;1: print("data in col is", "col[4]") else: print("the data entered is", float(col[2])) total = total + int(col[2]) row_count += 1 average = total/row_count print(average) csvwriter.writerow([aver]) csvfile1.close() csvfile2.close() In print("the data entered is", float(col[2])), the error was: ValueError: could not convert string to float: C Here is the CSV file: A B C D E alpha 100 200 300 400 baker 300 500 700 900 cyber 250 340 590 780 dove 320 570 430 220 eggs 670 990 430 570 fish 330 260 870 230 golf 160 320 480 640 halo 280 680 540 320 idom 520 450 670 810 joker 210 240 450 690
has comment: http://stackoverflow.com/comment/81115261
has comment: http://stackoverflow.com/comment/81115123
has comment: http://stackoverflow.com/comment/81116243
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81115209
has comment: http://stackoverflow.com/comment/81114942
has comment: http://stackoverflow.com/comment/81114837
has comment: http://stackoverflow.com/comment/81115278
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81114908
has comment: http://stackoverflow.com/comment/81115079
has comment: http://stackoverflow.com/comment/81115096
has comment: http://stackoverflow.com/comment/81114995
tagged with: python
has comment: http://stackoverflow.com/comment/81115088
accepted answer: http://stackoverflow.com/a/47083026
has comment: http://stackoverflow.com/comment/81115568
has comment: http://stackoverflow.com/comment/81115064
has comment: http://stackoverflow.com/comment/81115172
has answer: http://stackoverflow.com/a/47083026
has comment: http://stackoverflow.com/comment/81114968
has comment: http://stackoverflow.com/comment/81116034

http://stackoverflow.com/a/47175260
answers question: http://stackoverflow.com/q/47153575
score: 0
type: Answer
has body: You were not far from a solution, you just have to append data from line2 to line1 and use it: ... csvout = csv.writer(open("final.csv", "wb"), quoting = csv.QUOTE_ALL) while True: try: line1 = csv1.next() line2 = csv2.next() if line1[0] != line2[0]: # control same first field raise Exception("Desynch", line1[0], '#', line2[0]) line1.append(line2[1]) # append field from b.csv csvout.writerow(line1) # and write it to final.csv except StopIteration: break

http://stackoverflow.com/a/47300760
type: Answer
has body: The lost text bits, "¿Sí?" and "A mí no me suena.", are available as the tail property of each element (the text following the element's end tag). Here is a way to get the wanted output (tested with Python 2.7). Assume that vocal.xml looks like this: eh ¿Sí? Pues... laugh A mí no me suena. Code: from xml.etree import ElementTree as ET root = ET.parse("vocal.xml") for u in root.findall(".//u"): v = u.find("vocal") if v.get("type") == "filler": frags = [u.text, v.findtext("desc"), v.tail] else: frags = [u.text, v.tail] print " ".join(t.encode("utf-8").strip() for t in frags).strip() Output: eh ¿Sí? Pues... A mí no me suena.
answers question: http://stackoverflow.com/q/47208193
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47208193

http://stackoverflow.com/a/47175216
upvote count: 1
has comment: http://stackoverflow.com/comment/81300206
has comment: http://stackoverflow.com/comment/81299967
type: Answer
has comment: http://stackoverflow.com/comment/81299909
score: 1
has comment: http://stackoverflow.com/comment/81299816
has comment: http://stackoverflow.com/comment/81300215
accepted answer of: http://stackoverflow.com/q/47175128
has body: You have a local file named org.py that shadows an optional built-in package (only used in Jython). From your traceback: File "C:\Python3\lib\site-packages\numpy\core\numeric.py", line 37, in import pickle File "C:\Python3\lib\pickle.py", line 93, in from org.python.core import PyStringMap File "C:\Users\Jakub\desktop\Nowy\workspace\python\org.py", line 2, in &lt;module&gt; from tensorflow.examples.tutorials.mnist import input_data C:\Users\Jakub\desktop\Nowy\workspace\python\org.py is not the Jython package the pickle module looks for. You only see this exception when you run your script because the directory your script is located in (C:\Users\Jakub\desktop\Nowy\workspace\python here) is added to sys.path automatically. The attribute error is caused by the circular import; numpy imports pickle which imports your org script again, which imports numpy, but that module has not yet completed all its imports, so names are missing at this time.
answers question: http://stackoverflow.com/q/47175128
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47083667
has comment: http://stackoverflow.com/comment/81116779
has comment: http://stackoverflow.com/comment/81116783
has comment: http://stackoverflow.com/comment/81117222
has comment: http://stackoverflow.com/comment/81118259
answer count: 1
has comment: http://stackoverflow.com/comment/81116745
has answer: http://stackoverflow.com/a/47084555
has comment: http://stackoverflow.com/comment/81117641
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81118623
has title: python set() membership and hashable objects
upvote count: 0
score: -2
downvote count: 2
accepted answer: http://stackoverflow.com/a/47084555
has body: I wanted to store instances of a class in a set, so I could use the set methods to find intersections, etc. My class has a __hash__() function, along with an __eq__ and a __lt__, and is decorated with functools.total_ordering When I create two sets, each containing the same two objects, and do a set_a.difference(set_b), I get a result with a single object, and I have no idea why. I was expecting none, or at the least, 2, indicating a complete failure in my understanding of how sets work. But one? for a in set_a: print(a, a.__hash__()) for b in set_b: print(b, b.__hash__(), b in set_a) (&lt;foo&gt;, -5267863171333807568) (&lt;bar&gt;, -8020339072063373731) (&lt;foo&gt;, -5267863171333807568, False) (&lt;bar)&gt;, -8020339072063373731, True) Why is the &lt;foo&gt; object in set_b not considered to be in set_a? What other properties does an object require in order to be considered a member of a set? And why is bar considered to be a part of set_a, but not foo? edit: updating with some more info. I figured that simply showing that the two objects' hash() results where the same meant that they where indeed the same, so I guess that's where my mistake probably comes from. @total_ordering class Thing(object): def __init__(self, i): self.i = i def __eq__(self, other): return self.i == other.i def __lt__(self, other): return self.i &lt; other.i def __repr__(self): return "&lt;Thing {}&gt;".format(self.i) def __hash__(self): return hash(self.i)
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/q/47216436
has comment: http://stackoverflow.com/comment/81382314
type: Question
upvote count: 0
has body: How can I adjust the following function so that if the variable assigned to st1 does not appear at all in string (1 does not appear in string, and the string is *********), the function just returns the string back (*********) but if the string does contain 1, it replaces every 1 with 2 as done below. Thank you for your help. def replacest1(string,st1,st2): for i in string: if i == st1: N_W = string.replace(st1 , st2) return N_W print(replacest1("***1***1***","1","2"))
answer count: 1
has comment: http://stackoverflow.com/comment/81382468
downvote count: 1
favorite count: 0
has title: Python: Replace a character in string
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47216552
duplicate of: http://stackoverflow.com/q/12723751
has answer: http://stackoverflow.com/a/47216552
has comment: http://stackoverflow.com/comment/81382625
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81383074

http://stackoverflow.com/comment/81335400
has text: Packages are containers for modules and other subpackages. In your example `x` is the package and `y` the module, similar to "from the shopping bag take the apple", not the other way around.
comment on: http://stackoverflow.com/q/47193079
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47093717
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/6773124
answer count: 1
tagged with: javascript
tagged with: jquery
favorite count: 0
has answer: http://stackoverflow.com/a/47093796
has body: I am new to penetration testing. My requirement is to update registry values from browser using a client side programming language like javascript. Is it possible?
duplicate of: http://stackoverflow.com/q/6773124
tagged with: security
has comment: http://stackoverflow.com/comment/81136982
score: -2
tagged with: penetration-testing
tagged with: python
type: Question
has title: Is it possible to possible update registry values using a client side programming language
upvote count: 0
downvote count: 2

virtual-machine
tag name: virtual-machine
tags question: http://stackoverflow.com/q/47111880
type: Tag
tags question: http://stackoverflow.com/q/47106792

http://stackoverflow.com/comment/81327023
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47183033
type: Comment
has text: "wsgi.py" Updated in man body

http://stackoverflow.com/a/47077447
score: 12
has comment: http://stackoverflow.com/comment/115191524
has comment: http://stackoverflow.com/comment/81105831
upvote count: 12
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47077329
accepted answer of: http://stackoverflow.com/q/47077329
has comment: http://stackoverflow.com/comment/81105039
has comment: http://stackoverflow.com/comment/115192684
type: Answer
has body: If you want to get MyType, you can find it under .__args__: import typing def f(x: typing.List[MyType]): ... print(f.__annotations__["x"].__args__[0]) # prints &lt;class '__main__.MyType'&gt; List (i.e. typing.List) is accessible from .__base__, and the actual list class comes from .__orig_bases__: print(f.__annotations__["x"].__base__) # prints typing.List[float] print(f.__annotations__["x"].__orig_bases__[0]) # prints &lt;class 'list'&gt;

http://stackoverflow.com/a/47168359
has comment: http://stackoverflow.com/comment/83273791
type: Answer
has body: Matplotlib provides a widget called Cursor. You can use this already for the lines in the heatmap plot. This can use blitting in order not to redraw the canvas all the time, matplotlib.widgets.Cursor(ax1,useblit=True) To update the plots next to it, you may use the same blitting technique, but need to implement it manually. This way only the lines that change while moving the mouse will be updated and hence the whole interactive experience is much smoother. import matplotlib.pyplot as plt import matplotlib.widgets import numpy as np # define the plot range in x and y axes and change array size t = np.arange(0.0, 40.0, 0.01) t2 = np.arange(0.0, 20.0, 0.01) #create a 2d grid to create the intensity map t_x,t_y=np.meshgrid(t,t2) #create the intensity map s = 10*np.sin(0.1*np.pi*(t_x))*np.sin(0.5*np.pi*t_y)+t_x+t_y #create the Gui class fig=plt.figure(dpi=150) ax1=fig.add_subplot(221) ax2=fig.add_subplot(223,sharex=ax1) ax3=fig.add_subplot(222,sharey=ax1) ax1.margins(0) ax2.margins(0) ax3.margins(0) ax2.set_ylim(s.min(), s.max()) ax3.set_xlim(s.min(), s.max()) ax1.imshow(s,aspect='auto') l2, = ax2.plot(np.arange(0,s.shape[1]),np.ones(s.shape[1])*np.nan) l3, = ax3.plot(np.ones(s.shape[0])*np.nan, np.arange(0,s.shape[0])) class Cursor(): def __init__(self, **kwargs): self.cursor = matplotlib.widgets.Cursor(ax1,useblit=True,**kwargs) self.cid = fig.canvas.mpl_connect("motion_notify_event", self.cursor_move) self.cid2 = fig.canvas.mpl_connect("draw_event", self.clear) self.bg1 = None self.bg2 = None self.needclear = False def cursor_move(self,event): if event.inaxes == ax1: self.needclear = True x,y = int(event.xdata),int(event.ydata) slice_y = s[:,x] slice_x = s[y,:] l2.set_ydata(slice_x) l3.set_xdata(slice_y) fig.canvas.restore_region(self.bg1) fig.canvas.restore_region(self.bg2) l2.set_visible(True); l3.set_visible(True) ax2.draw_artist(l2) ax3.draw_artist(l3) fig.canvas.blit(ax2.bbox) fig.canvas.blit(ax3.bbox) else: if self.needclear: self.clear() self.needclear = False…
answers question: http://stackoverflow.com/q/47167496
has comment: http://stackoverflow.com/comment/83273481
has comment: http://stackoverflow.com/comment/83259294
accepted answer of: http://stackoverflow.com/q/47167496
score: 1
has comment: http://stackoverflow.com/comment/83259180
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83393274

http://stackoverflow.com/comment/91701822
type: Comment
type: QuestionComment
has text: See https://stackoverflow.com/questions/47068709/your-cpu-supports-instructions-that-this-tensorflow-binary-was-not-compiled-to-u
score: 0
comment on: http://stackoverflow.com/q/47199553

http://stackoverflow.com/comment/81200760
type: Comment
comment on: http://stackoverflow.com/a/47125329
type: AnswerComment
has text: I thought you had scooped me but I don't think this is what she's asking for.
score: 1

http://stackoverflow.com/comment/81131082
comment on: http://stackoverflow.com/q/47090886
has text: Yes, I assumed so. I still don't understand your question. What is a cross reference, and why is it a problem?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81245671
has text: Could be a cut-paste thing, but your code is not indented properly I think, after the `for line in f:...` Fix it if requied.
type: Comment
comment on: http://stackoverflow.com/q/47147653
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81180718
type: QuestionComment
has text: I have read, and the way I used *args and **kwargs is what I came up with :<
score: 0
comment on: http://stackoverflow.com/q/47115342
type: Comment

http://stackoverflow.com/q/47079459
has answer: http://stackoverflow.com/a/47079624
has comment: http://stackoverflow.com/comment/81107926
upvote count: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81108208
favorite count: 0
tagged with: docker
score: 2
type: AnsweredQuestion
has body: Using dockerbuild file, how can I do there something like: export PYTHONPATH=/:$PYTHONPATH using RUN directive or other option
has comment: http://stackoverflow.com/comment/81107873
tagged with: python
accepted answer: http://stackoverflow.com/a/47079624
has title: Adding path to pythonpath in dockerbuild file
type: Question

http://stackoverflow.com/q/47069678
tagged with: java
tagged with: python
has answer: http://stackoverflow.com/a/50312611
tagged with: bokeh
has comment: http://stackoverflow.com/comment/81168889
has body: Here is a problem I am stuck with presently. Recently I have been exploring bokeh for plotting and kafka for streaming. And I thought of making a sample live dashboard using both of them. But the problem is I use bokeh with python and kafka stream api's with Java. Is there a way to use them together by any chance. The only way I can see is both of them can be used with scala. But presently I don't want to get into scala.
score: 0
tagged with: apache-kafka-streams
type: UnansweredQuestion
has title: Using bokeh plotting with kafka streaming
answer count: 1
type: Question
tagged with: apache-kafka

robotframework
tags question: http://stackoverflow.com/q/47169550
tags question: http://stackoverflow.com/q/47086206
tags question: http://stackoverflow.com/q/47120167
tags question: http://stackoverflow.com/q/47120465
tags question: http://stackoverflow.com/q/47067506
tags question: http://stackoverflow.com/q/47163056
tag name: robotframework
tags question: http://stackoverflow.com/q/47091374
tags question: http://stackoverflow.com/q/47084454
type: Tag

http://stackoverflow.com/a/47183890
has comment: http://stackoverflow.com/comment/86648722
has comment: http://stackoverflow.com/comment/86649268
has comment: http://stackoverflow.com/comment/86648345
has comment: http://stackoverflow.com/comment/86648890
upvote count: 59
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86647625
has comment: http://stackoverflow.com/comment/86647508
has comment: http://stackoverflow.com/comment/81349378
has comment: http://stackoverflow.com/comment/86647567
score: 59
accepted answer of: http://stackoverflow.com/q/47183159
has comment: http://stackoverflow.com/comment/81330758
type: Answer
has comment: http://stackoverflow.com/comment/101749158
answers question: http://stackoverflow.com/q/47183159
has comment: http://stackoverflow.com/comment/86634268
has body: What is keras_layer in your code? You can set weights these ways: model.layers[i].set_weights(listOfNumpyArrays) model.get_layer(layerName).set_weights(...) model.set_weights(listOfNumpyArrays) Where model is an instance of an existing model. You can see the expected length of the list and its array shapes using the method get_weights() from the same instances above.

http://stackoverflow.com/a/63505446
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47152271
has body: I figure out of this manner. I know that is not the best solution but it works!!. In this case, I just only download the first 50 payloads Here my code: def get_recent_change(self) -&gt; list: # se inicializa un socket r = requests.session() # se establece la conexión responds = r.get(self.__url, stream=True) try: # se capturan los eventos client = sseclient.SSEClient(responds) print('Connection established') except Exception as e: print(e) # limitador del stram cont = 0 payloads = [] try: print('Downloading info') for event in client.events(): #el primer evento no sirve if cont==0: pass # captura muchos payloads en un solo evento, tocó separarlos for st in event.data.split('\n'): # Progress bar of the poor print('-', end='',flush=True) #se guardan en una lista payloads.append(json.loads(st)) if cont &gt;= 50: break cont +=1 except Exception as e: print(e) return payloads

http://stackoverflow.com/q/47141225
answer count: 1
tagged with: django
tagged with: django-rest-framework
type: AnsweredQuestion
score: 0
has title: Filtering django rest framework query set using a custom filter backend
tagged with: python
accepted answer: http://stackoverflow.com/a/47142132
has answer: http://stackoverflow.com/a/47142132
type: Question
has body: I'm having problems with filtering the query set. Here is a simplified data model: Entry - id - broadcast_groups User - id - groups So an entry can be broadcasted (shared) in a group. I have a GET /entries/ endpoint that returns entry objects. I want to filter a query set to return entries that fulfill following requirements: are not broadcasted in any group OR are broadcasted in groups the user is member of. I'm scratching my head how to achieve this. I figured that maybe writing a custom FilterBackend is a good idea. Here is what I have so far: class CanViewPublicOrGroupMemberEntriesFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): user = request.user return queryset.filter(broadcast_groups__in=user.groups.all()) However, this does not yield results that I am expecting. What would be a filter() syntax to achieve such filtering? Or maybe I'm approaching the problem from the wrong side?

http://stackoverflow.com/q/47144979
tagged with: dataframe
tagged with: python
upvote count: 4
score: 4
has title: How to join a multi-index series to a single index dataframe with Pandas?
type: AnsweredQuestion
answer count: 3
tagged with: pandas
tagged with: join
downvote count: 0
has body: Consider the following single index DataFrame: energy fat 1 2000 28 2 1900 17 3 2200 30 4 1750 15 5 1800 18 6 1600 12 I also have a multindex Series: 1 vitamin-c 0.0004 vitamin-a 0.0150 2 vitamin-c 0.0030 3 vitamin-d 1.2000 vitamin-e 1.0007 vitamin-c 1.2020 4 vitamin-a 0.0780 5 vitamin-b 0.9650 6 vitamin-e 1.9801 vitamin-c 1.0011 How can I join the two so the result looks like this: energy fat vitamins 1 2000 28 vitamin-c 0.0004 vitamin-a 0.0150 2 1900 17 vitamin-c 0.0030 3 2200 30 vitamin-d 1.2000 vitamin-e 1.0007 vitamin-c 1.2020 4 1750 15 vitamin-a 0.0780 5 1800 18 vitamin-b 0.9650 6 1600 12 vitamin-e 1.9801 vitamin-c 1.0011 I tried df.join(series, how = 'inner') but all I got is the following error message: "ValueError: cannot join with no level specified and no overlapping names" Can someone please explain me what im doing wrong here and how i can achieve the combination of the two ? Thank you !
has answer: http://stackoverflow.com/a/47145127
has answer: http://stackoverflow.com/a/47145274
accepted answer: http://stackoverflow.com/a/47145274
tagged with: multi-index
has comment: http://stackoverflow.com/comment/81240257
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47145286
possible better answer: http://stackoverflow.com/a/47145286

http://stackoverflow.com/q/47213526
score: 0
has body: Is there a way tell python script to take a screenshot automatically and save it to desktop? All I am finding is great stuff on here, but it all seems to prompt to grab a selection after executing the script. I have found at least 5 pages on stackoverflow and none were automatic. Thanks
upvote count: 1
tagged with: screenshot
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/81376684
favorite count: 0
type: Question
tagged with: linux
linked to: http://stackoverflow.com/q/69645
has comment: http://stackoverflow.com/comment/81376692
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81377060
has title: Python automatic screenshot, no screen grabbing. Linux / Unix / OS X only
has answer: http://stackoverflow.com/a/47213638
tagged with: python
has comment: http://stackoverflow.com/comment/81377102

http://stackoverflow.com/q/47131857
type: Question
type: UnansweredQuestion
has body: I'm new to Python and I've been trying to start a Discord bot on my computer, but whenever I try to install sudo pip install discord.py I get the following error: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/tmp/pip-build-QOFKFs/aiohttp/setup.py", line 60, in &lt;module&gt; raise RuntimeError("aiohttp requires Python 3.4.2+") RuntimeError: aiohttp requires Python 3.4.2+ I'm running Linux Mint 18.2 and I'm almost 100% positive I've got Python and Pip up to date.
tagged with: python
has title: How do I fix this error I'm getting when I try to install this package with pip install?
score: 1
has answer: http://stackoverflow.com/a/47131944
answer count: 1
has comment: http://stackoverflow.com/comment/81213165
downvote count: 0
has comment: http://stackoverflow.com/comment/81213144
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/81166714
type: AnswerComment
has text: And can you put up this timetuple, in my script to parse every date from the txt file? Because I do not think I have to do it manually?
comment on: http://stackoverflow.com/a/47108160
type: Comment
score: 0

http://stackoverflow.com/q/47222328
tagged with: python-3.x
tagged with: python
tagged with: flask
tagged with: pythonanywhere
linked to: http://stackoverflow.com/q/4383571
has answer: http://stackoverflow.com/a/47223835
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
has title: How would I create a Flask WebApp which inputs keywords and outputs data from a python script which is already written?
upvote count: 1
favorite count: 0
has body: I am trying to make a WebApp with Flask which gets an input from a user which are keywords and uses that input to scrape the keywords off another website. I have written the Python script to do this using Selenium. Currently the script runs perfectly fine on my computer and outputs printed strings. It takes ~5 seconds to run (as it opens a Firefox browser). However, I want to take this a step further by creating a website which allows users to type in the keywords, returning them the outputted strings. So far I have tried implementing Flask on pythonanywhere.com but am having trouble connecting my script to the WebApp. What I have so far is the following code (mostly found online and from tutorials): from flask import Flask from flask import render_template, abort, jsonify, request,redirect, json from script_to_run import main app = Flask(__name__) app.debug = True @app.route('/') def index(): return render_template('index.html') @app.route('/learning', methods=['POST']) def learning(): data = json.loads(request.data) # data == {"userInput": "whatever text you entered"} response = main(data) return jsonify(response) if __name__ == '__main__': app.run() This is my main app where script_to_run is the python script i want to import to run. e.g. it may be the following def main(): import selenium #some selenium web scraping code here return 'successfully returned data' And finally I have my html code: Calculation Test Page Results will go here Submit I have two main questions: 1. Is what I am trying to do possible given that my script takes about 5 seconds to run and requires Firefox 2. How would I go about fixing my current code (I am currently unable to import main from script_to_run so can't even test what I've got properly) Please note that I am a total beginner. I am okay at python (roughly 9 months learning the basics) and have almost no knowledge of web development (but can intuitively figure out basic html). Thanks!
type: Question

http://stackoverflow.com/q/47104642
has title: How to create a histogram?
has comment: http://stackoverflow.com/comment/81159939
answer count: 1
has comment: http://stackoverflow.com/comment/81159888
tagged with: histogram
has answer: http://stackoverflow.com/a/47104697
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81160595
has comment: http://stackoverflow.com/comment/81160024
tagged with: matplotlib
score: -3
tagged with: python
has body: I have below dataframe. I want to create a simple histogram by sorting number of tweets numbers. **Source** **Number of Tweets** Twitter for Android 59472 Twitter for iPhone 27244 Twitter Web Client 9239 Twitter Lite 6479 Twitter for iPad 1159 TweetCaster for Android 407 Twitter for Windows Phone 233 TweetDeck 219 Mobile Web (M2) 197 Twitter for Windows 134 Commun.it 121 Facebook 18 Media Studio 16 MeTweets for Windows Phone 14 Here is the code; my_plot = data.sort(columns='Number of Tweets',ascending=False).plot( kind='bar',legend=None,title="Tweet Numbers Per Source") my_plot.set_xlabel("Source") my_plot.set_ylabel("Tweet Numbers") But I get the warning: /home/bd/anaconda3/lib/python3.5/site-packages/ipykernel/__main__.py:1: FutureWarning: sort(columns=....) is deprecated, use sort_values(by=.....) if __name__ == '__main__':` Also, when I code: my_plot.show() I get below error message. AttributeError: 'AxesSubplot' object has no attribute 'show' How can I fix this?
accepted answer: http://stackoverflow.com/a/47104697
type: AnsweredQuestion
upvote count: 0
downvote count: 3

http://stackoverflow.com/a/47123624
has body: Like I said in the comments, you would have to create your own corpora for Indian names and test your text against that. The NLTK Book teaches you how to do this in Chapter 2 (Section 1.9 to be exact). from nltk.corpus import PlaintextCorpusReader # You can use a regular expression to find the files, or pass a list of files files = ".*\.txt" new_corpus = PlaintextCorpusReader("/path/", files) corpus = nltk.Text(new_corpus.words()) See also: Creating a new corpus with NLTK
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47123094
answers question: http://stackoverflow.com/q/47123094
upvote count: 2
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/comment/95355381
score: 0
type: AnswerComment
has text: the `conda-forge` channel uses really old packages. Using this channel, you may also be forced to downgrade your python version. To be on the safe side, use the default anaconda channel, i.e use `-c defaults`
comment on: http://stackoverflow.com/a/47262847
type: Comment

http://stackoverflow.com/comment/81242391
comment on: http://stackoverflow.com/a/47145844
score: 0
type: AnswerComment
has text: Thanks. Your answer is correct in general, but I forgot to say that my class uses __slots__ to define the member variables, so I cannot use something like `self.__func__ = self.__func1`.
type: Comment

http://stackoverflow.com/q/47158882
type: Question
tagged with: python-2.7
tagged with: kivy-language
has comment: http://stackoverflow.com/comment/81268644
upvote count: 0
answer count: 1
has title: when i click row then it shows error IndexError: list index out of range
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47163787
has body: menu.py import kivy kivy.require('1.9.0') # replace with your current kivy version ! import sqlite3 as lite from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty,NumericProperty from kivy.lang import Builder from kivy.uix.dropdown import DropDown from kivy.uix.recycleview.views import RecycleDataViewBehavior from kivy.uix.button import Button from kivy.uix.recyclegridlayout import RecycleGridLayout from kivy.uix.behaviors import FocusBehavior from kivy.uix.recycleview.layout import LayoutSelectionBehavior from kivy.uix.popup import Popup from kivy.core.window import Window import sys #Window.borderless = True #Window.clearcolor = (0, 0.517, 0.705, 1) Window.size = (900, 500) #from easygui import msgbox #db =lite.connect(':memory:') con = lite.connect('test.db') con.text_factory = str cur = con.cursor() class EditStatePopup(Popup): obj = ObjectProperty(None) start_point = NumericProperty(0) max_table_cols = NumericProperty(0) new_data = ListProperty([]) stateId = StringProperty("") stateName = StringProperty("") stateCode = StringProperty("") def __init__(self, obj, **kwargs): super(EditStatePopup, self).__init__(**kwargs) self.obj = obj self.start_point = obj.start_point self.max_table_cols = obj.max_table_cols self.stateId = obj.rv_data[obj.start_point]["text"] self.stateName = obj.rv_data[obj.start_point + 1]["text"] self.stateCode = obj.rv_data[obj.start_point + 2]["text"] def package_changes(self, stateId, stateName, stateCode): print(stateName) self.new_data.append(stateId) self.new_data.append(stateName) self.new_data.append(stateCode) class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior, RecycleGridLayout): ''' Adds selection and focus behaviour to the view. ''' class SelectableButton(RecycleDataViewBehavior, Button): ''' Add selection support to the Button ''' index = None selected = BooleanProperty(False) selectable = BooleanProperty(Tru…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81267739
has comment: http://stackoverflow.com/comment/81267338
tagged with: python
has comment: http://stackoverflow.com/comment/81268700
score: -1
has comment: http://stackoverflow.com/comment/81267190
tagged with: kivy
accepted answer: http://stackoverflow.com/a/47163787

http://stackoverflow.com/q/47219662
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47219833
has title: how to elegantly parse argumens in python before expensive imports?
has comment: http://stackoverflow.com/comment/123156736
has comment: http://stackoverflow.com/comment/81388852
has answer: http://stackoverflow.com/a/47219833
favorite count: 0
score: 8
upvote count: 8
has comment: http://stackoverflow.com/comment/81388825
type: Question
answer count: 2
downvote count: 0
has body: I have a script, which parses a few arguments, and has some expensive imports, but those imports are only needed if the user gives valid input arguments, otherwise the program exits. Also, when the user says python script.py --help, there is no need for those expensive imports to be executed at all. I can think of such a script: import argparse def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--argument', type=str) args = parser.parse_args() return args if __name__ == "__main__": args = parse_args() import gensim # expensive import import blahblahblah def the_rest_of_the_code(args): pass if __name__ == "__main__": the_rest_of_the_code(args) This does the job, but it doesn't look elegant to me. Any better suggestions for the task? EDIT: the import is really expensive: $ time python -c "import gensim" Using TensorFlow backend. real 0m12.257s user 0m10.756s sys 0m0.348s
possible better answer: http://stackoverflow.com/a/47219837
tagged with: python
has answer: http://stackoverflow.com/a/47219837
has comment: http://stackoverflow.com/comment/81388783
has comment: http://stackoverflow.com/comment/81410434
tagged with: argparse

http://stackoverflow.com/q/47146838
has comment: http://stackoverflow.com/comment/81244047
has comment: http://stackoverflow.com/comment/81244229
downvote count: 0
upvote count: 1
tagged with: python
tagged with: dictionary
tagged with: recursion
type: AnsweredQuestion
has body: I've scoured documentation and used the help of many teammates, but have not been able to figure out how to replace a dictionary with values provided as kwargs through (in my case) a test function: Template dictionary: { "id": "id_1234", "integer_value": 1234, "level_one": { "id": 1234, "foo": "true", "list_one": [], "list_two": [ 522 ], "url": "http://google.com", "level_two": { "thing_one": { "yes": "false", "no": "false" }, "thing_two": { "yes": "false", "no": "false" } }, "another_field": "true", "bar": 15000 } } Recursive dictionary function: def update_dictionary(template_dict, **kwargs): for k, v in kwargs.items(): print(v) print(isinstance(v, collections.Mapping)) if isinstance(v, collections.Mapping): print("This is the k value") print(k) template_dict[k] = update_dictionary(template_dict.get(k, {}), v) else: print("We're going into the else now") template_dict[k] = v return template_dict I got the above function from another forum on here, but it doesn't seem to work when passing kwargs. isinstance check turns out to be False for any fields that are not in the first level of the nested dictionary. Any help is appreciated! Line in test where the kwargs are passed: new_dict = update_dictionary(template_dict, another_field = 'false', integer_value=12345)
accepted answer: http://stackoverflow.com/a/47147095
has comment: http://stackoverflow.com/comment/81244238
has answer: http://stackoverflow.com/a/47147095
answer count: 1
score: 1
has title: Python 3 use kwargs to replace nested dictionary values
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/81190286
has text: I can't think of any solution right now, but one idea is that you can use multiprocessing to make things faster. Perhaps this could even be done using GPU.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47120159

http://stackoverflow.com/q/47170729
tagged with: django
tagged with: javascript
has answer: http://stackoverflow.com/a/47171925
tagged with: python
has comment: http://stackoverflow.com/comment/81291182
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81291711
answer count: 1
type: Question
has body: Good day! I'll Forgive Forgiveness, I'm zero in programming. But I want to learn. I need to transfer data using the POST method, without updating the page. Through django, how should the javascript and views.py look like! ФИО Шифр Группы Пол Семейное положение Номер комнаты Войти Ждем ответа @csrf_exempt def polls(request, form=None): if request.method == 'POST' and form.is_valid(): pass else: return render(request, 'base.html')
has title: Receiving data from the server without updating the page
accepted answer: http://stackoverflow.com/a/47171925
has comment: http://stackoverflow.com/comment/81291042

http://stackoverflow.com/q/47080378
has title: TypeError : list indices must be integers not str
tagged with: amazon-ec2
answer count: 1
tagged with: amazon-web-services
type: Question
has comment: http://stackoverflow.com/comment/81110259
tagged with: boto
has comment: http://stackoverflow.com/comment/81110991
has comment: http://stackoverflow.com/comment/81110137
tagged with: python
has comment: http://stackoverflow.com/comment/81110750
has answer: http://stackoverflow.com/a/47269226
accepted answer: http://stackoverflow.com/a/47269226
has body: I'd like to create an alarm whose metric (trigger) is ApproximateNumberOfMessagesVisible in a Queue 'myDownlinQueue', the alarm takes the action of autoscaling an AutoScalingGroup. However based on the code I am writing I get the error mentioned in the title. Maybe I am doing it wrong, but below is the code that causes this error. # ==== AutoSCaling config ======================= autoscaling_group = { "name": "myAG", #descriptive name for your auto scaling group "min_size": 0 , #Minimum number of instances that should be running at all times "max_size": 0 #Maximum number of instances that should be running at all times } lc_name = 'myLG' #Descriptive name for your launch configuration #=================AMI to launch====================================================== as_ami = { "id": "ami-******c", #The AMI ID of the instance your Auto Scaling group will launch "VpcId" : "vpc-0c805575", "security_groups": "sg-xxxxxxxa", #The security group(s) your instances will belong to "instance_type": "t2.micro", #The size of instance that will be launched "instance_monitoring": True #Indicated whether the instances will be launched with detailed monitoring enabled. Needed to enable CloudWatch } conn_reg = boto.ec2.connect_to_region(region_name=awsRegion) zones = conn_reg.get_all_zones() zoneStrings = [] for zone in zones: zoneStrings.append(zone.name) print " Available zones : " + zone.name conn_vpc = boto.connect_vpc() subnetids = conn_vpc.get_all_subnets() conn_as = AutoScaleConnection(AWS_ACCESS_KEY,AWS_SECRET_KEY) lc = LaunchConfiguration(name = lc_name, image_id = as_ami["id"], instance_type = as_ami["instance_type"], user_data = "user-data.bls", associate_public_ip_address = True, instance_monitoring=as_ami["instance_monitoring"]) conn_as.create_launch_configuration(lc) ag = AutoScalingGroup(group_name = autoscaling_group["name"], availability_zones= zoneStrings, vpc_zone_identifier = subnetList, launch_config=lc, min_size = autoscaling_group["min_size"], max_size = aut…
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81127458

http://stackoverflow.com/q/47188237
answer count: 0
has body: player_health = 100 variable_shelter = "0" variable_water_goodoutcome = "0" variable_water_badoutcome = "-100" variable_food_goodoutcome = "0" variable_food_badoutcome = "-100" var_a = 0 var_b = 1 user_answer_1 = "fire" user_answer_2 = "water" user_answer_3 = "shelter" user_answer_4 = "food" name_input = input("Hello! Welcome to Survival Scenarios! What is your Name?") question1_input = input("You are stranded on an island after your plane crashed.You have little time before nightfall. For your survival you have the choice of finding or building food, water, shelter, or fire. What is you choice?") if question1_input == user_answer_1: import random variable_fire_goodoutcome = 0 variable_fire_badoutcome = 100 var_choice1 = [variable_fire_goodoutcome,variable_fire_badoutcome] var_chances = random.randint(var_a,var_b) if var_chances == variable_fire_goodoutcome: print(name_input +"'s" " Health") print[player_health - variable_fire_goodoutcome] if var_chances != variable_fire_goodoutcome: print(name_input +"'s" " Health") print[player_health - variable_fire_badoutcome] print("Sorry you died") add information of their death later if question1_input == user_answer_2: import random variable_water_goodoutcome = 0 variable_water_badoutcome = 100 var_choice2 =[variable_water_goodoutcome,variable_water_badoutcome] var_chances1 = random.randit(var_a,var_b) if var_chances1 == variable_water_goodoutcome: print(name_input +"'s"" Health") print[player_health - variable_water_goodoutcome] if var_chances1 != variable_water_goodoutcome: print(name_input +"'s"" Health") print[player_health - variable_water_badoutcome] keeps coming up with this error: NameError: name 'var_chances' is not defined on line 29 If anyone could please help it would be appreciated.
has title: I am Making a Random Survival Game
type: Question
has comment: http://stackoverflow.com/comment/81326179
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81326262
has comment: http://stackoverflow.com/comment/81325838
score: 0

http://stackoverflow.com/comment/81221328
type: Comment
comment on: http://stackoverflow.com/q/47134646
score: 0
type: QuestionComment
has text: I see the get_queryset() method should be returning queryset object i guess.

http://stackoverflow.com/a/56977057
type: Answer
answers question: http://stackoverflow.com/q/47213631
score: 0
upvote count: 1
downvote count: 1
has body: I tried the solution by MaFF and it worked --- the installation may have failed to add the PATH to the env. so I manually added it as suggested by MaFF, uninstall and reinstall is not necessary.

http://stackoverflow.com/q/47201984
has body: This Python code gives sorted elements according to string elements. How we convert list elements, which are in string format in integer type? This is my code: def insertionSort(arr, n): for i in range(1, n): key = arr[i] j = i - 1 while j &gt;= 0 and arr[j] &gt; key: arr[j+1] = arr[j] j = j - 1 arr[j+1] = key print '\nSorted elements: ', return (' ').join(arr) arr = (raw_input("enter elements: ")).split(',') print insertionSort(arr, len(arr))
has comment: http://stackoverflow.com/comment/81352315
has answer: http://stackoverflow.com/a/47202104
type: Question
has title: Python code for Insertion sort taking input as a string value
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47202104
upvote count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
score: 1

http://stackoverflow.com/comment/81260536
comment on: http://stackoverflow.com/q/47089555
score: 0
has text: Nice to hear that the root cause was pinpointed! You should probably write an answer to your own question and mark it as such.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47068935
has body: I have a dataframe which contains the following columns: feat norm window type user_id ---------------------------------------- 0 all 0.110000 0 true user1 1 all1 0.232110 0 null user2 2 all2 0.324234 0 true user3 3 all 0.323120 0 null user4 4 all 0.322000 1 true user1 5 all1 0.100000 1 null user1 6 all1 0.200000 1 null user2 7 all2 0.300000 1 true user3 I need to make a result dataframe that contains : feat user result_norm -------------------------------- all user1_true -0.212 all1 user2_null 0.03211 all2 user3_true 0.0324 all user4_null 0.323120 Note : user4 entry is in output, since its window is 0 and respective '1' entry is not in dataframe. It is as good as subtraction window 0 norm with 0 value. i.e. for every user, type and feature I need to subtract norms and make a new dataframe. We get the above shown result table by subtracting (user1,true,all,0) norm with (user1,true,all,1) norm. Basically per user, per type, per feat get difference of norms between the windows. It is not necessary that all user,type, feat combination has its opposite window entry to subtract from, in this case if window is 0, we copy the row to output dataframe or else discard it. I have currently achieved by doing : data = data.groupby(by=['user_id', 'feat', 'type']) and iterating on each groups using for loop like this : for tuple, group in data: #perform operations on this group Though this solution works, it is extremely slow since groupby is expensive operation. The dataframe I have contains about 9000000 entries. Any way to improve this?
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
has title: Effecient way to parse pandas dataframe
answer count: 1
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/47068973
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47068973
downvote count: 0
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/81246942
type: AnswerComment
score: 0
type: Comment
has text: Thanks! I'm curious though, it seems that Z is an array whose rows correspond to the r position and columns correspond to theta position. I don't quite understand how or why matplotlib converts this data to correspond to some x,y coordinate.
comment on: http://stackoverflow.com/a/47147769

http://stackoverflow.com/comment/81260965
type: Comment
has text: In database it will always be in UTC with timezone info, but when you show it in your templates it will auto translates to user's timezone.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47136029

http://stackoverflow.com/comment/81334856
has text: `cv2.minAreaRect(points)`
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47192709

http://stackoverflow.com/q/47141998
type: Question
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47146646
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/47142304
has body: How to get user id from JWT token. My JWT token has payload something like this: { "username": "Steve", "is_admin": false, "id": 1 } How do I get access to user id? I actually want to update certain fields in database as per the id, that are for a specific user. Secondly after gaining the access how do I get update the fields? models.py class Profile(models.Model): branch = models.CharField(max_length=20, null=True) year = models.IntegerField(null=True) image = models.ImageField(upload_to="accounts/images/", null=True, blank=True) serializer.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('branch', 'year' ,'image',) What will be the view to update these fields?
possible better answer: http://stackoverflow.com/a/47146646
has answer: http://stackoverflow.com/a/47142304
has title: How to get user id from JWT
tagged with: django-rest-framework

http://stackoverflow.com/comment/81403824
comment on: http://stackoverflow.com/a/47222936
has text: can you explain what is happening on `a = a.reindex(range(1, a.index.max() + 1))`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81124489
has text: The indentation in your code doesn't seem right.
comment on: http://stackoverflow.com/q/47087380
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47213347
has body: I have to represent a directory structure as a graph using PyQt. e.g. Inside the 'Main' directory I have some files along with few other directories viz 'Inbox', 'Sent', 'Outbox', etc. These sub-directories will consist of emails downloaded from an IMAP server. The user should definitely have the access to drag and pull nodes (especially the leaves). I referred to the example set of PyQt but did not find any such example where I can dynamically add a node and edge to the graph. Although, I saw an example at Bezier curve with control points but could not figure out a way. All the examples in PyQt example set usually accept a numpy array as an input, and plots it to x &amp; y coordinates of a 2D graph. I am not sure how to map directories with a numpy array, as I do not intend to plot using coordinates. The example code from PyQt looks like: ## Define positions of nodes pos = np.array([[0,0],[10,0],[0,10],[10,10],[5,5],[15,5]]) ## Define the set of connections in the graph adj = np.array([[0,1],[1,3],[3,2],[2,0],[1,5],[3,5],]) ## Define the symbol to use for each node (this is optional) symbols = ['o','o','o','o','t','+'] ## Define the line style for each connection (this is optional) lines = np.array([(255,0,0,255,1),(255,0,255,255,2),(255,0,255,255,3), (255,255,0,255,2),(255,0,0,255,1),(255,255,255,255,4),], dtype=[('red',np.ubyte),('green',np.ubyte), ('blue',np.ubyte), 'alpha',np.ubyte),('width',float)]) ## Update the graph g.setData(pos=pos, adj=adj, pen=lines, size=1, symbol=symbols, pxMode=False) To present what I meant, I created a simple non-interactive plot using Plotly. The direcory Inbox and Outbox will have subdirectories as well. . Can anybody help me implementing the same using PyQt without showing any axes on the graph or point to me to some other resource?
tagged with: python
tagged with: pyqtgraph
tagged with: plot
score: 3
tagged with: pyqt
upvote count: 3
tagged with: plotly
has title: Build an interactive tree graph in python using PyQtGraph
linked to: http://stackoverflow.com/q/2173146
downvote count: 0
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/47215427
upvote count: 1
has comment: http://stackoverflow.com/comment/81380282
has comment: http://stackoverflow.com/comment/81380412
answers question: http://stackoverflow.com/q/47215367
has body: The text attribute is a propery without setter. If you want to modify it, you should copy it to a new variable like this: from copy import copy my_text = copy(r.text)
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81380509
has comment: http://stackoverflow.com/comment/81390110
downvote count: 0

http://stackoverflow.com/comment/118499905
has text: FYI, `pip-review` needs to be installed first with `pip`
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/56798606
type: Comment

http://stackoverflow.com/a/50679235
has body: Using a built version of jpy in conda solved the issue. I suggest eg: conda install -c terradue jpy hope this still helps somebody
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47201502

http://stackoverflow.com/comment/81392242
score: 1
type: QuestionComment
has text: Also, you could convert to datetime when reading your CSV. Use `parse_dates='ensirekisterointipvm'` when calling `read_csv`.
type: Comment
comment on: http://stackoverflow.com/q/47221348

http://stackoverflow.com/comment/81252249
score: 1
comment on: http://stackoverflow.com/q/47150564
type: QuestionComment
has text: In OAuth you don't log people out of the authorization server (Google in your case). How, if, when and how often the authorization server checks the users identify is its own decision. In the end it authorized your application, not the other way around. And it will do so until the user revokes the token for your app. It you invalidate the token on your side, it has no impact on the trust state of the user on the authorization server.
type: Comment

http://stackoverflow.com/comment/81343299
type: AnswerComment
comment on: http://stackoverflow.com/a/47197241
score: 0
type: Comment
has text: I also check the validity in the application, but the primary key constraint is supposed to act as a safety net, and was specified so I will probably have to run with it.

http://stackoverflow.com/comment/81263663
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47156173
type: Comment
has text: Thank you so much. This really helps me :) Anyway, will this program work if the number of nodes is 1000?

http://stackoverflow.com/a/47093101
has body: import re re.findall(r'\[\] (.*)\n\n', detaildesc_final) Output: ['some text', 'some_other_text', 'some_other_text', 'some_other_text', 'some_other_text', 'some_other_text', 'some_other_text', 'some_other_text', 'some_other_text', 'some_other_text', 'some_other_text', 'some_other_text']
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47092367
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81157504
score: 0
type: Comment
has text: Thanks for your comment. What am i supposed to change then ?
type: QuestionComment
comment on: http://stackoverflow.com/q/47103557

http://stackoverflow.com/comment/81247810
type: Comment
has text: Is that 2 columns at first?
type: QuestionComment
comment on: http://stackoverflow.com/q/47148683
score: 2

http://stackoverflow.com/q/47128289
type: Question
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/81206679
downvote count: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/13905741
tagged with: python
score: 2
type: AnsweredQuestion
has body: I am porting a library to Python 3. I have a class with a lot of class variables that are initialized with range(). Here's a cut-down example: class Test(object): base = 3 a,b,c,d = [base+y for y in range(4)] print (Test.b) This code works fine in Python 2. $ python2 test.py 1001 But it fails in Python 3: $ python3 test.py Traceback (most recent call last): File "test.py", line 1, in &lt;module&gt; class Test(object): File "test.py", line 3, in Test a,b,c,d = [base+y for y in range(4)] File "test.py", line 3, in &lt;listcomp&gt; a,b,c,d = [base+y for y in range(4)] NameError: name 'base' is not defined Question: What is going on? How can I port this to Python 3 without a lot of ugly repetitive code?
accepted answer: http://stackoverflow.com/a/47128383
has title: Python class variable initialization different in Python 3
has answer: http://stackoverflow.com/a/47128383
has comment: http://stackoverflow.com/comment/81206647
linked to: http://stackoverflow.com/q/13905741
favorite count: 0

http://stackoverflow.com/comment/81214437
score: 0
has text: Those are just objects in the `collections` namespace. Just as if you wrote a module, and did something like `import xyz`, then if you looked at `dir(my_module)` it would have `xyz` in it...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47132404

http://stackoverflow.com/comment/81126414
has text: Are you only interested in the *end* result or do you actually need all of those intermediate DataFrames for something else?
score: 0
comment on: http://stackoverflow.com/q/47088372
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81286615
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47167906
type: Comment
has text: Possible duplicate of [How to do relative imports in Python?](https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python)

http://stackoverflow.com/a/47105385
accepted answer of: http://stackoverflow.com/q/47105358
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47105358
downvote count: 0
upvote count: 1
has body: Unfortunately you can't. During the class' body execution, the class itself is not yet defined. You can always create the class and change it later, or create the class using type(...)/metaclasses. But you shouldn't go this route unless you really need it.
type: Answer
score: 1

http://stackoverflow.com/a/47119021
has comment: http://stackoverflow.com/comment/81189676
has comment: http://stackoverflow.com/comment/81365455
has body: with open('metadata.csv', 'w', newline='') as f_handle: fieldnames = ['id', 'author'] writer = csv.DictWriter(f_handle, fieldnames=fieldnames) writer.writeheader() for row in data: writer.writerow(row) So the thing is, your data is in the form of dictionaries, while the Writer object expects tuples. You should be using the DictWriter object instead.
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81187893
downvote count: 0
answers question: http://stackoverflow.com/q/47118937

http://stackoverflow.com/q/47152271
has body: I'm currently using the following code to subscribe to a Server Side Event API: import requests import sseclient import json import pprint def get_recent_change(): url = 'https://stream.wikimedia.org/v2/stream/recentchange' response = requests.get(url, stream=True) client = sseclient.SSEClient(response) for event in client.events(): pprint.pprint(json.loads(event.data)) return get_recent_change() Which works! Outputting the following data stream (only one entry shown): {'bot': True, 'comment': 'fixing url', 'id': 998191574, 'length': {'new': 664, 'old': 662}, 'meta': {'domain': 'commons.wikimedia.org', 'dt': '2017-11-07T07:24:14+00:00', 'id': 'a8e00e00-c38c-11e7-b9f1-b083fecef9b0', 'offset': 526240012, 'partition': 0, 'request_id': 'e9052543-9df8-4ff6-a94e-06629f9aef0e', 'schema_uri': 'mediawiki/recentchange/1', 'topic': 'eqiad.mediawiki.recentchange', 'uri': 'https://commons.wikimedia.org/wiki/File:St_Cuthbert%27s_High_School_-_geograph.org.uk_-_71872.jpg'}, 'minor': True, 'namespace': 6, 'parsedcomment': 'fixing url', 'patrolled': True, 'revision': {'new': 266424348, 'old': 155939348}, 'server_name': 'commons.wikimedia.org', 'server_script_path': '/w', 'server_url': 'https://commons.wikimedia.org', 'timestamp': 1510039454, 'title': "File:St Cuthbert's High School - geograph.org.uk - 71872.jpg", 'type': 'edit', 'user': 'HiW-Bot', 'wiki': 'commonswiki'} How do I write a test for get_recent_change()? Everything I try hangs because the stream is never closed... Any ideas?
tagged with: server-sent-events
has title: How do I test Server Sent Event API responses in Python?
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 0
score: 6
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/63505446
tagged with: pytest

http://stackoverflow.com/comment/96647600
score: 0
comment on: http://stackoverflow.com/q/47191039
type: Comment
has text: How to do order_by DESC?
type: QuestionComment

http://stackoverflow.com/comment/81279943
type: Comment
type: QuestionComment
score: 0
has text: the two lines `for line in userdetails` amd `usn = userdetails.readline` (which should be `readlines()`) are redundant; looping through a file object (like `userdetails`) will return the `line` is a string. try printing the values that you are reading and see what you get rather than what you expect, I have a feeling you will be very surprised. Reading [the docs](https://docs.python.org/3/library/functions.html#open) on how to use `open` may also help.
comment on: http://stackoverflow.com/q/47164684

http://stackoverflow.com/q/47181092
upvote count: 36
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/65150467
has answer: http://stackoverflow.com/a/55106031
possible better answer: http://stackoverflow.com/a/55106031
linked to: http://stackoverflow.com/q/46308370
accepted answer: http://stackoverflow.com/a/47181813
type: AnsweredQuestion
score: 36
answer count: 3
has body: When I am doing the slicing, an unexpected thing happened that seems the first to be view but the second is copy. First First slice of row, then slice of column. It seems is a view. &gt;&gt;&gt; a = np.arange(12).reshape(3, 4) &gt;&gt;&gt; a[0:3:2, :][:, [0, 2]] = 100 &gt;&gt;&gt; a array([[100, 1, 100, 3], [ 4, 5, 6, 7], [100, 9, 100, 11]]) Second But if I first slice of column, then slice of row, it seems a copy: &gt;&gt;&gt; a[:, [0, 2]][0:3:2, :] = 0 &gt;&gt;&gt; a array([[100, 1, 100, 3], [ 4, 5, 6, 7], [100, 9, 100, 11]]) I am confused because the two methods finally will cause seem position to change, but why the second actually doesn't change the number?
has title: Numpy: views vs copy by slicing
tagged with: slice
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47181813

http://stackoverflow.com/comment/81198931
type: AnswerComment
comment on: http://stackoverflow.com/a/47118698
has text: @coldspeed thanks for the nice pythonic one liner! But, that was a little trimmed down version of this. Notice that I use an overcomplicated `mode` method to fill the `group` column here? That is not included in the other question. I wonder if it's still possible to write by a list comprehension.
score: 0
type: Comment

http://stackoverflow.com/comment/81335398
type: QuestionComment
has text: Show the full traceback. Debug your program, for example by printing all your (intermediate) variables.
comment on: http://stackoverflow.com/q/47193072
score: 0
type: Comment

http://stackoverflow.com/comment/81181079
type: Comment
score: 0
type: AnswerComment
has text: Yeah, that works. But it's super ugly. There's really only a single character there that needs escaping (or putting it first or last). Also, why `findall` instead of `search`?
comment on: http://stackoverflow.com/a/47115589

http://stackoverflow.com/comment/81082649
has text: I am attempting to match my current location to my office location and if they match, send an arrival SMS. Sitting at my office now, when I run above code, there's a mismatch between lat-longs I get from https://mynasadata.larc.nasa.gov/latitudelongitude-finder/ and the code. Any approx value would work.
type: Comment
comment on: http://stackoverflow.com/a/47067230
score: 0
type: AnswerComment

http://stackoverflow.com/q/47088598
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47098433
has comment: http://stackoverflow.com/comment/81127007
has comment: http://stackoverflow.com/comment/81146120
has comment: http://stackoverflow.com/comment/81126722
has answer: http://stackoverflow.com/a/47098433
has body: I am creating a program that uses age to determine factors such as annual fees, and to count annual fees i am using the modulus operator (%). For some reason a whole number % 1 is not creating 0. Why is it doing this and how can I fix it? My expected output is the word "year" printing every 12 iterations. age=int(input("Age")) quit="" while quit!="quit": print(age%1) if age%1==0 or age%1==1: print("Year.") quit=input("Type quit to quit") age+=1/12
tagged with: python
tagged with: modulus
has comment: http://stackoverflow.com/comment/81126839
has comment: http://stackoverflow.com/comment/81126770
has comment: http://stackoverflow.com/comment/81127144
type: AnsweredQuestion
has title: Why is modulus % not working?
has comment: http://stackoverflow.com/comment/81126925
has comment: http://stackoverflow.com/comment/81149501
score: 0
has comment: http://stackoverflow.com/comment/81126914

http://stackoverflow.com/comment/81200709
comment on: http://stackoverflow.com/a/47124708
type: Comment
type: AnswerComment
score: 0
has text: Thanks very much John. I think I was trapped in not getting mylist[:mid] would return a new list and all the work afterwards was done to the new one independently.

http://stackoverflow.com/comment/81349702
type: Comment
score: 0
type: QuestionComment
has text: Because any non-empty string is True-like as per the boolean rules Python uses...
comment on: http://stackoverflow.com/q/47200642

http://stackoverflow.com/comment/81414262
type: AnswerComment
has text: No problem, and glad it helped! If your issue is solved, mind marking the question as answered?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47207051

http://stackoverflow.com/a/47212932
score: 0
has body: I would try the following; def my_model_with_shortcut(): def _create_shortcut(inputs): # here create model as in case you know inputs, e.g.: aux = Dense(10, activation='relu')(inputs) output = Dense(10, activation='relu')(aux) return output return _create_shortcut Now you should have your scenario possible.
type: Answer
answers question: http://stackoverflow.com/q/47212464

http://stackoverflow.com/comment/81601652
score: 0
comment on: http://stackoverflow.com/q/47195630
type: Comment
type: QuestionComment
has text: Unfortunately, I have no idea yet. In both cases simple-salesforce uses `json.dumps()` before sending data to API

http://stackoverflow.com/a/47164368
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47164130
downvote count: 0
type: Answer
has body: Use this expression and capture the group 1: (?:[b])([0-9]{3}) Here is a sample: https://regex101.com/r/fL4csm/2 In the case of using python, i suggest you to try to add some code that you coded instead of asking for how to code it. Check this link: https://stackoverflow.com/help/on-topic

http://stackoverflow.com/comment/82889757
comment on: http://stackoverflow.com/a/47959838
type: Comment
has text: ```fastText``` first calculates word embeddings, and then uses them for classification. You need only the embeddings. See the discussion of producing embeddings of texts (instead of words) here: https://github.com/facebookresearch/fastText/issues/26
score: 2
type: AnswerComment

http://stackoverflow.com/comment/81119944
has text: Last comment, a `for` loop can have an `else`. The `else` is only executed if the loop exits normally. If you `break` out of the for loop, the else does not execute. So you don't need to test anything coming out of your for loop. You just need an "else" that raises an exception because if it were long enough, you would have hit a "break".
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47084046

http://stackoverflow.com/q/47115893
tagged with: selenium-webdriver
score: 0
has comment: http://stackoverflow.com/comment/81246083
has title: Python Webdriver how to find dynamic parameter on web table
answer count: 0
has body: Python > webdriver I want the method to get an id > locate the row on the web table > click on the name of the row I have: table with the ids (in red - to find) and name (in blue - to click on) Table screenshot HTML of the table where I want to click method the gets parameter 'list_id' = id number in the platform (ex. 813231) to locate the list In the code below: I defined the table on the web page 'customer' - found the row contains "813231" clicked on the first columns (because the id include on each html column name) That's the closest I've got but far from what I want. How can I find the parameter 'list_id' and click on the text on the third column? ** attached the screenshot in the links above. table = driver.find_element_by_xpath("//div[@class='body-container']/table") customer = table.find_element_by_xpath("//tr/td[contains(text(), '813231')]") customer.click()
tagged with: jquery
tagged with: webdriver
type: Question
has comment: http://stackoverflow.com/comment/81200348
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python

http://stackoverflow.com/comment/81203888
has text: Yes, the indentation is correct on my own code. Thank you for that answer. I cant believe i missed that!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47126839
type: Comment

http://stackoverflow.com/a/47204259
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47178453
has body: I finally solved it import os rootdir = my root folder # creates a file f that contains all the lines of the files # with "root.vrpj" or "root.vprj" in their name # and who are inside "App_integrations" folders # without duplicates #creating the big file with all the file containing the lines I need f = open('final_file.txt', 'a') for root, dirs, files in os.walk(rootdir): for filename in files: if (filename.endswith(("root.vrpj", "root.vprj")) and ("App_Integration" in os.path.join(root, filename))): full_name = os.path.join(root, filename) data = open(full_name).read() f.write(data + "\n") f.close() #copying the lines I need to f1 without duplicates lines_seen = set() f = open('final_file.txt') f1 = open('testread1.txt', 'a') doIHaveToCopyTheLine=False for line in f.readlines(): if (("Table" in line) and (line not in lines_seen)): doIHaveToCopyTheLine=True if doIHaveToCopyTheLine: f1.write(line) lines_seen.add(line) f1.close() f.close()
answers question: http://stackoverflow.com/q/47178453
score: 0
type: Answer

object-composition
tag name: object-composition
type: Tag
tags question: http://stackoverflow.com/q/47164697

http://stackoverflow.com/q/47166000
has comment: http://stackoverflow.com/comment/81282701
has body: I have a Python code which is logging some data into a .csv file. logging_file = 'test.csv' dt = datetime.datetime.now() f = open(logging_file, 'a') f.write('\n "{:%H:%M:%S}",{},{}'.format(dt,x,y,)) The above code is the core part and this produces continuous data in .csv file as "00:34:09" ,23.05,23.05 "00:36:09" ,24.05,24.05 "00:38:09" ,26.05,26.05 ... etc., Now I wish to add the following lines in first row of this data. time, data1,data2.I expect output as time, data1, data2 "00:34:09" ,23.05,23.05 "00:36:09" ,24.05,24.05 "00:38:09" ,26.05,26.05 ... etc., I tried many ways. Those ways not produced me the result as preferred format.But I am unable to get my expected result. Please help me to solve the problem.
has comment: http://stackoverflow.com/comment/81281777
has comment: http://stackoverflow.com/comment/81281747
answer count: 1
has comment: http://stackoverflow.com/comment/81282219
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81281998
type: UnansweredQuestion
score: -2
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/47166080
has title: Constant first row of a .csv file?
tagged with: python
has comment: http://stackoverflow.com/comment/81281817
upvote count: 0
tagged with: python-2.7
downvote count: 2

http://stackoverflow.com/a/47204216
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/81504482
has comment: http://stackoverflow.com/comment/81382677
has body: Probably you need dont_filter=True. Like this yield scrapy.Request(url='http://www.*********.com/search/list/ajax', method="POST", headers=headers, meta=querystring, dont_filter=True)
has comment: http://stackoverflow.com/comment/81360668
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47202569

http://stackoverflow.com/comment/81165795
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47107231
has text: @wwii it's more of a general question, but I just happened to be working with regex's when it came up.
score: 0

http://stackoverflow.com/q/47213246
has title: Correctly closing of polygons generated using skimage.measure.find_contours()
accepted answer: http://stackoverflow.com/a/47218340
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/70146969
score: 3
answer count: 2
has answer: http://stackoverflow.com/a/47218340
upvote count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/70146969
favorite count: 0
type: Question
tagged with: scikit-image
tagged with: python
has body: I'm currently using skimage.measure.find_contours() to find contours on a surface. Now that I've found the contours I need to able to find the area enclosed within them. When all of the vertices are within the data set this is fine as a have a fully enclosed polygon. However, how do I ensure the polygon is fully enclosed if the contour breaches the edge of the surface, either at an edge or at a corner? When this happens I would like to use the edge of the surface as additional vertices to close off the polygon. For example in the following image, with contours shown, you can see that the contours end at the edge of the image, how do I close them up? Also in the example of the brown contour, which is just a single line, I don't think I want an area returned, how would I single out this case? I know I can check for enclosed contours/polygons by checking if the last vertices of the polygon is the same as the first. I have code for calculating the area inside a polygon, taken from here def find_area(array): a = 0 ox,oy = array[0] for x,y in array[1:]: a += (x*oy-y*ox) ox,oy = x,y return -a/2 I just need help in closing off the polygons. And checking for the different cases that might occur. Thanks Update: After applying the solution suggested by @soupault I have this code: import numpy as np import matplotlib.pyplot as plt from skimage import measure # Construct some test data x, y = np.ogrid[-np.pi:np.pi:100j, -np.pi:np.pi:100j] r = np.sin(np.exp((np.sin(x)**3 + np.cos(y)**2))) # Coordinates of point of interest pt = [(49,75)] # Apply thresholding to the surface threshold = 0.8 blobs = r &gt; threshold # Make a labelled image based on the thresholding regions blobs_labels = measure.label(blobs, background = 0) # Show the thresholded regions plt.figure() plt.imshow(blobs_labels, cmap='spectral') # Apply regionprops to charactersie each of the regions props = measure.regionprops(blobs_labels, intensity_image = r) # Loop through each region in regionprops, identify if the…

http://stackoverflow.com/comment/81326081
type: Comment
type: AnswerComment
score: 5
has text: While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
comment on: http://stackoverflow.com/a/47187536

http://stackoverflow.com/comment/81087220
comment on: http://stackoverflow.com/q/47069688
score: 0
type: Comment
type: QuestionComment
has text: The error is caught inside `foo()` instead of in the executor

http://stackoverflow.com/comment/81174467
type: Comment
type: QuestionComment
score: 0
has text: @Maxim, actually oddly, after a few runs of the script, the error disappeared. I'm not running into the problem anymore, and not exactly sure what fixed it.
comment on: http://stackoverflow.com/q/47086810

http://stackoverflow.com/q/47179961
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47180030
has answer: http://stackoverflow.com/a/47180030
tagged with: legend
accepted answer: http://stackoverflow.com/a/47180122
tagged with: python
has body: Hi I have a numpy array a = np.random.uniform(0,1, size = (10,3)) I want to plot each of the columns with its own label plt.plot(a, label = ['label1', 'label2', 'label3']) plt.legend() How can I do that? The above is my tentative, but didn't work.
has answer: http://stackoverflow.com/a/47180122
type: AnsweredQuestion
score: 2
answer count: 2
upvote count: 3
tagged with: matplotlib
downvote count: 1
favorite count: 0
has title: Matplotlib: adding legend for each column of numpy array
type: Question

http://stackoverflow.com/a/47174398
has comment: http://stackoverflow.com/comment/81298365
score: 0
has body: Since double loops on Would be O(X*Y) where X and Y are the lengths of your lists, the easier solution would be to sort both lists O(X*log(X)) + O(Y*log(Y)) then iterate throught both at once like so: i = 0 j = 0 while True: x_el = X[i] y_el = Y[j] # do something with it and increase i and/or j accordingly if i &gt;= len(X) or j &gt;= len(Y): break
type: Answer
answers question: http://stackoverflow.com/q/47174294

http://stackoverflow.com/comment/81385685
has text: I have got it! The HEX for number 3 is 33 in ASCII. So that's why it shows it as a single 3. This was really a little mind boggling.
score: 0
comment on: http://stackoverflow.com/q/47208775
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47194224
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47193886
has body: Try this hope it helps: https://repl.it/OAQv class Car: pass module_name = __import__('sys').modules[__name__] setattr(module_name, 'Mustang', Car()) setattr(module_name, 'Camaro', Car()) setattr(module_name, 'Challenger', Car()) print(Mustang) print(Camaro) print(Challenger) to dynamically create instance of class using list of strings class Car: pass module_name = __import__('sys').modules[__name__] cars = ['Mustang', 'Camaro', 'Challenger'] for car in cars: setattr(module_name, car, Car()) print(Mustang) print(Camaro) print(Challenger)
downvote count: 0

http://stackoverflow.com/comment/81082331
type: QuestionComment
comment on: http://stackoverflow.com/q/47066817
type: Comment
score: 0
has text: Also, the broken file, can you open it in Notepad/TextEdit ?

http://stackoverflow.com/comment/81172501
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47111279
has text: Not every rendition of the RegEx module per each language is created the same, hence why there are differences between PHP's RegEx and VB.NET's RegEx, and in sum they all scale differently to Python's RegEx.

http://stackoverflow.com/a/47118784
downvote count: 0
answers question: http://stackoverflow.com/q/47118756
type: Answer
score: 3
upvote count: 3
has body: Use groupby + count/size: df.groupby(['v1', 'v2']).v3.transform('count') 0 6.0 1 6.0 2 6.0 3 6.0 4 6.0 5 6.0 6 6.0 7 6.0 8 6.0 9 6.0 10 6.0 11 6.0 12 3.0 13 3.0 14 3.0 Name: v3, dtype: float64 Use the mask to filter df: df = df[df.groupby(['v1', 'v2']).v3.transform('count').eq(6)] # == 6 df v1 v2 v3 0 0 -30 -15.00000 1 0 -30 -7.50000 2 0 -30 -11.25000 3 0 -30 -13.12500 4 0 -30 -14.06250 5 0 -30 -13.59375 6 0 -10 -5.00000 7 0 -10 -7.50000 8 0 -10 -6.25000 9 0 -10 -5.62500 10 0 -10 -5.93750 11 0 -10 -6.09375 count does not count NaNs, while size does. Use whatever is appropriate for you.

http://stackoverflow.com/q/47127575
has comment: http://stackoverflow.com/comment/81205870
has answer: http://stackoverflow.com/a/47128027
tagged with: python
tagged with: numpy
has title: Copy data from numpy to ctypes quickly
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81205537
answer count: 1
accepted answer: http://stackoverflow.com/a/47128027
has body: I have a ctypes object shared between a c++ and python process. The python process takes the input values from that object, runs them through Tensorflow, and I'm left with a numpy array as output. As these arrays are pretty big I'm wondering if there is a better approach to copying the data from the output of tensorflow back to the shared ctypes object so the c++ process can act on them. (speed is the issue, yes.) Right now I'm copying each value one by one: output = np.array([12, 13, 11, 10]) # in reality this is fairly large (the Tensorflow result) for i, value in enumerate(output): data.pressure[i] = ctypes.c_double(value) where data is the ctypes object shared in memory. (structured after this example) On the other hand, copying data from the ctypes object into numpy is easy, I'm wondering if there is something that does the opposite (from numpy to the ctypes array) Here is that easy code: # Creating a numpy array from the ctypes array input = np.reshape(data.velocity, (1, 29791)) # Tensorflow returns a numpy array output = sess.run(final, feed_dict={Input: input}) # Now how do I get the data from output into data.pressure? Edit: For reference, this is how the ctypes looks (python side) class TransferData(ctypes.Structure): _fields_ = [ ('statusReady', ctypes.c_bool), # ... ('velocity', ctypes.c_double * (31 * 31 * 31)), ('pressure', ctypes.c_double * (31 * 31 * 31)) ]
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: ctypes

http://stackoverflow.com/comment/81085873
has text: `nonzero` from a sparse matrix is almost trivial, but constructing a sparse matrix to start with is relatively slow. Once constructed the fastest sparse operations are matrix multiplication. Indexing, summing, iteration are all slower with sparse.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47068017

http://stackoverflow.com/q/47136614
has body: I have once created and trained a GeneralizedLinearModel in Matlab, then saved it to my drive. Regularly I load this model in Matlab and use the '.predict' on some data. Now I would like to load the saved model (with its specific coefficients) into Python and run the'.predic' the same as in Matlab. Does anyone know how to do that or alternatively how to implement the prediction given the coefficients?
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/81222564
type: UnansweredQuestion
has title: load Matlab's GeneralizedLinearModel in Python
tagged with: matlab
type: Question
score: 0
has comment: http://stackoverflow.com/comment/81222704
has comment: http://stackoverflow.com/comment/81222620

http://stackoverflow.com/q/47101273
favorite count: 0
type: Question
has body: I have a pandas dataframe with a column "value" and a column "timestamp". Now I would like to filter the rows according to thresholds of the timestamp. I have done the following: idx = df.index[df['timestamp'] &gt;= start and df['timestamp'] &lt;= end] df = df.loc[idx] df is the dataframe and start and end are two integers. Somehow this does not work. I'm getting an error: ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). EDIT: There is a further problem. start is a dataframe with only one value (one row, one column). End is a dataframe with several rows and only one column (but I'm only interested in the last row). When I do the following print(end.iloc[-1]) print(start.iloc[0]) I'm getting the following output 1508504026077 start_timestamp_milli 1508502348946 Name: 0, dtype: int64 When I then try to do print(df[column] &gt;= start.iloc[0]) I'm getting an error: ValueError: Can only compare identically-labeled Series objects Consequently, mask=(df['timestamp'] &gt;= start &amp; df['timestamp'] &lt;= end) also failes.
tagged with: python
has answer: http://stackoverflow.com/a/47101312
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47101312
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
has title: Selecting rows of pandas dataframe according to threshold of column
answer count: 1

http://stackoverflow.com/comment/81095761
score: 0
has text: @Zinarod,IPython 5.4.1 is using Python 2.7.12 which is in /usr/bin/python
comment on: http://stackoverflow.com/q/47072355
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47107617
has body: It doesn't matter whether you use django template or use reactjs to send Post request. So this function will be in the views.py file, you can add the @login_required decorator for all required endpoints, django have it own authentication(by default it will associate with the User model, but you can change it)to protect the API, and you can use DRF token or JWT in your application to post to serve(check this for details:http://www.django-rest-framework.org/api-guide/authentication/)
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47107549

http://stackoverflow.com/q/47164814
score: 1
tagged with: datetime
tagged with: python
accepted answer: http://stackoverflow.com/a/47164880
type: Question
has body: I am trying to convert the a Data frame column name (Timestamp) into the written abbreviation of that month and the year. Here is an example of the current data frame: 2016-01-01 2016-02-01 2016-03-01 2016-04-01 00:00:00 00:00:00 00:00:00 00:00:00 Metric 1 Data Data Data Data Metric 2 Data Data Data Data Metric 3 Data Data Data Data This is my desire output: Jan 2016 Feb 2016 March 2016 April 2016 Metric 1 Data Data Data Data Metric 2 Data Data Data Data Metric 3 Data Data Data Data Here is the code I used to build the Data Frame: start = '2016-01-01' end = '2016-04-01' data_dates = pd.date_range(start, end, freq='MS') data_results = pd.DataFrame(data_dates) data_results.columns = ['Date'] data_results = data_results['Date'].tolist() df = pd.DataFrame(columns = data_results, index = ['Metric 1', 'Metric 2', 'Metric 3']) I have try using the following with no results. data_results['Date'] = data_results['Date'].apply(lambda x: calendar.month_abbr[x])
answer count: 2
has answer: http://stackoverflow.com/a/47164880
downvote count: 0
upvote count: 1
has title: Converting timestamp into Month name and year as a Data frame column name
favorite count: 0
tagged with: datetime-format
possible better answer: http://stackoverflow.com/a/47164846
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/47164846

http://stackoverflow.com/q/47223184
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47223279
has title: How to install numpy and scipy for python2.7
has comment: http://stackoverflow.com/comment/81396258
has comment: http://stackoverflow.com/comment/81396153
has answer: http://stackoverflow.com/a/47223739
tagged with: python
score: -1
type: Question
tagged with: numpy
tagged with: python-2.7
answer count: 2
upvote count: 0
type: UnansweredQuestion
has body: I used the redhat Linux. I want to install the numpy and scipy for python2.7. I tried to install and do the following activities: 1. download the numpy and scipy using wget command 2. extract the tar file using the tar command 3. when I build using the python setup.py build and when I try the python setup.py commands the error happen as "This is the wrong setup.py file to run" The setup.py file is found inside the folder. For example: /home/desktop/kk/python setup.py build here inside kk there is the setup.py file. what is the problem and solution?

http://stackoverflow.com/q/47170865
has comment: http://stackoverflow.com/comment/81291953
has comment: http://stackoverflow.com/comment/81291546
tagged with: python
has body: I created a new django project. I have a models.py file. I added a handful tables to the file. Now I am trying to migrate it so that I can start updating the project. I am trying to run the following lines but it is saying that there are no changes detected even though the file has changed. Comars-mbp:Yap omarjandali$ python3 manage.py makemigrations No changes detected omars-mbp:Yap omarjandali$ python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. omars-mbp:Yap omarjandali$ omars-mbp:Yap omarjandali$ python3 manage.py runserver Performing system checks... System check identified no issues (0 silenced). November 08, 2017 - 02:52:28 Django version 1.11.5, using settings 'Yap.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. this is the table added to the models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django_localflavor_us.models import USStateField #-------------------------------- # the following are tables realted to the app and general information #-------------------------------- # Profile saves every users profile information class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # server first_name = models.CharField(max_length=25, default='first') last_name = models.CharField(max_length=25, default='last') bio = models.CharField(max_length=220, default='bio') dob = models.DateField(default='1950-01-01') street = models.CharField(max_length=200, default='street address') city = models.CharField(max_length=100, default='city') state = USStateField(default='CA') zip_code = models.IntegerField(default=12345) phone = models.BigIntegerField(default=0) # user balance = models.DecimalField(decimal_places=2, max_digits=9, default=0) dwolla_id = models.CharField(max_length=200, default='https://api-sandbox.dwolla.com')…
has title: Cant migrate changed models.py initial - django
has comment: http://stackoverflow.com/comment/81291432
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: django
score: 0

http://stackoverflow.com/a/47106725
answers question: http://stackoverflow.com/q/47106678
downvote count: 0
has comment: http://stackoverflow.com/comment/81164371
score: 3
has body: Use dtype=float in main array. Your array is integer by default. import numpy as np A = np.array([[2,1,-1,8], [-3,-1,2,-11], [-2,1,2,-3]], dtype=float) B = A[1] + (A[0]*(-A[1,0]/A[0,0])) print(B) A[1] = A[1] + (A[0]*(-A[1,0]/A[0,0])) print(A[1]) #Output: #[ 0. 0.5 0.5 1. ] #[ 0. 0.5 0.5 1. ]
type: Answer
upvote count: 3

http://stackoverflow.com/a/47116956
upvote count: 6
answers question: http://stackoverflow.com/q/47116572
downvote count: 0
has body: Just use the FileSystemLoader: import os import glob from jinja2 import Environment, FileSystemLoader # Create the jinja2 environment. current_directory = os.path.dirname(os.path.abspath(__file__)) env = Environment(loader=FileSystemLoader(current_directory)) # Find all files with the j2 extension in the current directory templates = glob.glob('*.j2') def render_template(filename): return env.get_template(filename).render( foo='Hello', bar='World' ) for f in templates: rendered_string = render_template(f) print(rendered_string) example.j2: {{ foo }} {{ bar }}
type: AcceptedAnswer
score: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/47116572

http://stackoverflow.com/q/47203561
score: 1
favorite count: 0
type: Question
has title: Extract data from Nested Arrays of JSON file into Dataframe
downvote count: 0
upvote count: 1
tagged with: python
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47203984
has body: Have a Json file that is arrays containing arrays I can get all "parts" with with code below but unable to figure out the json_normalize parms usage to extract different levels within nested arrays? ie want 'id' from vehicle array with 'id' from model array with all parts array car | camry | "value":"engine","price":10.82 Thanks f = open('sample.json') data = json.load(f) f.close() df1 = json_normalize(data['vehicle'], 'model') df2 = df1'parts' ddf = pd.DataFrame(columns=['value','charge']) for (index,row) in df2.iterrows(): if pd.notnull(row[0]): e = row[0] ddf.loc[index] = [e[0]['value'], e[0]['charge']] { "vehicle":[ { "id":"car", "model":[ { "id":"camry", "parts": [ { "value":"engine", "charge":10.82 } ] } , { "id":"avelon", "parts": [ { "value":"seats", "charge":538.26 } ] } , { "id":"prius", "parts": [ { "value":"seats", "charge":10.91 } ] } , { "id":"corolla", "markup": { "value":"61" } , "accessories": [ { "value":"vvvvv" }] } ] } ] }
tagged with: pandas

c++
tags question: http://stackoverflow.com/q/47182113
tags question: http://stackoverflow.com/q/47103625
tags question: http://stackoverflow.com/q/47163112
tags question: http://stackoverflow.com/q/47086715
tags question: http://stackoverflow.com/q/47207209
tags question: http://stackoverflow.com/q/47116450
tags question: http://stackoverflow.com/q/47083839
tags question: http://stackoverflow.com/q/47077332
tags question: http://stackoverflow.com/q/47079444
tags question: http://stackoverflow.com/q/47111513
tags question: http://stackoverflow.com/q/47165041
tags question: http://stackoverflow.com/q/47139917
tags question: http://stackoverflow.com/q/47186425
tags question: http://stackoverflow.com/q/47211231
tags question: http://stackoverflow.com/q/47167251
tags question: http://stackoverflow.com/q/47111379
tags question: http://stackoverflow.com/q/47123545
tags question: http://stackoverflow.com/q/47128926
tags question: http://stackoverflow.com/q/47149399
tags question: http://stackoverflow.com/q/47205879
type: Tag
tags question: http://stackoverflow.com/q/47073202
tags question: http://stackoverflow.com/q/47099472
tags question: http://stackoverflow.com/q/47191909
tags question: http://stackoverflow.com/q/47198551
tags question: http://stackoverflow.com/q/47137677
tags question: http://stackoverflow.com/q/47114146
tag name: c++
tags question: http://stackoverflow.com/q/47113548

http://stackoverflow.com/comment/81155977
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47102808
has text: My program output many dictionary lines and I would like to aggregate these to a list to create data frame with pandas.
score: 0

http://stackoverflow.com/comment/81256134
has text: `from urllib.parse import quote_plus` works in python 3.1.6
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47137518
type: QuestionComment

http://stackoverflow.com/comment/81283006
type: QuestionComment
has text: What is the error on the client side? Can you see anything unusual in a network trace?
comment on: http://stackoverflow.com/q/47164951
score: 1
type: Comment

http://stackoverflow.com/comment/81265110
score: 0
type: Comment
type: QuestionComment
has text: follow the link @erip posted, it says how to install
comment on: http://stackoverflow.com/q/47157699

http://stackoverflow.com/comment/81342330
type: Comment
comment on: http://stackoverflow.com/a/47188650
score: 0
type: AnswerComment
has text: Indeed if `containsSampledData` is `false` then you are not being sampled. Do you see any patterns as to where the data is wrong: is it for specific dates, specific hours, or campaigns, or does it seem completely random across the board?

http://stackoverflow.com/comment/81232083
has text: @Mitchell van Zuylen Would you please update your code with urls.py as well?
score: 0
comment on: http://stackoverflow.com/q/47140257
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81181107
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47109633
type: AnswerComment
has text: I have tried running a script on startup but it doesnt change the state of the pins untill I open buttons.php thats when I hear the relays click on and off. Its like it stores the gpio writes then when I open the page it writes all the commands that I have previously sent before that point

http://stackoverflow.com/comment/81150395
has text: Flip by rows : `matrizFinal[::-1]`?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47100230
type: QuestionComment

http://stackoverflow.com/a/47115244
type: AcceptedAnswer
downvote count: 0
has body: The QFont object itself has pixelSize, pointSize and pointSizeF for getting the size. It has family for getting the font family. if ok: button.setFont(font) line.setFont(font) return font.pointSizeF(), font.family()
type: Answer
accepted answer of: http://stackoverflow.com/q/47115171
score: 3
answers question: http://stackoverflow.com/q/47115171
upvote count: 3

http://stackoverflow.com/q/47153151
has answer: http://stackoverflow.com/a/47153243
has answer: http://stackoverflow.com/a/47153961
has body: I want to save a json data into single file in hdfs. currently my approach is to save data into hdfs using spark then merge the data into local (local_tmp_file) and then move it into hdfs (dest) getmerge_command = 'hdfs dfs -getmerge ' + dest + ' ' + local_tmp_file move_command = 'hdfs dfs -moveFromLocal ' + local_tmp_file + ' ' + dest the problem happened when there is a lot of process run at the same time and use the temporary local storage which makes the disk full. Is anyone have any solution for this?
linked to: http://stackoverflow.com/q/31610971
downvote count: 1
has title: save data into single file in hdfs using spark
favorite count: 0
type: Question
tagged with: pyspark
tagged with: python
score: -1
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/47153243
accepted answer: http://stackoverflow.com/a/47153961
upvote count: 0

http://stackoverflow.com/a/47213664
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47213140
score: 2
accepted answer of: http://stackoverflow.com/q/47213140
type: Answer
has body: Ran into the same problem at my previous workplace. You'll want to check out beautifulsoup. from bs4 import BeautifulSoup soup = BeautifulSoup(html) print soup.text You'll find its documentation here: https://www.crummy.com/software/BeautifulSoup/bs4/doc/ You can ignore elements based on attributes. As to understanding external stylesheets im not too sure. However what you could do there and something that would not be too slow (depending on the page) is to look into rendering the page with something like phantomjs and then selecting the rendered text :)
upvote count: 2

http://stackoverflow.com/a/47096499
score: 1
answers question: http://stackoverflow.com/q/47096081
type: Answer
has comment: http://stackoverflow.com/comment/81268211
accepted answer of: http://stackoverflow.com/q/47096081
has comment: http://stackoverflow.com/comment/81142752
has comment: http://stackoverflow.com/comment/81143513
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81142793
has body: You can use groupby and transform with a custom consistency function. First, create some example data (Note: G_Source corresponds to your G2 whereas G_Target corresponds to G1 in your example): Create example data import pandas as pd import numpy as np values = np.random.randint(0, 5, size=(10, 2)) columns = ["G_Source", "G_Target"] df = pd.DataFrame(values, columns=columns).sort_values("G_Source") print(df) G_Source G_Target 0 0 3 3 0 2 4 0 4 5 0 4 7 0 1 8 1 3 9 2 0 6 3 2 1 4 1 2 4 2 Next, let's define the consistency function. Basically, we're looking for the count of the most common value. Therefore, it is easy to use value_counts in conjunction with max. Define consistency function def get_consistency(series): max_common = series.value_counts().max() size = series.shape[0] return max_common / size Groupby and transform Next, we group by the source group (G_Source) and compute the consistency along the target group (G_Target) via transform. df["consistency"] = df.groupby("G_Source")["G_Target"].transform(get_consistency) print(df) G_Source G_Target consistency 0 0 3 0.4 3 0 2 0.4 4 0 4 0.4 5 0 4 0.4 7 0 1 0.4 8 1 3 1.0 9 2 0 1.0 6 3 2 1.0 1 4 1 0.5 2 4 2 0.5
has comment: http://stackoverflow.com/comment/81143568
has comment: http://stackoverflow.com/comment/81142681
has comment: http://stackoverflow.com/comment/81143671
has comment: http://stackoverflow.com/comment/81150814
upvote count: 1

http://stackoverflow.com/comment/81242140
has text: @Bahrom: Substrings vary and have no particular order, I have a few tokens that repeat
comment on: http://stackoverflow.com/q/47144893
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/47164554
tagged with: python
has comment: http://stackoverflow.com/comment/81278918
type: Question
has title: Sum particular list values
score: 0
tagged with: list
answer count: 2
has comment: http://stackoverflow.com/comment/81279050
has comment: http://stackoverflow.com/comment/81279592
has body: I want to sum 3d list values by first two criteria. What is the best way to get from this list a = [['Mercedes', 'AMG', 100], ['Mercedes', 'Cabrio', 200], ['Mercedes', 'AMG', 300], ['Opel', 'Combo', 400], ['Opel', 'MOKKA', 500], ['Opel', 'MOKKA', 600], ['BMW', 'X5', 700]] this result: result = [['Mercedes', 'AMG', 400], ['Mercedes', 'Cabrio', 200], ['Opel', 'Combo', 400], ['Opel', 'MOKKA', 1100], ['BMW', 'X5', 700]]
has answer: http://stackoverflow.com/a/47164943
possible better answer: http://stackoverflow.com/a/47164943
has comment: http://stackoverflow.com/comment/81279667
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47164793
accepted answer: http://stackoverflow.com/a/47164793

http://stackoverflow.com/a/47108338
type: Answer
answers question: http://stackoverflow.com/q/47108253
has body: You're printing the id attribute, but what you want to print is products and label_us from the options object. And since product is a list, you need to loop over it. for key, attribute in spConfig['attributes'].iteritems(): for option in attribute['options']: if option['label_us']: label = option['label_us'].strip() for product_id in option['products']: print product_id, "-", label
accepted answer of: http://stackoverflow.com/q/47108253
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81175592
upvote count: 1
score: 1

http://stackoverflow.com/q/47198551
type: Question
tagged with: swig
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47216411
favorite count: 0
has title: swig macro $descriptor within helper function
has body: Intro My typical swig interface file is similar to the following: %{ //COPY THIS BLOCK AS IS #include &lt;headers.h&gt; static CppClass* get_CppClass_from_swig_object(PyObject* obj) { void* self_obj = nullptr; int ok = SWIG_Python_ConvertPtr(obj, &amp;self_obj, SWIGTYPE_p_CppClass, 0); if(!SWIG_IsOK(ok)) { PyErr_SetString(PyExc_TypeError, "Object must be a CppClass"); return nullptr; } return reinterpret_cast&lt;CppClass*&gt;(self_obj); } static CppClass convert_to_CppClass(PyObject* py_obj) { CppClass* converted_ptr = get_CppClass_from_swig_object(py_obj); if(converted_ptr==nullptr) throw std::runtime_error("Python object is not a CppClass"); return CppClass(*converted_ptr); } %} %typemap(in) std::vector&lt;CppClass&gt;&amp; (std::vector&lt;CppClass&gt; temp) { try{ temp = SequenceConverter::to_vector&lt;CppClass&gt;($input, convert_to_CppClass); $1 = &amp;temp; }catch(std::exception&amp; e){ PyErr_SetString(PyExc_RuntimeError, e.what()); SWIG_fail; } } %typemap(typecheck, precedence=SWIG_TYPECHECK_CPPCLASS_VECTOR) std::vector&lt;CppClass&gt;&amp; { $1 = 0; if(PyTuple_Check($input)) $1 = 1; else if(PyList_Check($input)) $1 = 1; } class CppClass { public: CppClass(); CppClass(const CppClass&amp; other); //other methods }; but I would like to avoid explicitly using SWIGTYPE_p_CppClass within get_CppClass_from_swig_object. As is, it is not possible to use the $descriptor(CppClass) swig macro as I would like to, because the %{ ... %} block is copied as -is rather than interpreted by swig, and so the $descriptor swig macro would not be interpreted. On the other hand, if i would remove the % and use a { ... } block, swig would try and wrap the whole get_CppClass_from_swig_object and convert_to_CppClass classes rather than simply defining them so they can be used in the typemap. Question How can I change my file structure and allow using $descriptor macro within the conversion helpers? TL;DR %{...%} blocks are neither preprocessed nor wrapped by swig {...} blocks are both…
score: 1
answer count: 1
tagged with: c++

http://stackoverflow.com/q/47091227
answer count: 1
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47091426
has comment: http://stackoverflow.com/comment/81131943
tagged with: python
has title: Loop doesn't run every time (Python)
has body: I'm trying to create gradient descent using Python 3.x and PyCharm. Code isn't elegant, but it did it's work. But after running it for several times, "for" loop stopped working. I'm thinking it might be a memory issue or something like this, but if it is, I'm no sure how to fix it. thrust_forward() thrust = neu['d'] thrust_new = 0 def back_and_forward(): randomize_steps_effect() thrust_backward() thrust_forward() global thrust_new thrust_new = neu['d'] iterations = 5000000 def start_process(): print('') print('Progress:') for i in range (0,iterations): global thrust_new global thrust while thrust_new &lt; thrust: back_and_forward() thrust = thrust_new if i%(iterations/100) == 0: print('|', sep = '', end='', flush=True) print('') print('Final: P = ' +str(thrust/9.8) + str(prm)) start_process() Main parameters are stored in dictionaries: #Parametres prm = { 'm':3, #kg/s ... 'ph':-50000 #Pa } #Parameters steps stp = { 'a':0.01, ... 'ph':50 #Pa } #Additional vars neu = { 'a':0, ... 'd':0 } There is randomize function for steps, so "thrust" eventually increases and while loop breaks: #Randomize steps def randomize_steps_effect(): for key, values in stp.items(): r = random.randint(0,3) if r != 0 and (key != 'm' or key != 'w'): stp[key] *= -1 Forward and backward functions: def thrust_forward(): neu['a'] = forward_multiply(prm['m'],prm['w']) neu['c'] = forward_add(prm['pa'],prm['ph']) neu['b'] = forward_multiply(neu['c'],prm['Fa']) neu['d'] = forward_add(neu['a'],neu['b']) def thrust_backward(): global max_w neu['a'] += stp['a'] * backward_add() neu['b'] += stp['b'] * backward_add() prm['Fa'] += stp['Fa'] * backward_multiply_F_wrt_b(prm['Fa'],neu['c']) neu['c'] += stp['c'] * backward_multiply_F_wrt_b(neu['c'],prm['Fa']) prm['pa'] += stp['pa'] * backward_add() prm['ph'] += stp['ph'] * backward_add() prm['m'] += stp['m'] * backward_multiply_F_wrt_b(prm['m'],prm['w']) if prm['w'] &gt;= max_w: stp['w'] = 0 prm['w'] += stp['w'] * backward_multiply_F_wrt_b(prm['w'],prm['m'])
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47091426
has comment: http://stackoverflow.com/comment/81154606

http://stackoverflow.com/comment/81262691
has text: From your reception to the downvotes, and subsequent criticism, it seems evident you have completely missed the point of the question. I don't think I can do anything more to make you understand, so I'll just leave it up to OP to clarify.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47156307

http://stackoverflow.com/comment/81400855
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47212637
type: QuestionComment
has text: "or list of such" - I didn't see that wording. Thanks. Last night I kept getting a syntax error for all three, but could not find anything wrong in the code. This morning I see I was missing the comma separating the elements of the list in the list based solution. (That last approach, using a list, was my preferred syntax.) I'm not convinced the ordered pair would have worked, and I'm sure the first option shouldn't work. Now that I have it working I'm all set - thanks!!

http://stackoverflow.com/comment/81381902
comment on: http://stackoverflow.com/a/47216245
score: 0
has text: Yes, I could, but I need it to return a dictionary where the keys are of type str
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81187691
type: AnswerComment
score: 0
has text: @Topto `item.location['y']` gives the height of web element, you can scroll to element by it heigth
comment on: http://stackoverflow.com/a/47118228
type: Comment

http://stackoverflow.com/comment/81172132
comment on: http://stackoverflow.com/a/47111083
type: AnswerComment
score: 0
has text: Thank you for answering this , it works perfectly , again sorry for the length of the post , i'm still getting used to this.
type: Comment

http://stackoverflow.com/comment/81160302
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47104742
has text: how do you know that the content looks like this? do you print it or save it to a file or?
score: 1

http://stackoverflow.com/comment/81121616
has text: Should I delete my question since it is a duplicate?
comment on: http://stackoverflow.com/q/47084515
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81254263
score: 0
type: Comment
has text: Never Mind...The mistake was that I havn't added endpoints to the libraries Adding this to the end of app.yaml fixed the problem. - name: endpoints version: 1.0
type: QuestionComment
comment on: http://stackoverflow.com/q/47151522

http://stackoverflow.com/comment/81333254
has text: are your user id and item id string or integer? If they are integers, you will have to first convert the Uid and Iid to int because input returns string
type: QuestionComment
comment on: http://stackoverflow.com/q/47191956
score: 0
type: Comment

http://stackoverflow.com/comment/81187852
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47119036
score: 0
has text: I feel rather stupid. How should I install pip using python 3?

http://stackoverflow.com/comment/81310778
score: 0
comment on: http://stackoverflow.com/q/47180843
type: Comment
type: QuestionComment
has text: The suggested changes there don't work for me. I'll give pymssql a go however.

http://stackoverflow.com/comment/81384079
type: Comment
has text: @doriclazar thanks for reply but I am still getting the same error with run "python manage.py runserver "
type: QuestionComment
comment on: http://stackoverflow.com/q/47216089
score: 0

typeerror
tags question: http://stackoverflow.com/q/47101428
tags question: http://stackoverflow.com/q/47100024
tags question: http://stackoverflow.com/q/47107313
tags question: http://stackoverflow.com/q/47165189
tag name: typeerror
tags question: http://stackoverflow.com/q/47081872
tags question: http://stackoverflow.com/q/47117979
tags question: http://stackoverflow.com/q/47193691
tags question: http://stackoverflow.com/q/47193072
tags question: http://stackoverflow.com/q/47172769
type: Tag
tags question: http://stackoverflow.com/q/47087236
tags question: http://stackoverflow.com/q/47073294
tags question: http://stackoverflow.com/q/47128869

zappa
tags question: http://stackoverflow.com/q/47108354
type: Tag
tag name: zappa
tags question: http://stackoverflow.com/q/47146586

http://stackoverflow.com/comment/81204631
score: 0
comment on: http://stackoverflow.com/q/47126885
type: QuestionComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/158277/discussion-between-prabhat-doongarwal-and-paul).
type: Comment

http://stackoverflow.com/a/47175307
has body: .append = assigns a value to append method, which is read only and its not what you want. .append() makes and actual call to append method This can be solved with little research. Please grab a good Python book and spent few hours on it. Good luck! my_list = [] print('please enter your score for player 1, round 1') my_list.append(int(input([0]))) print('please enter your score for player 1, round 2') my_list.append(int(input([1]))) print('please enter your score for player 1, round 3') my_list.append(int(input([2])))
type: Answer
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81299779
answers question: http://stackoverflow.com/q/47175195

http://stackoverflow.com/comment/81350193
type: Comment
type: QuestionComment
has text: Awesome, thank you! I am just checking that out now (I am getting a valuerror: no axis named train), but I should be able to fix that!. Ill let you know if it works when I get the axis sorted
comment on: http://stackoverflow.com/q/47200853
score: 0

http://stackoverflow.com/comment/81396891
comment on: http://stackoverflow.com/q/47209532
score: 2
has text: AMD GPGPU is in a bit of a state of flux. History, AMD was behind OpenCL and clBLAS, but now they're focused on CUDA-compatibility via HIP and hipBLAS. None of it is exactly mature, but I expect (hope) that frameworks like PyCUDA will become vendor-agnostic. It's not clear how much of a future OpenCL will have.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47177586
has title: How to apply a function in parallelized fashion on all the columns of RDD(spark dataframe)?
has answer: http://stackoverflow.com/a/47189270
answer count: 1
tagged with: rdd
favorite count: 0
type: Question
has body: I created a function(func) that accepts 2 inputs: 1. A 2 dimensional array - X 2. A 1 dimensional array - Y I am able to carry out the desired operation, by converting RDD into pandas dataframe and then creating np.array(pandas datframe) as input X to func. Let's say X has 10 cols. I want to process all 10 cols in parallel fashion So that I can call func for each of 10 cols at same time. How can I achieve it using RDD dataframe using pyspark in order to get the output of function for all 10 cols?
tagged with: function
type: UnansweredQuestion
downvote count: 2
tagged with: pyspark
upvote count: 1
tagged with: python
score: -1
tagged with: parallel-processing

http://stackoverflow.com/a/47098208
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47097663
has comment: http://stackoverflow.com/comment/81146470
type: Answer
has body: assuming you really did research and came out empty(which is highly unlikely),you could use something like from tkinter import * import wikipedia def on_click(): q = get_q.get() text.insert(INSERT, wikipedia.summary(q)) root = Tk() question = Label(root, text="Question") question.pack() get_q = Entry(root, bd =5) get_q.pack() submit = Button(root,text='Submit',command=on_click) submit.pack() text = Text(root) text.pack() root.mainloop() Do try to research more and readthedocs,they are your best friend in programming
answers question: http://stackoverflow.com/q/47097663
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47147531
type: Answer
has body: I believe that reduce( (lambda x, y: x &amp; (df[y[0]]&lt;y[1])), list_of_filters ) will do it.
score: 0
answers question: http://stackoverflow.com/q/47147414

http://stackoverflow.com/comment/81293279
comment on: http://stackoverflow.com/q/47171900
has text: Are you asking about documentation meta-syntax?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81370763
score: 0
has text: As @SachinKukreja told in comment check the answer , drop the db and run makemigrations and migrate again , you will loose your data.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47210402

http://stackoverflow.com/comment/81388952
has text: Hi thanks for replying, the reason I wish to use a class, is because I have many functions with various click amounts I wish to add to the code. In a way to neaten up the Code I was hoping to store these various functions with different click amounts as a class and then to import this class to beaten up the main Code file.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47219705

http://stackoverflow.com/comment/81193094
score: 0
comment on: http://stackoverflow.com/q/47121767
type: Comment
type: QuestionComment
has text: `with open('usernames.csv', 'a', newline='')` use the `a`ppend mode.

http://stackoverflow.com/comment/81263350
comment on: http://stackoverflow.com/q/47156680
type: Comment
type: QuestionComment
has text: Well, try [`\b((?:\d+|\d{1,3}(?:[,.\s]\d{3})*)(?:[,.\s]*\d+)?)(?:\s(?:euro|€))`](https://regex101.com/r/0LPXcI/4)
score: 0

http://stackoverflow.com/comment/81330357
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47174885
has text: Shamos & Preparata discuss problems on rectangles. http://www.springer.com/gp/book/9780387961316. Also read my addendum.

http://stackoverflow.com/comment/85758527
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47996686
has text: This is a nice feature. Thanks! Is it also possible to control the size of the arrow head?
score: 0

http://stackoverflow.com/q/47135655
has title: How to validation of Excel file location is valid or not
has comment: http://stackoverflow.com/comment/81224086
tagged with: excel
favorite count: 0
answer count: 0
score: 1
has body: I am trying that print dynamic value into the .xlsx file. I am trying that print of that. worksheet.write("A13","Hello") But I am trying that user is given the location and value just like location = ("A13") value = ("Hello") self.get_value_location(location, value, worksheet) def get_value_location(location,value,worksheet): worksheet.write(location,value) So, my question how to validation given that location is proper in the .xlsx file
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81225124
upvote count: 1
tagged with: validation
type: UnansweredQuestion
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/81372716
score: 1
type: Comment
type: AnswerComment
has text: The problem with this is that it doesn't respect the module's `__all__` list, and doesn't skip leading-underscore names for modules with no `__all__` list.
comment on: http://stackoverflow.com/a/47211651

http://stackoverflow.com/comment/81222940
type: Comment
comment on: http://stackoverflow.com/q/47136904
score: 1
type: QuestionComment
has text: What's `content`? I assume it's a dict? Anyway, this is completely unrelated to pickle.

http://stackoverflow.com/q/47162644
tagged with: pandas
has comment: http://stackoverflow.com/comment/81275925
downvote count: 1
tagged with: stem
has comment: http://stackoverflow.com/comment/81275010
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/64283603
possible better answer: http://stackoverflow.com/a/64283603
has comment: http://stackoverflow.com/comment/81275450
has body: import pandas as pd from nltk.stem import PorterStemmer, WordNetLemmatizer porter_stemmer = PorterStemmer() df = pd.read_csv("last1.csv",sep=',',header=0,encoding='utf-8') df['rev'] = df['reviewContent'].apply(lambda x : filter(None,x.split(" "))) Dataset I am trying to stem my dataframe. While tokenizing I am getting this error for df['rev'] = df['reviewContent'].apply(lambda x : filter(None,x.split(" "))) AttributeError: 'float' object has no attribute 'split' While using Stemming I also get the float problem df['reviewContent'] = df["reviewContent"].apply(lambda x: [stemmer.stem(y) for y in x]) TypeError: 'float' object is not iterable What can I do?
has answer: http://stackoverflow.com/a/47163314
accepted answer: http://stackoverflow.com/a/47163314
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81275470
has title: Stemming Pandas Dataframe 'float' object has no attribute 'split'
score: 2
type: AnsweredQuestion
upvote count: 3
answer count: 2

http://stackoverflow.com/comment/81293200
has text: There is the [code](https://gist.github.com/eyllanesc/3d200020db4af413282dc8a96eb732b5). Please do not forget to mark my answer as correct.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47167107
type: AnswerComment

http://stackoverflow.com/comment/81211661
comment on: http://stackoverflow.com/q/47129619
type: Comment
type: QuestionComment
has text: for example, like `print_members("Book Club", "Allen", "Karla", "Matt", "Nadia")` as well, that's why there's an asterisk in the argument
score: 0

http://stackoverflow.com/q/47108253
has title: Parsing Javascript text in Python
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: -1
tagged with: parsing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47108338
has body: I am parsing this section of HTML &lt;script type="text/javascript"&gt; var spConfig = new Product.Config({"attributes":{"150":{"id":"150","code":"size_shoe","label":"Schuhgr\u00f6\u00dfe","options":[{"id":"494","label":"36","price":"0","oldPrice":"0","products":["393318"],"label_us":"\r\n4Y","label_uk":"3.5","label_cm":"23","label_int":null},{"id":"476","label":"36.5","price":"0","oldPrice":"0","products":["393321"],"label_us":"\r\n4.5Y","label_uk":"4","label_cm":"23.5","label_int":null,"out_of_stock":"Out of Stock"},{"id":"130","label":"37.5","price":"0","oldPrice":"0","products":["393324"],"label_us":"\r\n5Y","label_uk":"4.5","label_cm":"23.5","label_int":null,"out_of_stock":"Out of Stock"},{"id":"12","label":"38","price":"0","oldPrice":"0","products":["393327"],"label_us":"\r\n5.5Y","label_uk":"5","label_cm":"24","label_int":null},{"id":"500","label":"38.5","price":"0","oldPrice":"0","products":["393330"],"label_us":"\r\n6Y","label_uk":"5.5","label_cm":"24","label_int":null,"out_of_stock":"Out of Stock"},{"id":"10","label":"40","price":"0","oldPrice":"0","products":["393333"],"label_us":"\r\n7Y","label_uk":"6","label_cm":"25","label_int":null,"out_of_stock":"Out of Stock"}]}},"template":"\u20ac#{price}","basePrice":"89.95","oldPrice":"89.95","productId":"393306","chooseText":"Choose an Option...","taxConfig":{"includeTax":true,"showIncludeTax":true,"showBothPrices":false,"defaultTax":19,"currentTax":19,"inclTaxTitle":"Incl. Tax"}}); &lt;/script&gt; This is my code import urllib2, requests, json, re from bs4 import BeautifulSoup as bs url = ("link") session = requests.session() response = session.get(url) soup = bs(response.text, 'html.parser') scripts = soup.findAll('script') def getIds(): for script in scripts: if 'spConfig =' in script.getText(): regex = re.compile(r'var spConfig = new Product.Config\((.*?)\);') match = regex.search(script.getText()) spConfig = json.loads(match.groups()[0]) for key in spConfig['attributes']: # Should only call once for product…
upvote count: 0
answer count: 1
tagged with: javascript
downvote count: 1
accepted answer: http://stackoverflow.com/a/47108338
favorite count: 0
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/81166768

http://stackoverflow.com/a/47117648
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: Yes, you could do like this: def split_last_col(mat): """returns a tuple of two matrices corresponding to the Left and Right parts""" A = [line[:-1] for line in mat] B = [line[-1] for line in mat] return A, B split_last_col([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) output: ([[1, 2], [4, 5], [7, 8]], [3, 6, 9])
accepted answer of: http://stackoverflow.com/q/47117625
answers question: http://stackoverflow.com/q/47117625

http://stackoverflow.com/comment/81399154
type: Comment
type: QuestionComment
score: 0
has text: Because you're supplying a negative index. If x=0, x-1=-1 and a negative index supplied to a list counts backwards from the end. so col[-1] is the last entry in the col list or 'J' in your example. Try checking if x(and y) are >0 to pick left (and up) and < grid -1 to pick right (and down.) Then you don't need the try:...
comment on: http://stackoverflow.com/q/47186915

http://stackoverflow.com/comment/81361514
comment on: http://stackoverflow.com/q/47202065
score: 1
type: QuestionComment
type: Comment
has text: Try using `pycurl` if you can. However to address the issue. Use `import json` and then instead of writing a string create your `json_string` as a python dictionary and use `json.dumps(json_string)`

http://stackoverflow.com/comment/81180493
type: QuestionComment
comment on: http://stackoverflow.com/q/47115281
has text: `str(fmt % v)` is just `(fmt % v)`. Of course, you could use `str(str(str(str(str(fmt % v)))))` if you want to pile up pointless calls to `str`...
score: 0
type: Comment

http://stackoverflow.com/a/47192246
answers question: http://stackoverflow.com/q/47192150
has comment: http://stackoverflow.com/comment/109010674
type: Answer
has body: An empty list in python takes 72 bytes, so consider this: ls = [] takes 72 bytes x = '1234567' takes 44 bytes now, this: [x] list contains the string x takes 124 bytes (72 + 8 + 44). But, your question: [x, x, x, x, x] A list that contains the string x 5 times takes 156 bytes (72 + 5 * 8 + 44). Very nice explained here: https://code.tutsplus.com/tutorials/understand-how-much-memory-your-python-objects-use--cms-25609
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47121926
upvote count: 2
accepted answer: http://stackoverflow.com/a/47124235
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/81193463
downvote count: 1
answer count: 1
has title: Convert range of two date time's into a list of dates and count of seconds per that date python
linked to: http://stackoverflow.com/q/47052626
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47124235
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/81193506
has body: I'm interested in creating a function that gets two following datetime objects (start date and end date) as input and returns a list of tuples. I would like a tuple for each date between start and end date, and the number of seconds in this date. For example: import datetime #there are total 86400 seconds within a date start_date=datetime.datetime(2017, 10, 17,22,30,0) # this has 60*60+60*30= 5400 within that date end_date=datetime.datetime(2017, 10, 19,10,30,11) # this date has 10*60*60+60*30+11=37811 seconds desired_list_of_tupple=[(datetime.datetime(2017, 10, 17),5400),(datetime.datetime(2017, 10, 18),86400),(datetime.datetime(2017, 10, 19),37811)] For 2017-10-17 number of seconds is 5400 (number of seconds between 22:30 and midnight. For 2017-10-18 number of seconds is 86400 (whole day is in range). For 2017-10-19 number of seconds is 37811 (number of seconds from midnight up until 10:30:11 ). Any help on that would be great!

http://stackoverflow.com/q/47143315
accepted answer: http://stackoverflow.com/a/48912788
type: AnsweredQuestion
has body: I'm "compiling" a program using PyInstaller using a .spec file. I'm using the .spec file because I need to include an extra file in the program. When I try to do PyInstaller --onefile Prog.spec, it still makes a folder in dist with all the files separate instead of making a single file as I'd expect. If I do PyInstaller --onefile Prog.py then it does make a single .exe file in dist, which is what I want. Is there something special I need to do when using a .spec file?
tagged with: pyinstaller
upvote count: 32
tagged with: python
has answer: http://stackoverflow.com/a/47148293
has title: Using --onefile with a .spec in PyInstaller
type: Question
linked to: http://stackoverflow.com/q/7674790
answer count: 2
downvote count: 0
score: 32
possible better answer: http://stackoverflow.com/a/47148293
has answer: http://stackoverflow.com/a/48912788
favorite count: 0

http://stackoverflow.com/q/47121093
has comment: http://stackoverflow.com/comment/81191990
favorite count: 0
type: Question
has title: No module name 'plotly'
score: 1
tagged with: plotly
tagged with: python
has body: I've installed the packages for plotly by using pip install plotly as well as conda install plotly Command prompt But even after that my jupyter notebook is not reading it and causing error No module named plotly No module named plotly
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/88117594
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/q/47154587
upvote count: 0
accepted answer: http://stackoverflow.com/a/47155610
downvote count: 2
tagged with: error-handling
has answer: http://stackoverflow.com/a/47155610
has comment: http://stackoverflow.com/comment/81258803
answer count: 1
has title: Python TypeError even though I am only working with int and float
has comment: http://stackoverflow.com/comment/81259275
type: AnsweredQuestion
tagged with: python
score: -2
has body: The code below runs fine in my test cases, but it results in the following errors when launch the program manually: bm25 = tf * (k + 1) bm25 = bm25 / (k * (1 - b + b * dl / avdl) + tf) bm25 = bm25 * math.log(n/df, 2) File "inverted_index.py", line 116, in read_from_file bm25 = tf * (k + 1) TypeError: cannot concatenate 'str' and 'int' objects All the symbols are variables (either float or int). I am not trying to do anything that involves strings. I just want to do the calculation... The error propagates to the next line of the computation if I comment out the line that is causing the error: # bm25 = tf * (k + 1) bm25 = bm25 / (k * (1 - b + b * dl / avdl) + tf) bm25 = bm25 * math.log(n/df, 2) File "inverted_index.py", line 117, in read_from_file bm25 = bm25 / (k * (1 - b + b * dl / avdl) + tf) TypeError: unsupported operand type(s) for -: 'int' and 'str' Note bm25 is initialized to zero. Initially I did the whole computation in one line, but that was too long for my style checker. I am new to python and I don't how to resolve this. What am I doing wrong? EDIT 1: The full code is quite long: def read_from_file(self, file_name, b, k): """ &gt;&gt;&gt; ii = InvertedIndex() &gt;&gt;&gt; ii.read_from_file("example.txt", b=0, k="inf") &gt;&gt;&gt; sorted(ii.inverted_lists.items()) [('animated', [(1, 0.415), (2, 0.415), (4, 0.415)]), \ ('animation', [(3, 2.0)]), ('film', [(2, 1.0), (4, 1.0)]), \ ('movie', [(1, 0.0), (2, 0.0), (3, 0.0), (4, 0.0)]), \ ('non', [(2, 2.0)]), \ ('short', [(3, 1.0), (4, 2.0)])] """ """ &gt;&gt;&gt; ii = InvertedIndex() &gt;&gt;&gt; ii.read_from_file("example.txt", b=0.75, k=1.75) &gt;&gt;&gt; sorted(ii.inverted_lists.items()) [('animated', [(1, 0.459), (2, 0.402), (4, 0.358)]), \ ('animation', [(3, 2.211)]), ('film', [(2, 0.969), (4, 0.863)]), \ ('movie', [(1, 0.0), (2, 0.0), (3, 0.0), (4, 0.0)]), \ ('non', [(2, 1.938)]), \ ('short', [(3, 1.106), (4, 1.313)])] """ dls = [] avdl = 0 with open(file_name, "r") as file: record_id = 1 for line in file…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81259097
has comment: http://stackoverflow.com/comment/81258861

http://stackoverflow.com/a/47119754
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47119569
type: Answer
has body: results = Rating.objects.filter(User_id_id = 1) data = [] for res in results: data.append( { "name": res.Product_id.name, "Price": res.Product_id.price, "avgrating": res.Product_id.avgrating, "rate": res.rate }) Why did i use User_id_id? Beacuse, Django appends '_id' for all names related to keys. So if you are using the key value directly, use '_id'.
has comment: http://stackoverflow.com/comment/81189517
has comment: http://stackoverflow.com/comment/81189472
score: 1
accepted answer of: http://stackoverflow.com/q/47119569

http://stackoverflow.com/q/47196339
tagged with: python
accepted answer: http://stackoverflow.com/a/47197825
has comment: http://stackoverflow.com/comment/81343914
type: Question
has title: Writing CSV from Elasticsearch result using python with records exceeding 10000 ?
answer count: 1
has answer: http://stackoverflow.com/a/47197825
has comment: http://stackoverflow.com/comment/81341987
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/46682018
tagged with: http://stackoverflow.com/tag/csv
has body: Im able to create the CSV using the solution provided here: Export Elasticsearch results into a CSV file but problem arises when the records exceeds 10000 (size=10000), is there any way to write all the records?
tagged with: elasticsearch

http://stackoverflow.com/comment/81358947
score: 0
comment on: http://stackoverflow.com/q/47204860
has text: Which tensorflow version are you using?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81094451
type: QuestionComment
score: 0
has text: @BugFinder Not sure what you mean entirely. Never used ftp in C# before, but an example I saw for something else uses `System.Net.FtpWebRequest` and `System.Net.FtpWebResponse` if that's what you mean.
comment on: http://stackoverflow.com/q/47073021
type: Comment

http://stackoverflow.com/q/47100362
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81151586
has comment: http://stackoverflow.com/comment/81150703
has title: django static files are sometimes not serving
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81150864
has body: Dear Stackoverflow community. I have for a while now been struggling with my static files during development in my Django project. The problem is mainly that my stylesheets are sometimes working and sometimes not. Example - my base.html's stylesheet base_style.css is always loading, but when I add a stylesheet for the file home.html which I have loaded through the jinja template tags It sometimes works and sometimes not, the same goes for my other views. Using python3 and Django 1.11.5 Here is my settings file (Static) = STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") Here is my template Base.html = {% load static %} Leaf Hem(current) Blog Story Kontakt {% block content %} {% endblock content %} LEAF Suspendisse hendrerit tellus laoreet luctus pharetra. Aliquam porttitor vitae orci nec ultricies. Curabitur vehicula, libero eget faucibus faucibus, purus erat eleifend enim, porta pellentesque ex mi ut sem. © 2017, All rights reserved — Menu — About Us Contact Copyright Example Follow Us Facebook Twitter Instagram RSS Here is my home.html file = {% extends 'base.html' %} {% block content %} {% load static %} [enter image description here][1] Leaf A genuinly healthy all natural energy drink "I love how it tastes so fresh" Mathias "This is the best ive drinken" Eric "I wish this product came out years ago!" Rebecca "I Which i could drink it all the time" Jake "I Which i could drink it all the time" Anna Previous Next Leaf "En Genuint Hälsosam, Helt Naturlig Energidryck" Mer info {% endblock content %} Folder Structure! (Tried to include a picture of my folder structure on here) I really hope anyone would be able to help me with this, this is my first post on here and I am quite new at coding.
tagged with: django-staticfiles
type: Question
tagged with: static-files
type: UnansweredQuestion

http://stackoverflow.com/q/47102808
downvote count: 2
has title: Putting Many dictionaries in a list
accepted answer: http://stackoverflow.com/a/47102908
has answer: http://stackoverflow.com/a/47102918
possible better answer: http://stackoverflow.com/a/47102918
favorite count: 0
type: Question
has body: I would like to create many dictionaries in a list to build a Data Frame. {'customer': 1.0, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'} {'customer': 2.0, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'} {'customer': 3.0, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'} I would like to get these dictionaries to a list like this: [{'customer': 1.0, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'}, {'customer': 2.0, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'}, {'customer': 3.0, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/81155977
has comment: http://stackoverflow.com/comment/81155814
tagged with: python
has answer: http://stackoverflow.com/a/47102908
has comment: http://stackoverflow.com/comment/81155821
has comment: http://stackoverflow.com/comment/81155839
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81155843
answer count: 2

http://stackoverflow.com/comment/81203727
type: Comment
score: 0
type: AnswerComment
has text: Please remember to `accept` and `up-vote` if this works fine for you as well!
comment on: http://stackoverflow.com/a/47125864

http://stackoverflow.com/comment/81274198
comment on: http://stackoverflow.com/q/47159700
score: 1
has text: Could include the exact output you would like to obtain from the sample you gave? Also, I think regexes might not be enough to handle this problem of yours, since the source is too unstructured.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47172689
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47185166
accepted answer: http://stackoverflow.com/a/47185166
tagged with: django-forms
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/74841736
has comment: http://stackoverflow.com/comment/81295148
has title: django-bootstrap3 Parameter "field" should contain a valid Django BoundField?
has answer: http://stackoverflow.com/a/74841736
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: django-templates
answer count: 2
has body: I am using django-bootstrap3 to render my forms on the template and i have been struggling to find what is causing the error Parameter "field" should contain a valid Django BoundField when i try to load the page with the form on it. I have attached my code and error below. can someone please point for me what i'm doing wrong? forms.py class OrderForm(forms.Form): first_name = forms.CharField(max_length=50) last_name = forms.CharField(max_length=50) email = forms. EmailField(max_length=50) institution_name = forms.CharField(max_length=150) phone = forms.IntegerField() address = forms.CharField(max_length=100) city = forms.CharField(max_length=50) item = forms.CharField(max_length=100) serial_number = forms.CharField(max_length=50) problem = forms.CharField(widget=forms.Textarea(attrs—Crows':10,'cols':18,'style':'resize:none', [placeholder':'Please define your problem here'l),label='Problem description') [placeholder':'Please define your problem here'l),label='Problem description') views.py def Orderview(request): if request.method == 'Post': order_form = OrderForm(request.POST) if order_form.is_valid(): cd = order form.cleaned data subject = '{} repair order from {}'.format(cd['item'],cd['institution_name']) from_email = cd['email'] to = [settings.EMAIL_HOST_USER,] ctx = { 'first_name':cd['first_name'], 'last_name':cd['last_name'], 'email':cd['email'], 'institution_name':cd['institution_name'], 'phone':cd['phone'], 'address':cd['address'], 'city':cd['city'], 'item':cd['item'], 'serial_number.:cd['serial_number'], 'problem':cd['problem'], } message = get_template('electroapp/email/order.html').render(Context(ctx)) msg = EmailMessage(subject,message,to=to,from_email=from_email) msg.content_subtype='html' msg.send() messages.success(request,' Your Repair order has been sent',) return redirect('electroapp:repair_order') else: order_form = OrderForm() return render(request,'electroapp/orderform.html',{'Order_form':order_form}) template browser error console logs
tagged with: django-views
downvote count: 0
has comment: http://stackoverflow.com/comment/81295507

http://stackoverflow.com/a/47146640
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47145934
has body: If you use pandas, and make a dataframe... if you enter 4 for the number of rows, and the numbers 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16... the script below import pandas as pd n = int(input("Enter the number of rows in a matrix: ")) a = [[0] * n for i in range(n)] col_names = [] row_names = [] for i in range(n): col_names.append('col ' + str(i+1)) row_names.append('row ' + str(i+1)) for j in range(n): a[i][j] = int(input()) print(pd.DataFrame(a,columns = col_names, index = row_names)) ...will produce the following output. col 1 col 2 col 3 col 4 row 1 1 2 3 4 row 2 5 6 7 8 row 3 9 10 11 12 row 4 13 14 15 16 Another option... using numpy... and the same values from the first option... import numpy as np n = int(input("Enter the number of rows in a matrix: ")) a = [[0] * n for i in range(n)] for i in range(n): for j in range(n): a[i][j] = int(input()) print(np.matrix(a)) ...would produce [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]]
score: 1
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47145934
upvote count: 1

http://stackoverflow.com/comment/81096623
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47073706
has text: But what's the difference? It gives me the same result.

http://stackoverflow.com/a/47095637
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47091629
score: 1
type: Answer
has body: The DataFrame.to_sql command should solve your problem documentation here: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html
accepted answer of: http://stackoverflow.com/q/47091629

http://stackoverflow.com/comment/81166987
type: Comment
score: 0
type: AnswerComment
has text: I have a txt file with thousands of items. Will you show me how to do this automatically? I am a beginner programmer ...
comment on: http://stackoverflow.com/a/47108160

http://stackoverflow.com/a/47081962
has comment: http://stackoverflow.com/comment/81113284
type: Answer
answers question: http://stackoverflow.com/q/47081872
has body: You should do something like : df.replace({'Fence':{'NA': 0, 'MnWw': 1,'GdWo': 2,'MnPrv': 3,'GdPrv': 4},'SaleCondition':{'Abnorml': 1, 'Alloca': 1, 'AdjLand': 1, 'Family': 1, 'Normal': 0, 'Partial': 0}}) the format should be .replace({'col1':{},'col2':{}}) not .replace({'col1':{}},{'col2':{}})
has comment: http://stackoverflow.com/comment/81113239
accepted answer of: http://stackoverflow.com/q/47081872
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2
has comment: http://stackoverflow.com/comment/81114092

http://stackoverflow.com/a/47161663
has comment: http://stackoverflow.com/comment/81290942
has comment: http://stackoverflow.com/comment/81274431
has comment: http://stackoverflow.com/comment/81272931
has comment: http://stackoverflow.com/comment/81273934
has comment: http://stackoverflow.com/comment/81274505
has comment: http://stackoverflow.com/comment/81273978
answers question: http://stackoverflow.com/q/47161513
type: Answer
has body: Say s is the line of your file, you can use lookbehind assertion. ?&lt;= to check for variables! &gt;&gt;&gt; import re &gt;&gt;&gt; s 'Y-6.352 Z281.116 A3=-1.0 B3=0.0 C3=0.0' &gt;&gt;&gt; re.findall("(?&lt;=[AZaz])?(?!\d*=)[0-9.+-]+",s) ['-6.352', '281.116', '-1.0', '0.0', '0.0'] If you want to do the same with files, import re with open('input file.txt','r') as file: for line in file: print re.findall("(?&lt;=[AZaz])?(?!\d*=)[0-9.+-]+",line)
has comment: http://stackoverflow.com/comment/81272991
has comment: http://stackoverflow.com/comment/81273892
score: 0

http://stackoverflow.com/comment/81311284
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47132548
has text: I answered this, but then realized that the question and my answer duplicated this one: [Django DateTimeField Stores datetime regardless of the tzinfo](https://stackoverflow.com/questions/33280135/django-datetimefield-stores-datetime-regardless-of-the-tzinfo)

http://stackoverflow.com/comment/81117508
type: Comment
comment on: http://stackoverflow.com/a/47083708
type: AnswerComment
score: 0
has text: thanks for the response! Yes your idea of flow is correct, but what I don't understand is why between steps 3 & 4 it automatically sends a redirect to /FormB? i.e.: 1. I'm in viewA, I submit form2 in /viewA 2. I should be redirected to /index (but instead I am immediately redirected to /viewB without me first hitting the submit button for form B in the index view) - This is what I can't seem to figure out why? And to your second part, even when I change the redirect to be: 'if formB.validate_on_submit(): return redirect(url_for('different_view'))' I get the issue

http://stackoverflow.com/a/47128621
has body: Sounds like you simply want: def getSimilarItems(word,list1): return [int(letter in list1) for letter in word]
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47128539
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/47097949
tagged with: python
has answer: http://stackoverflow.com/a/47097982
has title: How to efficiently add seconds place to date time
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
tagged with: timedelta
score: 1
upvote count: 1
has body: I have a pandas data frame full of 1 second data of the form "10/23/2017 6:00". Each time appears 60 times in the file, and I'd like to know if there is an easy/efficient/smart way to add seconds to each row such that I get "10/23/2017 6:00:00, 10/23/2017 6:00:01 ..."
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47097982
tagged with: datetime

http://stackoverflow.com/comment/81243358
type: AnswerComment
comment on: http://stackoverflow.com/a/47146322
has text: Dear Simon, can you elaborate on that? To be specific, I tried this client_id: 00000000481695BB and it worked fine, but this client_id 0000000048201716 doesn't. Is there a place where I can configure Host Address? Thanks.
type: Comment
score: 0

http://stackoverflow.com/comment/81268288
type: QuestionComment
score: 0
has text: Show us how `text` looks like
comment on: http://stackoverflow.com/q/47159417
type: Comment

http://stackoverflow.com/comment/81131121
score: 0
comment on: http://stackoverflow.com/q/47090519
type: Comment
has text: @DanhPham added an example
type: QuestionComment

environment-variables
tags question: http://stackoverflow.com/q/47212500
tags question: http://stackoverflow.com/q/47207892
tags question: http://stackoverflow.com/q/47127856
tags question: http://stackoverflow.com/q/47166090
tag name: environment-variables
tags question: http://stackoverflow.com/q/47117758
type: Tag

http://stackoverflow.com/comment/81348737
has text: Can i replace the if statement with list_of_files=glob.glob('*.txt') or something in order to mantain the program structure I already have?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47199392
type: AnswerComment

http://stackoverflow.com/comment/81254692
score: 0
comment on: http://stackoverflow.com/q/47124791
has text: @Jarad I tried with `sep=','` that works fine if I am trying to read only some part of the data but if I am trying to read the complete dataset it shows `Out of Memory` error on the terminal and when I see data usage my total memory is being used for the purpose.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81348929
type: Comment
score: 0
type: AnswerComment
has text: You can't copy 2 file in single one, but you can make 2 copy of a single file. (may be I don't understand something in your question)
comment on: http://stackoverflow.com/a/47199933

http://stackoverflow.com/q/47121824
has comment: http://stackoverflow.com/comment/81196215
type: Question
has body: I am currently working on a game where I wish to give the player an option of four characters to play. Here is my current code to do this: running = 1 charactersChoice = ['char.png', 'char2.png', 'char3.png', 'char4.png'] choice = '' while choice == '': screen.fill((47, 79, 79)) screen.blit(pygame.image.load(charactersChoice[0]), (100,100)) screen.blit(pygame.image.load(charactersChoice[1]), (700,100)) screen.blit(pygame.image.load(charactersChoice[2]), (100,600)) screen.blit(pygame.image.load(charactersChoice[3]), (700,600)) keys = pygame.key.get_pressed() #Choose character if keys[pygame.K_1]: choice = charactersChoice[0] if keys[pygame.K_2]: choice = charactersChoice[1] if keys[pygame.K_3]: choice = charactersChoice[2] if keys[pygame.K_4]: choice = charactersChoice[3] pygame.display.flip() while running == 1: #rest of code for game here As you can see, I blit the four different character profiles onto the screen and then check if the player has pressed the keys 1-4 to select their option. After selecting their option, it should move onto the main loop. Currently, if I press the key '1' while the code is running, it will not change the variable choice to what is intended. Hope I have explained my problem well enough.
has title: Not detecting key press in pygame
has comment: http://stackoverflow.com/comment/81196696
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81196803
has comment: http://stackoverflow.com/comment/81196778
has comment: http://stackoverflow.com/comment/81196733
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81196486
accepted answer: http://stackoverflow.com/a/47123498
score: 1
has answer: http://stackoverflow.com/a/47123498
linked to: http://stackoverflow.com/q/17938170
tagged with: pygame

http://stackoverflow.com/a/47066353
type: Answer
answers question: http://stackoverflow.com/q/47066197
downvote count: 0
score: 3
has body: Another variation to other answers: np.flatnonzero(a == b)
upvote count: 3

http://stackoverflow.com/comment/81135250
comment on: http://stackoverflow.com/a/47081425
type: Comment
has text: Try running `pip install -r requirements.txt` and see what happens
score: 0
type: AnswerComment

http://stackoverflow.com/q/47149109
duplicate of: http://stackoverflow.com/q/493174
type: UnansweredQuestion
tagged with: arrays
downvote count: 0
upvote count: 1
has body: I'm trying to make a program that takes a string of number words "One hundred ninety two thousand seven hundred thirty one" and turn it into the corresponding number. This is the code I have so far: def string_to_num(text): text = text.lower() words = text.split() numbers = [] output1 = [] output2 = [] output3 = [] output4 = [] hold = 1 l = 1 for current_word in words: number = word_to_number(current_word) numbers.append(number) for i in range(len(numbers)): current_num = numbers[i] if i == len(numbers)-1: output1.append(current_num) continue else: previous_num = numbers[i-1] if current_num &gt; 999: output1.append(current_num) continue else: if previous_num &lt; current_num: output1.append(current_num * previous_num) output1.pop(i-l) l += 1 continue else: output1.append(current_num) continue for i in range(1, len(output1[:])): current_num = output1[i] previous_num = output1[i-1] if current_num &gt; 999: output2.append(current_num) continue else: if output1[i-1] &gt; current_num and previous_num &lt; 1000: output2.append(current_num + previous_num) continue else: output2.append(current_num) print('output2', output2) string_to_num('One hundred ninety two thousand seven hundred thirty one') It works in the way that at the beginning, the function takes the number word and puts it through another function I have 'word_to_number()' that converts it to its corresponding number. I put all the values of numbers into a loop that gives the following result: [1, 100, 90, 2, 1000, 7, 100, 30, 1] The next part of the program adds makes sure the hundreds are added multiplied by the right factor. It takes the previous list and converts it into a list that looks like this: [100, 90, 2, 1000, 700, 30, 1] Note that the 100 and 700 are now combined. The part that Im having trouble with is adding the numbers together and adding them to a new list, output2. The current code above produces the following list: [190, 92, 1000, 700, 730, 31] When it should look like this: [192, 1000, 731] A…
tagged with: list
score: 1
has comment: http://stackoverflow.com/comment/81248142
tagged with: python
linked to: http://stackoverflow.com/q/493174
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81248208
has title: Converting number words into numbers - Python
answer count: 0

http://stackoverflow.com/a/60042154
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47172770
has body: If you are working with several images (for example, 1000 images), it may be difficult for you to identify which image is giving you problems. It may also be that, there are several others that are corrupt. In such a case, the code below can be useful. for file in filenames: try: image = cv2.resize(cv2.imread(file), (size, size)) except: print(file) where filenames is a list which contains names of the images.
score: 1
downvote count: 0

http://stackoverflow.com/comment/140207078
type: Comment
comment on: http://stackoverflow.com/a/79501986
type: AnswerComment
score: 0
has text: If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/36764598)

decode
tag name: decode
tags question: http://stackoverflow.com/q/47184755
tags question: http://stackoverflow.com/q/47153004
tags question: http://stackoverflow.com/q/47217821
tags question: http://stackoverflow.com/q/47219198
type: Tag
tags question: http://stackoverflow.com/q/47080272

http://stackoverflow.com/comment/81359036
type: QuestionComment
has text: To clarify "div which contains strong tag only": Do you mean divs with nothing but a strong tag, or _only_ divs that contain a strong tag?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47203650

http://stackoverflow.com/a/47165486
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/81280711
has comment: http://stackoverflow.com/comment/81280897
has comment: http://stackoverflow.com/comment/81280857
has body: Add an indent by pressing [TAB] in front of your existing indentation on the line ... ghost_door = randint(1,3) Currently, you have got: while feeling_brave: ghost_door = randint(1, 3) You have not got the "statements" for the loop as an indent, so the interpreter treats it as two consecutive commands. However, having while feeling_brave: ghost_door = randint(1, 3) tells the interpreter to execute your second line while the loop is running.
answers question: http://stackoverflow.com/q/47165343
has comment: http://stackoverflow.com/comment/81280781

http://stackoverflow.com/a/47115644
has body: As we eventually worked out in the comments, the problem is that there are superfluous commas in the command string and the data need to be 8-bit. So, in concrete terms, use: bytesize=serial.EIGHTBITS ... ... ON = b"\x08\x22\x00\x00\x00\x00\xD6"
answers question: http://stackoverflow.com/q/47106515
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47106515
upvote count: 1

build
tag name: build
tags question: http://stackoverflow.com/q/47146196
tags question: http://stackoverflow.com/q/47080174
type: Tag

http://stackoverflow.com/q/47121919
has comment: http://stackoverflow.com/comment/81194474
has comment: http://stackoverflow.com/comment/81194372
type: AnsweredQuestion
score: 0
tagged with: array-broadcasting
has comment: http://stackoverflow.com/comment/81195649
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81194154
downvote count: 1
has title: Indexing numpy array with bounds checking
has answer: http://stackoverflow.com/a/47123313
accepted answer: http://stackoverflow.com/a/47123313
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81193929
tagged with: indexing
has comment: http://stackoverflow.com/comment/81195613
has comment: http://stackoverflow.com/comment/81195621
has body: Suppose I have some random numpy array: &gt;&gt;&gt; x = np.random.randn(10, 4, 4) So this can be viewed as 10 4x4 arrays. Now, I also have some coordinates with respect to each of these arrays: &gt;&gt;&gt; coords.shape (10, 4, 4, 2) and a particular element of this array might look like the following: &gt;&gt;&gt; coords[i][j][k] array([ 2, 2]) Now, I'd like to create an array, y of size (10, 4, 4), where y[i][j][k] = x[coords[i][j][k]] if coords[i][j][k] is in bounds, and 0 otherwise. I've tried doing something like the following: &gt;&gt;&gt; y = np.where(np.logical_and( np.all(coords &gt;= 0, axis = 3), np.all(coords &lt;= 3, axis = 3)), x[tuple(coords)], 0) But I can't quite get the broadcasting rules correct, and I'm getting errors. For example, say we have, &gt;&gt;&gt; x = np.array([ [[1., 2.], [4., 5.]], [[6., 7.], [8., 9.]]]) with, &gt;&gt;&gt; coords = np.array([ [[[0,-1], [0, 0]], [[1, 1], [1, 0]]], [[[1, 1], [1, 0]], [[7, 2], [0, 0]]] ]) Then, I'd somehow like to get y = np.array([ [[0., 1.], [5., 4.]], [[9., 8.], [0., 6.]]]) How can I achieve this in Python?
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/81194222

http://stackoverflow.com/comment/81114882
has text: Show the code you have. That makes this question more specific and more answerable.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47082106

http://stackoverflow.com/comment/81286669
type: Comment
score: 0
type: QuestionComment
has text: i can make a customize input function with pyHook, pythoncom, sys and pysignal modules, do you like it ir not?
comment on: http://stackoverflow.com/q/47167139

http://stackoverflow.com/q/47197627
has comment: http://stackoverflow.com/comment/81417066
has comment: http://stackoverflow.com/comment/81414972
score: 0
answer count: 0
type: Question
has title: How can I improve downloading speed with python urllib.request
type: UnansweredQuestion
has body: How can I improve downloading speed with urllib.request? I want to download image from web and It works well. But it takes too long downloading it. It took 42 seconds to excute donwload_album_art() func. What Can I do for that? Can I use mutiprocess or etc? h import os import shutil import requests from bs4 import BeautifulSoup from urllib import request URL = 'https://music.bugs.co.kr/chart/track/day/total' PATH = os.getcwd() + '/static/images/' # Scrapping html code def get_html(target_url): _html = "" response = requests.get(target_url) if response.status_code == 200: _html = response.text return _html # parse image url and save in list def get_image_url(): html = get_html(URL) soup = BeautifulSoup(html, 'html.parser') img_url = [] for image in soup.select('a.thumbnail &gt; img'): if image.has_attr('src'): img_url.append(image.get('src')) else: continue return img_url # download album art in static/images directory def download_album_arts(): images = get_image_url() for i in range(0, 100): url = images[i] file_name = PATH + str(i + 1) + '.png' request.urlretrieve(url, file_name) # delete all album art def delete_album_art(): path = os.getcwd() + '/static/images' if os.path.exists(path): shutil.rmtree(path) os.mkdir(path) else: os.mkdir(path)
tagged with: python

http://stackoverflow.com/a/47095148
score: 1
has comment: http://stackoverflow.com/comment/81223877
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81223457
has comment: http://stackoverflow.com/comment/81169560
has comment: http://stackoverflow.com/comment/81169666
has comment: http://stackoverflow.com/comment/81169735
type: Answer
accepted answer of: http://stackoverflow.com/q/47094200
has comment: http://stackoverflow.com/comment/81229908
has body: This is the way I do it: separate the classes between construction (loading) of the UI and changing its content. form_class = uic.loadUiType("MyPythonProgram.ui")[0] class MyWindowClass(QtGui.QMainWindow, form_class): def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) self.setupUi(self) class myGui: def __init__(self): self.gui = MyWindowClass() # that's the trick! # self.addindResultsToQListView() # doesn't work, because I don't have your list items self.gui.btn_buscar.clicked.connect(self.buscar) self.editText = None def show(self): self.gui.show() def addingResultsToQListView(self): for item in SomeList: # you need to specify this `list` before this works! self.gui.listView.addItems(item) def buscar(self): self.editText = self.gui.textEdit.text() self.gui.textEdit.setText("") app = QtGui.QApplication(sys.argv) MyWindow = MyGui() MyWindow.show() app.exec_() The trick is to reference the MyWindowClass, which is the constructor of your gui and hence the GUI itself, as an object within the class that controls the content of your GUI (myGui). You call myGui on toplevel which then calls MyWindowClass as the object self.gui. From then on, whenever you want to address something in your GUI you name it self.gui. and add the QObject. I also tried to understand what you want to do for the pushBotton. The content of your TextEdit (in PyQt they are called lineEdit btw) is stored in the variable self.editText which is initialized as None. Afterwards, the lineEdit is cleared from the user content.
answers question: http://stackoverflow.com/q/47094200
has comment: http://stackoverflow.com/comment/81161783
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/60665621
type: Answer
has body: This worked for me. Ubuntu 18.04. sudo pip2 uninstall backports.functools-lru-cache sudo apt install python-backports.functools-lru-cache
answers question: http://stackoverflow.com/q/47179433
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47115583
has comment: http://stackoverflow.com/comment/81181255
has title: Can you use JavaScript inside an email, which is sent using Python?
has comment: http://stackoverflow.com/comment/81181309
has answer: http://stackoverflow.com/a/47115635
answer count: 2
has comment: http://stackoverflow.com/comment/81181203
has comment: http://stackoverflow.com/comment/81181046
has body: Can you use JavaScript inside an email, which is sent using Python? My aim is to send a working clock inside an email. I am trying to use Python to do so. I am using IDLE and the Python libraries stmplib, email and html2text to send emails. My code looks like the code shown below. I omitted some details (style and script) as they are unimportant. me = "my.email@gmail.com" you = "my.email@gmail.com" msg = MIMEMultipart('alternative') msg['Subject'] = "Clock" msg['From'] = me msg['To'] = you html = """\ Clock HH : MM : SS """ text = html2text(html) part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') msg.attach(part1) msg.attach(part2) s = SMTP('smtp.gmail.com:587') s.ehlo() s.starttls() s.login("my.email@gmail.com", "my password") s.sendmail(me, you, msg.as_string()) s.quit() The full version of the HTML in this code gives me a properly functioning clock, but if I attempt sending it to myself using Gmail I receive a different result. Viewing the HTML: In Gmail: This shows, that parts of the CSS load, but others like the font or the font size don't. It also shows that the JavaScript does not load. (Normally viewing the HTML code in a browser gives a functioning clock, while in an email doesn't.) Is there a way to send an email with this clock?
score: 1
has comment: http://stackoverflow.com/comment/81181012
has answer: http://stackoverflow.com/a/47115655
tagged with: http://stackoverflow.com/tag/html
tagged with: email
downvote count: 1
has comment: http://stackoverflow.com/comment/81181219
linked to: http://stackoverflow.com/q/3054315
favorite count: 0
has comment: http://stackoverflow.com/comment/81181130
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81181055
has comment: http://stackoverflow.com/comment/81181011
duplicate of: http://stackoverflow.com/q/3054315
type: UnansweredQuestion
tagged with: javascript
tagged with: python
tagged with: css

http://stackoverflow.com/comment/81166583
has text: Your code works, as demonstrated in my answer below. If what you have isn't working, it is in code you haven't shown. Make a [mcve].
comment on: http://stackoverflow.com/q/47107754
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47117203
has comment: http://stackoverflow.com/comment/81184809
has comment: http://stackoverflow.com/comment/93290657
score: 1
type: Answer
has body: You basically have it already figured out. Just a few tweaks. You can use iloc this way for i in range(x_test.shape[0]): row_i = x_test.iloc[i] # a row in x_test y_pred = c.predict(row_i) if y_pred &lt; 0.4: new_train = new_train.append(row_i) Or use it this way for i in range(len(x_test)): row_i = x_test.iloc[i, :] # a row in x_test y_pred = c.predict(row_i) if y_pred &lt; 0.4: new_train = new_train.append(row_i) Both will produce a result of type &lt;class 'pandas.core.series.Series'&gt; Using the .append() method on a pd.DataFrame object is not an in-place operation. See here for more.
answers question: http://stackoverflow.com/q/47117136
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81274120
type: QuestionComment
comment on: http://stackoverflow.com/q/47162144
has text: If you read up on the Python documentation for [Private Variables](https://docs.python.org/3.6/tutorial/classes.html#private-variables), you'll see this line: "This mangling is done without regard to the syntactic position of the identifier, **as long as it occurs within the definition of a class**."
score: 0
type: Comment

http://stackoverflow.com/q/47069054
type: Question
has comment: http://stackoverflow.com/comment/81086448
has comment: http://stackoverflow.com/comment/81087338
score: 0
tagged with: instagram
has title: Instagram python bot, How to make it close and restart when i run on a error?
tagged with: bots
has answer: http://stackoverflow.com/a/64450018
tagged with: python
has comment: http://stackoverflow.com/comment/81086675
has comment: http://stackoverflow.com/comment/81086603
has comment: http://stackoverflow.com/comment/81086563
has answer: http://stackoverflow.com/a/68668922
answer count: 3
has body: So i got this Bot for Instagram on GitHub . I have edited the script so it run the longest time possible i guess ,until I have 3 ,"error 400" in a row then the script stop to prevent get banned. I want to make a loop that, when I encountered an error, it closes and restart again. #!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import time sys.path.append(os.path.join(sys.path[0], 'src')) from check_status import check_status from feed_scanner import feed_scanner from follow_protocol import follow_protocol from instabot import InstaBot from unfollow_protocol import unfollow_protocol bot = InstaBot( login="USERNAME", password="PASSWORD", like_per_day=2500, comments_per_day=1500, tag_list=['photo', '', 'car', 'nature', 'city'], tag_blacklist=['racist', 'example', 'example', 'example', ], user_blacklist={}, max_like_for_one_tag=50, follow_per_day=0, follow_time=1 * 60, unfollow_per_day=300, unfollow_break_min=15, unfollow_break_max=30, log_mod=0, proxy='', # List of list of words, each of which will be used to generate comment # For example: "This shot feels wow!" comment_list=[["this", "the", "your"], ["photo", "picture", "pic", "shot", "snapshot"], ["is", "looks", "is really"], ["great", "super", "good", "very good", "good", "wow", "WOW", "cool", "GREAT","magnificent", "magical", "very cool", "stylish", "beautiful", "so beautiful", "so stylish", "so professional", "lovely", "so lovely", "glorious","so glorious", "very glorious", "adorable", "excellent", "amazing"], [".", "..", "...", "!", "!!", "!!!"]], # Use unwanted_username_list to block usernames containing a string ## Will do partial matches; i.e. 'mozart' will block 'legend_mozart' ### 'free_followers' will be blocked because it contains 'free' unwanted_username_list=[ 'second', 'stuff', 'art', 'project', 'love', 'life', 'food', 'blog', 'free', 'keren', 'photo', 'graphy', 'indo', 'travel', 'art', 'shop', 'store', 'sex', 'toko', 'jual', 'online', 'murah', 'jam', 'kaos', 'case', 'baju', 'fashion…
has answer: http://stackoverflow.com/a/50083732
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81086597
tagged with: error-handling
tagged with: loops
has comment: http://stackoverflow.com/comment/81087377

http://stackoverflow.com/comment/81238030
type: Comment
type: AnswerComment
has text: Actually Scott Boston Solved the problem.
score: 0
comment on: http://stackoverflow.com/a/47143776

http://stackoverflow.com/comment/81357669
score: 0
has text: Not sure if it's final answer, but you should certainly use `asyncio.CancelledError` instead of `concurrent.futures.CancelledError` - these are different classes.
comment on: http://stackoverflow.com/q/47175297
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81321534
type: Comment
has text: Please use "presumably" only if there are indeed gaps in the relevant info. This is not at all the case here, as [`predict`](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression.predict) returns *labels*, not probabilities (the latter are returned by [`predict_proba`](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression.predict_proba))
type: AnswerComment
comment on: http://stackoverflow.com/a/47185684
score: 0

http://stackoverflow.com/q/47088896
tagged with: numpy
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47089014
tagged with: algorithm
tagged with: function
has body: I made a factorial function using numpy. Here's the code: import numpy as np def factorial(x): n=[] if x==1: return 1 if x&gt;1: while x&gt;1: x-=1 n.append(x+1) return np.prod(np.array(n)) That function does work well until factorial(12). On the other hand, this one works with any number: def fact(n): num = 1 while n &gt; 1: num *= n n -= 1 return num This get worse when for example I try to calculate 20!: factorial(20) Out[65]: -2102132736 #Wrong fact(20) Out[66]: 2432902008176640000 #Correct Does anybody could help me to understand what's wrong with my function? Thanks in advance
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81130742
score: 0
has title: Problems with factorial function in Python (see codes)
has answer: http://stackoverflow.com/a/47089014
answer count: 1
type: Question

http://stackoverflow.com/comment/81165938
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47089036
has text: WHY do you wish to do this? We might be able to offer an alternative.

http://stackoverflow.com/comment/93035658
score: 0
type: Comment
has text: worked great `python 2.7.12` and `ubuntu 16.04`. How much speedups, anyone?
type: AnswerComment
comment on: http://stackoverflow.com/a/50073238

http://stackoverflow.com/comment/81146798
has text: I understand. Thank you.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47092069
type: Comment

http://stackoverflow.com/comment/81214792
type: QuestionComment
has text: Is there always going to be `H\d\d\d` 3 times consecutively ?
type: Comment
comment on: http://stackoverflow.com/q/47132438
score: 0

http://stackoverflow.com/comment/81244798
score: 0
comment on: http://stackoverflow.com/q/47147146
has text: I've seen that question too, but I didn't tried that, wait a sec
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47203845
tagged with: arguments
has comment: http://stackoverflow.com/comment/81356196
tagged with: python
tagged with: parameter-passing
has body: In google appengine NDB there are queries like this: query = Account.query(Account.userid &gt;= 40) How come the Account.userid &gt;= 40 expression is not expanded at call time to true or false before passed as an argument? How is the filter expression passed to the query? Is it done with operator overloading?
has title: Why is this python expression parameter is not expanded at call time?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47213245
has answer: http://stackoverflow.com/a/47213245
answer count: 1
has comment: http://stackoverflow.com/comment/81375007
favorite count: 0
score: 8
type: Question
has comment: http://stackoverflow.com/comment/81356145
upvote count: 8
tagged with: function
tagged with: google-app-engine
downvote count: 0

http://stackoverflow.com/comment/81388054
type: AnswerComment
has text: I tried it with larger arrays, and `np.einsum` is actually much slower, and it's not because of the parsing. I don't exactly know why, but it's most likely because the operations aren't as simple and straightforward as in the usual matrix multiplication where NumPy uses a really efficient implementation. In fact, titipata's solution of just doing `(x.dot(M) * x).sum(axis=1)` is faster, and probably as fast as it gets.
type: Comment
comment on: http://stackoverflow.com/a/47216168
score: 0

http://stackoverflow.com/a/47115976
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: It works for me like this: %matplotlib inline waps_df1['NEG_04_08'].plot() You only need to import pandas to produce a plot, you can lose matplotlib and pyplot. Well that does produce a plot, not sure if it is the kind of plot you want:
answers question: http://stackoverflow.com/q/47115745
has comment: http://stackoverflow.com/comment/81190622

http://stackoverflow.com/a/47146710
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47146558
has body: You will not find a python3 installation via yum. You should simply use the standard python.org installation: wget https://www.python.org/ftp/python/3.4.5/Python-3.4.5.tgz tar xfz Python-3.4.5.tgz cd Python-3.4.5/ ./configure sudo make altinstall Go to python.org to choose your desired Python version to install.

http://stackoverflow.com/comment/81380334
type: Comment
score: 0
type: AnswerComment
has text: Thank you, I have to learn about yield. My structure is kinda huge and I am getting memory errors. I am not using list(...) but am trying to just iterate over the result and print it out (for now). Is there a reason that for x in unroll(d): print(x) would not work?
comment on: http://stackoverflow.com/a/47215358

http://stackoverflow.com/q/47221144
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/81398859
has comment: http://stackoverflow.com/comment/81408831
tagged with: python
has comment: http://stackoverflow.com/comment/81412292
has body: I am having an ordering problem with the Sklearn.neighbors classifier. Namely, what I want is in case of a tie the classifier to predict the first result appearing on the dataframe. The documentation of Sklearn.neighbors says: ''Warning Regarding the Nearest Neighbors algorithms, if two neighbors, neighbor k+1 and k, have identical distances but different labels, the results will depend on the ordering of the training data.'' However I found out that this is true only in case I use as an algorithm ''brute force'' i.e: clf = NearestNeighbors(n_neighbors=2, algorithm='brute').fit(X) My problem is that even by using brute as an algorithm, the order gets lost after a specific number of predicting neighbors. Namely: clf.kneighbors(np.array(y), n_neighbors=1) -&gt; Predicts 0 row which is correct in terms of ordering clf.kneighbors(np.array(y), n_neighbors=2) -&gt; Predicts 0 and 101 rows which are correct in terms of ordering clf.kneighbors(np.array(y), n_neighbors=3) -&gt; Predicts 0, 101 and 115 rows which are correct in terms of ordering But then when I use n_neighbors=4 I get: clf.kneighbors(np.array(y), n_neighbors=4) -&gt; Predicts 4416, 223, 7626 and 2047 rows which are not correct in terms of ordering And it keeps going like this for any number>3. The order is completely lost. Anyone that has dealt with this problem before?
type: Question
answer count: 0
upvote count: 1
type: UnansweredQuestion
tagged with: scikit-learn
tagged with: nearest-neighbor
favorite count: 0
has title: Sklearn.neighbors Classifier - Order of results in case of a tie

http://stackoverflow.com/q/47066197
has title: check two arrays for matching elements given the same index and return number of matches
has comment: http://stackoverflow.com/comment/81080870
linked to: http://stackoverflow.com/q/10580676
has comment: http://stackoverflow.com/comment/81080848
has answer: http://stackoverflow.com/a/47066353
tagged with: python
upvote count: 4
has body: Given two arrays, is there a numpy non-loop way to check if each ith index matches between the arrays, aka check for every i if a[i]==b[i]? a = np.array([1,2,3,4,5,6,7,8]) b = np.array([2,3,4,5,6,7,8,9]) Output: 0 matches I expect this has already been asked but I could not find what I was looking for, apologies if it is.
has answer: http://stackoverflow.com/a/55979307
answer count: 4
accepted answer: http://stackoverflow.com/a/47066209
tagged with: numpy
has comment: http://stackoverflow.com/comment/81080884
score: 2
downvote count: 2
has answer: http://stackoverflow.com/a/47066250
has comment: http://stackoverflow.com/comment/81081153
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47066209
possible better answer: http://stackoverflow.com/a/47066250
type: AnsweredQuestion

http://stackoverflow.com/a/47171774
upvote count: 3
has body: In lines like: #!python ... return "%.2f" % (allRes / (allRes + (5 * 70))) ... you're converting the results of your arithmetic expression: (allRes / (allRes + (5 * 70))) into a string using the % operator with a formatting string antecedent. So just change that line (and others like it) to: #!python ... return float(allRes) / (allRes + (5 * 70)) In this case I've also added a call to the float() constructor/conversion function to ensure that the entire expression will be evaluated using floating point (real) semantics rather than risk integer division if this code were executed by an other version of Python.
answers question: http://stackoverflow.com/q/47171700
has comment: http://stackoverflow.com/comment/81293232
has comment: http://stackoverflow.com/comment/81293145
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81293154
has comment: http://stackoverflow.com/comment/81321716
score: 3
has comment: http://stackoverflow.com/comment/81418412

http://stackoverflow.com/a/47103307
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81156986
upvote count: 1
has body: Your index is wrong sys.argv[0] will be the path of the python script. What you want is: if __name__ == '__main__': if len(sys.argv) == 1: sys.argv.append("apple") select() But, this is a weird way of doing things. After a bit more thought, this occurred to me: choice=['orange','apple', 'grapes', 'banna'] def select(): parser = argparse.ArgumentParser(prog='one', description='name test') parser.add_argument( 'fname', nargs='?', default='apple', action="store", type=str, choices=choice, help="furits name") args = parser.parse_args(sys.argv[1:2]) print 'selected name {0}\n'.format(args.fname) if __name__ == '__main__': select() Note the nargs='?' and default='apple' additions to the call to add_argument(). These make the parameter optional and set the default value to "apple" if no argument is supplied.
type: Answer
accepted answer of: http://stackoverflow.com/q/47103242
has comment: http://stackoverflow.com/comment/81158264
answers question: http://stackoverflow.com/q/47103242

http://stackoverflow.com/a/47222596
type: Answer
accepted answer of: http://stackoverflow.com/q/47222422
answers question: http://stackoverflow.com/q/47222422
score: 0
has comment: http://stackoverflow.com/comment/81395410
has body: You can probably do something like this. pip install -U pip==(version of pip you want) I don't know if it will work or not you can always try.
type: AcceptedAnswer

http://stackoverflow.com/comment/81325423
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47187838
has text: doesn't that code melt your brain?
score: 0

http://stackoverflow.com/comment/81157408
type: AnswerComment
score: 0
has text: Yes, I've tested this, but I copied the string object from the original question! That'll teach me next time. Now it should work, at least in python 2.x
comment on: http://stackoverflow.com/a/47103487
type: Comment

http://stackoverflow.com/a/47120048
has comment: http://stackoverflow.com/comment/81211679
has comment: http://stackoverflow.com/comment/81212047
has comment: http://stackoverflow.com/comment/81211835
score: 7
type: Answer
answers question: http://stackoverflow.com/q/47119879
has comment: http://stackoverflow.com/comment/81210974
has comment: http://stackoverflow.com/comment/100495928
has comment: http://stackoverflow.com/comment/81259548
accepted answer of: http://stackoverflow.com/q/47119879
has body: Override get_field_names in you serializer: class ServerSerializer(serializers.HyperlinkedModelSerializer): def get_field_names(self, *args, **kwargs): field_names = self.context.get('fields', None) if field_names: return field_names return super(ServerSerializer, self).get_field_names(*args, **kwargs) then use it like: serializer = ServerSerializer(servers, context={'fields': ['name']}) serializer = ServerSerializer(servers, context={'fields': ['name', 'ip_address']}) * EDIT * Turn it into mixin, to make it more reusable: class FieldMixin(object): def get_field_names(self, *args, **kwargs): field_names = self.context.get('fields', None) if field_names: return field_names return super(FieldMixin, self).get_field_names(*args, **kwargs) and use it: class ServerSerializer(FieldMixin, serializers.HyperlinkedModelSerializer):
has comment: http://stackoverflow.com/comment/81208530
type: AcceptedAnswer
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/81212114

http://stackoverflow.com/comment/81496077
comment on: http://stackoverflow.com/q/47208653
has text: why you are using a template tag and a view
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47122752
tagged with: openpyxl
tagged with: python
has title: Python using openpyxl, load_workbook, grab pattern, and print value of cell
tagged with: excel
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81201699
has comment: http://stackoverflow.com/comment/81200608
has body: I'm still new to Python while exploring, learning, and today I'm working with openpyxl. How do I print a cell value (in this case date) based on the last position of my pattern? I have a worksheet I am trying grab data from row by row since my data set is less then 15 rows totals. The data looks as follows: Apps, 11/3/2017, 11/4/2017, 11/5/2017, 11/6/2017, 11/7/2017, 11/8/2017... app_1, a, a, a, b, c,d,e... app_2, a,b,c,d,e.... app_3, a,a,a,a,b,b,b,b,b,b,c,c,c,c,d,d,d,d,e,e,e,e.... I am able to grab each row, store it into a variable, get the value of cell, and get cell coordinates. For example, I want to 1) look at the Apps column, 2) note app_1, 3) locate letter pattern "aaa", 4) note last coordinate of "aaa" and print date to a new cell of 11/5/2017. Here is a sample of my code so far: from openpyxl import load_workbook wb = load_workbook('example.xlsx') ws1 = wb['Sheet1'] row1 = ws1.iter_rows(min_row=1,max_row=1) row2 = ws1.iter_rows(min_row=2,max_row=2) row3 = ws1.iter_rows(min_row=3,max_row=3) def row_one_apps_dates(): # I have this for each row for row in row1: for cell in row: if cell.value =='a' : print(cell.column, cell.row)#print(cell.coordinate) def row_two(): for row in row2: for cell in row: if cell.value =='a' or 'b' or 'c' or 'd' or 'e': print(cell.column, cell.row)#print(cell.coordinate) My Output: A 2 B 2 C 2 D 2 E 2 F 2 Thank you for any help as I continue to grow in python. UPDATE1: At this point I am trying to retrieve the last value, but keep getting multiple results instead of the last one. Here is my code: for row in row2: for cell in row: if cell.value == 'a': result = cell.column last_result = result[-1] print(last_result) OUTPUT: B C D E F G None I want to retrieve G only and will later add 1 making it G1. Grab value of G1 which would be a date.
type: Question
tagged with: iterator
tagged with: for-loop
type: UnansweredQuestion

http://stackoverflow.com/q/47183786
has body: I'm developing some code for my coursework in School but my idea requires me to find the max value in some different arrays. It seems quite easy but the main problem is that I will not know how many elements in the list there are because my list contains result every time a user has done my quiz. For example, if my list contained: main_list=[["Name1",[21,22,25]], ["name2",[26,21,24]], ["name3",[29,21,24]]] Every time my main program is executed it will add another element to the list. So if it was executed again my list would become: main_list=[["Name1",[21,22,25]], ["name2",[26,21]], ["name3",[29,21,24]], ["name4",[21]]] So you see that I will not be able to see how many elements there are. Yet I need to add up the 2nd element in the 2 dimensional lists (main_list[0][1] + main_list[1][1] + main_list[2][1] etc.) and find biggest value in them. How would I do this?
has comment: http://stackoverflow.com/comment/81316667
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47183914
score: 0
has answer: http://stackoverflow.com/a/47183914
answer count: 1
type: Question
type: AnsweredQuestion
has title: Find the max value in multidimensional lists without knowing how many elements there are
has comment: http://stackoverflow.com/comment/81316839
tagged with: python

http://stackoverflow.com/q/47192096
tagged with: http://stackoverflow.com/tag/csv
downvote count: 1
favorite count: 0
score: -1
has body: So I have a csv file with a bunch of bridge data. There's 25 bridges and each bridge number is in column 1. The rest of the columns have corresponding bridge condition data. For example in row 1, 1 is the bridge number, 6 is the condition rating in 1992, 8 is the condition rating in 1993, 8 is the condition rating in 1994, 7 is the condition rating in 1995, and so on. I've written a code so far that asks for the users input which is a bridge number between 1-25 and the output I'm trying to achieve is the various conditions that the inputted bridge number is in and for how many years it's in. For example, bridge 1 has 1 year in condition rating 6, 2 years in condition rating 8, 10 years in condition rating 7 and so on. see the image link. Here's what I've come up with thus far but I'm really new to python and could use some (a lot) of help. Could someone please help me call for the right bridge number from the csv? f = open("NBIBridge.csv", "r") n = int(input("Please enter a bridge number: ")) while n &lt; 1 or n &gt;25: n = int(input("please enter a bridge number &gt;1 and &lt;25: ")) bridge = [] for line in f: temp = line.split(",") i = int(temp[n]) j = int(temp[n]) temp = [j,n] bridge.append(temp)
type: Question
upvote count: 0
tagged with: input
type: UnansweredQuestion
tagged with: python
has title: How to read data from csv and print out specifics in python
has comment: http://stackoverflow.com/comment/81333544
answer count: 1
has answer: http://stackoverflow.com/a/47194064

http://stackoverflow.com/comment/108058404
score: 0
comment on: http://stackoverflow.com/a/48069535
has text: @Oscar pykalman is just a library and it will work fine for this problem if you have a suitable system model and some trace data. As far as I know it's not an easy problem. It depends strongly on your application domain (is it a vehicle, a jet or a person) and which assumptions you can do to simplify the modelling. If I find something interesting, I'll post a link.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/61457071
type: Answer
has body: r = int(input("Enter Number of Rows : ")) c = int(input("Enter Number of Cols : ")) a = [] for i in range(r): b = [] for j in range(c): j = int(input("Enter Number in pocket [" + str(i) + "][" + str(j) + "]")) b.append(j) a.append(b) print("Matrix is ......") for i in range(r): for j in range(c): print(a[i][j], end=" ") print()
answers question: http://stackoverflow.com/q/47145934
score: 0

http://stackoverflow.com/a/47128463
type: Answer
has body: df.set_index(['a','b']).stack().reset_index().drop('level_2',1).rename(columns={0:'c'}) Out[754]: a b c 0 1 2 3 1 1 2 4 2 1 2 5 3 6 7 8 4 6 7 9 5 6 7 0
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47127940

http://stackoverflow.com/a/47116948
answers question: http://stackoverflow.com/q/47116887
score: 0
has body: You don't have a counter as you append the letter but not its number of occurrences. So to simplify: def initialLets(keyStr): '''Return a dictionary in which each key is the initial letter of a word in t and the value is the number of words that begin with that letter. Upper and lower case letters should be considered different letters.''' strList = keyStr.split() # We initiate the variable that gonna take our results result = {} for words in strList: if words[0] not in result: # if first letter not in result then we add it to result with counter = 1 result[words[0]] = 1 else: # We increase the number of occurence result[words[0]] += 1 return result text = "I'm born to trouble I'm born to fate" print(initialLets(text))
type: Answer

http://stackoverflow.com/a/47128311
answers question: http://stackoverflow.com/q/47128265
has body: Pandas is the way to go BUT if you can't do that for whatever reason then I suppose you could create a dictionary for each ID and then find the ID that corresponds to the max value in the dictionary. I assume your data looks something like this: ID Bikes A 100 B 225 C 600 D 700 E 300 Then you could use: import csv dct = {} with open(r'your_file.csv') as f: reader = csv.reader(f, delimiter = ',') next(reader) for row in reader: identifer = row[0] bikes = row[1] dct[identifer] = bikes print(max(dct, key=dct.get)) #output D
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/81206684
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47128265

http://stackoverflow.com/q/47129013
has comment: http://stackoverflow.com/comment/81209435
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81210881
accepted answer: http://stackoverflow.com/a/47135784
tagged with: pandas-groupby
has comment: http://stackoverflow.com/comment/81209511
tagged with: pandas
has answer: http://stackoverflow.com/a/47135784
tagged with: matplotlib
has title: plot histogram for many columns quickly using groupby function of pandas dataframe
has body: I have a pandas dataframe, which looks like Here one of column is named label, that can take only two possible values 0 or 1. I would like to make histogram for label 1 and for label 0 separately one top of other, like I am able to make this for one of the column (named "MA_CL05") like: temp = infile.groupby('label') for k, v in temp: if k == 1: v.MA_CL05.hist(label='1',figsize=(15,15),bins=25,alpha=1.0,histtype = 'step',lw=4) if k == 0: v.MA_CL05.hist(label='0',figsize=(15,15),bins=25,alpha=1.0,histtype = 'step',lw=4) plt.legend(loc=1, prop={'size': 51}) plt.show() I can copy and past this patch for all of 20 columns and it will be fine. But, is there any easy way to plot this histogram of type (2) in one go?
has comment: http://stackoverflow.com/comment/81209521
answer count: 1
linked to: http://stackoverflow.com/q/47087173
has comment: http://stackoverflow.com/comment/81209552
type: Question
has comment: http://stackoverflow.com/comment/81209493

http://stackoverflow.com/q/47152353
has body: I want to creat a GridSpec inside a Gridpec. I can already create some GridSpecs like my Code here: import matplotlib.pyplot as plt for i in range(40): i = i + 1 ax1 = plt.subplot(10, 4, i) plt.axis('on') ax1.set_xticklabels([]) ax1.set_yticklabels([]) ax1.set_aspect('equal') plt.subplots_adjust(wspace=None, hspace=None) plt.show() But I want 40 gridspecs. In Every Gridspec should be another 21 Grids (inner_grid) and in every inner_grid should be one grid on the top and 6 grids in a row should fill the rest. Nearly like the picture in the end of this link: https://matplotlib.org/tutorials/intermediate/gridspec.html But I don't really understand it. I have tried this: import matplotlib as mpl from matplotlib.gridspec import GridSpec import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt fig = plt.figure(figsize=(5,10), dpi=300) ax = plt.subplot(gs[i]) #trying to make multiple gridspec # gridspec inside gridspec outer_grid = gridspec.GridSpec(48, 1, wspace=0.0, hspace=0.0) for i in range(21): #ax = plt.subplot(5, 5, i) inner_grid = gridspec.GridSpecFromSubplotSpec(5, 5, subplot_spec=outer_grid[i], wspace=0.0, hspace=0.0) a, b = int(i/4)+1, i % 4+1 for j in enumerate(product(range(1, 4), repeat=2)): ax = plt.Subplot(fig, inner_grid[j]) ax.set_xticks([]) ax.set_yticks([]) fig.add_subplot(ax) all_axes = fig.get_axes()
tagged with: matplotlib
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/47159851
type: UnansweredQuestion
tagged with: python
has title: Gridspec inside Gridspec
score: 0

http://stackoverflow.com/a/47205091
answers question: http://stackoverflow.com/q/47205055
type: Answer
has body: Replace for s in status[r]: with for s in r: r contains an element of status (in this case the list to iterate over in the inner for loop), not an index. You should also replace text=status[r][s] with text = s, for the same reason. If you want just the indices, you can use: for i in range(len(lst)): for some list lst and if you want both indices and elements (in this case, you need the indices to pass in the column and row values), use: for i, elem in enumerate(lst):
has comment: http://stackoverflow.com/comment/81359065
has comment: http://stackoverflow.com/comment/81359007
upvote count: 2
has comment: http://stackoverflow.com/comment/81359140
downvote count: 0
score: 2
has comment: http://stackoverflow.com/comment/81358941

http://stackoverflow.com/comment/81287607
comment on: http://stackoverflow.com/q/47168595
score: 0
has text: Hi @WillianFuks - it's referenced here: https://cloud.google.com/bigquery/docs/running-queries#bigquery-query-python It's not a live stream I'm running a python script as a one time thing, but the script has to run multiple jobs as an error gets thrown when the length of the query string passes a limit, I think 250k limit, from memory.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81218320
score: 2
comment on: http://stackoverflow.com/q/47134324
has text: `oldPizzaScores` should be a copy, not reference to `pizzaScores`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81258506
comment on: http://stackoverflow.com/q/47153905
has text: You have to mutate the variable. *assignment is not mutation*.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47121655
accepted answer of: http://stackoverflow.com/q/47119525
answers question: http://stackoverflow.com/q/47119525
has comment: http://stackoverflow.com/comment/81194403
type: Answer
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/81194467
has body: If all of the unique values fit into memory then call compute beforehand for item in df[col].unique().compute() ... Otherwise I recommend writing to disk with something like parquet and then iterating off of that df[col].unique(split_out=10).to_parquet(...) s = dd.read_parquet(...) for item in s.iteritems(): ...
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81386058
type: AnswerComment
has text: Does it matter if i add just a copy of the predicted values to dataframe? I mean the values are still encoded.
comment on: http://stackoverflow.com/a/47217986
type: Comment
score: 0

http://stackoverflow.com/q/47088992
has answer: http://stackoverflow.com/a/47105882
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81160225
has comment: http://stackoverflow.com/comment/81129870
favorite count: 0
type: Question
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81127371
tagged with: ipv4
answer count: 2
has answer: http://stackoverflow.com/a/47104625
tagged with: ipv6
has body: How do I convert an IPv6 address to an IPv4 address, and likewise how do I then parse the IPv4 address into a set of integers? I have : a = ' ff06::c3' I would like: 4278583296.0.0.195 And from there I would like to get: a1 = 4278583296 a2 = 0 a3 = 0 a4 = 195
type: UnansweredQuestion
has title: How to convert from IPv6 to IPv4, and from there to an integer format
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81130258
has comment: http://stackoverflow.com/comment/81127324

http://stackoverflow.com/comment/81220549
type: AnswerComment
comment on: http://stackoverflow.com/a/47097871
score: 0
has text: Thanks for reply! I solved my problem in the other way but your solution helped me a lot, thanks!
type: Comment

http://stackoverflow.com/q/47101182
tagged with: intellij-idea
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47475621
tagged with: conda
score: 3
linked to: http://stackoverflow.com/q/135688
has body: I looked at the Intellij documentation on how to do this - https://www.jetbrains.com/help/idea/conda-support-creating-conda-environment.html - for which the following is the crux: When I follow those steps the Conda environment does not show up: Out of curiosity I then clicked on the Python 2.7.14 to see what that would offer: So there would actually be the ability to create a virtualenv: but that's likely different from conda/anaconda. Does anyone have this working in Intellij? I a on IJ Ultimate 2017.1.
tagged with: anaconda
upvote count: 3
answer count: 1
has title: Adding an anaconda SDK to an Intellij Project
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/81399967
type: AnswerComment
has text: Ooop forgot to call strip()| instead of only calling it.
comment on: http://stackoverflow.com/a/47207660
type: Comment
score: 0

http://stackoverflow.com/q/47170280
has comment: http://stackoverflow.com/comment/81290851
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81290522
has comment: http://stackoverflow.com/comment/81290895
has comment: http://stackoverflow.com/comment/81290385
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/47170444
answer count: 2
has comment: http://stackoverflow.com/comment/81290737
has body: My question is related to reading MATLAB data into Python. The scipy.io would do this but many variables in MATLAB is in the shape n*1 or 1*m. Suppose I have variables with different names foo1, foo2, foo3, ... How should I apply foo = np.squeeze(foo) to each of these variables. Is there a way to deal with this problem without apply the spueeze function to every variable explicitly? Thanks in advance.
has title: How to execute foo = fun(foo) for many different variables in numpy
has answer: http://stackoverflow.com/a/47170444
accepted answer: http://stackoverflow.com/a/47170634
has comment: http://stackoverflow.com/comment/81290798
tagged with: python
has answer: http://stackoverflow.com/a/47170634

http://stackoverflow.com/a/47107785
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47107766
has comment: http://stackoverflow.com/comment/81166009
answers question: http://stackoverflow.com/q/47107766
has comment: http://stackoverflow.com/comment/81165983
has body: Check this &gt;&gt;&gt; list_string = ["This is a string that I want." , "this is also a string that I want!" , "and this" , "and also this one!!"] &gt;&gt;&gt; [[i] for i in list_string] [['This is a string that I want.'], ['this is also a string that I want!'], ['and this'], ['and also this one!!']] &gt;&gt;&gt; You can call individual lists using list_string[0],list_string[1] so on
type: Answer

networkx
tags question: http://stackoverflow.com/q/47191816
tags question: http://stackoverflow.com/q/47094949
tags question: http://stackoverflow.com/q/47120253
tag name: networkx
tags question: http://stackoverflow.com/q/47204842
tags question: http://stackoverflow.com/q/47213650
tags question: http://stackoverflow.com/q/47102028
tags question: http://stackoverflow.com/q/47208674
tags question: http://stackoverflow.com/q/47146755
tags question: http://stackoverflow.com/q/47105308
tags question: http://stackoverflow.com/q/47168382
type: Tag
tags question: http://stackoverflow.com/q/47210530

http://stackoverflow.com/comment/81300479
type: Comment
score: 0
has text: Thanks, I'll remember that.
type: QuestionComment
comment on: http://stackoverflow.com/q/47175484

http://stackoverflow.com/comment/81112835
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47081089
type: Comment
has text: This answers the question but doesn't close the file and doesn't conform PEP8.

http://stackoverflow.com/comment/81386741
type: Comment
type: QuestionComment
score: 0
has text: Could you include some example characters with your question? I want to try this but I don't know what kind of characters might cause this.
comment on: http://stackoverflow.com/q/47218571

http://stackoverflow.com/q/47111701
tagged with: literate-programming
has comment: http://stackoverflow.com/comment/81173359
has answer: http://stackoverflow.com/a/47111708
has body: I am trying to fetch values of each row of pandas dataframe using below code. points = [ makePoint(row) for row in df.iterrows() ] here df has 4 column. each contains integer data. while i try to print row, it returns follow, 1 3 2 3 3 4 4 5 Name: 0, dtype: int64 I just need [3,3,4,5] and don't want index, name and dtype.
tagged with: python
score: 0
tagged with: pandas
type: UnansweredQuestion
has title: Python: How to get values and not object type while iterating through pandas Data Frame?
answer count: 1
tagged with: loops
type: Question

http://stackoverflow.com/comment/81244544
type: Comment
comment on: http://stackoverflow.com/a/47147107
type: AnswerComment
has text: @wim: You might have more relevant experience. I haven't used `async` yet, and I'm not familiar with how you'd use async functions to handle this.
score: 0

http://stackoverflow.com/comment/81244676
comment on: http://stackoverflow.com/q/47096903
score: 0
type: Comment
has text: Thanks a lot for your answer, it solved my problem.
type: QuestionComment

http://stackoverflow.com/comment/81379930
has text: Thank you for your reply. I got this error: TypeError: 'KeysView' object does not support indexing.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47214490
type: Comment

http://stackoverflow.com/comment/118075267
score: 0
comment on: http://stackoverflow.com/q/47157536
type: QuestionComment
type: Comment
has text: Does this answer your question? [How do convert a pandas/dataframe to XML?](https://stackoverflow.com/questions/18574108/how-do-convert-a-pandas-dataframe-to-xml)

http://stackoverflow.com/q/47095656
answer count: 1
has answer: http://stackoverflow.com/a/47095692
accepted answer: http://stackoverflow.com/a/47095692
has title: Python: "AttributeError: 'Namespace' object has no attribute" argparse
favorite count: 0
type: Question
has body: My code looks like this: parser.add_argument('-i', '--input', help='Input path/to/file.csv', required=True) parser.add_argument('-oh', '--output-html', help='Output path/to/confusion_matrix.html', required=True) parser.add_argument('-oc', '--output-csv', help='Output path/to/confusion_matrix.csv', required=True) args = parser.parse_args() .... y_true = pd.Series(true_data, name="Actual") y_pred = pd.Series(pred_data, name="Predicted") df_confusion = pd.crosstab(y_true, y_pred) df_confusion.to_html(args.output-html) df_confusion.to_csv(args.output-csv) When i try to run it, it gives me this error: df_confusion.to_html(args.output-html) AttributeError: 'Namespace' object has no attribute 'output' However, if i change from df_confusion.to_html(args.output-html) To df_confusion.to_html(args.output) It works as it should. Can anyone explain why it doesn't work, and how can i make it work with args.output-html?
upvote count: 5
score: 5
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81140605
downvote count: 0

http://stackoverflow.com/comment/81150198
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47098991
score: 0
has text: thanks. filenames.split("\n"): does not seem to work as my filenames from glob is a list of paths while you assigning to a string

http://stackoverflow.com/comment/81242054
comment on: http://stackoverflow.com/q/47145741
has text: excellent, I used a bunch of search terms trying to find such a post, but apparently was not thorough enough...I guess we just need another of the same post with a different title.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47166432
accepted answer of: http://stackoverflow.com/q/47165783
upvote count: 4
answers question: http://stackoverflow.com/q/47165783
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/137194817
downvote count: 0
type: Answer
has body: It's actually not just for lambdas; any function that takes default parameters will use the same syntax. For example def my_range(start, end, increment=1): ans = [] while start &lt; end: ans.append(start) start += increment return ans (This is not actually how range works, I just thought it would be a simple example to understand). In this case, you can call my_range(5,10) and you will get [5,6,7,8,9]. But you can also call my_range(5,10,increment=2), which will give you [5, 7, 9]. You can get some surprising results with default arguments. As this excellent post describes, the argument is bound at function definition, not at function invocation as you might expect. That causes some strange behavior, but it actually helps us here. Consider the incorrect code provided in your link: def create_multipliers(): return [lambda x : i * x for i in range(5)] for multiplier in create_multipliers(): print multiplier(2) When you call multiplier(2), what is it actually doing? It's taking your input parameter, 2, and returning i * 2. But what is i? The function doesn't have any variable called i in its own scope, so it checks the surrounding scope. In the surrounding scope, the value of i is just whatever value you left it -- in this case 4. So every function gives you 8. On the other hand, if you provide a default parameter, the function has a variable called i in its own scope. What's the value of i? Well, you didn't provide one, so it uses its default value, which was bound when the function was defined. And when the function was defined, i had a different value for each of the functions in your list! It is a bit confusing that they've used the same name for the parameter variable as they did for the iterating variable. I suspect you could get the same result with greater readability with def create_multipliers(): return [(lambda x, y=i: y*x) for i in range(5)]
score: 4

http://stackoverflow.com/q/47160355
has comment: http://stackoverflow.com/comment/81270681
has comment: http://stackoverflow.com/comment/81270311
has comment: http://stackoverflow.com/comment/81270522
tagged with: python
has title: Stripping a character only once in python
has answer: http://stackoverflow.com/a/47160969
has comment: http://stackoverflow.com/comment/81270397
accepted answer: http://stackoverflow.com/a/47160969
has comment: http://stackoverflow.com/comment/81271046
has comment: http://stackoverflow.com/comment/81270445
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/81270802
type: Question
tagged with: strip
has comment: http://stackoverflow.com/comment/81270592
has body: I am parsing values from a file, some of which can be string literals, enclosed in double quotes. To get the actual value I have to strip the double quotes: &gt;&gt;&gt; raw_value = r'"I am a string"' &gt;&gt;&gt; processed_value = raw_value.strip('"') &gt;&gt;&gt; print(processed_value) I am a string However, some values contain escaped double quotes, which can be at the end: &gt;&gt;&gt; raw_value = r'"Simon said: \"Jump!\""' &gt;&gt;&gt; processed_value = raw_value.strip('"') &gt;&gt;&gt; print(processed_value) Simon said: \"Jump!\ You see my problem here: the escaped double quote is stripped away which leaves an orphaned double quote when I write the file back and makes it unreadable. I could do: def unique_strip(some_str): beginning = 1 if some_str.startswith('"') else 0 end = -1 if some_str.endswith('"') and some_str[-2] != "\\" else None return some_str[beginning:end] Using previous example: &gt;&gt;&gt; unique_strip(raw_value) 'Simon said: \\"Jump!\\"' &gt;&gt;&gt; raw_value = r'"Simon said: \"Jump!\"' &gt;&gt;&gt; unique_strip(raw_value) 'Simon said: \\"Jump!\\"' So now it even works if the trailing double quote is missing. Is there a more pythonic way to do this, using built-in strip for example ? If not, is there anything wrong or any loophole in my method ? Update I guess my function raises IndexError for an input like some_str = '"'. So maybe: def unique_strip(some_str): beginning = 1 if some_str.startswith('"') else 0 end = -1 if len(some_str) &gt; 1 and some_str.endswith('"') and some_str[-2] != "\\" else None return some_str[beginning:end]

http://stackoverflow.com/comment/81104699
type: AnswerComment
has text: depending on the exact setup, OP might also need to use `conn.dialect.server_side_cursors = True` and `conn.execution_options(stream_results = True)` as the database driver will otherwise fetch all the results locally, then stream them to python in chunks
score: 4
type: Comment
comment on: http://stackoverflow.com/a/47077999

http://stackoverflow.com/q/47143592
has comment: http://stackoverflow.com/comment/81237339
has comment: http://stackoverflow.com/comment/81237752
has comment: http://stackoverflow.com/comment/81237660
answer count: 1
has title: Python Dataframe: Extract Date from Datetime field -- 'Not Callable' Error
accepted answer: http://stackoverflow.com/a/47144014
tagged with: series
type: Question
has body: Updated Follow-up Question: Error received after running code below: UnboundLocalError: local variable 'month_name' referenced before assignment I have an object column that I converted into datetime successfully called "dtin". Below is what the data looks like: I want to create a new column that extracts out just the month from the dtin column (see screen shot). Below is the code I tried and the resulting error: Any help is greatly appreciated.
has answer: http://stackoverflow.com/a/47144014
tagged with: datetime
tagged with: callable
has comment: http://stackoverflow.com/comment/81237608
tagged with: python
has comment: http://stackoverflow.com/comment/81237628
tagged with: date
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/47124708
accepted answer of: http://stackoverflow.com/q/47124512
answers question: http://stackoverflow.com/q/47124512
type: Answer
has comment: http://stackoverflow.com/comment/81200709
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
has body: mylist[:mid] returns a list. In list_sort1 you are (attempting to) sort this list and then promptly discarding it. Later on, you are using a second (unmodified) instance of mylist[:mid]. Etc. for mylist[mid:]. On the other hand, in the second version you are assigning the results of mylist[:mid] etc. to variables and hence not discarding the result of sorting them.

http://stackoverflow.com/comment/81280359
comment on: http://stackoverflow.com/q/47165314
score: 0
has text: No error at all
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47215306
answers question: http://stackoverflow.com/q/47215275
has comment: http://stackoverflow.com/comment/81380478
type: Answer
has body: itertools.combinations is working properly. You are breaking up the result with cell = tuple(set(i[0]+i[1])). That adds the two strings (e.g. '910') then breaks up the digits. i has the correct result of, for this example, ('9','10').
upvote count: 2
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47215275
type: AcceptedAnswer

http://stackoverflow.com/comment/81116438
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47064768
has text: @axiom. My suggestion is to use **only** the file-system, and not to use a `dict` at all. That will easily be fast enough for most use-cases (unless there are many thousands of directories to check).
type: QuestionComment

http://stackoverflow.com/comment/81266358
comment on: http://stackoverflow.com/a/47155828
type: AnswerComment
has text: and how do you know??!!!! you do not sure! this is not a general answer for OP question, ask op about this discussion and if he say i just have this type of data, i will vote up you!
score: 0
type: Comment

http://stackoverflow.com/a/47103654
upvote count: 3
score: 3
has body: I'm learning about OrderedDicts in python but when I create new dictionaries it preserves the order anyway. This is accidentally the case with python 3.6 It is an implementation detail. See Dictionaries are ordered in Python 3.6+
type: Answer
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47103618
answers question: http://stackoverflow.com/q/47103618

http://stackoverflow.com/q/47129592
type: Question
has body: everyone: I am new to beautiful soup, working on parse table, i was able to get to cell level. Let's say cell is something I am trying to extract... I know type(cell) is I know cell content is Raptors v. Jazz UNDER 196 When I do cell.text, i get output: Raptors v. Jazz UNDER 196 But what I truly want to get is expected output: Raptors v. Jazz UNDER 196 because item inside is the winning team.... How do I do that? Thanks in advance
answer count: 2
type: UnansweredQuestion
has title: beautiful soup extract cell but keep format
downvote count: 0
upvote count: 1
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/47129749
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/47129779
favorite count: 0

http://stackoverflow.com/comment/81364476
comment on: http://stackoverflow.com/a/47190571
has text: @YingSquared- I tried that and i am still getting the same error message. When I copy and paste the URL, generate the excel file, and open it, the data is all there, but python seem to be having trouble reading the URL. raise RemoteDataError('Unable to read URL: {0}'.format(url)) RemoteDataError: Unable to read URL: http://www.google.com/finance/historical?q=F&startdate=Sep+27%2C+2017&enddate=Nov+07%2C+2017&output=csv
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81298289
has text: This cuts time by a factor 20: OP's -> 1 loop, best of 3: 607 ms per loop - @lcastillov -> 10 loops, best of 3: 29.7 ms per loop
type: Comment
comment on: http://stackoverflow.com/a/47174270
score: 0
type: AnswerComment

http://stackoverflow.com/a/47130262
accepted answer of: http://stackoverflow.com/q/47130141
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47130141
has comment: http://stackoverflow.com/comment/81213563
has comment: http://stackoverflow.com/comment/81210685
has comment: http://stackoverflow.com/comment/81211969
has body: Starting off approach We can use np.unique to get the counts of occurrences and also tag each element from 0 onwards, letting us index into those counts with the tags for the desired output, like so - In [43]: a Out[43]: array([[1, 1, 1], [2, 2, 2], [3, 4, 5]]) In [44]: _,ids,c = np.unique(a, return_counts=True, return_inverse=True) In [45]: c[ids].reshape(a.shape) Out[45]: array([[3, 3, 3], [3, 3, 3], [1, 1, 1]]) For positive integers numbers in input array, we can also use np.bincount - In [73]: c = np.bincount(a.ravel()) In [74]: c[a] Out[74]: array([[3, 3, 3], [3, 3, 3], [1, 1, 1]]) For negative integers numbers, simply offset by the minimum in it. Extending to generic n-dims Let's use bincount for this - In [107]: ar Out[107]: array([[[1, 1, 1], [2, 2, 2], [3, 4, 5]], [[2, 3, 5], [4, 3, 4], [3, 1, 2]]]) In [104]: ar2D = ar.reshape(-1,ar.shape[-2]*ar.shape[-1]) # bincount2D_vectorized from https://stackoverflow.com/a/46256361/ @Divakar In [105]: c = bincount2D_vectorized(ar2D) In [106]: c[np.arange(ar2D.shape[0])[:,None], ar2D].reshape(ar.shape) Out[106]: array([[[3, 3, 3], [3, 3, 3], [1, 1, 1]], [[2, 3, 1], [2, 3, 2], [3, 1, 2]]])
type: Answer
has comment: http://stackoverflow.com/comment/81210804
score: 3
upvote count: 3

http://stackoverflow.com/comment/81104692
score: 0
has text: @L3viathan It is a piped command, something like `df -h | grep '\d+\%.+'`. Will this work?
comment on: http://stackoverflow.com/q/47075754
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47100725
answers question: http://stackoverflow.com/q/47100398
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/81151870
type: Answer
upvote count: 4
has body: If you check the page source (for example via view-source: in Chrome or Firefox, or by writing your html string to a file) you'll see that the element you are looking for is not there. In fact, the rates are loaded dynamically: You can follow the script URL and you'll see that the response is something like the following: document.write(' 2.75% ') This response is probably regular enough to be able to use regexes on it.

http://stackoverflow.com/comment/81270072
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47160098
has text: So my original script has some output of deep learning and neural network steps I want to monitor. In my test script I narrowed it down to some dummy output to see if the output is unbuffered. @ElisByberi for that I've got to edit code. Some programs are so huge it would end in a mess to edit it all.. I'm looking for something `python -u` or `PYTHONUNBUFFERED` instead that they're working.. I don't even know why they're not working as advertised.

http://stackoverflow.com/comment/81282604
type: QuestionComment
has text: @PRMoureu I wasn't restarting the server after making changes to templates... Just started using Django recently, after using Meteor for a while where dev server restarts automatically on file change. `linebreaksbr` tag works everywhere now.
comment on: http://stackoverflow.com/q/47164931
score: 0
type: Comment

http://stackoverflow.com/q/47103242
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81161113
type: Question
has title: python passing command line argument with-in program
tagged with: argparse
accepted answer: http://stackoverflow.com/a/47103307
tagged with: python
has answer: http://stackoverflow.com/a/47103307
has body: I have below python program takes argument from command line. import argparse import sys choice=['orange','apple', 'grapes', 'banna'] def select(): parser = argparse.ArgumentParser(prog='one', description='name test') parser.add_argument( 'fname', action="store", type=str, choices=choice, help="furits name") args = parser.parse_args(sys.argv[1:2]) print 'selected name {0}\n'.format(args.fname) if __name__ == '__main__': select() this works python s.py apple selected name apple How can inline argument with-in main function. I tried this but its not working. change main line this. if __name__ == '__main__': sys.argv[0]='apple' select() getting below error. usage: one [-h] {orange,apple,grapes,banna} one: error: too few arguments How can I achieve this in argument? thanks -SR
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/q/47074315
favorite count: 0
has comment: http://stackoverflow.com/comment/81099800
type: AnsweredQuestion
has body: First I tried the SocketServer class. Then I got to know that SocketServer is available in Python2. For Python3 you need to make it lower case such as socketserver. I am trying to implement a Socket server which can respond to multiple threads and doesnt block the call. Following is the code for Server class ForkingServer(socketserver.ForkingMixIn, socketserver.TCPServer): pass But it gives the above mentioned error. Does anyone have any clue?
has comment: http://stackoverflow.com/comment/81099322
has title: AttributeError: module 'socketserver' has no attribute 'ForkingMixIn'
has comment: http://stackoverflow.com/comment/81097299
upvote count: 4
has comment: http://stackoverflow.com/comment/81096838
has answer: http://stackoverflow.com/a/47075664
has comment: http://stackoverflow.com/comment/81098739
has comment: http://stackoverflow.com/comment/81099387
type: Question
tagged with: python-multithreading
tagged with: sockets
answer count: 1
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81099928
accepted answer: http://stackoverflow.com/a/47075664
score: 4

http://stackoverflow.com/a/47107133
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47106956
has body: Try this def check_word(word): symbols = list("()1234567890!?_@#$%^&amp;*.,'") word_list = list(word) while word_list[-1] in symbols: word_list.pop() print word_list temp="".join(word_list) actuallength=0 for i in temp: if i in symbols: return False else: actuallength+=1 if (actuallength &gt;3): return True else: return False Output &gt;&gt;&gt; check_word("jaanus123") ['j', 'a', 'a', 'n', 'u', 's'] True &gt;&gt;&gt; check_word("123sander") ['1', '2', '3', 's', 'a', 'n', 'd', 'e', 'r'] False &gt;&gt;&gt; check_word("123joonas123") ['1', '2', '3', 'j', 'o', 'o', 'n', 'a', 's'] False &gt;&gt;&gt; check_word("te1234et1234") ['t', 'e', '1', '2', '3', '4', 'e', 't'] False &gt;&gt;&gt; check_word("mar132gus") ['m', 'a', 'r', '1', '3', '2', 'g', 'u', 's'] False &gt;&gt;&gt;

heatmap
tags question: http://stackoverflow.com/q/47175398
tags question: http://stackoverflow.com/q/47115600
tag name: heatmap
type: Tag
tags question: http://stackoverflow.com/q/47163728

http://stackoverflow.com/q/47073202
linked to: http://stackoverflow.com/q/49137
type: Question
has comment: http://stackoverflow.com/comment/81094615
has comment: http://stackoverflow.com/comment/81094616
duplicate of: http://stackoverflow.com/q/49137
tagged with: c++
has comment: http://stackoverflow.com/comment/81095156
score: 0
answer count: 0
has title: use the return value of a python function through a c++ script
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81095307
has comment: http://stackoverflow.com/comment/81094840
has body: I would like to call a python function through a c++ script. I know how to call a c++ function in a python code but no the other way. for example, I would like to use the return value of this python function in a c++ script like this: import pandas as pd def concat(x1,x2): a = pd.DataFrame(pd.concat([pd.DataFrame(x1), pd.DataFrame(x2)], axis=1)) return a # void Foot::update(){ ccerr &lt;&lt; "Merge " &lt;&lt; PLate-&gt;me-&gt;vertIncl &lt;&lt; endl; con[a] = concat(model-&gt;getA(),model-&gt;getB())} Is it possible?
has comment: http://stackoverflow.com/comment/81094732

http://stackoverflow.com/comment/85840560
type: AnswerComment
has text: This didn't work for me initially. However, I tried editing google-cloud-sdk/lib/googlecloudsdk/core/resource/resource_projector.py to see what was going in that file and found that making just a tiny change (adding a new line for example) was enough to make everything work again. I guess the system needs a nudge to use the new protobuf?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48255247

http://stackoverflow.com/q/47206481
type: Question
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47206739
has body: I have written some code that contains several while loops. answer = "yes" while answer == "yes": name = input("what is your name?") while len(name) &gt; 0 and name.isalpha(): print("okay") break else: print("error") continue job = input("what is your job?") while job.isalpha(): print("great") else: print("not so great") continue age = input("how old are you?") while age.isnumeric(): print('nice') else: print("not so nice") continue What I want the code to do is check for a valid name entry, and if it is invalid re-ask the user for their name. I want it to do the same thing with their job. Unfortunately, when I use continue after the job statement, instead of just re-asking for their job, it re-asks for their name as well. Does anyone know how to make it only re-ask for the job, and not re-do the whole program? Does anyone know how I could replicate this for multiple while loops I.e. Asking for job, name, age, star sign etc.? Thank you.
has comment: http://stackoverflow.com/comment/81361880
score: 0
has comment: http://stackoverflow.com/comment/81361853
has answer: http://stackoverflow.com/a/47206657
tagged with: python
has title: Use of continue in python - how to break out of an individual loop?

http://stackoverflow.com/a/47212723
upvote count: 2
has body: What is usually done is saving a scale object as you may read here. Here is how you could save scale object: from sklearn.externals import joblib joblib.dump(scale, 'filename.pkl') and here is how you could reload it: scale = joblib.load('filename.pkl') When predicting new data - it's the best to reload scaler - scale data accordingly and then to use your model. You could even create a new class with scaler kept and saved like keras.model.
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47208048

http://stackoverflow.com/q/47081088
has answer: http://stackoverflow.com/a/50984173
tagged with: python
score: 11
upvote count: 11
has body: I am trying to truncate a postgres destination table prior to insert, and in general, trying to fire external functions utilizing the connections already created in GLUE. Has anyone been able to do so?
answer count: 4
has answer: http://stackoverflow.com/a/72750988
possible better answer: http://stackoverflow.com/a/72750988
downvote count: 0
accepted answer: http://stackoverflow.com/a/50984173
has answer: http://stackoverflow.com/a/56148807
has answer: http://stackoverflow.com/a/62707286
favorite count: 0
type: Question
has title: AWS Glue - Truncate destination postgres table prior to insert
has comment: http://stackoverflow.com/comment/82716920
has comment: http://stackoverflow.com/comment/87043584
type: AnsweredQuestion
tagged with: postgresql
linked to: http://stackoverflow.com/q/47556678
tagged with: aws-glue
tagged with: pyspark

http://stackoverflow.com/comment/81263770
comment on: http://stackoverflow.com/q/47156680
type: QuestionComment
type: Comment
has text: @Adriano Yeah, I removed the redundant non-capturing group from the end. The `s?` is not important as I understand only the number itself is what OP needs to get in the end.
score: 0

http://stackoverflow.com/q/47161162
tagged with: arrays
score: -3
has comment: http://stackoverflow.com/comment/81271877
has comment: http://stackoverflow.com/comment/81271884
tagged with: python
has comment: http://stackoverflow.com/comment/81272222
upvote count: 0
has comment: http://stackoverflow.com/comment/81272712
downvote count: 3
has comment: http://stackoverflow.com/comment/81272152
has comment: http://stackoverflow.com/comment/81272623
answer count: 1
has title: Stuck programming with arrays in Python
has comment: http://stackoverflow.com/comment/81272172
tagged with: coordinates
has comment: http://stackoverflow.com/comment/81272470
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81272112
tagged with: numpy
has comment: http://stackoverflow.com/comment/81272155
has comment: http://stackoverflow.com/comment/81272013
has comment: http://stackoverflow.com/comment/81272097
type: UnansweredQuestion
has body: For an assignment, we have to input an airplane wing thickness to length ratio, generate an x array of evenly spaced 20 points from 0 to 1, calculate the y coordinates (with the equation in my code below), and clearly display them back to the user. I've gotten started, but I am completely lost even after looking at other user questions about how to use arrays in Python. My question is: where do I go from here? Here is my code so far: import numpy import math x = numpy.array([0, 1, 0.05]) y = 0 sqrt = x**(0.5) tString = input("What is the thickness to length ratio (as a decimal)?") t = float(tString) y = (5*t)*((0.2969*sqrt) - (0.1260*x) - (0.3516*(x**2)) + (0.2843*(x**3)) - (0.1015*(x**5)))
has answer: http://stackoverflow.com/a/47162150

http://stackoverflow.com/comment/81226332
type: Comment
type: QuestionComment
has text: I think that is the gunicorn picking the port, but I'm not entirely sure. What happens if you specify port where you also specify host? `app.run(host='0.0.0.0', debug=True, port=1337)`
comment on: http://stackoverflow.com/q/47137356
score: 0

http://stackoverflow.com/a/47092633
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47092567
type: Answer
has body: Use mask with fillna: df['A'] = df['A'].mask(df['B'] == 0, df['A'].fillna(3)) Alternatives with loc, numpy.where: df.loc[df['B'] == 0, 'A'] = df['A'].fillna(3) df['A'] = np.where(df['B'] == 0, df['A'].fillna(3), df['A']) print (df) A B 0 3.0 0 1 3.0 0 2 0.0 0 3 NaN 1 4 NaN 1
answers question: http://stackoverflow.com/q/47092567
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/81329159
comment on: http://stackoverflow.com/a/47189850
type: Comment
score: 0
type: AnswerComment
has text: The code is outputting incorrect an please proceed before the question is asked.Why?

http://stackoverflow.com/comment/81330888
score: 0
has text: Applying the regex supplied by @Juan , this seems to do the trick: `re.split("(.+)\.(.+) (.+):(.+)", line)[1:5]`
comment on: http://stackoverflow.com/q/47190553
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81122411
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47086372
has text: XML isn't suitable for random access. That said, a few hundred megabytes should be tolerable with LXML + an xpath query to pull out the bits you care about.

http://stackoverflow.com/q/47096651
type: Question
tagged with: numpy
score: 5
has title: Elegant way to compare to torch.FloatTensor on GPU
tagged with: tensor
has answer: http://stackoverflow.com/a/47207031
accepted answer: http://stackoverflow.com/a/47207031
upvote count: 5
tagged with: python
has body: I try to compare two torch.FloatTensor (with only one entry) lying on GPU like this: if (FloatTensor_A > FloatTensor_B): do something The problem is, that (FloatTensor_A &gt; FloatTensor_B) gives ByteTensor back. Is there a way to do boolean comparison between these two scalar FloatTensors, without loading the tensors on CPU and converting them back to numpy or conventional floats?
type: AnsweredQuestion
tagged with: boolean
has comment: http://stackoverflow.com/comment/81181335
answer count: 2
tagged with: pytorch
has comment: http://stackoverflow.com/comment/81214847
downvote count: 0
has comment: http://stackoverflow.com/comment/81350487
has answer: http://stackoverflow.com/a/47105868
possible better answer: http://stackoverflow.com/a/47105868
favorite count: 0

http://stackoverflow.com/q/47104901
has comment: http://stackoverflow.com/comment/81160760
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81160544
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47109589
accepted answer: http://stackoverflow.com/a/47109589
score: 1
tagged with: http://stackoverflow.com/tag/pdf
linked to: http://stackoverflow.com/q/19453338
tagged with: python
has comment: http://stackoverflow.com/comment/81160612
linked to: http://stackoverflow.com/q/1679798
type: AnsweredQuestion
has body: Is there a newer way to open a PDF using an external viewer from Python 3 in Linux other than subprocess? This sounds like a noobish and duplicate question, but I looked at this question and this question, and all of the answers are over 7 years old and recommended discouraged methods like os.system, old methods like manually creating a subprocess.Popen or Windows-only methods like os.startfile. So in the time since these questions were answered, have preferred methods of launching a PDF reader from within Python emerged, or are these still the best answers?
downvote count: 0
has comment: http://stackoverflow.com/comment/81160391
upvote count: 1
has comment: http://stackoverflow.com/comment/81160811
has comment: http://stackoverflow.com/comment/81160451
has title: Preferred Method of Opening a PDF in Python 3
answer count: 1
linked to: http://stackoverflow.com/q/434597

rx-py
tag name: rx-py
type: Tag
tags question: http://stackoverflow.com/q/47124972

http://stackoverflow.com/a/47138374
upvote count: 4
downvote count: 0
score: 4
has body: Nevermind, found it: ar3=ar2[~np.isnan(ar2).any(axis=1)] Thanks anyway
type: Answer
answers question: http://stackoverflow.com/q/47138318

http://stackoverflow.com/comment/81183644
has text: Yeah, so you would just drop counts greater than 20, then groupby the count and divided by the length of initial dataframe ..
comment on: http://stackoverflow.com/q/47116484
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81245245
type: AnswerComment
comment on: http://stackoverflow.com/a/47123331
type: Comment
has text: I'm selecting your answer as it's the most actionable and directionable. Thank you!
score: 0

linux
tags question: http://stackoverflow.com/q/47201502
tags question: http://stackoverflow.com/q/47090964
tags question: http://stackoverflow.com/q/47202790
tags question: http://stackoverflow.com/q/47075723
tags question: http://stackoverflow.com/q/47110606
tags question: http://stackoverflow.com/q/47130246
tags question: http://stackoverflow.com/q/47090170
tags question: http://stackoverflow.com/q/47213526
tags question: http://stackoverflow.com/q/47145750
tags question: http://stackoverflow.com/q/47092750
tag name: linux
tags question: http://stackoverflow.com/q/47111880
tags question: http://stackoverflow.com/q/47180843
tags question: http://stackoverflow.com/q/47216910
tags question: http://stackoverflow.com/q/47205334
tags question: http://stackoverflow.com/q/47128326
tags question: http://stackoverflow.com/q/47208409
tags question: http://stackoverflow.com/q/47095053
tags question: http://stackoverflow.com/q/47144548
tags question: http://stackoverflow.com/q/47065831
tags question: http://stackoverflow.com/q/47142536
tags question: http://stackoverflow.com/q/47120873
tags question: http://stackoverflow.com/q/47119114
tags question: http://stackoverflow.com/q/47088746
tags question: http://stackoverflow.com/q/47136965
tags question: http://stackoverflow.com/q/47205923
tags question: http://stackoverflow.com/q/47210998
tags question: http://stackoverflow.com/q/47193026
tags question: http://stackoverflow.com/q/47160966
tags question: http://stackoverflow.com/q/47132966
tags question: http://stackoverflow.com/q/47164834
tags question: http://stackoverflow.com/q/47200971
tags question: http://stackoverflow.com/q/47077093
tags question: http://stackoverflow.com/q/47199121
tags question: http://stackoverflow.com/q/47178796
type: Tag
tags question: http://stackoverflow.com/q/47118453
tags question: http://stackoverflow.com/q/47198250
tags question: http://stackoverflow.com/q/47178948
tags question: http://stackoverflow.com/q/47217105
tags question: http://stackoverflow.com/q/47070435
tags question: http://stackoverflow.com/q/47212940
tags question: http://stackoverflow.com/q/47190283
tags question: http://stackoverflow.com/q/47155173

http://stackoverflow.com/comment/81536432
comment on: http://stackoverflow.com/a/47262847
type: AnswerComment
has text: This (setting the kernel_spec_manager_class value in config) is done automatically by the nb_conda_kernels.install module (see https://github.com/Anaconda-Platform/nb_conda_kernels/blob/3478523f366b11dd62ed6bd1535196c7c5a7e8c5/nb_conda_kernels/install.py#L76-L77), which is called automatically as part of the conda package installation (see the post-link script in the conda recipe at https://github.com/Anaconda-Platform/nb_conda_kernels/blob/3478523f366b11dd62ed6bd1535196c7c5a7e8c5/conda.recipe/post-link.sh)
score: 0
type: Comment

http://stackoverflow.com/comment/81406886
comment on: http://stackoverflow.com/a/47223451
type: Comment
score: 0
type: AnswerComment
has text: Hey, sorry, I sent the message unfinished by mistake and didn't have time to correct it. There is one case in which I want to use a string in the last tick to show the greater than or equal sign (for example ">=10"). Using "plt.norm" gives an error because it only works with numbers. Is it possible to make your solution work in that case?

http://stackoverflow.com/a/47088129
type: Answer
answers question: http://stackoverflow.com/q/47088007
score: 0
type: AcceptedAnswer
has body: In the GitHub Repo for Tensorflow, if you look at the two __init__.py files inside tensorflow-master/tensorflow/python/keras/ and tensorflow-master/tensorflow/python/keras/layers/, you can see which modules are imported as part of the package structure. This determines what and how you as a user import things when using the package and its modules. David Beazley has a really good talk on the innerworkings of this: https://www.youtube.com/watch?v=0oTh1CXRaQ0
has comment: http://stackoverflow.com/comment/81126035
accepted answer of: http://stackoverflow.com/q/47088007

http://stackoverflow.com/q/47149906
answer count: 0
has comment: http://stackoverflow.com/comment/81249585
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81249659
has body: I want to take a benchmark of the time it takes to sort large amounts of data using MergeSort, and I have the following script which opens several text files, reads them, and turns every line (which is a random integer between 1 and 999) into an integer element within a list. data = [] for file in ["10.txt", "100.txt", "1000.txt", "10000.txt", "100000.txt", "1000000.txt", "10000000.txt", "100000000.txt"]: tempList = [] with open(file) as myfile: for line in myfile: tempList.append(int(line.rstrip())) data.append(tempList) However, the issue is I get a memory error when trying to add 100,000,000 elements to a list. FileIO aside, I tried something alone the lines of this: data = [] for limit in [10, 100, 1000, 10000, 100000, 1000000, 10000000, 10000000]: tempList = [] for i in range(limit): tempList.append(random.randint(1,999)) data.append(tempList) However, the same issue occurs; it simply can't handle 100 million items. Is this an issue with my machine (mine is fairly high end). Is there any more efficient way to do this?
type: Question
tagged with: out-of-memory
has title: avoiding memoryError when dealing with large datasets in python
has comment: http://stackoverflow.com/comment/81249621
tagged with: python
has comment: http://stackoverflow.com/comment/81251287
tagged with: memory
has comment: http://stackoverflow.com/comment/81249587
has comment: http://stackoverflow.com/comment/81249673
has comment: http://stackoverflow.com/comment/81249834
score: 0
has comment: http://stackoverflow.com/comment/81286434

http://stackoverflow.com/q/47143521
favorite count: 0
type: AnsweredQuestion
upvote count: 19
has comment: http://stackoverflow.com/comment/139803670
tagged with: conv-neural-network
tagged with: batch-normalization
accepted answer: http://stackoverflow.com/a/47143624
answer count: 3
has body: I have the following architecture: Conv1 Relu1 Pooling1 Conv2 Relu2 Pooling3 FullyConnect1 FullyConnect2 My question is, where do I apply batch normalization? And what would be the best function to do this in TensorFlow?
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/47143624
has answer: http://stackoverflow.com/a/65741559
has answer: http://stackoverflow.com/a/59939495
possible better answer: http://stackoverflow.com/a/59939495
has title: Where to apply batch normalization on standard CNNs
downvote count: 0
tagged with: machine-learning
tagged with: python
score: 19
linked to: http://stackoverflow.com/q/34716454

http://stackoverflow.com/q/47152610
has comment: http://stackoverflow.com/comment/81257542
tagged with: machine-learning
tagged with: scikit-learn
tagged with: python
possible better answer: http://stackoverflow.com/a/60396595
has comment: http://stackoverflow.com/comment/138388299
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/64742353
upvote count: 38
has answer: http://stackoverflow.com/a/73588475
has title: What is the difference between xgb.train and xgb.XGBRegressor (or xgb.XGBClassifier)?
accepted answer: http://stackoverflow.com/a/47243394
tagged with: xgboost
downvote count: 1
favorite count: 0
has body: I already know "xgboost.XGBRegressor is a Scikit-Learn Wrapper interface for XGBoost." But do they have any other difference?
has answer: http://stackoverflow.com/a/60396595
type: Question
score: 37
has answer: http://stackoverflow.com/a/47243394
tagged with: regression

http://stackoverflow.com/comment/81294192
has text: I like this as well.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47172385
score: 0

http://stackoverflow.com/a/47209654
upvote count: 7
score: 7
type: Answer
accepted answer of: http://stackoverflow.com/q/47209598
answers question: http://stackoverflow.com/q/47209598
has body: my_salary = 55.000 is your problem. You've defined a float with the value of 55.000 (fifty-five), not 55,000. Change this line to my_salary = 55000
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81478326
type: Comment
comment on: http://stackoverflow.com/a/47141356
type: AnswerComment
has text: @shukshin.ivan Thanks for the comment. I didn't test the mercator.py thoroughly, indeed, it is possible the implementation is not precise enough, but it demonstrates the idea. I will have a look once I have some free time.
score: 0

http://stackoverflow.com/comment/81380078
score: 0
type: AnswerComment
has text: Ah thanks. Yeah I ended up trying it again, and it didn't make a notable difference, but I think your expression fits the use case better. I think it ends up being an issue of html being god-awful to run regular expressions over. I also wanted to capture anything inside the p element in a non-greedy fashion. May have been unclear
type: Comment
comment on: http://stackoverflow.com/a/47215202

http://stackoverflow.com/a/47087118
has comment: http://stackoverflow.com/comment/81124224
has comment: http://stackoverflow.com/comment/81125167
answers question: http://stackoverflow.com/q/47086990
score: 0
has body: If the current prefix matches all the entered names, you add one more character to it. When it fails to match, you break out of the loop - but the character that caused the failure is still attached to the end of prefix. There are various ways to fix this, but one possibility is to just remove the last character by adding this statement outside the loop: prefix = prefix[:-1] # python slice notation - remove the last element There are some style issues with your code. Those would be best addressed on CodeReview rather than Stackoverflow. I would have done it this way (after replacing your input statements with a hard-coded test case): x = ["Joseph", "Jose", "Josie", "Joselyn"] n = 0 try: while all(a[n] == x[0][n] for a in x[1:]): n += 1 except IndexError: pass print(x[0][:n]) This script prints "Jos".
has comment: http://stackoverflow.com/comment/81162163
has comment: http://stackoverflow.com/comment/81124067
type: Answer

http://stackoverflow.com/comment/81163472
type: Comment
has text: that did it. Thanks for the help
type: QuestionComment
comment on: http://stackoverflow.com/q/47106291
score: 0

http://stackoverflow.com/comment/81177696
score: 0
comment on: http://stackoverflow.com/q/47113097
has text: Is this using your script or using the script in my answer?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47127813
type: Answer
has comment: http://stackoverflow.com/comment/81205784
has comment: http://stackoverflow.com/comment/81205851
has comment: http://stackoverflow.com/comment/81205823
answers question: http://stackoverflow.com/q/47127761
score: 0
has body: You can make a dict right of the bat with a dict comp and than iterate the list to print as you wanted. What you had done was create a list, which does not have an items() method. with open('notepad.txt') as f: d = {line.split(' ')[0]:line.split(' ')[1] for line in f} for k,v in d.items(): print("Key : {0}, Value: {1}".format(k,v))
has comment: http://stackoverflow.com/comment/81205859
has comment: http://stackoverflow.com/comment/81205914
has comment: http://stackoverflow.com/comment/81205893
has comment: http://stackoverflow.com/comment/81205835
has comment: http://stackoverflow.com/comment/81205926
has comment: http://stackoverflow.com/comment/81205873

http://stackoverflow.com/q/47119525
has comment: http://stackoverflow.com/comment/81188804
has comment: http://stackoverflow.com/comment/81190676
tagged with: bigdata
answer count: 1
has comment: http://stackoverflow.com/comment/81188940
has body: I am using python 2.7 with dask dataframe I have a df that is too big for memory but fits into disk beautifully. I group by an index, and than need to iterate over the groups, I found here how to do it. When I try to use the suggested code: for value in drx["col"].unique(): print value I get an error File "/usr/local/lib/python2.7/dist-packages/dask/dataframe/core.py", line 1709, in getitem raise NotImplementedError() NotImplementedError Assuming that it's not implemented, I found the way to iterate the series I get using unique() is this But when I try to utilize it like so: data = table["col"].unique() it = data.iteritems() for val in it: print 1 My memory explodes as if all the values of the columns are saved in memory for as long as I use the iterator. How can I use the iterator values without saving all of them into memory?
linked to: http://stackoverflow.com/q/39731098
favorite count: 0
has comment: http://stackoverflow.com/comment/81188978
has answer: http://stackoverflow.com/a/47121655
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: database
tagged with: dataframe
tagged with: python
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/47121655
tagged with: dask
has title: Python dask iterate series.unique() values lazily

http://stackoverflow.com/q/47153044
upvote count: 1
tagged with: fsm
answer count: 1
accepted answer: http://stackoverflow.com/a/47316973
favorite count: 0
type: Question
tagged with: pygraphviz
score: 1
tagged with: python
has title: Python Transitions: how to map all possible transitions of an FSM to a graph
tagged with: graphviz
tagged with: transition
has answer: http://stackoverflow.com/a/47316973
has body: I couldn't install pygraphviz on my Windows 10 system so as a workaround I am trying to store the states and transitions of the FSM in a separate graph. For example: from transitions import Machine from graphviz import Digraph class Matter(object): pass # The states states=['hungry', 'satisfied', 'full', 'sick'] # And some transitions between states. transitions = [ { 'trigger': 'eat', 'source': 'hungry', 'dest': 'satisfied' }, { 'trigger': 'eat', 'source': 'satisfied', 'dest': 'full' }, { 'trigger': 'eat', 'source': 'full', 'dest': 'sick' }, { 'trigger': 'rest', 'source': ['satisfied', 'full', 'sick'], 'dest': 'hungry' }] # Initialize machine = Matter() fsm = Machine(machine, states=states, transitions=transitions, initial=states[0]) dot = Digraph(comment='FSM') src = machine.state for event in transitions: machine.trigger(event['trigger']) dst = machine.state dot.edge(src,dst,event['trigger']) src = dst print (dot) Here my graph doesn't include all the possible transitions and includes only the sequential transitions. Output: digraph { hungry -&gt; satisfied [label=eat] satisfied -&gt; full [label=eat] full -&gt; sick [label=eat] sick -&gt; hungry [label=rest] } As you can see the multiple state transitions are not present in the graph. Is there a way I can trigger all the transitions and store it in the graph or do I have to write a custom code for all of this to work.
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/81095852
comment on: http://stackoverflow.com/a/47073633
type: Comment
type: AnswerComment
has text: Correct, it works perfect, thanks mate. It was very helpful!
score: 0

http://stackoverflow.com/q/47193745
type: Question
has comment: http://stackoverflow.com/comment/81337492
has comment: http://stackoverflow.com/comment/81337243
has comment: http://stackoverflow.com/comment/92265852
upvote count: 9
has answer: http://stackoverflow.com/a/68616272
type: UnansweredQuestion
downvote count: 2
has body: I tried to use Requests library in Python for crawling. I first imported the requests module, then I use the get function to call the website for getting a response named r, but I can not understand why the type of r is class. Could you please tell me why? I also want to check the request header, I checked some documents, it says that I can use r.request.headers, what does the request here mean, is it a method? >>> import requests >>> r=requests.get("http://www.baidu.com") >>> type(r) <class 'requests.models.Response'>
tagged with: python
has answer: http://stackoverflow.com/a/70601744
tagged with: python-requests
answer count: 4
tagged with: class
has title: For python, what does it mean for <class 'requests.models.Response'>
has answer: http://stackoverflow.com/a/47193790
has comment: http://stackoverflow.com/comment/81336568
has answer: http://stackoverflow.com/a/68532975
has comment: http://stackoverflow.com/comment/81336600
score: 7
has comment: http://stackoverflow.com/comment/81336570
has comment: http://stackoverflow.com/comment/81336571
has comment: http://stackoverflow.com/comment/81363129
linked to: http://stackoverflow.com/q/27803503
favorite count: 0

http://stackoverflow.com/a/47102942
has comment: http://stackoverflow.com/comment/112838104
answers question: http://stackoverflow.com/q/47101566
has comment: http://stackoverflow.com/comment/112810421
type: Answer
has body: I'm a dummy. MrJLP was correct, changing my environment to 2.7 allowed me to install with no problems.
score: -1
upvote count: 0
downvote count: 1

http://stackoverflow.com/comment/81183283
type: QuestionComment
has text: Tkinter does have radiobuttons [link](http://effbot.org/tkinterbook/radiobutton.htm)
score: 0
comment on: http://stackoverflow.com/q/47116602
type: Comment

http://stackoverflow.com/comment/81344455
score: 2
comment on: http://stackoverflow.com/a/47197865
type: AnswerComment
has text: You realize, btw, that `__call__` is never actually being *called*, right? I.e., nothing you wrote in `__call__` is doing anything...
type: Comment

http://stackoverflow.com/a/47161544
answers question: http://stackoverflow.com/q/47159610
type: Answer
score: 0
has body: Assuming that you get the error AttributeError: 'NoneType' object has no attribute 'strip' You just need to exclude the None objects from being stripped. for item in patch_message: if item.text: print item.text.strip()

http://stackoverflow.com/a/47118617
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81187086
has body: Try using get(): webbrowser.get('chrome').open('https://www.youtube.com') EDIT Make sure to use the full path to the site
has comment: http://stackoverflow.com/comment/81187175
score: 2
accepted answer of: http://stackoverflow.com/q/47118598
has comment: http://stackoverflow.com/comment/81187162
has comment: http://stackoverflow.com/comment/81187057
type: Answer
answers question: http://stackoverflow.com/q/47118598
has comment: http://stackoverflow.com/comment/81187124
upvote count: 2

http://stackoverflow.com/comment/81134469
score: 0
type: Comment
type: QuestionComment
has text: Is the above code, your complete code which you can show us? If there is more code, please show me.
comment on: http://stackoverflow.com/q/47091374

http://stackoverflow.com/comment/81123230
type: Comment
has text: @Wen Yes, it works! :) My only concern is the difference in results. For example, the first row gives 0.490 when I use your code. But the other code (TI_row=(2.718281+(table['eventid']+table['nkill']+table['nwound'])/3), TI=np.log10(TI_row)) and Excel give 0.484. Not a big difference but still not good for the research purpose
comment on: http://stackoverflow.com/a/47083621
score: 0
type: AnswerComment

http://stackoverflow.com/a/47082266
has comment: http://stackoverflow.com/comment/81205748
has comment: http://stackoverflow.com/comment/81119770
has body: You can build a forest of prefix tries and then search of "height" (how far is it from the root) of the deepest node with two (non-null) children. This node represents the longest common prefix. If you don't care about performance, you can simply iterate all the words in the list and compare each one of them (its prefix) to the rest while keeping updating the max: def common_prefix_size(s1, s2): res, i = 0, 0 while i &lt; min(len(s1), len(s2)): if s1[i] == s2[i]: res += 1 i += 1 else: break return res def longest_prefix(lst): res = '' maxsize = 0 for i in range(len(lst) - 1): for j in range(i + 1, len(lst)): t = common_prefix_size(lst[i], lst[j]) maxsize = max(maxsize, t) if maxsize == t: res = lst[i][:maxsize] return res myList = ["foo", "foobar", "football", "footbag", "bar"] print(longest_prefix(myList)) # footba
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/81209783
has comment: http://stackoverflow.com/comment/81115191
downvote count: 0
has comment: http://stackoverflow.com/comment/81202310
has comment: http://stackoverflow.com/comment/81121961
has comment: http://stackoverflow.com/comment/81202743
answers question: http://stackoverflow.com/q/47082106
type: Answer

http://stackoverflow.com/comment/81158585
has text: Wait why do you need the second line anyway? Later on you have tweepy.OAuthHandler?
type: Comment
comment on: http://stackoverflow.com/a/47103691
type: AnswerComment
score: 0

http://stackoverflow.com/comment/132041059
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47119476
has text: Thanks Thomas, In my case I added an infinite loop with some safeguards that manually sends a message in the ping format the server needs. Feels hacky but doesn't seem to be any other workaround save forking that i can see. Cheers
type: Comment

http://stackoverflow.com/comment/81124798
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47086735
type: Comment
has text: @olooney. No, `__iter__` is not sufficient to define a mapping, and is not needed at all for unpacking.

http://stackoverflow.com/comment/81278233
type: Comment
has text: I think you should go into more detail on what you want to achieve. If you know how to use `annotate` to plot different arrow, show a [mcve] and clearly state what hinders you in using a colormap for their color.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47163796

http://stackoverflow.com/q/47188417
has answer: http://stackoverflow.com/a/47192063
tagged with: list
answer count: 3
tagged with: algorithm
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47190207
accepted answer: http://stackoverflow.com/a/47188481
has answer: http://stackoverflow.com/a/47188481
has title: merging entries in Python list
possible better answer: http://stackoverflow.com/a/47190207
type: Question
score: 0
has body: Suppose I have a list test = ['a','b','b','b','a','b','a','a','b','b']. If I want to combine all the adjacent 'b' together to get test2 = ['a','b','a','b','a','a','b'], then what is the most efficient and elegant way of doing it?
tagged with: python

http://stackoverflow.com/a/47189514
has body: To end up with a list of numbers instead of strings, I recommend the following: a = [] for line in open("Input.txt"): li=line.strip() if li.startswith("point_load"): l = li.split(',') for num in l[1:]: try: num = float(num.strip()) a.append(num) except ValueError: print 'num was not a number' The difference here is the list slice which takes the entire line starting from the second comma-separated element (more here: understanding-pythons-slice-notation) l[1:] Also, stripping then converting the strings to floats (since you have decimals) num = float(num.strip()) Resulting array: a = [3.0, -300.0, 6.5, 500.0]
has comment: http://stackoverflow.com/comment/81359439
answers question: http://stackoverflow.com/q/47189319
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/81331631

http://stackoverflow.com/comment/81239755
has text: Thank you! it worked when opening CMD in ADMINISTRATOR mode.
type: QuestionComment
comment on: http://stackoverflow.com/q/47144719
score: 0
type: Comment

http://stackoverflow.com/comment/81359681
type: Comment
comment on: http://stackoverflow.com/a/47198682
has text: It loads the pdf alright but calling the setCurrentPage is what causes the error
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81389400
has text: I engulfed my code in a for loop of range 10000, and it took 0.04 seconds (2.2GHz 64 bit Ubuntu Python 3.5.2) if I remove *print* statement and replace it with `s=s+(int(n)-10**(length-1)+1)*length`. If I print 10000 times, then it takes 0.1 sec. But anyway , *NOICE*!!
type: Comment
comment on: http://stackoverflow.com/a/47219531
score: 0
type: AnswerComment

http://stackoverflow.com/q/47117629
tagged with: python
has comment: http://stackoverflow.com/comment/81185499
has comment: http://stackoverflow.com/comment/81185734
has answer: http://stackoverflow.com/a/47126260
score: 0
has comment: http://stackoverflow.com/comment/81186875
answer count: 2
tagged with: tkinter
has body: Is there a way I can make the opening of the cmd window optional in a python GUI app, like if option xyz is given, open an cmd window otherwise don't? import sys import tkinter master = tkinter.Tk() #tk gui stuff goes here if sys.argv[1] == "console": #open cmd winow master.mainloop() I was planning to only open the cmd window if the user wants to see the debugging output etc.
has comment: http://stackoverflow.com/comment/81185535
has title: Make opening of cmd window optional in a tkinter app?
has comment: http://stackoverflow.com/comment/81185362
type: Question
has answer: http://stackoverflow.com/a/47123938
type: UnansweredQuestion

http://stackoverflow.com/comment/81212047
type: Comment
has text: Yes, it works if I add this into ServerSerializer class, what I try to do is impletement parent class for these kind of serializer, would you mind to show me how to do it?
type: AnswerComment
comment on: http://stackoverflow.com/a/47120048
score: 0

http://stackoverflow.com/a/47218340
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81413236
downvote count: 0
has comment: http://stackoverflow.com/comment/81403015
accepted answer of: http://stackoverflow.com/q/47213246
has comment: http://stackoverflow.com/comment/81448944
has comment: http://stackoverflow.com/comment/81660384
has body: If you need to measure the properties of different regions, it is natural to start with finding the regions (not contours). The algorithm will be the following, in this case: Prepare a labeled image: 1.a Either fill the areas between different contour lines with the different colors; 1.b Or apply some image thresholding function, and then run skimage.measure.label (http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.label); Execute regionprops using the very labeled image as an input (http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.regionprops); Iterate over regions in regionprops and calculate the desired parameters (area, perimeter, etc). Once you identified the regions in your image via regionprops, you can call .coords for each of them to get the enclosed contour.
answers question: http://stackoverflow.com/q/47213246
has comment: http://stackoverflow.com/comment/81448849
has comment: http://stackoverflow.com/comment/81448746
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/81172997
has text: the answer should include as many peoples from the last row ,and the sum should <= 5
comment on: http://stackoverflow.com/q/47111361
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/47107322
has body: Use a list comprehension to add |, then join(): ''.join([x+'|' for x in my_list]) # abc,1234,,ickd,sold|yeje,38393,,dkdi,eole|euei,38393,,idkd,dikd| Simply using '|'.join() won't get you the final | you require.
answers question: http://stackoverflow.com/q/47107228
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/a/47166685
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47165595
has body: Try This ( I wrote a Class for You with fully error_handling, you can write this Code more efficient ... with BeautifulSoup or another package ( does not work for private user! ) ): import requests, json class SteamGameGrabber(object): def __init__(self): self.url = '' self.headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} self.start_tag = "var rgGames" self.end_tag = "var rgChangingGames" self.last_data = {} def send_request(self): try: response = requests.get(self.url, headers=self.headers) raw_data = str(response.content, encoding="utf-8") except: return [False, "Something Wrong! Connection Lost!"] else: if response.status_code == 200: return [True, raw_data] else: return [False, "Check Your Connection ( status_code is Not 200 )!"] def pars_data(self, get_input): def find_between(s, first, last): try: start = s.index(first) + len(first) end = s.index(last, start) except: return [False, "Parsing Error"] else: return [True, s[start:end]] if " Steam Community :: Error " in get_input: return [False, "I Can Not Find This ID on Steam Server"] if ' ' in get_input: return [False, "This profile is private, I can not Decode it, sorry."] get_data = find_between(get_input, self.start_tag, self.end_tag) if get_data[0] is True: dict_data = json.loads(get_data[1].strip().lstrip("=").rstrip(";").strip()) try: for box in dict_data: game_id = str(box['appid']).strip() game_name = box['name'].strip() if game_name in self.last_data: pass else: self.last_data[game_name] = game_id except: return [False, "Format is Wrong"] else: return [True, self.last_data] else: return [False, get_data[1]] def call_all(self, get_id): if get_id.strip() == "": return "Please Insert Your Steam ID" else: self.url = 'http://steamcommunity.com/id/{0}/games/?tab=all'.format(get_id) get_state_1 = self.send_request() if get_state_1[0] is True: get_state_2 = self.pars_data(get_state_1[1]) return get_state_2[1] e…
type: Answer
answers question: http://stackoverflow.com/q/47165595
upvote count: 1
score: 1

http://stackoverflow.com/comment/81245423
type: Comment
comment on: http://stackoverflow.com/q/47147563
type: QuestionComment
has text: `byte = str` doesn't do what you think it does. Python doesn't require you to declare variables or their types, and that's not setting the type of `byte`.
score: 1

http://stackoverflow.com/comment/140090807
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47077829
has text: This question is similar to: [Cannot use Requests-Module on AWS Lambda](https://stackoverflow.com/questions/40741282/cannot-use-requests-module-on-aws-lambda). If you believe it’s different, please [edit] the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.
type: Comment

http://stackoverflow.com/comment/81143555
type: AnswerComment
comment on: http://stackoverflow.com/a/47096105
type: Comment
has text: @Sammy Then check for the first article node. Like this "//article[1]/div/p[contains(b/text(), 'anything')]"
score: 0

http://stackoverflow.com/a/47113937
type: Answer
has body: A simlar, but somewhat more compact solution. #! /usr/bin/env/python3 """ Count the occurence of each symbol. Each symbols occurs M times, make a list of the first M integers and store the symbol and the list in a dictionary. This is the group. Randomly permute each group and create a new temporary dictionary that contains the mod of N for each group element. Iterate over the original sequence and concate the two giving the result, popping element from the temporary dictionary. """ from collections import Counter from random import shuffle N = 3 seq = ["A", "B", "D", "C", "B", "C", "A", "B", "A", "C", "A", "D", "A", "D", "A"] symbol = Counter(seq) group = {key: list(range(count)) for key, count in symbol.items()} # Do some shuffling for s in range(10): for element_group in group.values(): shuffle(element_group) tmp_shuffle = {k: [e % N + 1 for e in g] for k, g in group.items()} grouped_seq = [e + str(tmp_shuffle[e].pop()) for e in seq] print(grouped_seq) Sample output from a run: ['A3', 'B3', 'D2', 'C2', 'B1', 'C1', 'A3', 'B2', 'A2', 'C3', 'A1', 'D3', 'A1', 'D1', 'A2'] ['A3', 'B3', 'D3', 'C1', 'B2', 'C2', 'A3', 'B1', 'A2', 'C3', 'A1', 'D2', 'A2', 'D1', 'A1'] ['A2', 'B1', 'D2', 'C1', 'B3', 'C3', 'A3', 'B2', 'A1', 'C2', 'A3', 'D3', 'A1', 'D1', 'A2'] ['A1', 'B2', 'D1', 'C1', 'B1', 'C2', 'A3', 'B3', 'A2', 'C3', 'A3', 'D2', 'A1', 'D3', 'A2'] ['A1', 'B3', 'D2', 'C3', 'B2', 'C2', 'A2', 'B1', 'A3', 'C1', 'A2', 'D1', 'A1', 'D3', 'A3'] ['A2', 'B1', 'D1', 'C3', 'B3', 'C2', 'A3', 'B2', 'A1', 'C1', 'A1', 'D3', 'A3', 'D2', 'A2'] ['A2', 'B1', 'D1', 'C1', 'B3', 'C3', 'A2', 'B2', 'A3', 'C2', 'A1', 'D3', 'A1', 'D2', 'A3'] ['A2', 'B3', 'D2', 'C1', 'B2', 'C3', 'A2', 'B1', 'A3', 'C2', 'A3', 'D3', 'A1', 'D1', 'A1'] ['A1', 'B3', 'D3', 'C2', 'B2', 'C1', 'A3', 'B1', 'A2', 'C3', 'A3', 'D1', 'A1', 'D2', 'A2'] ['A3', 'B2', 'D1', 'C3', 'B1', 'C1', 'A3', 'B3', 'A2', 'C2', 'A1', 'D2', 'A1', 'D3', 'A2']
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47112109

http://stackoverflow.com/comment/81320031
comment on: http://stackoverflow.com/q/47185461
has text: @Maxim I see, so you are saying I can run normalization for 1948 times, normalizing data with respoect to every example? But, I kind of don't understand how is that centering the data. Every example can have it's own min and max value right?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81182030
has text: @GPPK fair enough. Just reworked the question.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47115721
type: QuestionComment

http://stackoverflow.com/comment/81394682
has text: print calls `str` while dict's str conversion uses `repr` on its values.
score: 4
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47222436

http://stackoverflow.com/a/47123331
accepted answer of: http://stackoverflow.com/q/47106385
has body: tldr; http://scikit-learn.org/stable/auto_examples/ensemble/plot_partial_dependence.html I'd like to clear up some of the wording to make sure we're on the same page. Predictive power: what features significantly contribute to the prediction Feature dependence: are the features positively or negatively correlated, i.e., does a change in the feature X cause the prediction y to increase/decrease 1. Predictive power Your feature importance shows you what retains the most information, and are the most significant features. Power could imply what causes the biggest change - you would have to check by plugging in dummy values to see their overall impact, much like you would have to do with linear regression coefficients. 2. Correlation/Dependence As pointed out by @Tiago1984, it depends heavily on the underlying algorithm. XGBoost/GBM are additively building a committee of stubs (decision trees with a low number of trees, usually only one split). In a regression problem, the trees are typically using a criterion related to the MSE. I won't go into the full details, but you can read more here: https://medium.com/towards-data-science/boosting-algorithm-gbm-97737c63daa3. You'll see that at each step it calculates a vector for the "direction" of the weak learner, so you in principle know the direction of the influence from it (but keep in mind it may appear many times in one tree, in multiple steps of the additive model). But, to cut to the chase; you could just fix all your features apart from f19 and make a prediction for a range of f19 values and see how it is related to the response value. Take a look at partial dependency plots: http://scikit-learn.org/stable/auto_examples/ensemble/plot_partial_dependence.html There's also a chapter on it in Elements of Statistical Learning, Chapter 10.13.2.
answers question: http://stackoverflow.com/q/47106385
has comment: http://stackoverflow.com/comment/81210009
type: Answer
has comment: http://stackoverflow.com/comment/81245245
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81208086

http://stackoverflow.com/comment/81172993
type: Comment
score: 3
type: QuestionComment
has text: Thats not java, thats python
comment on: http://stackoverflow.com/q/47111513

http://stackoverflow.com/comment/81246127
score: 0
comment on: http://stackoverflow.com/q/47147857
type: Comment
has text: the subprocess.communicate() returns a tuple (stdoutdata, stderrdata). That is where the output of the process will be.
type: QuestionComment

http://stackoverflow.com/q/47122284
tagged with: statistics
has answer: http://stackoverflow.com/a/47125794
type: AnsweredQuestion
tagged with: math
has comment: http://stackoverflow.com/comment/81221209
tagged with: python
score: 1
accepted answer: http://stackoverflow.com/a/47189575
type: Question
has body: I have 4 different distributions which I've fitted to a sample of observations. Now I want to compare my results and find the best solution. I know there are a lot of different methods to do that, but I'd like to use a quantile-quantile (q-q) plot. The formulas for my 4 distributions are: where K0 is the modified Bessel function of the second kind and zeroth order, and &Gamma; is the gamma function. My sample style looks roughly like this: (0.2, 0.2, 0.2, 0.3, 0.3, 0.4, 0.4, 0.4, 0.4, 0.6, 0.7 ...), so I have multiple identical values and also gaps in between them. I've read the instructions on this site and tried to implement them in python. So, like in the link: 1) I sorted my data from the smallest to the largest value. 2) I computed "n" evenly spaced points on the interval (0,1), where "n" is my sample size. 3) And this is the point I can't manage. As far as I understand, I should now use the values I calculated beforehand (those evenly spaced values), put them in the inverse functions of my above distributions and thus compute the theoretical quantiles of my distributions. For reference, here are the inverse functions (partly calculated with wolframalpha, and as far it was possible): where W is the Lambert W-function and everything in brackets afterwards is the argument. The problem is, apparently there doesn't exist an inverse function for the first distribution. The next one would probably produce complex values (negative under the root, because b = 0.55 according to the fit) and the last two of them have a Lambert W-Function (where I'm unsecure how to implement them in python). So my question is, is there a way to calculate the q-q plots without the analytical expressions of the inverse distribution functions? I'd appreciate any help you could give me very much!
answer count: 3
has answer: http://stackoverflow.com/a/47189575
has comment: http://stackoverflow.com/comment/81203420
has title: How to generate a Q-Q plot manually without inverse distribution function in python
has comment: http://stackoverflow.com/comment/81241351
has answer: http://stackoverflow.com/a/47146605
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81230033
possible better answer: http://stackoverflow.com/a/47125794
favorite count: 0

http://stackoverflow.com/comment/81334339
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47192439
score: 0
has text: Yes computers do what they are told: `journal=[]`

http://stackoverflow.com/q/47067456
downvote count: 2
has body: Is there a way to count number of images(JPEG,PNG,JPG) in a pdf document through python?
favorite count: 0
type: Question
score: 0
tagged with: pdfminer
tagged with: python
has answer: http://stackoverflow.com/a/47068882
has title: Count Images in a pdf document through python
has answer: http://stackoverflow.com/a/47067638
answer count: 2
tagged with: pypdf
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/81287768
type: AnswerComment
comment on: http://stackoverflow.com/a/47168896
has text: I haven’t tried, but if I put ‘s.init_printing(use_latex=True)’ will it print it like in LaTeX just by using the dollar signs?
type: Comment
score: 0

http://stackoverflow.com/a/47169280
accepted answer of: http://stackoverflow.com/q/47169221
answers question: http://stackoverflow.com/q/47169221
has comment: http://stackoverflow.com/comment/81319140
has comment: http://stackoverflow.com/comment/81309606
type: Answer
score: 4
upvote count: 4
has body: Options The flask application is blocking your GUI. You have two options: threading/multithreading separate applications Multiple Threads It is possible to write tkinter applications with multiple threads, but you must take care to do it. tkinter must be run within the primary thread tkinter cannot be accessed or implemented from any thread other than the primary Separate Processes I would recommend using the subprocess module. If you separate our your functionality into two applications and use the subprocess module to start/stop the flask application, I think you will have what you want.
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47101566
has comment: http://stackoverflow.com/comment/81153776
tagged with: anaconda
score: 1
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81155026
tagged with: conda
has title: Problems installing geograpy with Anaconda Prompt
tagged with: python-newspaper
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81154813
upvote count: 2
type: UnansweredQuestion
has body: I am trying to use the geograpy module through the Anaconda Prompt. When I run pip install geograpy I get this warning that terminates the installation newspaper3k is in my AppData/Local/Continuum/Anaconda3/Lib/site-packages folder after I followed the instructions to install it on a non unix/linux machine but whenever I try to install geograpy I still get that error. How to I bypass this warning as I already have the newspaper3k requirement satisfied?
tagged with: geograpy
has answer: http://stackoverflow.com/a/47102942
has comment: http://stackoverflow.com/comment/92417582
downvote count: 1
linked to: http://stackoverflow.com/q/43535987
has comment: http://stackoverflow.com/comment/81153389

http://stackoverflow.com/q/47084179
upvote count: 4
score: 2
tagged with: image-segmentation
tagged with: deep-learning
downvote count: 2
answer count: 1
tagged with: image-processing
tagged with: machine-learning
has body: I am trying to train a network for multiclass segmentation and I want to use dice coefficient (See this) as loss function instead of cross entropy. You can have a look at the formula here (where S is segmentation and G is ground truth.) One naive simple solution is to take an average of the dice coefficient of each class and use that for loss function. This approach would not differentiate between classes with larger area against the classes with smaller number of pixels (voxels). Does anybody have any suggestions?
has title: How to calculate multi class dice coefficient for multiclass image segmentation?
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50976096

http://stackoverflow.com/a/47099786
has comment: http://stackoverflow.com/comment/81171599
has body: Your calibration is poorly estimated: as you can see, straight lines in the scene grid are not transformed to straight lines in the (allegedly) undistorted image. Once you have a better calibration, you can compute (using the inverse mapping) the location of the 4 sides of the undistorted image in the original ones. These define your usable image boundaries, and can guide the placement of the camera with respect to the scene.
answers question: http://stackoverflow.com/q/47081309
has comment: http://stackoverflow.com/comment/81186726
type: Answer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47081309
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/47209532
has comment: http://stackoverflow.com/comment/81396891
downvote count: 0
has answer: http://stackoverflow.com/a/47210268
upvote count: 4
favorite count: 0
tagged with: lapack
type: Question
tagged with: numpy
has title: NumPy + BLAS + LAPACK on GPU (AMD and Nvidia)
answer count: 2
tagged with: blas
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48100987
score: 4
has body: We have a Python code which involves expensive linear algebra computations. The data is stored in NumPy arrays. The code uses numpy.dot, and a few BLAS and LAPACK functions which are currently accessed through scipy.linalg.blas and scipy.linalg.lapack. The current code is written for CPU. We want to convert the code so that some of the NumPy, BLAS, and LAPACK operations are performed on a GPU. I am trying to determine the best way to do this is. As far as I can tell, Numba does not support BLAS and LAPACK functions on the GPU. It appears that PyCUDA may the best route, but I am having trouble determining whether PyCUDA allows one to use both BLAS and LAPACK functions. EDIT: We need the code to be portable to different GPU architectures, including AMD and Nvidia. While PyCUDA appears to offer the desired functionality, CUDA (and hence, PyCUDA) cannot run on AMD GPUs.

http://stackoverflow.com/comment/81207681
score: 0
has text: Why can't you just do `@app.route('/video_feed') def video_feed(): return redirect("http://cemrcam1.cemr.wvu.edu/nphMotionJpeg?resolution=640x480")`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47128013

http://stackoverflow.com/q/47149085
has title: Python KNN weighting during .predict()?
tagged with: nearest-neighbor
has comment: http://stackoverflow.com/comment/81248282
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47164244
has comment: http://stackoverflow.com/comment/81270346
has answer: http://stackoverflow.com/a/47164244
has comment: http://stackoverflow.com/comment/81251719
tagged with: python
has body: I'm using a KNN algorithm for a class (instructed to use this algorithm, may not what you'd expect for application, see below) Essentially, we have a raspberry pi set up to collect the signal strengths of 6 local WIFI router Mac addresses. At different locations on a floor of our building we've recorded these signal strengths in .csv files. Using python I've created a script which uses the functions on this page. http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html I fit a knn as below: from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=1, algorithm = 'auto') knn.fit(strengths, labels) where strengths is a nested array like this: [[Loc1strengths],[Loc2strengths],[Loc3strengths],[Loc4strengths],[Loc5strengths],[Loc6strengths]] labels is set up like this: [Loc1, Loc2, Loc3, Loc4, Loc5, Loc6] Later in the script, I collect the signal strengths of the 6 local WIFI router Mac addresses and try to predict the location of my pi using knn.predict() and hope to get the location of the pi, Location1 for example. The results aren't great, it does a relatively poor job of figuring out where it is. I was wondering if there was a way to weight the function of knn.predict() so that the neighbors of the most recent location are weighted more heavily, the pi won't move to the other side of the floor without crossing the other points. Any help would be appreciated!
tagged with: knn
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81273208
downvote count: 0
has comment: http://stackoverflow.com/comment/81248321
answer count: 1
score: 1
upvote count: 1
tagged with: scikit-learn

http://stackoverflow.com/comment/81256657
comment on: http://stackoverflow.com/q/47153518
score: 0
type: Comment
type: QuestionComment
has text: So why not just return `B()` in `A.__new__`? You should not be passing in `B` in to the `super(cls, A).__new__` method.

http://stackoverflow.com/comment/81310023
type: Comment
type: QuestionComment
has text: I would go for selenium in your case, here is a simulair question with solutions using selinium: https://stackoverflow.com/questions/15122864/selenium-wait-until-document-is-ready
score: 0
comment on: http://stackoverflow.com/q/47180554

http://stackoverflow.com/q/47205879
downvote count: 0
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49118651
has body: I saw recently the 5 point landmarking model from dlib: https://github.com/davisking/dlib-models I am instereing to use it to pose estimation, but I do not find the function in dlib that perform it. My question does it exist in dlib (C++, Python)? If not, could you suggest efficient and small time consuming pose estimation algorithm and/or open sources from 5 point that are provided by dlib ? Thanks
score: 1
tagged with: python
has title: How to estimate face pose from 5 face landmarks in dlib ?
type: Question
tagged with: c++
tagged with: dlib
tagged with: pose-estimation
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/81265693
comment on: http://stackoverflow.com/q/47139986
type: Comment
has text: @OptimusCrime Every newspaper story,coming to us from around the world, has the following features: 1. Story_type 2. Brand_mention 3. client_focus 4. tonality and 5. segment. To give you a quick sense, class story_type can be (1c1) product review (1c2) interview of country marketing head (1c3) interview of country ceo (1c4) demand and sales figures and (1c5) accident reports featuring Toyota cars. so on. For tonality, the classes will be (4c1) positive, (4c2) neutral, (4c3) negative, and (4c4) negative, with escalation.
type: QuestionComment
score: 0

http://stackoverflow.com/q/47105592
has comment: http://stackoverflow.com/comment/81163180
linked to: http://stackoverflow.com/q/8951255
has title: Can't import functions from different module in the same project
has comment: http://stackoverflow.com/comment/81161807
has comment: http://stackoverflow.com/comment/81161852
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47106161
linked to: http://stackoverflow.com/q/36622183
has body: I have two scripts: script1: from test import script2 if __name__ == '__main__': foo() script2: def foo(): print 'hello' In the structure: test: │ A │-----B: │ script2.py │script1.py I am trying to call the function foo() from script2.py in script1.py. I received the error: This inspection detect names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level itesm are supported better than instance items. I read number of similar cases but they didn't help me: Call a function from another file in Python How to import a function from parent folder in python? Import Script from a Parent Directory
has comment: http://stackoverflow.com/comment/81161823
has comment: http://stackoverflow.com/comment/81162106
tagged with: python
has comment: http://stackoverflow.com/comment/81161850
type: Question
tagged with: python-import
answer count: 1
linked to: http://stackoverflow.com/q/20309456
has answer: http://stackoverflow.com/a/47106161

http://stackoverflow.com/q/47103079
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81176357
type: UnansweredQuestion
has title: Django loaddata does not create m2m relations
tagged with: loaddata
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/81156585
has comment: http://stackoverflow.com/comment/81174943
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81162627
answer count: 0
tagged with: http://stackoverflow.com/tag/json
downvote count: 0
has body: I'm upgrade django from 1.8.4 to 1.11.6 and encountered problem. I have two models: from django.db import models class File(models.Model): title = models.CharField(max_length=128, verbose_name=_('title')) description = models.CharField( max_length=255, blank=True, null=True, verbose_name=_('description') ) class Task(models.Model): output_data = models.ManyToManyField( File, blank=True, verbose_name=_('output_data') ) I'm running manage.py loaddata with the following data for models above: files.json: [ { "fields": { "description": "", "title": "Data file 2", }, "model": "files.file", "pk": 2 } ] tasks.json: [ { "fields": { "output_data": [2] }, "model": "tasks.task", "pk": 1 } ] loaddata creates file and task, but not create m2m relation. Before the update everything worked fine. UPD: I found where loaddata create m2m relation: local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py:972, method set: def set(self, objs, **kwargs): if not rel.through._meta.auto_created: opts = self.through._meta raise AttributeError( "Cannot set values on a ManyToManyField which specifies an " "intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name) ) # Force evaluation of `objs` in case it's a queryset whose value # could be affected by `manager.clear()`. Refs #19816. objs = tuple(objs) clear = kwargs.pop('clear', False) db = router.db_for_write(self.through, instance=self.instance) with transaction.atomic(using=db, savepoint=False): if clear: self.clear() self.add(*objs) else: old_ids = set(self.using(db).values_list(self.target_field.target_field.attname, flat=True)) new_objs = [] for obj in objs: fk_val = ( self.target_field.get_foreign_related_value(obj)[0] if isinstance(obj, self.model) else obj ) if fk_val in old_ids: old_ids.remove(fk_val) else: new_objs.append(obj) self.remove(*old_ids) self.add(*new_objs) I understand what is happening here, but I do not see the logic in what is happening. If someone knows why this is …
has comment: http://stackoverflow.com/comment/81156458
tagged with: fixtures
has comment: http://stackoverflow.com/comment/81174535

http://stackoverflow.com/comment/81156057
type: Comment
comment on: http://stackoverflow.com/a/47102306
type: AnswerComment
has text: you really wanted that then you have to convert string into dictionary using regex and that will too complicated man,and you are saying manipulating from file1.py its not gonna possible the way you have given data ,all dict should be inside a list to iterate and to serve your purpose.btw this code serves your purpose
score: 0

http://stackoverflow.com/comment/81265213
type: Comment
comment on: http://stackoverflow.com/a/47157921
type: AnswerComment
score: 1
has text: There's a notable difference between "it works" and "you should actually do this". See [Why is using `eval` bad practice](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice).

http://stackoverflow.com/comment/81304936
type: QuestionComment
comment on: http://stackoverflow.com/q/47177476
has text: https://stackoverflow.com/questions/22183859/javascript-err-content-length-mismatch
score: 0
type: Comment

http://stackoverflow.com/comment/81374934
comment on: http://stackoverflow.com/q/47212344
score: 0
type: QuestionComment
has text: @IliyanBobev no, it's rather a thing that I'm doing for my own music library, I want to use it to automatically add ID3 tags for downloaded tracks from youtube-dl :)
type: Comment

http://stackoverflow.com/a/47147841
has body: First, what actually did happen with your attempt to do it from the shell? UNIX (and Linux) has the uniq command that does just this. In Python the solution depends on your needs. Do you have to retain the original order of the records? If not, then you can simply add each line, as a string, to a set. When you hit end of file, just write the set to your destination file. If you need to retain the order, then maintain a set with seen items. For each line, if the item is not in the set, then write it to the destination file and add it to the set. If it's been seen before, do nothing.
type: Answer
score: 2
upvote count: 3
downvote count: 1
answers question: http://stackoverflow.com/q/47147805

http://stackoverflow.com/comment/81184123
comment on: http://stackoverflow.com/a/47117025
type: AnswerComment
score: 0
has text: so, is there any solution to avoid these warnings?
type: Comment

http://stackoverflow.com/comment/81333871
type: QuestionComment
has text: Also, you couldn't really store a list of `int` objects, which *have variable size in Python*, sequentially. So check `sys.getsizeof(0)`, then `sys.getsizeof(1)`, and finally, `sys.getsizeof(10000000000000000)`
comment on: http://stackoverflow.com/q/47192150
score: 1
type: Comment

http://stackoverflow.com/q/47214273
favorite count: 0
type: Question
tagged with: python
has title: tkinter GUI list of buttons
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47214873
tagged with: tkinter
score: 1
tagged with: user-interface
downvote count: 0
answer count: 1
has body: for emoji, descriptor in emoji_descriptor img = ImageTk.PhotoImage(Image.open("emojis/"+descriptor+".png")) b = Button(emojiApp, text = descriptor, command=lambda x=emoji: appendEmoji(x), image=img) b.pack() #after the list of buttons have been made for i in range(len(buttons)): buttons[i].grid(row = i//4, column = i%4) Where emoji_descriptor can be a list of pairs of emojis with descriptions: [(❤️,"red_heart"), (,"wink_tongue_out"), ...] In this case I have 20 emojis/descriptors and the only one who's image shows up and who's button is actually active is the last one in the list. I've never used GUI for python so I'm not entirely sure how to resolve this error... Any recommendations?
upvote count: 1
tagged with: emoji
accepted answer: http://stackoverflow.com/a/47214873

http://stackoverflow.com/a/47119130
has body: The issue is that zip returns a zip object, which is an iterator. Most well-behaved iterators are single pass: &gt;&gt;&gt; z = zip((1,2),('a','b')) &gt;&gt;&gt; z &lt;zip object at 0x10193a908&gt; &gt;&gt;&gt; next(z) (1, 'a') &gt;&gt;&gt; next(z) (2, 'b') &gt;&gt;&gt; next(z) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration &gt;&gt;&gt; list(z) [] In other words: &gt;&gt;&gt; z = zip((1,2),('a','b')) &gt;&gt;&gt; first = list(z) &gt;&gt;&gt; second = list(z) &gt;&gt;&gt; first [(1, 'a'), (2, 'b')] &gt;&gt;&gt; second [] So, if you want to re-use the zipped values, you need to keep a reference around to the materialized list, just as you do in your third attempt. Just to be clear, this isn't specific to the list function, but with anything that iterates over the zip-object: &gt;&gt;&gt; z = zip((1,2),('a','b')) &gt;&gt;&gt; d1 = dict(z) &gt;&gt;&gt; d2 = dict(z) &gt;&gt;&gt; d1 {1: 'a', 2: 'b'} &gt;&gt;&gt; d2 {}
type: Answer
accepted answer of: http://stackoverflow.com/q/47119116
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47119116
score: 8
has comment: http://stackoverflow.com/comment/81188031
upvote count: 8
has comment: http://stackoverflow.com/comment/81188058

http://stackoverflow.com/q/47153558
score: 0
has title: How to deal with the two custom User model case in Django?
type: UnansweredQuestion
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/81256915
has comment: http://stackoverflow.com/comment/81256722
has comment: http://stackoverflow.com/comment/81270330
has answer: http://stackoverflow.com/a/47158323
tagged with: python
type: Question
has body: I make two models that inherit form from django.contrib.auth.models import AbstractUser, names User and AdminUser. But there are check identified errors when runserver, so I add : AUTH_USER_MODEL = "qiyun_admin_usermanage.User" In my settings.py. the half error gone, but there still has the qiyun_admin_usermanage.AdminUser's issue. I don't know whether I can set two custom models in the AUTH_USER_MODEL, or there must only be one AUTH_USER_MODEL? The traceback: ... django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: qiyun_admin_usermanage.AdminUser.groups: (fields.E304) Reverse accessor for 'AdminUser.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'AdminUser.groups' or 'User.groups'. qiyun_admin_usermanage.AdminUser.user_permissions: (fields.E304) Reverse accessor for 'AdminUser.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'AdminUser.user_permissions' or 'User.user_permissions'. qiyun_admin_usermanage.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'AdminUser.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'AdminUser.groups'. qiyun_admin_usermanage.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'AdminUser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'AdminUser.user_permissions'.

http://stackoverflow.com/comment/81384854
type: QuestionComment
comment on: http://stackoverflow.com/q/47217001
has text: I picked ur second suggestion which works better. U mind writing as an answer? I will green tick it as soon as SO allows it
score: 0
type: Comment

http://stackoverflow.com/comment/81290123
type: Comment
type: QuestionComment
score: 0
has text: Shouldn't that be something like `soup.select('tr.a')[0]` ?
comment on: http://stackoverflow.com/q/47169767

http://stackoverflow.com/q/47116316
answer count: 1
tagged with: pypi
favorite count: 0
type: Question
has body: I'm fairly new to Django so apologies in advance if this is obvious. In Rails projects, I use a gem called bundler-audit to check that the patch level of the gems I'm installing don't include security vulnerabilities. Normally, I incorporate running bundler-audit into my CI pipeline so that any time I deploy, I get a warning (and fail) if a gem has a security vulnerability. Is there a similar system for checking vulnerabilities in Python packages?
has answer: http://stackoverflow.com/a/47116317
accepted answer: http://stackoverflow.com/a/47116317
tagged with: circleci
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: circleci-workflows
downvote count: 0
score: 1
upvote count: 1
has title: Is there a Python/Django equivalent to Rails bundler-audit?

http://stackoverflow.com/comment/81114026
score: 1
has text: Considering that the purpose of `importlib` is to avoid shenanigans like that... please don't.
comment on: http://stackoverflow.com/a/47082173
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47141354
has comment: http://stackoverflow.com/comment/81232822
favorite count: 0
has comment: http://stackoverflow.com/comment/81232928
type: Question
linked to: http://stackoverflow.com/q/35496743
score: -3
tagged with: python
duplicate of: http://stackoverflow.com/q/35496743
tagged with: excel
accepted answer: http://stackoverflow.com/a/47141619
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47141619
has comment: http://stackoverflow.com/comment/81233149
has title: Filtering Files based on Dates
upvote count: 0
has body: I have bunch of files named FXRATES_DD-MM-YYY.xlsx residing in a folder.How can I filter out and read only certain files based on specific date range?
answer count: 1
downvote count: 3

http://stackoverflow.com/comment/81207409
type: Comment
has text: Oh try my updated answer. It was because you called return before checking if the value of num2 is 0. Once `return`is called, it automatically exits the loop or function thus ignoring the next line of codes. Before returning the answer, check if `num == 0` first.
comment on: http://stackoverflow.com/a/47127793
type: AnswerComment
score: 0

http://stackoverflow.com/a/47151009
answers question: http://stackoverflow.com/q/47150674
upvote count: 1
score: 1
has body: From the source code of PIL (of the fromarray function https://github.com/python-pillow/Pillow/blob/master/PIL/Image.py) we can see that it can handle only 1, 2, 3 and 4 channel images (see the _fromarray_typemap dictionary in the above source code link). I think you should drop the non colour channels to be able to apply the fromarray function: image = image[:,:,:3]
downvote count: 0
type: Answer

http://stackoverflow.com/q/47197007
answer count: 2
downvote count: 0
tagged with: pandas
possible better answer: http://stackoverflow.com/a/47197449
accepted answer: http://stackoverflow.com/a/47197611
has comment: http://stackoverflow.com/comment/81345594
linked to: http://stackoverflow.com/q/37396264
has answer: http://stackoverflow.com/a/47197449
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81342793
tagged with: python
has title: Pandas DataFrame: resampling along integer index / grouping by groups of n elements
has answer: http://stackoverflow.com/a/47197611
has body: I know about pandas resampling functions using a DateTimeIndex. But how can I easily resample/group along an integer index? The following code illustrates the problem and works: import numpy as np import pandas as pd df = pd.DataFrame(np.random.randint(5, size=(10, 2)), columns=list('AB')) print(df) A B 0 3 2 1 1 1 2 0 1 3 2 3 4 2 0 5 4 0 6 3 1 7 3 4 8 0 2 9 4 4 # sum of n consecutive elements n = 3 tuples = [(i, i+n-1) for i in range(0, len(df.index), n)] df_new = pd.concat([df.loc[i[0]:i[1]].sum() for i in tuples], 1).T print(df_new) A B 0 4 4 1 8 3 2 6 7 3 4 4 But isn't there a more elegant way to accomplish this? The code seems a bit heavy-handed to me.. Thanks in advance!
score: 2
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/q/47153518
has body: I am having difficulties with invoking the __new__ method. When creating an instance of A(), I want to return an instance of B() instead if the input below 10. But the instance is created *without running the __new__ or __init__ methods of B, why is that? class A (object): def __init__ (self, IP, s): print 'arrived to init a' self.IP=IP print self.IP print s def __new__ (cls, IP, s): print "arrived to new a" if IP&gt;10: self = object.__new__ (cls) return self # return n else: return super (cls, A).__new__ (B) class B(object): def __init__(self,d,s,ar): print 'arrived to b' self.ip=d print self.ip print s print ar def __new__(cls,d,s,ar): print 'arrived to new b' self = object.__new__(cls) return self # return n def __repr__(self): return 'B({}, ..., ...)'.format(getattr(self, 'ip', '&lt;missing&gt;')) a = A(10 ,"a") print a This outputs arrived to new a B(&lt;missing&gt;, ..., ...) instead of arrived to new a arrived to new b arrived to b 10 'a' ? B(10, ..., ...)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81257182
tagged with: python
tagged with: class
has title: __new__ is never run on alternate class
score: 0
has comment: http://stackoverflow.com/comment/81256738
has answer: http://stackoverflow.com/a/47153718
has comment: http://stackoverflow.com/comment/81257110
answer count: 1
has comment: http://stackoverflow.com/comment/81256632
type: Question
has comment: http://stackoverflow.com/comment/81257386
has comment: http://stackoverflow.com/comment/81256657

http://stackoverflow.com/comment/81220617
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47074803
has text: More or less that is what I'm doing actually, I'm doing that first scan

http://stackoverflow.com/a/47158323
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/98462073
answers question: http://stackoverflow.com/q/47153558
has body: There could be only one of AUTH_USER_MODELs. If you want to separate users and admin, there is a snippet: from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin class CustomUser(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=40) ... PermissionsMixin adds is_superuser column to your DB where permissions could be handled.
downvote count: 1
type: Answer

http://stackoverflow.com/comment/81128189
score: 0
has text: I'm not sure. Does the code snippet below run without an error on your machine? ```d = { "actions": [ { "action_type": "offsite_conversion.custom.xxxxxxxxxxx", "value": "7" }, { "action_type": "offsite_conversion.custom.xxxxxxxxxxx", "value": "144" }, { "action_type": "offsite_conversion.custom.123xxxxxxxxx", "value": "34" }]}; df = pd.DataFrame(d['actions']); print df.pivot(columns='action_type', values='value') ```
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47089025

http://stackoverflow.com/a/47177612
has comment: http://stackoverflow.com/comment/81305897
has comment: http://stackoverflow.com/comment/81306055
accepted answer of: http://stackoverflow.com/q/47176888
has comment: http://stackoverflow.com/comment/81306334
type: Answer
has comment: http://stackoverflow.com/comment/81305854
downvote count: 0
score: 1
upvote count: 1
has body: When running locally there is no need to pass additional modules as zip with the --py-files flag, your code is local and so is the master and workers (they all have access to your code and modules necessary). However, when you want to submit a job to a cluster, the master and the workers need to have access to your main.py file, along with all the modules it uses, thus, using the --py-files argument, you are specifying the location of the extra modules and both master and workers have access to every part of the code that needs to be run. If you just run spark-submit main.py on a cluster, it won't work because 1) the location of main.py is relative to your system, so the cluster won't be able to locate main.py and 2) due to ImportErrors of the main.py. Note: The usage of this flag is before specifying the main.py and the zipped files (as well as main.py) need to be somewhere accessible to the whole cluster, not local on your machine, e.g. on an ftp server. For example, to submit on a cluster through mesos: spark-submit --master mesos://path/to/service/spark --deploy-mode cluster --py-files http://somedomainforfileserving/src.zip http://somedomainforfileserving/main.py Edit: As for jar dependencies, e.g. the ElasticSearch connector, you can put the jars within the src, e.g. in src/jars, so that it gets zipped and distributed to all, and then when submitting to your cluster, reference the relative to src path to the jar. E.g.: spark-submit --master mesos://path/to/service/spark --deploy-mode cluster --jars src/jars/elasticsearch-spark-someversion.jar --py-files http://somedomainforfileserving/src.zip http://somedomainforfileserving/main.py
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81306602
answers question: http://stackoverflow.com/q/47176888
has comment: http://stackoverflow.com/comment/81305676

http://stackoverflow.com/a/47137970
upvote count: 19
type: Answer
accepted answer of: http://stackoverflow.com/q/47137909
has body: Simplest way is to sort before plotting: df_c = df_c.sort_values('Count')
answers question: http://stackoverflow.com/q/47137909
type: AcceptedAnswer
downvote count: 0
score: 19

http://stackoverflow.com/a/47157189
has comment: http://stackoverflow.com/comment/81274018
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47156861
upvote count: 1
has body: Untested but this should get you started (well, this exact snippet is untested - I've done similar hacks that worked properly): def test_call_count(): real_say = Foo.say.im_func call_count = [0] def patched_say(self, *args, **kw): call_count[0] += 1 return real_say(self, *args, **kw) Foo.say = patched_say amount = Foo().say_it() Foo.say = real_say assert amount == 123 assert call_count[0] == 1
has comment: http://stackoverflow.com/comment/81274974
type: Answer

http://stackoverflow.com/comment/81342795
has text: You have to exclude middle when you recurse to avoid infinite recursion. You forgot to exclude it from the last case.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47196917

http://stackoverflow.com/comment/81175524
has text: now how to calculate the length of df[name].split(",") I did, `df["count"]=len(df["pre-keys"].str.split(","))` but getting 4 as length
comment on: http://stackoverflow.com/a/47112184
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/81203837
score: 0
type: Comment
type: QuestionComment
has text: do you have any special reasons to exclude parents from CategoryForm?
comment on: http://stackoverflow.com/q/47126208

http://stackoverflow.com/q/47165165
type: UnansweredQuestion
tagged with: python
has title: foreignkey error in sqlalchemy
score: 0
has comment: http://stackoverflow.com/comment/81281235
has comment: http://stackoverflow.com/comment/81280779
tagged with: sqlalchemy
type: Question
has body: I get the following error when trying to build my database using db_create.py. According to the documentation when you use backref it is supposed to add a foreignkey to the other class, but for some reason it's not. Error: sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Message.users - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression. models.py class Message(db.Model): id=db.Column(db.Integer, primary_key=True) message=db.Column(db.String(69), unique=True, nullable=False) timestamp=db.Column(db.DateTime) #Problem Code below users=db.relationship('Message_User', backref='message', lazy='dynamic') children=db.relationship('Message_Group', backref='message', lazy='dynamic') #group backrefs Group class Message_User(db.Model): __tablename__='message_user' id=db.Column(db.Integer, primary_key=True) acknowledge=db.Column(db.DateTime, default=False) timestamp=db.Column(db.DateTime) #group backrefs Message_Group #message backrefs Message db_createpy #!flask/bin/python from migrate.versioning import api from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO from app import db import os.path db.create_all() if not os.path.exists(SQLALCHEMY_MIGRATE_REPO): api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository') api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) else: api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
answer count: 0

http://stackoverflow.com/q/47139180
type: Question
has answer: http://stackoverflow.com/a/47139415
has answer: http://stackoverflow.com/a/47139421
tagged with: python
has comment: http://stackoverflow.com/comment/81227945
type: UnansweredQuestion
tagged with: python-3.x
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81228048
has body: Here is the python code, how can I start the application as a daemon using only python 1.py command? import eventlet from eventlet import wsgi def hello_world(env, start_response): if env['PATH_INFO'] != '/': start_response('404 Not Found', [('Content-Type', 'text/plain')]) return ['Not Found\r\n'] start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Hello, World!\r\n'] wsgi.server(eventlet.listen(('', 8090)), hello_world)
has comment: http://stackoverflow.com/comment/81228922
upvote count: 2
has comment: http://stackoverflow.com/comment/81227819
answer count: 2
score: 1
has title: Running python service as background service
downvote count: 1
favorite count: 0
tagged with: centos

http://stackoverflow.com/comment/81117650
type: QuestionComment
comment on: http://stackoverflow.com/q/47084040
has text: Before your code gets too complicated, have a look at David Beazley's talks about generators and how to chain them. For example, you could create a `def with_report_type(type, rows): return (row for row in rows if ... == type)` and then use `rows = with_date('10-27-2017', with_type('SOD ', reader))`
score: 0
type: Comment

http://stackoverflow.com/q/47169474
upvote count: 31
accepted answer: http://stackoverflow.com/a/47172471
downvote count: 0
favorite count: 0
score: 31
type: AnsweredQuestion
tagged with: aiohttp
tagged with: python-asyncio
has title: Parallel asynchronous IO in Python's coroutines
answer count: 1
has body: Simple example: I need to make two unrelated HTTP requests in parallel. What's the simplest way to do that? I expect it to be like that: async def do_the_job(): with aiohttp.ClientSession() as session: coro_1 = session.get('http://httpbin.org/get') coro_2 = session.get('http://httpbin.org/ip') return combine_responses(await coro_1, await coro_2) In other words, I want to initiate IO operations and wait for their results so they effectively run in parallel. This can be achieved with asyncio.gather: async def do_the_job(): with aiohttp.ClientSession() as session: coro_1 = session.get('http://example.com/get') coro_2 = session.get('http://example.org/tp') return combine_responses(*(await asyncio.gather(coro_1, coro_2))) Next, I want to have some complex dependency structure. I want to start operations when I have all prerequisites for them and get results when I need the results. Here helps asyncio.ensure_future which makes separate task from coroutine which is managed by event loop separately: async def do_the_job(): with aiohttp.ClientSession() as session: fut_1 = asyncio.ensure_future(session.get('http://httpbin.org/ip')) coro_2 = session.get('http://httpbin.org/get') coro_3 = session.post('http://httpbin.org/post', data=(await coro_2) coro_3_result = await coro_3 return combine_responses(await fut_1, coro_3_result) Is it true that, to achieve parallel non-blocking IO with coroutines in my logic flow, I have to use either asyncio.ensure_future or asyncio.gather (which actually uses asyncio.ensure_future)? Is there a less "verbose" way? Is it true that normally developers have to think what coroutines should become separate tasks and use aforementioned functions to gain optimal performance? Is there a point in using coroutines without multiple tasks in event loop? How "heavy" are event loop tasks in real life? Surely, they're "lighter" than OS threads or processes. To what extent should I strive for minimal possible number of such tasks?
tagged with: python
has answer: http://stackoverflow.com/a/47172471
type: Question

http://stackoverflow.com/q/47213650
downvote count: 0
has answer: http://stackoverflow.com/a/51262925
score: 13
favorite count: 0
tagged with: networkx
type: Question
has answer: http://stackoverflow.com/a/47996686
has answer: http://stackoverflow.com/a/47338796
type: UnansweredQuestion
tagged with: python
upvote count: 13
has body: I am plotting directed graph using networkx in python. However, I found that arrow head of edge is thick from one end instead of pointed arrow. I want to change the thick edge to pointed arrow. Here is my code, actual output, and desired output: import networkx as nx import matplotlib.pyplot as plt G=nx.DiGraph() item = [1,2] G.add_edge(*item) #color = item[-1], weight = 2) pos = nx.circular_layout(G) nx.draw(G, pos, with_labels = True, edge_color = 'b') plt.show() Output Desired output: Any suggestion would be really helpful?
tagged with: draw
has title: changing arrowhead type in networkx
answer count: 3

http://stackoverflow.com/a/47313035
has comment: http://stackoverflow.com/comment/81577847
has body: The DictReader tool in the csv library is handy for this sort of thing - it converts the column headings into dictionary keys, and then you can interrogate each row as you would any other dict. from csv import DictReader with open('test2.csv', newline='') as csvfile: srcdat = DictReader(csvfile) csvdict = [line for line in srcdat] for row in csvdict: if row['Host']: current_host = row['Host'] q = row[' Time OK'] q = q.split('.')[0] if int(q) &lt;100: print(f'Host failure for: {current_host}') print('Time OK: ', row[' Time OK']) the output isn't quite the format you want but should give you the foundation.
has comment: http://stackoverflow.com/comment/81577536
type: Answer
answers question: http://stackoverflow.com/q/47213771
has comment: http://stackoverflow.com/comment/81577891
score: 0

http://stackoverflow.com/q/47219198
tagged with: python
tagged with: scrapy
type: Question
has body: I wang to use scrapy and python 2.7.11 to stimulate a FormRequest to crawl http://www.istic.ac.cn/suoguan/QiKan_ShouYe.htm?lan=en&amp;journalId=IELEP0229&amp;yp=2018 Here is my code: def start_requests(self): posturl = 'http://www.istic.ac.cn/suoguan/essearch.ashx' url = 'http://www.istic.ac.cn/suoguan/QiKan_ShouYe.htm?lan=en&amp;journalId=IELEP0229&amp;yp=2018' journalId = re.search(r'journalId=(.*?)&amp;', url).group(1) yearNum = re.search(r'&amp;yp=(\d+)', url).group(1) postdata = { "indexname" : "xw_qk", "search" : "{0}/F(F_ReqNum)*{1}/F(F_YEAR)".format(journalId, yearNum), "page" : "0", "pagenum" : "20", "sort" : "", "type" : "content", } print journalId, yearNum print postdata self.logger.info('Visit_headpage........................') yield FormRequest(posturl, formdata = postdata, callback = self.parse_item) I need to post following data to the form: indexname=xw_qk&amp; search=IELEP0229%2F(F_ReqNum)*2018%2F(F_YEAR) &amp;page=0&amp;pagenum=20&amp;sort=&amp;type=content to crawl the page correctly. But my response is nothing, so I use fiddler to find the data posted form, and it is: indexname=xw_qk&amp; search=IELEP0229%2FF%28F_ReqNum%29%2A2018%2FF%28F_YEAR%29 &amp;page=0&amp;pagenum=20sort=&amp;&amp;type=content So it means these three signals get wrong decode:'(', ')', '*'. But when I print formdata in scrapy log, it still in the right format: {indexname':'xw_qk', 'search':'IELEP0229/(F_ReqNum)*2018/(F_YEAR)', 'page':'0', 'pagenum':'20', 'sort':'', 'type':'content} So how can I solve it?
has title: Why my formdata gets wrong decode when i used scrapy to post it?
has answer: http://stackoverflow.com/a/47226701
score: 0
tagged with: http-post
tagged with: decode
answer count: 2
has answer: http://stackoverflow.com/a/47219399
type: UnansweredQuestion

http://stackoverflow.com/a/47154002
answers question: http://stackoverflow.com/q/47152646
type: Answer
upvote count: 4
score: 4
accepted answer of: http://stackoverflow.com/q/47152646
downvote count: 0
type: AcceptedAnswer
has body: Its num_boost_round. As stated on the api documentation: num_boost_round (int) – Number of boosting iterations. To exactly match the output of xgb.train and scikit wrapper (XGBRegressor or XGBClassifier) you can look at my other answer here: https://stackoverflow.com/a/46947191/3374996

http://stackoverflow.com/comment/81171401
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47110543
type: AnswerComment
has text: Sir for that big data merge is definitely not suggested. It might take days to get the output.

http://stackoverflow.com/a/59683794
has comment: http://stackoverflow.com/comment/105524367
type: Answer
has comment: http://stackoverflow.com/comment/105551125
has body: pip3 install pyqt5 import PyQt5.QtWidgets as QtWidgets You can use it like that.It works for me.
score: 0
answers question: http://stackoverflow.com/q/47164979

http://stackoverflow.com/comment/81317989
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47184177
score: 0
has text: Yes, that's correct.

http://stackoverflow.com/a/47109835
score: 2
answers question: http://stackoverflow.com/q/47109769
has comment: http://stackoverflow.com/comment/81170639
has comment: http://stackoverflow.com/comment/81170112
upvote count: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/81170059
has comment: http://stackoverflow.com/comment/81170125
has body: This is simply not how Python works: if 0 &lt;= np.any(T2[i:]) &lt; 0.5*np.pi: gets evaluated in this order: if ( 0 &lt;= np.any(T2[i:]) ) &lt; 0.5*np.pi first ~~ second ~~ ~~~~~~ third ~~~~~~ ~ fourth ~ ~~~~~~~~~~~~~~~~~~~~~ fifth ~~~~~~ So, first the [] operator generates a slicing of T2, i.e. something that you can iterate through (first). Then, the any function checks whether any of these values is not False (ie. not equal to zero). That will return a single boolean, i.e. either True or False. (second) Since True is &gt;0 and False == 0, your first comparison is always True (third). You could as well just write if True &lt; 0.5*np.pi: Now, True, when compared to a numerical value, gets converted to 1. So, your overall statement is identical to if 1 &lt; 0.5*np.pi: which is always the case. So, no matter what you expected, Python will always execute what you enclosed in that if, because you explicitly asked it to do so. Python can't guess what you've meant with 0 &lt;= np.any(T2[i:]) &lt; 0.5*np.pi and honestly, I wouldn't have guessed what you meant, either.

http://stackoverflow.com/comment/81117626
type: Comment
has text: No need for that.
comment on: http://stackoverflow.com/a/47069916
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81080737
type: QuestionComment
comment on: http://stackoverflow.com/q/47066252
score: 1
type: Comment
has text: https://docs.python.org/3.6/tutorial/inputoutput.html#reading-and-writing-files

http://stackoverflow.com/q/47083402
accepted answer: http://stackoverflow.com/a/47084159
favorite count: 0
type: Question
has body: I haven't found anything on the internet so far, all I want to know is if its possible to change the current screen in kivy depending on the orientation of the phone's screen (Landscape or portrait) and how to do it. or at least a link to a tutorial because I couldn't find one myself.
tagged with: python
has answer: http://stackoverflow.com/a/47084159
tagged with: kivy
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has title: Python / Kivy - Changing Screen with phone screen orientation (android)

http://stackoverflow.com/comment/81233468
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47132508
type: AnswerComment
has text: That works with one small change. I had to change the index to 2 for some reason. Thanks! `driver.execute_script("document.getElementsByClassName('crm-accordion-body')[2].style.display='block';")`

http://stackoverflow.com/a/47210627
answers question: http://stackoverflow.com/q/47195598
score: 0
has body: The problem is you are using the wrong method to find a text (select() is made for css selector). You could use the keyword string with find_all and a function to select the tag you are looking for. def has_text_def(s): return s and s.startswith('Definition of') definitions = soup.find_all('p', string=has_text_def) By the way, you need to get the next element in the tree (with next_sibling) to access the definition : for p in definitions: print(p.next_sibling.next_sibling.text)
type: Answer

http://stackoverflow.com/comment/81150439
score: 0
comment on: http://stackoverflow.com/q/47100230
type: Comment
type: QuestionComment
has text: If `numpy` doesn't do it for you, use base Python. Convert to a list of lists, sort those, and convert back to an array.

pyarrow
tags question: http://stackoverflow.com/q/47113813
tag name: pyarrow
tags question: http://stackoverflow.com/q/47155431
type: Tag

http://stackoverflow.com/comment/81241844
score: 0
type: Comment
type: QuestionComment
has text: @DavidePatti latest from a fresh `pip install`, so that would be `selenium 3.7.0`. I admit I didn't think about trying other versions of selenium yet.
comment on: http://stackoverflow.com/q/47142311

http://stackoverflow.com/comment/81166211
type: QuestionComment
comment on: http://stackoverflow.com/q/47107663
has text: I edited, hope you understand now.
score: 0
type: Comment

http://stackoverflow.com/q/47216433
downvote count: 0
answer count: 1
has title: How to read the Font and Background color in excel using xlrd version 1.1.0
has answer: http://stackoverflow.com/a/47221563
has body: Actually I am using xlrd module 1.1.0 version, but I don't know how to read cell properties like background color, font, and whether cell is locked. I tried to use import xlrd book = xlrd.open_workbook("sample.xls", formatting_info=True) sheets = book.sheet_names() print "sheets are:", sheets for index, sh in enumerate(sheets): sheet = book.sheet_by_index(index) print "Sheet:", sheet.name rows, cols = sheet.nrows, sheet.ncols print "Number of rows: %s Number of cols: %s" % (rows, cols) for row in range(rows): for col in range(cols): print "row, col is:", row+1, col+1, thecell = sheet.cell(row, col) # could get 'dump', 'value', 'xf_index' print thecell.value, xfx = sheet.cell_`enter code here`xf_index(row, col) xf = book.xf_list[xfx] bgx = xf.background.pattern_colour_index print bgx t raises an error saying formatting information needs to be set while reading wb, but if I had that parameter then it shows it is still not implemented. Is there another module or how can this module itself be made to read cell properties? python xlrd Thank you in advance
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
score: 4
upvote count: 4
tagged with: xlrd

http://stackoverflow.com/a/47120794
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47120738
answers question: http://stackoverflow.com/q/47120738
has body: If you don't use another class, then you could just add buttonClicked to GUI, and then reference the button via self.btn. If you need another class, then you would have to pass a reference for the main class, in order to use its attributes. class Controller(): def __init__(self, gui): self.gui = gui def buttonClicked(self): self.gui.btn['bg'] = 'blue' class GUI(): def __init__(self,master): self.master = master self.controller = Controller(self) self.btn = tk.Button(master,command=self.controller.buttonClicked) self.btn.pack() root = tk.Tk() GUI(root) root.mainloop() By passing self to Controller, an instance of Controller can use all the variables, including the button, and edit them. You also need to remove the call to self.controller.buttonClicked when defining the command for your button, which I have done in the altered code above.
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/81557934
score: 0
type: AnswerComment
has text: I have made a GitHub repository that shows how you can make a predictor. It is based on TF-recomm: https://github.com/kiwidamien/TensorFlowRec
type: Comment
comment on: http://stackoverflow.com/a/47289537

http://stackoverflow.com/comment/81327745
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47189191
has text: Equality comparison is `==`. Your indentation is wrong.
score: 8

http://stackoverflow.com/a/49701584
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47214731
has body: So, it turns out my network was overfitting massively as my database was too small. Adding more data and regularization finally helped in getting a decent accuracy.
downvote count: 0

http://stackoverflow.com/a/67334192
score: 23
has body: @Midas.Inc answer works great. Just to provide a minimal working example for those who are interested: import numpy as np import h5py f = h5py.File('MyDataset.h5', 'a') for i in range(10): # Data to be appended new_data = np.ones(shape=(100,64,64)) * i new_label = np.ones(shape=(100,1)) * (i+1) if i == 0: # Create the dataset at first f.create_dataset('data', data=new_data, compression="gzip", chunks=True, maxshape=(None,64,64)) f.create_dataset('label', data=new_label, compression="gzip", chunks=True, maxshape=(None,1)) else: # Append new data to it f['data'].resize((f['data'].shape[0] + new_data.shape[0]), axis=0) f['data'][-new_data.shape[0]:] = new_data f['label'].resize((f['label'].shape[0] + new_label.shape[0]), axis=0) f['label'][-new_label.shape[0]:] = new_label print("I am on iteration {} and 'data' chunk has shape:{}".format(i,f['data'].shape)) f.close() The code outputs: #I am on iteration 0 and 'data' chunk has shape:(100, 64, 64) #I am on iteration 1 and 'data' chunk has shape:(200, 64, 64) #I am on iteration 2 and 'data' chunk has shape:(300, 64, 64) #I am on iteration 3 and 'data' chunk has shape:(400, 64, 64) #I am on iteration 4 and 'data' chunk has shape:(500, 64, 64) #I am on iteration 5 and 'data' chunk has shape:(600, 64, 64) #I am on iteration 6 and 'data' chunk has shape:(700, 64, 64) #I am on iteration 7 and 'data' chunk has shape:(800, 64, 64) #I am on iteration 8 and 'data' chunk has shape:(900, 64, 64) #I am on iteration 9 and 'data' chunk has shape:(1000, 64, 64)
has comment: http://stackoverflow.com/comment/129515013
upvote count: 23
type: Answer
answers question: http://stackoverflow.com/q/47072859
downvote count: 0

http://stackoverflow.com/a/47068708
has comment: http://stackoverflow.com/comment/81085379
downvote count: 0
answers question: http://stackoverflow.com/q/47068468
score: 1
upvote count: 1
type: Answer
has body: You are not storing the LabelEncoder() object anywhere. You need to save it like this: le = LabelEncoder() And then call fit(), or transform(). import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder ls = ['IP', 'IP', 'IP', 'IP', 'IP', 'IE', 'IP', 'IP', 'IP', 'IP', 'IP', 'IPD', 'IE', 'IE', 'IP', 'IE', 'IP', 'IP', 'IP'] data = pd.DataFrame(np.array(ls).reshape(-1,1), columns=['Resi']) le = LabelEncoder() data['Resi'] = le.fit_transform(data['Resi']) df['resi'] = LabelEncoder().fit_transform(df['resi']) list(le.inverse_transform(data['Resi'])) Out: ['IP', 'IP', 'IP', 'IP', 'IP', 'IE', 'IP', 'IP', 'IP', 'IP', 'IP', 'IPD', 'IE', 'IE', 'IP', 'IE', 'IP', 'IP', 'IP']

http://stackoverflow.com/a/50527865
answers question: http://stackoverflow.com/q/47143718
type: Answer
has body: Adding data_format='channels_last' in model.add() will work if backend is using Tensorflow, and data_format='channels_first' if backend is using theano.
score: 0

http://stackoverflow.com/comment/81265129
has text: Thank you. It works
type: Comment
comment on: http://stackoverflow.com/a/47157921
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81251618
score: 2
comment on: http://stackoverflow.com/q/47150813
has text: With `finditer()` you have access to different groups (sic!) while iterating only once. This one follows somewhat the generator concetp of `Python`. Thus, it is less memory intensive. With small to medium string sizes this might only have differences in milliseconds though.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81437385
type: Comment
comment on: http://stackoverflow.com/a/47194867
score: 0
type: AnswerComment
has text: I never got around to thanking you for this so I'm thanking you now! This was super helpful and I finally figured it all out! I am so much more thankful than you think!

google-cloud-sdk
tag name: google-cloud-sdk
type: Tag
tags question: http://stackoverflow.com/q/47200623

http://stackoverflow.com/comment/81194174
type: Comment
has text: If unknown happens to be an indicator of where the genres start and they're only at the end of the row then you might be able to build the mask as: `df.loc[:,'unknown':].sum(axis=1).gt(1)`
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47122261

http://stackoverflow.com/comment/81306443
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47178549
has text: You should advocate the use of `with` as much as possible, it makes for cleaner code.
score: 1

http://stackoverflow.com/a/47112070
answers question: http://stackoverflow.com/q/47111897
type: Answer
has comment: http://stackoverflow.com/comment/81229409
has comment: http://stackoverflow.com/comment/81174812
score: 2
upvote count: 2
downvote count: 0
has body: So, there's some serious problems with the code you posted. First, you don't want the distance_check process to finish, because it's running a while loop. You should not do p2.join(), nor should you be starting new processes all the time in your while loop. You're mixing too many ways of doing things here - either the two children run forever, or they each run once, not a mix. However, the main problem is that the original processes can't communicate with the original process, even via global (unless you do some more work). Threads are much more suited to this problem. You also have a return inside your distance_check() function, so no code below that statement gets executed (including the sleep, and the setting of constant1 (which should really have a better name). In summary, I think you want something like this: from threading import Thread from TestS import distance import Robot import time can_move_forward = True min_distance = 15 def move_forward(): global can_move_forward while can_move_forward: robot.forward(150) time.sleep(2) print('Moving forward for two seconds!') def check_distance(): global can_move_forward while True: if distance() &lt; min_distance: can_move_forward = False print('Something in the way! Checking again in 0.3 seconds!') time.sleep(0.3) def move_forward_and_check_distance(): p1 = Thread(target = move_forward) p2 = Thread(target = check_distance) p1.start() p2.start() Since you specified python-3.x in your tags, I've also corrected your print. Obviously I can't check that this will work as you want it to because I don't have your robot, but I hope that this is at least somewhat helpful.
has comment: http://stackoverflow.com/comment/81174854
has comment: http://stackoverflow.com/comment/81197428
has comment: http://stackoverflow.com/comment/81230817

http://stackoverflow.com/a/47080809
score: 0
has body: You can do it with itertools : A,B,C=np.eye(3,dtype=int) import itertools l=list(itertools.product((A,B,C),(A,B,C))) a923=np.array(l) or directly in numpy : points=np.array([ [1,0,0], [0,1,0], [0,0,1]]) n,dim=points.shape indices=np.indices((n,n)) # indice.T : # array([[[0, 0], # [1, 0], # [2, 0]], # # [[0, 1], # [1, 1], # [2, 1]], # # [[0, 2], # [1, 2], # [2, 2]]]) res = points[indices.T].reshape(n*n,2,dim)
answers question: http://stackoverflow.com/q/47080410
type: Answer
has comment: http://stackoverflow.com/comment/81112025

http://stackoverflow.com/a/47141663
has body: You can include error handlers like this, e.g. for displaying the internal server error in your example more nicely: import traceback (...some code...) @app.errorhandler(500) def internal_error(e): """ handle internal errors nicely """ tb = traceback.format_exc() return render_template('error.html', error=e.message, traceback=tb), 500 In your template you can then output the short error message, and (maybe depending on user rights if you have user management) the detailed stacktrace. As mentioned in the comments on your question, you should read the documentation to get the full picture.
answers question: http://stackoverflow.com/q/47141503
type: AcceptedAnswer
downvote count: 0
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47141503
score: 3
type: Answer

http://stackoverflow.com/a/47280258
type: AcceptedAnswer
has body: I didn't really like the previous solution, so I kept looking for others. The first option that worked for me is to bind the sender socket to the specific network interface address. The network interfaces addresses can be found using netifaces module, and I used this helpful answer to specify the Ethernet address. Another option that might work is the IPV6_MULTICAST_IF option- #x is the relevant interface index sock.setsockopt(socket.IPPROTO_IPV6,socket.IPV6_MULTICAST_IF,x) In Windows, python 2.7, one should add the line socket.IPPROTO_IPV6=41 before this code (since the relevant enum is not well defined). Additional information can be found here (Windows) or here (Linux). Although it seems like a simpler solution, I didn't completely managed to make it work, and not sure what is the proper way to find the right interface index (on Windows, Linux has several options).
type: Answer
accepted answer of: http://stackoverflow.com/q/47077323
score: 0
has comment: http://stackoverflow.com/comment/81529273
answers question: http://stackoverflow.com/q/47077323

http://stackoverflow.com/a/47206892
has comment: http://stackoverflow.com/comment/81476072
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/81482474
answers question: http://stackoverflow.com/q/47179408
has body: you could specifying the encoding to BINARY Tempfile uses: temp_file = Tempfile.new('test', :encoding =&gt; 'binary')
type: Answer
has comment: http://stackoverflow.com/comment/81479563
downvote count: 0

http://stackoverflow.com/a/47149347
has comment: http://stackoverflow.com/comment/81270036
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47149230
type: Answer
has comment: http://stackoverflow.com/comment/81359408
has body: There are several problems with your code. You are redefining printv, timeLabel, and creating a new Tk() object at every step in your while loop. More importantly, you define printv as a StringVar, but immediately redefine it as a string. You should define each of them once outside of the while loop and then use the set() method of printv. Here is a very basic timer in Tkinter. First of all, you should not be using time.sleep or while loops. The mainloop function is already a while loop, and most tkinter objects have a .after() method that allows you to call events after a window of time (in milliseconds). Notice that I created a class to encapsulate my entire UI. All variables are stored within the class and updated from its methods. The time is set within the script itself (currently to 1 hour, 20 minutes, 10 seconds), though that is easy to modify to accept args from the command line or from text fields in the UI. from tkinter import Tk, Label, StringVar from tkinter.ttk import Button, Entry class Timer: def __init__(self, master): self.seconds = 0 self.time = StringVar() self.time_label = Label(master, relief='flat', font=("Cambria", 20), textvariable=self.time) self.hr = StringVar() self.hr_label = Label(master, text='Hours:').grid(row=1, column=1, padx=5, pady=1) self.entry_hr = Entry(master, textvariable=self.hr, width=4) self.entry_hr.grid(row=1, column=2) self.mins = StringVar() self.min_label = Label(master, text='Minutes:').grid(row=2, column=1, padx=5, pady=1) self.entry_min = Entry(master, textvariable=self.mins, width=4) self.entry_min.grid(row=2, column=2) self.secs = StringVar() self.secs_label = Label(master, text='Seconds:').grid(row=3, column=1, padx=5, pady=1) self.entry_sec = Entry(master, textvariable=self.secs, width=4) self.entry_sec.grid(row=3, column=2) self.time.set('00:00:00') self.start_button = Button(master, text='Start') self.start_button.bind('&lt;Button-1&gt;', self.start_countdown) self.time_label.grid(row=0, columnspan=4, padx=30,…
score: 0
has comment: http://stackoverflow.com/comment/81268846
has comment: http://stackoverflow.com/comment/81270420
has comment: http://stackoverflow.com/comment/81269219
accepted answer of: http://stackoverflow.com/q/47149230
has comment: http://stackoverflow.com/comment/81361702

http://stackoverflow.com/comment/81127306
comment on: http://stackoverflow.com/q/47088637
has text: `invoice1 = Invoice.query.filter_by(id=invoice2).first()` what value does it returns?
score: 0
type: Comment
type: QuestionComment

diff
tags question: http://stackoverflow.com/q/47131361
tag name: diff
tags question: http://stackoverflow.com/q/47188073
type: Tag

http://stackoverflow.com/comment/81328937
comment on: http://stackoverflow.com/a/47189510
has text: Define "not working" exactly. There are many things that can go wrong. Is the client connecting at all, yes or no? If Yes, is the client receiving any data at all, yes or no? Where EXACTLY is the error being reported? At which step in your code? Please be more specific about WHAT exactly is not working.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81328489
type: AnswerComment
comment on: http://stackoverflow.com/a/47189049
score: 1
type: Comment
has text: @AlarisHart I would just advise you go through what was written and think about how it works. `totalPrice = totalPrice + 5.80*float(amount2)` adds the current value of totalPrice to 5.80*duck. If it is > 25, of course it will never become lower unless you have negative duck. SO is meant to be used for learning as opposed to a code writing service. If you get stuck again, you can always ask another question - though I would try to explain your issues and thought process a bit better the next time. It shows you put in the effort.

http://stackoverflow.com/comment/81340375
comment on: http://stackoverflow.com/q/47195785
type: Comment
type: QuestionComment
has text: and duplicate suggestion is wrong...
score: 2

http://stackoverflow.com/q/47205653
has comment: http://stackoverflow.com/comment/81360699
has title: python dictionary put values of keys into a list where the keys are in another list
has body: I have a dictionary which looks like a = {32: [2230], 37265: [2218], 51: [2223], 164: [2227], 3944: [2224]} however, values in a could contain multiple elements, like a = {32: [2200, 2230], 37265: [2201, 2218], 51: [2223], 164: [2227], 3944: [2224]} I have a list that stores the keys in a in groups, b = [[32, 51, 164], [3944, 37265]] now I want to get values of keys in each group in another list, clusters = [] for key_group in b: group = [] for key in key_group: group.extend(a[key]) if len(group) &gt; 1: clusters.append(group) so the final list looks like, clusters = [[2230, 2223, 2227], [2224, 2218]] if a contains multiple elements in a value list, clusters looks like, clusters = [[2200, 2230, 2223, 2227], [2224, 2201, 2218]] I am wondering what's the best way to do this. Also in case when b contains list(s) which has only one value/key, and if this key maps to a single element list in a, this list will be ignored, a = {32: [2200, 2230], 37265: [2201, 2218], 51: [2223], 164: [2227], 3944: [2224]} b = [[32, 51, 164], [3944], [37265]] while 3944 maps to [2224], which will be ignored, but 37265 maps to [2201, 2218], which will be kept, since len([2201, 2218]) &gt; 1. clusters will look like the following in this case, clusters = [[2200, 2230, 2223, 2227], [2201, 2218]]
has comment: http://stackoverflow.com/comment/81360754
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47205741
possible better answer: http://stackoverflow.com/a/47205741
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81360092
has answer: http://stackoverflow.com/a/47205804
has comment: http://stackoverflow.com/comment/81360896
tagged with: python
tagged with: dictionary
answer count: 4
has comment: http://stackoverflow.com/comment/81360118
has answer: http://stackoverflow.com/a/47205838
has answer: http://stackoverflow.com/a/47205919
accepted answer: http://stackoverflow.com/a/47205838
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0

http://stackoverflow.com/comment/81350286
comment on: http://stackoverflow.com/a/47200772
has text: Directory not found
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47138162
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47138259
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: export-to-csv
has title: Writing to CSV results in each letter having its own cell
tagged with: http://stackoverflow.com/tag/csv
has body: I have some code that parses HTML with BeautifulSoup, and prints the code. Here is the source code (gist linked if interested): import csv import requests from bs4 import BeautifulSoup import lxml r = requests.post('https://opir.fiu.edu/instructor_evals/instr_eval_result.asp', data={'Term': '1175', 'Coll': 'CBADM'}) soup = BeautifulSoup(r.text, "lxml") tables = soup.find_all('table') print(tables) print(tables) The output of my code before exporting to CSV looks like this: Question No Response Excellent Very Good Good Fair Poor Description of course objectives and assignments 0.0% 76.1% 17.4% 6.5% 0.0% 0.0% Communication of ideas and information 0.0% 78.3% 17.4% 4.3% 0.0% 0.0% I really liked this output, and wanted to export it to a CSV, so I then added the following: writer = csv.writer(open("C:\\Temp\\output_file.csv", 'w')) for table in tables: rows = table.find_all("tr") for row in rows: cells = row.find_all("td") if len(cells) == 7: # this filters out rows with 'Term', 'Instructor Name' etc. for cell in cells: print(cell.text + "\t", end="") writer.writerow(cell.text) print("") # newline after each row print("-------------") # table delimiter Unfortunately, this code results in each single unique character or letter having its own cell: So my question is this: how can I fix this code so that it properly exports the output to a CSV file, without adding a new cell for each and every character? I'm not exactly sure why it is doing this. It also seems to only be exporting the very first table, and ignoring every other piece of data in the code.
has answer: http://stackoverflow.com/a/47138259
tagged with: python

http://stackoverflow.com/comment/81240322
has text: @HuStmpHrrr Bro, I am not the OP xD
comment on: http://stackoverflow.com/a/47144535
type: Comment
type: AnswerComment
score: 1

dependencies
tags question: http://stackoverflow.com/q/47086702
type: Tag
tag name: dependencies

http://stackoverflow.com/a/47210031
has comment: http://stackoverflow.com/comment/81384843
answers question: http://stackoverflow.com/q/47205538
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47205538
has body: You might not want to pass sum to callback method using on_state property change because the method, callback will be invoked twice - once when you press the button, and once when you release the button. Therefore, you want to use on_press or on_release event with lambda function to pass sum to callback method. The best way depends on how many items you want to pass to the method. The example below illustrates two possibilities - lambda and partial functions. Overload method __init__ def __init__(self, **kwargs): super(DemoBox, self).__init__(**kwargs) We overload the method __init__() so as to add widgets and to define their behavior. One should not forget to call super in order to implement the functionality of the original class being overloaded. Also note that it is good practice not to omit the **kwargs while calling super, as they are sometimes used internally. By running __init__ we're passing **kwargs up the object hierarchy and also re-defining __init__ which would normally run the initialization of the parent class. super is used to allow us to pass **kwargs and run the parent __init__ without an explicit call to the parent class. In this case, BoxLayout inherits from Layout; without a super call you're overriding the parent class. Example main.py from kivy.app import App from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from functools import partial class DemoBox(BoxLayout): def __init__(self, **kwargs): super(DemoBox, self).__init__(**kwargs) self.orientation = "vertical" self.myFunc() def myFunc(self): sum = 2 + 2 btn1 = Button(id="summButton", text="Normal binding to a property change") btn1.bind(state=partial(self.callback, x=sum)) btn2 = Button(text="Bind on_press/on_release event") btn2.bind(on_press=lambda x: self.on_press(x=sum)) self.add_widget(btn1) self.add_widget(btn2) def callback(self, obj, value, x): print("callback: x=", x) def on_press(self, x): print("on_press: x=", x) class TestApp(App): title = "Kivy Passing A…
upvote count: 3
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/81409662

http://stackoverflow.com/q/47134358
downvote count: 0
upvote count: 1
tagged with: cloud-foundry
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/47162897
has title: How to do a cf push from python script?
has body: I am new to Cloud foundry. Here is the use case which I want to achieve, I want to write a python script, which will invoke the api end point, go to the corresponding org/space and then issue a cf push command. I was able to login and get the metadata of the orgs using below script: import os from cloudfoundry_client.client import CloudFoundryClient target_endpoint = 'https://run.api.pivotal.io' proxy = dict(http=os.environ.get('HTTP_PROXY', ''), https=os.environ.get('HTTPS_PROXY', '')) client = CloudFoundryClient(target_endpoint, proxy=proxy, skip_verification=True) client.init_with_user_credentials('abcd@mail.com', 'password') for organization in client.organizations: print organization['metadata']['guid'] Please sugggest, also if there are any links do share.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47162897
score: 1
answer count: 1

http://stackoverflow.com/q/47160587
downvote count: 0
tagged with: scrapy
has body: Is it possible to use Scrapy to generate a sitemap of a website including the URL of each page and its level/depth (the number of links I need to follow from the home page to get there)? The format of the sitemap doesn't have to be XML, it's just about the information. Furthermore I'd like to save the complete HTML source of the crawled pages for further analysis instead of scraping only certain elements from it. Could somebody experienced in using Scrapy tell me whether this is a possible/reasonable scenario for Scrapy and give me some hints on how to find instructions? So far I could only find far more complex scenarios but no approach for this seemingly simple problem. Addon for experienced webcrawlers: Given it is possible, do you think Scrapy is even the right tool for this? Or would it be easier to write my own crawler with a library like requests etc.?
favorite count: 0
type: Question
score: 5
has comment: http://stackoverflow.com/comment/81271775
type: UnansweredQuestion
has title: Sitemap creation with Scrapy
has comment: http://stackoverflow.com/comment/81272388
upvote count: 5
has comment: http://stackoverflow.com/comment/81271397
has comment: http://stackoverflow.com/comment/81272099
tagged with: python
has answer: http://stackoverflow.com/a/61992037
has comment: http://stackoverflow.com/comment/81272293
answer count: 1

http://stackoverflow.com/comment/81354531
has text: @CODE_DIY please check my answer I think this might help more.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47202397
type: AnswerComment

http://stackoverflow.com/comment/81131330
has text: I would say not, looking at the examples, but i think one of the lists _could_ be sorted
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47090519

django-templates
tags question: http://stackoverflow.com/q/47137992
tags question: http://stackoverflow.com/q/47168320
tags question: http://stackoverflow.com/q/47182268
tags question: http://stackoverflow.com/q/47172689
tags question: http://stackoverflow.com/q/47119131
tags question: http://stackoverflow.com/q/47072412
tags question: http://stackoverflow.com/q/47162413
tag name: django-templates
tags question: http://stackoverflow.com/q/47204828
tags question: http://stackoverflow.com/q/47177696
tags question: http://stackoverflow.com/q/47182403
type: Tag

http://stackoverflow.com/q/47184667
tagged with: tiles
answer count: 1
tagged with: gis
accepted answer: http://stackoverflow.com/a/47185145
type: Question
has comment: http://stackoverflow.com/comment/81344353
tagged with: python
has title: Tile numbers to lon./lat. in EPSG:3395
has answer: http://stackoverflow.com/a/47185145
has comment: http://stackoverflow.com/comment/81319150
has body: I need to convert tiles number into lon./lag in EPSG:3395 but i don't find the solution. I've found the code for EPSG:4326 but i don't find a way to adapt it for EPSG:3395. Code for 4326 (it works well) : $n = pow(2, $zoom); $lon_deg = $xtile / $n * 360.0 - 180.0; $lat_deg = rad2deg(atan(sinh(pi() * (1 - 2 * $ytile / $n)))); I need to convert tiles number into lon./lag in EPSG:3395 but i don't find a working solution. I have implemented some code based on this answer. when I've tried to convert 4326 degrees into 3395 degrees: def getVal(x, y, n): lon_deg = x / n * 360.0 - 180.0 lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * y / n))) lat_deg = math.degrees(lat_rad) #Convert in 3395 a = 6378137 #WGS84 semi-major axis b = 6356752.3142 #WGS84 semi-minor axis print(math.sqrt(1 - b^2 / a^2)) e = math.sqrt(1 - b^2 / a^2) #ellipsoid eccentricity c = math.pow((1 - e*math.sin(latitude)) / (1 + e*math.sin(latitude)), e/2) lat_deg = a * ln(math.tan(math.pi/4 + lat_deg/2) * c) lon_deg = a * lon_deg; I obtain the following Error message: Unsupported operand type(s) for float and INT Update: I have corrected to code to below by replacing ^ with **. Code: def getVal(x, y, n): #Calcuate coordinates in 4326 lon_deg = x / n * 360.0 - 180.0 lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * y / n))) lat_deg = math.degrees(lat_rad) #Convert coordinates in 3395 a = 6378137 #WGS84 semi-major axis b = 6356752.3142 #WGS84 semi-minor axis e = math.sqrt(1 - b**2 / a**2) #ellipsoid eccentricity c = math.pow((1 - e*math.sin(lat_deg)) / (1 + e*math.sin(lat_deg)), e/2) lon_deg = a * lon_deg; lat_deg = a * math.log(math.tan(math.radians(math.pi/4 + lat_deg/2) * c)) But still the projection is strange. I assume the problem is on this part: lat_deg = a * math.log(math.tan(math.radians(math.pi/4 + lat_deg/2) I had to insert math.radians as math.tan doesn't like degree angle. Any idea?
linked to: http://stackoverflow.com/q/34258537
tagged with: projection
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/81154914
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47102397
has text: Upvoters, care to explain?
score: 2

http://stackoverflow.com/q/47131193
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81212812
has comment: http://stackoverflow.com/comment/81212946
tagged with: data-analysis
score: 1
accepted answer: http://stackoverflow.com/a/47131625
has comment: http://stackoverflow.com/comment/81213113
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/47386216
has answer: http://stackoverflow.com/a/47131587
has comment: http://stackoverflow.com/comment/81212924
possible better answer: http://stackoverflow.com/a/47131587
type: AnsweredQuestion
has title: value matching between two DataFrames using pandas in python
has comment: http://stackoverflow.com/comment/81212267
answer count: 2
has body: Hi I have two DataFrames like below DF1 Alpha | Numeric | Special and | 1 | @ or | 2 | # lol ok | 4 | &amp; DF2 with single column Content boy or girl school @ morn pyc LoL ok student Chandra I want to search if anyone of the column in DF1 has anyone of the keyword in content column of DF2 and the output should be in a new DF `df11 = (df1.unstack() .reset_index(level=2,drop=True) .rename_axis(('col_order','col_name')) .dropna() .reset_index(name='val_low')) df22 = (df2['Content'].str.split(expand=True) .stack() .rename('val') .reset_index(level=1,drop=True) .rename_axis('idx') .reset_index())` df22['val_low'] = df22['val'].str.lower() df = (pd.merge(df22, df11, on='val_low', how='left') .dropna(subset=['col_name']) .sort_values(['idx','col_order']) .drop_duplicates(['idx'])) df = (pd.concat([df2, df.set_index('idx')], axis=1) .fillna({'col_name':'Other'})'val','col_name','Content') but it is not considering the spaces between lol ok expected_output_DF val col_name Content 0 or Alpha boy or girl 1 @ Special school @ morn 2 lol ok Alpha pyc LoL ok student 3 NaN Other Chandra someone help me with this
downvote count: 0
has comment: http://stackoverflow.com/comment/81212201
has comment: http://stackoverflow.com/comment/81212273
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/47131625

http://stackoverflow.com/comment/81332494
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47191492
score: 0
has text: i managed to fix else to return count that should be fine thank you

http://stackoverflow.com/comment/81376611
comment on: http://stackoverflow.com/q/47213315
type: Comment
type: QuestionComment
score: 0
has text: `apt install curl`, then `curl http://rivalregions.com/rss/all > file`

http://stackoverflow.com/comment/81499283
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47232117
type: Comment
has text: great, if it helped you please feel free to mark this question as answered :)

http://stackoverflow.com/a/47162452
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47161842
has body: Pretty simple in the end: I used frozenset, rather than set.

http://stackoverflow.com/a/56148807
answers question: http://stackoverflow.com/q/47081088
type: Answer
has body: After following step (4) of @thenaturalist's response, sc.addPyFile("/home/glue/downloads/python/pg8000.zip") import pg8000 worked for me in a development endpoint (zeppelin notebook) More info: https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-python-libraries.html
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81181210
type: AnswerComment
comment on: http://stackoverflow.com/a/47115578
score: 0
has text: Oops, was meant as a suggestion but became an edit. As int(True/False) evaluates to 1/0 you could go straight to adding the points. +1
type: Comment

http://stackoverflow.com/a/47118138
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81186430
has body: Starting from python3.5+, you can use glob and do a recursive traversal of your directories. Assuming you want to remove all CSV files, you can do this: root = os.getcwd() for file in glob.glob('*/**/*.csv'): try: os.remove(os.path.join(root, file)) except OSError: ...
has comment: http://stackoverflow.com/comment/81186297
has comment: http://stackoverflow.com/comment/81186245
has comment: http://stackoverflow.com/comment/81186263
has comment: http://stackoverflow.com/comment/81186289
type: Answer
accepted answer of: http://stackoverflow.com/q/47118121
has comment: http://stackoverflow.com/comment/81186317
answers question: http://stackoverflow.com/q/47118121
has comment: http://stackoverflow.com/comment/81186421
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/47174460
has comment: http://stackoverflow.com/comment/81299064
has comment: http://stackoverflow.com/comment/81305653
has comment: http://stackoverflow.com/comment/81298731
has comment: http://stackoverflow.com/comment/81298642
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47174294
has comment: http://stackoverflow.com/comment/81298690
has comment: http://stackoverflow.com/comment/81298554
score: 3
answers question: http://stackoverflow.com/q/47174294
has body: You could simply convert your inner lists to tuples. Python lists aren't hashable, so you cannot put them into a set. I guess that's the reason why your 3rd attempt didn't work. Sets substraction If your inner elements are hashable (e.g. int, float, string) and your inner lists are converted to tuples, you can convert your outer lists to sets and calculate set1 - set2. import random l1 = [[random.randrange(10), random.randrange(10)] for _ in range(100)] l2 = [[random.randrange(10), random.randrange(10)] for _ in range(100)] # set(l1) ## TypeError: unhashable type: 'list' set1 = {tuple(l) for l in l1} set2 = {tuple(l) for l in l2} print(l1) # [[0, 9], [9, 7], [8, 7], [6, 7], [1, 4], [2, 7], [8, 9], [8, 7], [5, 0], [3, 8], [8, 1], [6, 3], [5, 2], [0, 5], [2, 0], [2, 4], [7, 8], [2, 3], [4, 6], [4, 4], [3, 1], [7, 5], [2, 6], [8, 5], [6, 0], [0, 0], [4, 8], [5, 2], [1, 8], [6, 8], [9, 7], [0, 8], [5, 5], [4, 6], [0, 7], [0, 8], [7, 8], [5, 3], [2, 4], [1, 0], [8, 8], [6, 5], [8, 9], [7, 0], [8, 0], [1, 1], [1, 3], [2, 6], [3, 8], [7, 2], [6, 8], [3, 9], [1, 9], [9, 8], [3, 8], [1, 2], [1, 1], [2, 5], [7, 8], [3, 9], [0, 6], [9, 4], [4, 6], [9, 6], [8, 9], [7, 2], [4, 6], [9, 0], [0, 7], [0, 1], [5, 6], [5, 1], [1, 5], [9, 1], [8, 9], [4, 5], [4, 0], [4, 2], [1, 7], [9, 7], [4, 7], [1, 6], [9, 2], [7, 0], [9, 8], [3, 7], [9, 9], [9, 9], [0, 7], [3, 0], [0, 4], [4, 7], [9, 9], [0, 4], [9, 1], [2, 9], [7, 7], [5, 6], [6, 4], [7, 4]] print(l2) # [[0, 4], [2, 0], [1, 2], [9, 0], [8, 0], [2, 0], [5, 6], [6, 2], [2, 5], [0, 1], [9, 7], [8, 1], [3, 5], [3, 5], [3, 1], [0, 4], [4, 1], [1, 1], [3, 3], [0, 8], [3, 3], [5, 8], [1, 3], [0, 9], [6, 6], [4, 4], [6, 9], [0, 4], [5, 5], [0, 8], [4, 5], [4, 1], [0, 8], [2, 2], [2, 9], [1, 1], [7, 2], [8, 3], [6, 3], [1, 0], [6, 0], [4, 8], [1, 4], [8, 2], [9, 7], [5, 9], [6, 3], [7, 2], [9, 7], [8, 3], [8, 6], [3, 6], [7, 8], [9, 4], [1, 2], [6, 1], [1, 7], [5, 0], [8, 6], [7, 5], [0, 0], [6, 9], [1, 3], [0, 0], [8, 9], [6, 2], [4, 6], …
has comment: http://stackoverflow.com/comment/81298369
type: Answer

http://stackoverflow.com/comment/81094643
type: Comment
has text: You'll need to provide a lot more information before anyone can assist you. For example, what do you mean by a "new S3 File System"? (S3 is not a file system.) What are you doing when you receive the 'already exists' error -- show us your code or the command you are using. Feel free to Edit your question to add more details. For tips on asking a good question, see: [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask).
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47070460

http://stackoverflow.com/a/47190984
upvote count: 3
has body: You can just give them all default values of None, then pass the arguments as keyword arguments: def foo(a=None, b=None, c=None): print(a, b, c) foo(a=123, b=456) foo(a=123, c=789) foo(b=456, c=789) This example produces: 123 456 None 123 None 789 None 456 789
downvote count: 0
score: 3
type: Answer
answers question: http://stackoverflow.com/q/47190911

http://stackoverflow.com/a/47106682
score: 3
has body: What you are doing is Min-max scaling. "normalize" in scikit has different meaning then what you want to do. Try MinMaxScaler. And most of the sklearn transformers output the numpy arrays only. For dataframe, you can simply re-assign the columns to the dataframe like below example: import pandas as pd import numpy as np df = pd.DataFrame(data=np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns=['A', 'B', 'C']) Now lets say you only want to min-max scale the columns A and C: from sklearn.preprocessing import MinMaxScaler minmax = MinMaxScaler() df'A', 'C' = minmax.fit_transform(df'A', 'C')
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47106305
type: Answer

http://stackoverflow.com/a/47087955
accepted answer of: http://stackoverflow.com/q/47087907
type: Answer
has body: Use ffill along the first axis. df.ffill(axis=1) 1 2 3 4 0 b b b c 1 c c d d 2 d d d c
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47087907

http://stackoverflow.com/comment/81330926
type: Comment
comment on: http://stackoverflow.com/a/47170961
type: AnswerComment
has text: this has brought more light in my confusion, thanks again. Actually this is one part of a larger program, which uses turtle graphics as user interface. So all is already wrapped in a `screen.mainloop()`. Right now I use `turtle.textinput()` to update `u_choice`, but that's rather awkward and error prone. Thanks for your effort!
score: 0

http://stackoverflow.com/comment/81380617
has text: I don't know what you mean by that.
score: 0
comment on: http://stackoverflow.com/a/47215376
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47196053
accepted answer of: http://stackoverflow.com/q/47194856
answers question: http://stackoverflow.com/q/47194856
has body: I tested your Client.py and it seems works well, but when I send hex 0xfb, the program crushed like that, so I think your server part sends invalid data, which is not in utf-8 format. I suggest you to put a debug code like this: data = b''.join(iter(read_socket, b'')) print(bytes(data)) text += data.decode().strip() so you can see what bytes you sent and find the invalid data, that your server sends.
type: Answer
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47213770
tagged with: python
has title: Install problems with homebrew's python
has comment: http://stackoverflow.com/comment/81389511
has comment: http://stackoverflow.com/comment/88946148
has answer: http://stackoverflow.com/a/50983597
score: 1
tagged with: homebrew
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88961987
favorite count: 0
has comment: http://stackoverflow.com/comment/81377151
type: Question
has body: Setting up a new mac here. I just installed python with brew install python, but when I try to install virtualenv with sudo pip install virtualenv it returns sudo: pip: command not found. When I try sudo easy_install pip it returns the following response Traceback (most recent call last): File "/usr/local/bin/easy_install", line 11, in &lt;module&gt; load_entry_point('setuptools==33.1.1', 'console_scripts', 'easy_install')() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 565, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2697, in load_entry_point return ep.load() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2370, in load return self.resolve() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2376, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "build/bdist.macosx-10.12-intel/egg/setuptools/__init__.py", line 10, in &lt;module&gt; File "build/bdist.macosx-10.12-intel/egg/setuptools/extern/__init__.py", line 1, in &lt;module&gt; ImportError: No module named extern I can't imagine what is happening, but with my old installation I had any of this problems. Any help woul be really helpful…
type: UnansweredQuestion

http://stackoverflow.com/comment/81116891
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47083799
has text: Does it matter which three numbers are the same?
type: Comment

http://stackoverflow.com/comment/81078230
type: QuestionComment
has text: @juanpa.arrivillaga thank you for the help!
comment on: http://stackoverflow.com/q/47064885
score: 0
type: Comment

http://stackoverflow.com/a/47170712
score: 1
answers question: http://stackoverflow.com/q/47170100
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47170100
downvote count: 0
upvote count: 1
has body: df col 0 [a, b, c, d] 1 [d, e, f] 2 [h, i, j, k, l] 3 [m, n, o, p] 4 [q, r, s] Use the str accessor methods: df.col.str[1:-1].str.join(sep='/') 0 b/c 1 e 2 i/j/k 3 n/o 4 r Name: col, dtype: object

http://stackoverflow.com/q/47160723
has comment: http://stackoverflow.com/comment/81281042
answer count: 0
has comment: http://stackoverflow.com/comment/81282146
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81275881
has comment: http://stackoverflow.com/comment/81281161
has comment: http://stackoverflow.com/comment/81280919
has body: Is there a way to use ffmpeg in such a way that, it expects new data everytime it finishes it operation. For example, calling ffmpeg with a pipe, using a program, feed ffmpeg new frames while reading results, so keeping the process alive until desired time. Expected run: Run command -> write frame to stdin -> read result(stdout) -> write frame -> read result-> ... I am using Python3 to pipe ffmpeg, if it helps.
has title: FFmpeg use without closing process
tagged with: video-streaming
type: Question
tagged with: ffmpeg
score: 0

http://stackoverflow.com/comment/135377560
type: AnswerComment
comment on: http://stackoverflow.com/a/47393161
has text: `--install-option` was deprecated in [pip 22.3](https://pip.pypa.io/en/stable/news/#v22-3) and removed in [pip 23.1](https://pip.pypa.io/en/stable/news/#v23-1).
score: 2
type: Comment

http://stackoverflow.com/comment/81326732
type: Comment
has text: this actually has some edge case fails... imma edit real quick
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47188644

http://stackoverflow.com/q/47085598
has comment: http://stackoverflow.com/comment/81123065
tagged with: python-sip
has title: How do i install PyQt5 with python 3.7.0a2 on windows 10
has comment: http://stackoverflow.com/comment/81120911
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/57754547
has answer: http://stackoverflow.com/a/47085913
tagged with: python
has answer: http://stackoverflow.com/a/57754547
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/81121158
possible better answer: http://stackoverflow.com/a/47085913
has body: I am new to all of this and I am trying to install PyQt5, I entered "pip install pyqt5" and this is what happened - ( its cached because of previous download attempt) C:\Users\Liam>pip install pyqt5 Collecting pyqt5 Using cached PyQt5-5.9.1-5.9.2-cp35.cp36.cp37-none-win_amd64.whl Collecting sip&lt;4.20,>=4.19.4 (from pyqt5) Could not find a version that satisfies the requirement sip&lt;4.20,>=4.19.4 (from pyqt5) (from versions: ) No matching distribution found for sip&lt;4.20,>=4.19.4 (from pyqt5) Can anyone give me some pointers I am completely lost. Thank you for any help that you can give me Liam
tagged with: pyqt5

http://stackoverflow.com/q/47070252
score: 0
tagged with: google-cloud-platform
tagged with: api
has title: Google Cloud Billing API using Python
answer count: 1
tagged with: google-api-python-client
type: Question
has answer: http://stackoverflow.com/a/47135588
has body: I'm trying to get billingInfo for a google cloud project using python 3.6 I have done with request to billing API but the response is not expected, As Google's documentation for Billing Api says that it returns Name, ProjectId, billingAccountName &amp; billingEnabled. But it only returns name and projectId even for a project which doesn't associate with a billing account. Here's my code: projectName = form.cleaned_data['project_id'] # Get billing Info of selected project auth = getauth() service = discovery.build('cloudbilling', 'v1', http=auth, cache_discovery=False) name = 'projects/' + projectName billing_request = service.projects().getBillingInfo(name=name,) billing_response = billing_request.execute() data = billing_response print(json.dumps(data)) if data['name']: return HttpResponse(json.dumps(data), content_type='application/json') else: data = [] return HttpResponse(json.dumps(data), content_type='application/json') and it returns the response as : {"name": "projects/docker-184805/billingInfo", "projectId": "docker-184805"} Even billing is not enabled for this project. How can I get the proper billing info for a project on google cloud platform using API python client? Help me, please! Thanks in advance!
type: UnansweredQuestion
tagged with: google-cloud-billing
tagged with: python

http://stackoverflow.com/comment/81121662
score: 3
has text: `int(num)` in a string literal isn't `4`. String literal contents aren't executed as Python code.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47085990

http://stackoverflow.com/a/48942164
has body: The file: configs/tutorial/two_level.py has never been part of the main tree according to: git log -p -- '**/two_level.py' so you must provide its source. Supposing you are talking about configs/learning_gem5/part1/two_level.py, the problem is not reproducible on master at da79d6c6cde0fbe5473ce868c9be4771160a003b with the command: ./build/X86/gem5.opt configs/learning_gem5/part1/two_level.py which appears to run correctly.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47162863

http://stackoverflow.com/comment/81156877
type: AnswerComment
comment on: http://stackoverflow.com/a/47103158
score: 0
type: Comment
has text: @UpmostScarab, `w` mode should also truncate the file so this shouldnt change anything

http://stackoverflow.com/q/47104381
has answer: http://stackoverflow.com/a/47104581
upvote count: 8
has body: I'm trying to debug a for loop and want to see what's happening inside after it has run for a while. It iterates several thousand times and I'd want to check what's happening every hundred or so. Is there a way to tell pdb to run the next command a few hundred times so I can check quickly?
tagged with: python
favorite count: 0
score: 8
type: Question
has title: pdb repeat next command N times
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47104581
tagged with: pdb
tagged with: debugging
type: AnsweredQuestion

http://stackoverflow.com/q/47105636
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81161919
has answer: http://stackoverflow.com/a/47105693
has comment: http://stackoverflow.com/comment/81162041
answer count: 5
type: UnansweredQuestion
tagged with: function
has answer: http://stackoverflow.com/a/47105734
has comment: http://stackoverflow.com/comment/81162006
linked to: http://stackoverflow.com/q/10235973
tagged with: python
has answer: http://stackoverflow.com/a/47105758
has answer: http://stackoverflow.com/a/47105724
tagged with: parameters
has answer: http://stackoverflow.com/a/47105658
score: 0
has body: So I have this code and call me an idiot haha, but I cant get this to print None then 7. Code: def function(parameter): parameter = parameter + 1 parameter = 6 print(function(parameter)) print(parameter == 7) I need to know how to alter the variable that has the same name as the parameter in the function. Any help would be greatly appreciated, and if you don't understand the question I'd be glad to explain more.
has title: Why does this not print None then 7? Python

http://stackoverflow.com/a/50233142
has body: Nothing new to add just wanted to rephrase the above solution in a more function based way without tunneling: import socket import base64 import time, datetime import hmac import hashlib import ssl host = 'fix.gdax.com' #sandbox_host = 'fix-public.sandbox.gdax.com' port = 4198 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssl_sock = context.wrap_socket(s, server_hostname=host) ssl_sock.connect((host, port)) def check_sum(s): sum = 0 for char in s: sum += ord(char) sum = str(sum % 256) while len(sum) &lt; 3: sum = '0' + sum return sum def sign(t, msg_type, seq_num, api_key, password, secret): message = "\x01".join([t, msg_type, seq_num, api_key, "Coinbase", password]).encode("utf-8") hmac_key = base64.b64decode(secret) signature = hmac.new(hmac_key, message, hashlib.sha256) return base64.b64encode(signature.digest()).decode() def wrap_fix_string(msg_type, body): bodyLength = len("35={}|".format(msg_type)) + len(body) header = "8=FIX.4.2|9=00{}|35={}|".format(bodyLength, msg_type) msg = header + body return msg def generate_login_string(seq_num, t, api_key, password, secret): msgType = "A" sign_b64 = sign(t, msgType, seq_num, api_key, password, secret) body = f"49={api_key}|554={password}|96={sign_b64}|8013=S|52={t}|56=Coinbase|98=0|108=30|34={seq_num}|9406=N|" # using the same time (t) and seq_num as in signed text msg = wrap_fix_string(msgType, body) msg = msg.replace('|', '\x01') c_sum = check_sum(msg) return msg + "10={}\x01".format(c_sum) PASSPHRASE = "your passphrase" API_KEY = "your api key" API_SECRET = "your secret" seq_num = "1" t = str(datetime.datetime.utcnow()).replace("-","").replace(" ", "-")[:-3] logon = generate_login_string(seq_num, t, API_KEY, PASSPHRASE, API_SECRET) logon = logon.encode('ascii') print(f'logon: {logon}') ssl_sock.sendall(logon) print('GETTING') print(ssl_sock.recv(4096))
answers question: http://stackoverflow.com/q/47110454
has comment: http://stackoverflow.com/comment/115198806
score: 2
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81299408
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47175043
has text: why do you think the logger/config will survive daemonization..? (it's not the same process anymore)
type: Comment

http://stackoverflow.com/a/47203101
has body: replacements = { 'H':'1', 'e':'2', 'l':'3', 'o':'4', 'm':'5' } s = "Hello my name is TGMezza" for key in replacements: s = s.replace(key,replacements[key]) print(s) Or replacements = { 'H':'1', 'e':'2', 'l':'3', 'o':'4', 'm':'5' } s = "Hello my name is TGMezza" s = ''.join(replacements[x] if x in replacements else x for x in s)
score: 2
has comment: http://stackoverflow.com/comment/81355899
has comment: http://stackoverflow.com/comment/81355372
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/81355921
answers question: http://stackoverflow.com/q/47202965
type: Answer
has comment: http://stackoverflow.com/comment/81355534
has comment: http://stackoverflow.com/comment/81354935

http://stackoverflow.com/comment/81153653
type: Comment
score: 0
type: AnswerComment
has text: Your data are in a separate file with 4000 distinct variable names?
comment on: http://stackoverflow.com/a/47101663

http://stackoverflow.com/comment/81199892
type: AnswerComment
has text: @PandemicCode glad it help ,have nice day :-)
comment on: http://stackoverflow.com/a/47124040
type: Comment
score: 0

http://stackoverflow.com/comment/81329728
has text: Hey sorry if I don't respond to all accounts I'm still figuring out how StackOverflow operates with comments haha. ikolim and SP SP this totally works thank you for saving me from the headache! I spent hours last night.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47189421

http://stackoverflow.com/comment/81363038
type: QuestionComment
has text: Are the positions in both same?
comment on: http://stackoverflow.com/q/47207013
score: 0
type: Comment

http://stackoverflow.com/q/47103136
linked to: http://stackoverflow.com/q/47062396
tagged with: python
has comment: http://stackoverflow.com/comment/81158366
tagged with: caching
type: Question
has answer: http://stackoverflow.com/a/47117543
has body: I am trying to use this code to create an HTTP proxy cache server. When I run the code it starts running and connects to the port and everything but when I try to connect from the browser, for example, it opens a port on 55555 if I type in localhost:52523/www.google.com it works fine but when I try other sites specifically HTTP, for example, localhost:52523/www.microcenter.com or just localhost:52523/google.com it will display localhost didn’t send any data. ERR_EMPTY_RESPONSE and shows an exception in the console though it creates the cache file on my computer. I would like to find out how to edit the code so that I can access any website just as I would normally do on the browser without using the proxy server. It should be able to work with www.microcenter.com import socket import sys import urllib from urlparse import urlparse Serv_Sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # socket.socket function creates a socket. port = Serv_Sock.getsockname()[1] # Server socket created, bound and starting to listen Serv_Sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # socket.socket function creates a socket. Serv_Sock.bind(('',port)) Serv_Sock.listen(5) port = Serv_Sock.getsockname()[1] # Prepare a server socket print ("starting server on port %s...,"%(port)) def caching_object(splitMessage, Cli_Sock): #this method is responsible for caching Req_Type = splitMessage[0] Req_path = splitMessage[1] Req_path = Req_path[1:] print "Request is ", Req_Type, " to URL : ", Req_path #Searching available cache if file exists url = urlparse(Req_path) file_to_use = "/" + Req_path print file_to_use try: file = open(file_to_use[5:], "r") data = file.readlines() print "File Present in Cache\n" #Proxy Server Will Send A Response Message #Cli_Sock.send("HTTP/1.0 200 OK\r\n") #Cli_Sock.send("Content-Type:text/html") #Cli_Sock.send("\r\n") #Proxy Server Will Send Data for i in range(0, len(data)): print (data[i]) Cli_Sock.send(data[i]) print "Reading file from cache\n" exc…
type: UnansweredQuestion
answer count: 1
has title: http proxy cache server not limiting browser functionality
tagged with: http
tagged with: https
tagged with: proxy
score: 0

http://stackoverflow.com/a/47072460
downvote count: 0
upvote count: 1
has body: import math import itertools def is_prime(n): return all(n % i for i in range(2, int(math.sqrt(n) + 1))) prime_digits = {"2", "3", "5", "7"} def no_prime_digit(n): return not any(x in prime_digits for x in str(n)) def non_primes(): return (i for i in itertools.count() if no_prime_digit(i) and not is_prime(i)) def get_non_prime(n): return next(x for i, x in enumerate(non_primes()) if i == n - 1) print([(x, get_non_prime(x)) for x in [1, 10, 100]])
has comment: http://stackoverflow.com/comment/81094757
type: Answer
has comment: http://stackoverflow.com/comment/81094828
answers question: http://stackoverflow.com/q/47071321
score: 1

http://stackoverflow.com/comment/81124136
type: QuestionComment
has text: I didn't define "index", that was left up to him.
type: Comment
comment on: http://stackoverflow.com/q/47087022
score: 0

http://stackoverflow.com/comment/81214009
type: Comment
score: 0
has text: @RomanPerekhrest I'm posting an answer.
type: QuestionComment
comment on: http://stackoverflow.com/q/47131980

http://stackoverflow.com/comment/81285365
has text: What environment are you running this program in? Whatever it is, it lacks some feature that `getpass()` uses to hide character echo. If you're running the code from inside an IDE of some sort, try running it directly from the command line instead.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47167139
score: 2

http://stackoverflow.com/comment/81334502
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47190372
type: QuestionComment
has text: How large an image and on what hardware do you need the 2 seconds performance? Pretty sure Halide can take care of that for a pretty broad set of parameters. Will see if I can get some time later to try. This would be brute force, but taking advantage of parallelism in the hardware and a specific compiled implementation.

http://stackoverflow.com/comment/81119209
type: AnswerComment
comment on: http://stackoverflow.com/a/47084292
has text: Oh, it does appear that you need to change `for idx, item in enumerate(iterable):` so that it uses a different start: `for idx, item in enumerate(iterable, 1):` You may also want to change `buffer = Deque(maxlen=n)` to instead be `buffer, idx = Deque(maxlen=n), 0`.
score: 0
type: Comment

http://stackoverflow.com/comment/81368370
has text: You probably need `trainingSet.extend(dataset[:106])`. A few `print` statements can help you figure out what's going on. E. g. `print trainingSet` and `print len(trainingSet[0])`. These print statements are for Python 2.7 -- If you're on Python 3.x, you need extra parantheses, like so: `print(trainingSet)`.
comment on: http://stackoverflow.com/q/47209266
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47128717
answer count: 2
has comment: http://stackoverflow.com/comment/81207430
upvote count: 0
downvote count: 3
has answer: http://stackoverflow.com/a/47128738
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81207446
has body: I cannot seem to get my piece of code to work correctly. I am sure there are many different ways in order to get this piece of code working with less lines, but this is the only way I can write code for now while understanding it. When I use values such as 500 for max cost and "b" for desired_features I am only returned with Scarborough, when I should be returned with: Barcelona, California, Corfu, Scarborough, and Whitby as they all have beaches and cost less than 500. print("INPUT:") max_cost = input( "How many coins do you want to? " ) print("""\nDesired holdiday features: b = beach c = culture h = hot m = mountains """) desired_features = input( "Enter string of first letters of desired features: " ) #barcelona if (max_cost &gt;="320" and desired_features == ("bch","b","c", "h", "bc", "bh", "cb", "ch", "hb", "hc" )): \ destination_list = "Barcelona" else: destination_list = [] print (destination_list) #California if (max_cost &gt;="750" and desired_features == ("bhm" , "b", "h", "m", "bh", "bm", "hb", "hm", "mb", "mh" )):\ destination_list = "California" else: destination_list = [] print (destination_list) #Corfu if (max_cost &gt;="300" and desired_features == ("bh", "b", "h", "hb")):\ destination_list = "Corfu" else: destination_list = [] print (destination_list) #Paris if (max_cost &gt;="250" and desired_features == "c"): \ destination_list = "Paris" else: destination_list = [] print (destination_list) #Rome if (max_cost &gt;="300" and desired_features == ("ch", "c", "h", "hc")): \ destination_list = "Rome" else: destination_list = [] print (destination_list) #Scarborough if (max_cost &gt;="45" and desired_features == "b"): \ destination_list = "Scarborough" else: destination_list = [] print (destination_list) #Switzerland if (max_cost &gt;="450" and desired_features == ("cm", "c", "m", "mc")): \ destination_list = "Switzerland" else: destination_list = [] print (destination_list) #Whitby if (max_cost &gt;="60" and desired_features == ("bc", "c", "b", "bc")): …
has comment: http://stackoverflow.com/comment/81207442
type: UnansweredQuestion
has title: Python 3 not reading 'if's correctly
score: -3
has answer: http://stackoverflow.com/a/47128740
tagged with: python
has comment: http://stackoverflow.com/comment/81207433

http://stackoverflow.com/q/47142694
tagged with: python
type: UnansweredQuestion
tagged with: urllib
has comment: http://stackoverflow.com/comment/81236593
has body: For example, I would like to send a request to 12.34.56.78 with host header stackoverflow.com. However, Python seems to overwrite the Host header, and the actual packet sent still has Host: 12.34.56.78. How can I stop this behavior? from urllib import request a = request.build_opener() a.addheaders.append(('Host', 'stackoverflow.com')) a.open('http://12.34.56.78/') Note: the code runs on Python 3
tagged with: python-3.x
has title: How can I set an arbitary Host header in Python 3 urllib?
upvote count: 3
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47188260
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/81259231
comment on: http://stackoverflow.com/q/47152218
type: QuestionComment
has text: @SungJinSteveYoo yes
score: 0
type: Comment

http://stackoverflow.com/q/47112607
tagged with: pandas
score: 0
has comment: http://stackoverflow.com/comment/81175147
has body: I'm not sure how to phrase my search in order to find it so this is probably a duplicate. Please feel free to point me in the right direction. In pandas, I know that I can use iloc to grab particular pieces of a dataframe. I'm curious to know if there is a way to Read or Write particular items from said dataframe. In one case, I could get item08 by using (1, 1) and then reading it Or perhaps I want item28 I could use (2, 4) Maybe I'd like to change item22 on (2, 3) +--------------------------------------------+ 0 | item01 | item07 | item13 | item19 | item26 | +--------------------------------------------+ 1 | item02 | item08 | item14 | item21 | item27 | +--------------------------------------------+ 2 | item03 | item09 | item15 | item22 | item28 | +--------------------------------------------+ 3 | ... | ... | ... | ... | ... | +--------------------------------------------+ 0 1 2 3 4 How can this be done?
accepted answer: http://stackoverflow.com/a/47112714
answer count: 1
linked to: http://stackoverflow.com/q/13842088
type: Question
has title: Read or Write items from a pandas dataframe
has comment: http://stackoverflow.com/comment/81175106
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47112714
has comment: http://stackoverflow.com/comment/81175138
type: AnsweredQuestion

http://stackoverflow.com/comment/81342245
type: Comment
score: 0
type: AnswerComment
has text: so the value will be the id of the gift selected?
comment on: http://stackoverflow.com/a/47196220

http://stackoverflow.com/q/47136436
has answer: http://stackoverflow.com/a/47136484
has answer: http://stackoverflow.com/a/55617313
has answer: http://stackoverflow.com/a/53869812
has title: Python Pandas: Convert ".value_counts" output to dataframe
answer count: 5
tagged with: dataframe
tagged with: python
has body: Hi I want to get the counts of unique values of the dataframe. count_values implements this however I want to use its output somewhere else. How can I convert .count_values output to a pandas dataframe. here is an example code: import pandas as pd df = pd.DataFrame({'a':[1, 1, 2, 2, 2]}) value_counts = df['a'].value_counts(dropna=True, sort=True) print(value_counts) print(type(value_counts)) output is: 2 3 1 2 Name: a, dtype: int64 &lt;class 'pandas.core.series.Series'&gt; What I need is a dataframe like this: unique_values counts 2 3 1 2 Thank you.
type: AnsweredQuestion
upvote count: 166
tagged with: pandas
has answer: http://stackoverflow.com/a/67475845
has answer: http://stackoverflow.com/a/65707771
score: 165
accepted answer: http://stackoverflow.com/a/47136484
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/53869812
type: Question

http://stackoverflow.com/a/47211865
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/81373344
accepted answer of: http://stackoverflow.com/q/47211782
answers question: http://stackoverflow.com/q/47211782
downvote count: 0
has comment: http://stackoverflow.com/comment/81373238
has comment: http://stackoverflow.com/comment/81373160
score: 1
has body: Try writing rot, rot_speed = [0, 0], [0, 0]. This will set rot and rot_speed to separate values. Currently you have rot = rot_speed = [0, 0] which means that you're setting rot to be a pointer to rot_speed. Because of this, it will only change whenever rot_speed changes.
type: AcceptedAnswer

http://stackoverflow.com/comment/81270290
comment on: http://stackoverflow.com/q/47160153
has text: Importing Seaborn was the Problem. Thank you so much!
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81198920
type: AnswerComment
comment on: http://stackoverflow.com/a/47124040
type: Comment
has text: @PandemicCode same name column always create this type of issue, better rename it
score: 0

http://stackoverflow.com/comment/81186435
comment on: http://stackoverflow.com/a/47118103
score: 0
type: Comment
has text: @uriwashere It works for me... I'm not sure how you implemented the code sample. Here's a full working example, try it out and you'll see that it works fine when you give it a letter: https://pastebin.com/s24E12xu
type: AnswerComment

http://stackoverflow.com/comment/81252804
has text: @ Tim True, but it's slightly messier. But I guess it'd still be faster than doing it in Python.
type: QuestionComment
comment on: http://stackoverflow.com/q/47151375
score: 0
type: Comment

http://stackoverflow.com/q/47167435
has comment: http://stackoverflow.com/comment/81545575
favorite count: 0
type: Question
has title: Wordpress xmlrpc page returns non xml data for non browser applications
has answer: http://stackoverflow.com/a/47328746
type: UnansweredQuestion
has body: I am using python (http://python-wordpress-xmlrpc.readthedocs.io/en/latest/) to connect to wordpress to post contents. I have a few wordpress sites to which I connect using sitename.com/xmlrpc.php However one of my sites recently started reporting a problem while connection mentioning not a valid xml. When I view the page in browser I see the usual "XML-RPC server accepts POST requests only." but when I connect using python I see the following message: funct ion toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))}) ;return e}function toHex(){for(var d=[],d=1==arguments.length&amp;&amp;arguments[0].cons tructor==Array?arguments[0]:arguments,e="",f=0;fd[f]?"0":"" )+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c 63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("c299 e542498206cd9cff8fd57dfc56df");document.cookie="__test="+toHex(slowAES.decrypt(c ,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://targetDomainNameHere.com/xmlrpc.php?i=1";This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support I searched for the file aes.js, no luck. How to get this working ? How do I remove this? I am using the latest version of Wordpress as of 07.NOV.2017
tagged with: python
tagged with: xml-rpc
downvote count: 0
upvote count: 1
score: 1
answer count: 1
tagged with: wordpress

http://stackoverflow.com/q/47213847
score: 2
upvote count: 2
answer count: 2
downvote count: 0
tagged with: machine-learning
favorite count: 0
type: Question
tagged with: perceptron
has answer: http://stackoverflow.com/a/47213864
tagged with: python
type: UnansweredQuestion
has body: I am trying to follow the book by Daume http://ciml.info/dl/v0_99/ciml-v0_99-ch04.pdf (page 43). To fit a model for vanilla perceptron in python using numpy and without using sciki-learn library. The algorithm is given in the book How can we implement this model in practice? So far I have learned how to read the data and labels: def read_data(infile): data = np.loadtxt(infile) X = data[:,:-1] Y = data[:,-1] return X, Y The help will be appreciated!!
has title: How to implement Perceptron in Python?
tagged with: numpy
has answer: http://stackoverflow.com/a/50472416

http://stackoverflow.com/comment/81120811
comment on: http://stackoverflow.com/q/47083120
score: 1
type: QuestionComment
has text: @GSazheniuk, here is the error I'm getting:TypeError Traceback (most recent call last) <ipython-input-167-df7aa61b8df3> in <module>() ----> 1 TI_row=math.log10(2.718281+(table['eventid']+table['nkill']+table['nwound'])/3) TypeError: a float is required
type: Comment

http://stackoverflow.com/comment/81366864
score: 0
type: QuestionComment
has text: Don't complicate things! Seems like all you need is a neg. lookahead: [**`\s*[-,/](?!\d)`**](https://regex101.com/r/WzDvXv/2/)
comment on: http://stackoverflow.com/q/47208877
type: Comment

http://stackoverflow.com/q/47101002
tagged with: python
has title: Issue with os.system() in python3
tagged with: bash
downvote count: 4
upvote count: 0
has comment: http://stackoverflow.com/comment/81152624
score: -4
has comment: http://stackoverflow.com/comment/81152580
answer count: 1
tagged with: awk
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47101092
has comment: http://stackoverflow.com/comment/81152211
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81152199
has body: I am trying to develop a pipeline which involves running a UNIX command which I am doing inside a os.system() call. The call fails when python code is executed. The issue is when I copy paste and run the same code directly from the UNIX terminal it runs fine. I am not sure what is doing wrong here. This the os.system() command. cmd="paste " cmd+="&lt;(awk '{print $1, $2, $3}' "+DATA_DIRECTORY_y2h+"/data/trimmed_reads/S"+str(library)+"_STAR_transcriptome_vector_freeAligned.sortedByCoord.out.bam.idxstats) " cmd+="&lt;(awk '{print $3}' "+DATA_DIRECTORY_y2h+"/data/trimmed_reads/S"+str(library)+"_STAR_transcriptome_trimmed_vector_containingAligned.sortedByCoord.out.bam.idxstats) " cmd+="| awk '$3&gt;0 &amp;&amp; $4&gt;0'|awk '{a[NR]=$0;x+=(b[NR]=$3)}END{while(++i&lt;=NR)print a[i]\" \"100*b[i]/x}'|sort -grk5,5 &gt; " cmd+=DATA_DIRECTORY_y2h+"/data/trimmed_reads/S"+str(library)+"_STAR_transcript_read_coverage.txt" and when I print it out the command is paste &lt;(awk '{print $1, $2, $3}' /home/bigdata/sagnik/y2h//data/trimmed_reads/S1_STAR_transcriptome_vector_freeAligned.sortedByCoord.out.bam.idxstats) &lt;(awk '{print $3}' /home/bigdata/sagnik/y2h//data/trimmed_reads/S1_STAR_transcriptome_trimmed_vector_containingAligned.sortedByCoord.out.bam.idxstats) | awk '$3&gt;0 &amp;&amp; $4&gt;0'|awk '{a[NR]=$0;x+=(b[NR]=$3)}END{while(++i&lt;=NR)print a[i]" "100*b[i]/x}'|sort -grk5,5 &gt; /home/bigdata/sagnik/y2h//data/trimmed_reads/S1_STAR_transcript_read_coverage.txt

http://stackoverflow.com/comment/81312965
has text: Why did you use `prefetch_related` for fields which are not `ForeignKey` fields?
type: QuestionComment
comment on: http://stackoverflow.com/q/47178987
score: 0
type: Comment

http://stackoverflow.com/q/47085679
tagged with: http://stackoverflow.com/tag/json
type: Question
has body: I am trying to build a database-backed system using Python as an engine and JSON as the DB file. Currently, there are three files: # functions.py import json from pprint import pprint with open('db.json') as data_file: data = json.load(data_file) def getStudentByUsername(username, record): detail = json.load(open('db.json'))["students"][username][record] pprint(detail) &nbsp; # main.py import functions functions.getStudentByUsername('youngh', 'age') &nbsp; { // db.json "students": { "youngh": { "name": "Hayden Young", "age": 13, "email": "user@school.county.sch.uk" } } } But, I can't find a way to change my students object like this and still query by username: { //db.json "students": [ { "username": "youngh", "name": "Hayden Young" }] } Any ideas? I'm new to this type of use of Python 3.
has title: Python - JSON Module how to query nested objects
answer count: 2
tagged with: database
has answer: http://stackoverflow.com/a/47086000
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47085892
score: 0

ellipse
tags question: http://stackoverflow.com/q/47116977
tag name: ellipse
type: Tag

http://stackoverflow.com/a/47143674
has body: ('Group_'+mydat.astype('category').cat.codes.add(1).astype(str)).mask(mydat.isnull()) Out[1168]: 0 NaN 1 Group_1 2 Group_3 3 Group_2 4 Group_3 5 Group_1 6 NaN dtype: object
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47143335
type: Answer

http://stackoverflow.com/comment/81371947
type: AnswerComment
has text: Do you think `[ { "value":"engine", "charge":10.82 } ,{ "value":"engine1", "charge":9.43} ]` ?
comment on: http://stackoverflow.com/a/47203984
type: Comment
score: 0

http://stackoverflow.com/comment/81243004
comment on: http://stackoverflow.com/q/47146248
score: 1
has text: Your question should actually contain the Python code that does not work. SO is not a free code converting service.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81193954
comment on: http://stackoverflow.com/q/47122088
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ Nope. Still getting wrong array even after omitting np.uint8
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47188534
has answer: http://stackoverflow.com/a/47188594
accepted answer: http://stackoverflow.com/a/47188594
has answer: http://stackoverflow.com/a/47188632
type: AnsweredQuestion
has body: I spent hours trying to figure out how to pass the value to a function that only prints what it receives. fun1(50) def fun1(salary): salary_double = salary * salary salary_tax = salary 1.04 return salary, salary_double, salary_tax def fun2(): print (salary, salary_double, salary_tax from fun1) How can I pass the value of the returned variables in the fun1 to fun2?
downvote count: 0
upvote count: 1
score: 1
tagged with: python
favorite count: 0
possible better answer: http://stackoverflow.com/a/47188632
type: Question
has comment: http://stackoverflow.com/comment/81326409
has title: Passing returned variables between functions
answer count: 2
tagged with: function

http://stackoverflow.com/comment/81306880
comment on: http://stackoverflow.com/a/47178895
score: 0
type: AnswerComment
type: Comment
has text: def my_sort(lst, key = lambda x:x), is also possible, right?

http://stackoverflow.com/q/47197251
favorite count: 0
type: Question
has title: How to connect to LinkedIn REST API with python?
type: UnansweredQuestion
score: -2
tagged with: linkedin-api
upvote count: 1
tagged with: python
has body: I'm newbie in programming so please excuse me. To access LinkedIn I was using python-linkedin library but because some changes from LinkedIn, this library is not working anymore. What would be the best workaround for this?
has comment: http://stackoverflow.com/comment/81343785
linked to: http://stackoverflow.com/q/25183197
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/47197428
has comment: http://stackoverflow.com/comment/81343183
has comment: http://stackoverflow.com/comment/81343423

http://stackoverflow.com/q/47119259
type: AnsweredQuestion
score: 0
tagged with: pandas
has title: python pandas HDFStore append not contant size data
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/47813173
tagged with: hdfstore
has body: I am using python 2.7 with pandas and HDFStore I try to process a big data set, which fits into the disk but not to the memory. I store a large size data set in a .h5 file, the size of the data in each column is not constant, for instance, one column may have a string of 5 chars in one row and a string of 20 chars in another. So i had issues writing the data to file in iterations, when the first iteration contained a small size of data and the following batches contained larger size of data. I found that the issue was that the min_size was not used properly and the data did not fit into the columns, I used the following code to cache the database into the h5 without error colsLen = {} for col in dbCols: curs.execute('SELECT MAX(CHAR_LENGTH(%s)) FROM table' % col) for a in curs: colsLen.update({col: a[0]}) # get the first row to create the hdfstore rx = dbConAndQuery.dbTableToDf(con, table, limit=1, offset=0) #this is my utility that is querying the db hdf.put("table", table, format="table", data_columns=True, min_itemsize=colsLen) for i in range(rxRowCount / batchSize + 1): rx = dbConAndQuery.dbTableToDf(con, table, limit=batchSize, offset=i * batchSize + 1) hdf.append("table", table, format="table", data_columns=True, min_itemsize=colsLen) hdf.close() The issue is: how can i use HDFStore in cases where I can't query for the maximum size of each column's data in advance? e.g getting or creating data in iterations due to memory constrains. I found that I can process the data using dask with in disk dataframes, but it lacks some functionality that I need in pandas, so the main idea is to process the data in batches appending it to the existing HDFStore file. Thanks!
has answer: http://stackoverflow.com/a/47813173
type: Question
tagged with: bigdata
answer count: 1

http://stackoverflow.com/q/47198774
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47198831
has title: UnboundLocalError: local variable 'f' referenced before assignment
tagged with: python
has body: I have python function: FactorialFunction.py def factorial(n): if n == 0: return 1 f = n * factorial(n-1) print(f) return(f) factorial(4) shows nothing, when I run it in terminal but when I run it in python shell get "UnboundLocalError: local variable 'f' referenced before assignment"
has answer: http://stackoverflow.com/a/47198831

http://stackoverflow.com/comment/111543281
type: Comment
comment on: http://stackoverflow.com/a/47140427
score: 0
type: AnswerComment
has text: ref, how to chain many chord groups, https://stackoverflow.com/questions/51076827/celery-groups-and-chains/51097747#51097747

http://stackoverflow.com/comment/81311750
has text: @ sacha , I am very grateful to you , i hope you can help me in my problem as you did already, i use this code to get results for my Phd thesis , i use python for just one year so i am so sorry if i don't understand some comments about your code
type: QuestionComment
comment on: http://stackoverflow.com/q/47178793
score: 0
type: Comment

http://stackoverflow.com/a/47816648
has body: Faced with the same error my troubles went away after doing pip install ndg-httpsclient. yum install python-ndg_httpsclient or apt-get install python-ndg-httpsclient (or apt-get install python3-ndg-httpsclient) probably works too.
answers question: http://stackoverflow.com/q/47142848
type: Answer
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86708980
has comment: http://stackoverflow.com/comment/86670224

http://stackoverflow.com/comment/81165847
has text: 66 dropped out probably. Because he needs best matches in both lists and is open to dropping outs.
score: 0
comment on: http://stackoverflow.com/q/47090519
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47122023
has body: You can use pandas, i.e: import matplotlib.pyplot as plt import pandas as pd d = { 'a': {'L1':2, 'L2':5, 'L3':8}, 'b': {'L1':4, 'L2':7, 'L3':10}, 'c': {'L1':19, 'L2':0, 'L3':1}, } pd.DataFrame(d).plot(kind='bar') plt.show() Output: In your case you need dict keys in x-axis so you can use pd.DataFrame(d).T.plot(kind='bar')
score: 18
type: Answer
answers question: http://stackoverflow.com/q/47121997
upvote count: 18
has comment: http://stackoverflow.com/comment/83873830
has comment: http://stackoverflow.com/comment/81193932
has comment: http://stackoverflow.com/comment/81193680
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47121997
has comment: http://stackoverflow.com/comment/81193712

http://stackoverflow.com/q/47164238
favorite count: 0
tagged with: command-line
type: Question
has body: I am getting the below issue when trying to create a folder using the scrapy command. I tried searching for this issue and found a solution at https://groups.google.com/forum/#!topic/scrapy-users/8N6V_OGUqtI I tried the steps provided there and still I am getting this issue. Any help in getting this resolved would be appreciated. (C:\Users\dell\Anaconda3) C:\Users\dell&gt;activate scrapy-env (scrapy-env) C:\Users\dell&gt;scrapy startproject tutorial Traceback (most recent call last): File "C:\Users\dell\Anaconda3\envs\scrapy-env\Scripts\scrapy-script.py", line 5, in &lt;module&gt; sys.exit(scrapy.cmdline.execute()) File "C:\Users\dell\Anaconda3\envs\scrapy-env\lib\site-packages\scrapy\cmdline.py", line 128, in execute cmds = _get_commands_dict(settings, inproject) File "C:\Users\dell\Anaconda3\envs\scrapy-env\lib\site-packages\scrapy\cmdline.py", line 46, in _get_commands_dict cmds = _get_commands_from_module('scrapy.commands', inproject) File "C:\Users\dell\Anaconda3\envs\scrapy-env\lib\site-packages\scrapy\cmdline.py", line 29, in _get_commands_from_module for cmd in _iter_command_classes(module): File "C:\Users\dell\Anaconda3\envs\scrapy-env\lib\site-packages\scrapy\cmdline.py", line 19, in _iter_command_classes for module in walk_modules(module_name): File "C:\Users\dell\Anaconda3\envs\scrapy-env\lib\site-packages\scrapy\utils\misc.py", line 71, in walk_modules submod = import_module(fullpath) File "C:\Users\dell\Anaconda3\envs\scrapy-env\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 678, in exec_module File "&lt;frozen importlib._bootstrap&gt;", li…
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/55520971
has answer: http://stackoverflow.com/a/51813527
answer count: 3
score: 1
has title: Import Error:DLL failed when using scrapy in command prompt
tagged with: scrapy-shell
tagged with: scrapy
has answer: http://stackoverflow.com/a/47164350

http://stackoverflow.com/a/47184611
answers question: http://stackoverflow.com/q/47150638
type: Answer
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/111795943
has body: @allen, thank you so much for your answer. Based on your guess, I made the following code: In [3]: {'a': 1} Out[3]: {'a': 1} In [4]: C(1) ...: print(_) ...: print(type(_)) ...: print(number_of_instances(C)) ...: {'a': 1} &lt;class 'dict'&gt; 0 In [5]: So the _ underscore is only used for storing the value of last expression in interpreter of "Single Step Mode", not for "Continuous Mode". This might be a common mistake made by beginners. Anyway, thank you so much for your answer!
score: 2

http://stackoverflow.com/q/47085119
has comment: http://stackoverflow.com/comment/81120346
upvote count: 8
favorite count: 0
type: Question
has title: Mean Std in pandas data frame
tagged with: pandas
tagged with: python
tagged with: standard-deviation
has answer: http://stackoverflow.com/a/47086301
has comment: http://stackoverflow.com/comment/81119649
accepted answer: http://stackoverflow.com/a/47086301
score: 8
type: AnsweredQuestion
has body: Having a pandas data frame as follow: a b 0 1 12 1 1 13 2 1 23 3 2 22 4 2 23 5 2 24 6 3 30 7 3 35 8 3 55 I want to find the mean standard deviation of column b in each group. My following code give me 0 for each group. stdMeann = lambda x: np.std(np.mean(x)) print(pd.Series(data.groupby('a').b.apply(stdMeann)))
downvote count: 0
has comment: http://stackoverflow.com/comment/81120122
tagged with: mean
has comment: http://stackoverflow.com/comment/81120162
answer count: 1

http://stackoverflow.com/comment/81121124
has text: It seems like `user error` some cred detail not correct?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47083954

http://stackoverflow.com/q/47122035
linked to: http://stackoverflow.com/q/3840870
has comment: http://stackoverflow.com/comment/81197295
score: 0
answer count: 0
tagged with: guid-partition-table
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81194547
has title: How to find if disk is GPT using python on Windows?
type: Question
has body: I am on windows 7 and installed python 3.5. I would like to know if the disk/ partition supplied to the program is GPT or not. I am aware of the gdisks windows package and my attempt to use it made my USB disk corrupt. I need to just find the type of disk and I am not going to carry out any operation on it. Is there a way to find it under python? Any help is appreciated...
tagged with: python
has comment: http://stackoverflow.com/comment/81194195

http://stackoverflow.com/a/47384354
accepted answer of: http://stackoverflow.com/q/47148781
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47148781
score: 5
type: AcceptedAnswer
downvote count: 0
has body: Have a look at Science-Parse by Allen AI. It does a pretty decent job at extracting metadata from PDF documents. Often, its better than other text extracting software such as textract and pdfplumber. Extraction of mathematical formulae from PDF accurately has been a research topic for many years now. I have not found any open source projects/packages/softwares related to extracting mathematical formulae precisely, although there are a number of research papers which describe methods to do that such as this and this. (More research has been done on recognition of mathematical formula or converting them to a proper markup such as LaTeX, MathML, etc.) Most of these papers use information about the font, baseline, glyph bounding boxes, line spacing, etc. to correctly recognize mathematical formulae and extract them. For OCR, you can always use Infty. This is what the description for InftyReader says: InftyReader recognizes scanned images of printed scientific documents including Math formulae, an outputs the recognition results in various formats: XML format for InftyEditor, LaTeX, MathML, Human-Readable TeX for the blinds, etc.

http://stackoverflow.com/a/47102020
has comment: http://stackoverflow.com/comment/81156413
has comment: http://stackoverflow.com/comment/81155595
answers question: http://stackoverflow.com/q/47094680
has comment: http://stackoverflow.com/comment/81155738
has comment: http://stackoverflow.com/comment/81155866
has comment: http://stackoverflow.com/comment/81166252
score: 0
has comment: http://stackoverflow.com/comment/81156524
has body: Check this CODE def match(X,Y): N="TAG" K="QL" D="E" dummylist=[] spl_match = 0 for (i,j) in zip(X,Y): #print i, j if i=='N': if j == 'N': continue elif j in N: spl_match += 1 dummylist.append((i,j)) elif (i=='K'): if (j == 'K'): continue elif j in K: spl_match += 1 dummylist.append((i,j)) elif (i == 'D'): if(j == 'D'): continue elif j in D: spl_match += 1 dummylist.append((i,j)) elif (i=='X'): if(j=='X'): continue else: spl_match += 1 dummylist.append((i,j)) print "Given string",X,Y print "Special matched elements",dummylist print "No of Special Matches",spl_match if spl_match &gt; 2: return False else: return True OUTPUT &gt;&gt;&gt; match('NKXD','RKAC') Given string NKXD RKAC Special matched elements [('X', 'A')] No of Special Matches 1 True &gt;&gt;&gt; match('NKXD','KACT') Given string NKXD KACT Special matched elements [('X', 'C')] No of Special Matches 1 True &gt;&gt;&gt; match('NKXD','ACTI') Given string NKXD ACTI Special matched elements [('N', 'A'), ('X', 'T')] No of Special Matches 2 True &gt;&gt;&gt; &gt;&gt;&gt; match('NKXD','TQAK') Given string NKXD TQAK Special matched elements [('N', 'T'), ('K', 'Q'), ('X', 'A')] No of Special Matches 3 False &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/81156562
type: Answer
has comment: http://stackoverflow.com/comment/81156832

http://stackoverflow.com/comment/81215706
score: 0
has text: Still Error is same
comment on: http://stackoverflow.com/q/47132884
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47087520
type: Answer
answers question: http://stackoverflow.com/q/47087451
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81125761
has body: Based on your edit, you can use np.argsort: i = np.arange(len(df)) j = pd.Series(np.argmax(df.values, axis=1)) df['next'] = df.shift(-1).values[i, j] a b c d next 1 1 2 3 4 3.0 2 5 6 7 3 11.0 3 9 10 11 12 NaN
accepted answer of: http://stackoverflow.com/q/47087451

http://stackoverflow.com/a/47164196
type: Answer
score: 1
answers question: http://stackoverflow.com/q/47163874
type: AcceptedAnswer
downvote count: 0
has body: Your AVLTree class does not have a list but your Node class: self.node.list.append(value) #function trying to add
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47163874

http://stackoverflow.com/comment/81106466
has text: Modified answer following your comment.
comment on: http://stackoverflow.com/a/47078344
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81199392
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47112681
has text: when I use uppercase, it works but when I use lowercase it doesn't, it says that I haven't used any of the allowed characters and the totalscore needs to have a default value of the length of the users password

http://stackoverflow.com/comment/81264414
type: AnswerComment
score: 0
has text: Also your original question was “what factors” which is an open question. I gave you one of those factors. If you now edit your question to be more closed you should rephrase it better. I.e why does my program do X which I didn’t expect?
comment on: http://stackoverflow.com/a/47141970
type: Comment

http://stackoverflow.com/a/47119251
answers question: http://stackoverflow.com/q/47118730
accepted answer of: http://stackoverflow.com/q/47118730
type: AcceptedAnswer
score: 0
has body: You are passing the globals namespace, but your cpd_df is a local variable. Pass locals instead: def create_positional_dfs(position, list_of_metrics, minimum_minutes): if position == 'DM': relevant_df = DMs elif position == 'AM': relevant_df = AMs else: relevant_df = master cpd_df = pd.DataFrame(data=relevant_df, columns=list_of_metrics) cpd_query = """SELECT * FROM cpd_df WHERE [Total Mins] &gt;= """ + str(minimum_minutes) + """ AND Position = '""" + position + """'""" return psql.sqldf(cpd_query, locals()) # use locals here
type: Answer

http://stackoverflow.com/comment/81124114
type: QuestionComment
has text: You need to add `return` to the recursive case, i.e. `return largestNumber(numberList[1:])` Without it, it's discarding the recursive return value and returning `None` instead.
score: 5
comment on: http://stackoverflow.com/q/47087178
type: Comment

http://stackoverflow.com/q/47186614
upvote count: 1
score: 1
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has title: How to save the contents of text files as a list in json format sequentially (not concatenation)
favorite count: 0
tagged with: text-files
type: Question
has body: I have thousands of text files in a directory, and would like to save the content of each file in a list (one big file-list) while maintaining the order of the files as they are in the directory. The texts are not to be concatenated. Please see example of my desired output. Example=['textual content of file one', 'textual content of file two', 'textual content of file three'.....textual content of file n] My attempt: filelist=[file-1,file-2,...file-n] destinationfile="C:\\XXXXX\\dump_large_json.txt" with open(destinationfile, 'w',encoding='utf-8') as f: for file in filelist: with open(file, 'r') as f2: h=json.dump(f2,f) output: TypeError: Object of type 'TextIOWrapper' is not JSON serializable Any ideas on how to serially dump text files in json format would be appreciated.
tagged with: serialization
tagged with: python
has comment: http://stackoverflow.com/comment/81322992
has answer: http://stackoverflow.com/a/47188604
accepted answer: http://stackoverflow.com/a/47188604
has comment: http://stackoverflow.com/comment/81323162
linked to: http://stackoverflow.com/q/15343743
linked to: http://stackoverflow.com/q/10872604
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81322373
downvote count: 0
has comment: http://stackoverflow.com/comment/81322397

http://stackoverflow.com/q/47105572
has answer: http://stackoverflow.com/a/47105669
answer count: 2
has body: I have a list that looks like this: [['1', ' H ', ' Hydrogen', ' 1.00794(4)', 'FFFFFF', '1s1 ', '2.2', '37', '', '120', '1312', '-73', '-1, 1', 'gas', 'diatomic', '14', '20', '0.0000899', 'nonmetal', '1766'], ['2', ' He ', ' Helium', ' 4.002602(2)', 'D9FFFF', '1s2 ', '', '32', '', '140', '2372', '0', '', 'gas', 'atomic', '', '4', '0.0001785', 'noble gas', '1868'], etc...] that goes all the way down the periodic table. I also have a function (which is within a class, hence the self.) that is supposed to print a single sublist (one per element) which looks like this: def get_element_data(self, identifier): if type(identifier) == int: if self.check_atomic_number_exists(identifier): return self.parsed_data[identifier - 1] if type(identifier) == str: if len(identifier) &lt;= 2: print("passed in symbol") return (element for element in self.parsed_data if identifier == element[1]) if len(identifier) &gt; 2: print("passed in name") return (element for element in self.parsed_data if identifier == element[2]) parsing_object.get_element_data("Hydrogen") but if I run this it returns a generator object instead of the sublist. How can I make it return the sublist? Also, it works fine if I search by atomic number.
has comment: http://stackoverflow.com/comment/81161946
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81161879
has answer: http://stackoverflow.com/a/47105593
tagged with: python
has comment: http://stackoverflow.com/comment/81161916
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/81161782
has comment: http://stackoverflow.com/comment/81161758
has title: With a given list how can I make this searching function return the value instead of it's generator object
tagged with: sublist
tagged with: search
type: Question

http://stackoverflow.com/q/47178948
has comment: http://stackoverflow.com/comment/103391993
tagged with: python
has body: I want to know if there is any method of Python or probably from python-opencv that allows me to extract frames from a rtsp streaming. I know that such task can be done easily using a ffmpeg library but ffmpeg uses a lot of my CPU.
has title: How can I extract some frames of a rtsp using directly python or python-opencv?
has comment: http://stackoverflow.com/comment/81319259
type: Question
linked to: http://stackoverflow.com/q/20891936
answer count: 0
tagged with: ffmpeg
type: UnansweredQuestion
score: 0
tagged with: opencv
has comment: http://stackoverflow.com/comment/81317150
tagged with: linux

http://stackoverflow.com/q/47129865
downvote count: 1
has title: How to subtract a specific value in tuple
score: -1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47131057
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47129964
has comment: http://stackoverflow.com/comment/81209731
duplicate of: http://stackoverflow.com/q/17418108
has body: I will need to subtract one value in the tuple by 80 how can I do that? Before x=(300,400) After newx=(300,320) I have tried looking for list solutions but i'm looking for a simple function to subtract the tuple value I only need to subtract 1 value in the tuple, not the entire tuple.
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81209687
tagged with: python
has answer: http://stackoverflow.com/a/47131296
answer count: 4
has answer: http://stackoverflow.com/a/47131083
has comment: http://stackoverflow.com/comment/81209703
linked to: http://stackoverflow.com/q/17418108

http://stackoverflow.com/q/47138976
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81227451
score: 1
has answer: http://stackoverflow.com/a/47139046
has body: I have a directory containing mutliple files with similar names and subdirectories named after these so that files with like-names are located in that subdirectory. I'm trying to concatenate all the .sdf files in a given subdirectory to a single .sdf file. import os from os import system for ele in os.listdir(Path): if ele.endswith('.sdf'): chdir(Path + '/' + ele[0:5]) system('cat' + ' ' + '*.sdf' + '&gt;' + ele[0:5] + '.sdf') However when I run this, the concatenated file includes every .sdf file from the original directory rather than just the .sdf files from the desired one. How do I alter my script to concatenate the files in the subdirectory only?
tagged with: os.system
has comment: http://stackoverflow.com/comment/81227426
tagged with: python
has title: Using os.system() in a specific directory only
type: UnansweredQuestion
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81227311

http://stackoverflow.com/q/47110297
tagged with: python-3.x
has title: How get a max value from array of dictionaries with the same structure?
has comment: http://stackoverflow.com/comment/81170710
has answer: http://stackoverflow.com/a/47110491
tagged with: python
accepted answer: http://stackoverflow.com/a/47110471
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47110471
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/47110491
has comment: http://stackoverflow.com/comment/81170812
has body: I need get a max value of index from dictionary with the biggest index value. I guess this can be done by using function max() and lambda, but I don't know how do it correctly. data = [ {'address': '499 Eastern Parkway', 'city': 'Kenvil', 'company': 'GONKLE', 'country': 'India', 'index': 0, 'name': 'Shelby Gutierrez'}, {'address': '552 Butler Place', 'city': 'Rivereno', 'company': 'FITCORE', 'country': 'United States', 'index': 1, 'name': 'Jenny Cardenas'}, {'address': '176 Pleasant Place', 'city': 'Coultervillle', 'company': 'CONFRENZY', 'country': 'Sao Tome and Principe', 'index': 2, 'name': 'Boyer Austin'} ]
type: Question

http://stackoverflow.com/q/47083182
has title: Passing Data Between Different Versions of Python
score: 0
has comment: http://stackoverflow.com/comment/81116826
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47083686
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81115596
has comment: http://stackoverflow.com/comment/81115683
tagged with: python
linked to: http://stackoverflow.com/q/43861164
linked to: http://stackoverflow.com/q/1849523
has body: Similar to this question: Passing data between Python scripts, while separately running But I have two different versions of Python running (2.x and 3.x). We use 2.x in my shop, but are running 3.x on a virtual machine for machine learning libraries that 2.x doesn't support. Will this solution work for 2.x and 3.x, or is there another method?

scroll
type: Tag
tags question: http://stackoverflow.com/q/47211939
tags question: http://stackoverflow.com/q/47109480
tag name: scroll

http://stackoverflow.com/q/47215081
has answer: http://stackoverflow.com/a/47215202
tagged with: python
tagged with: regex
tagged with: web-crawler
has comment: http://stackoverflow.com/comment/81380004
type: Question
has comment: http://stackoverflow.com/comment/81379906
has title: Regular Expression different results from other languages
has comment: http://stackoverflow.com/comment/81379888
possible better answer: http://stackoverflow.com/a/47215202
has comment: http://stackoverflow.com/comment/81379931
has comment: http://stackoverflow.com/comment/81379680
accepted answer: http://stackoverflow.com/a/47215493
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47215493
has body: so I've been working on a web crawler to parse out readable contents from a news site I like, and I've been using regex pretty heavily in python2. I visited https://regexr.com/ to double check that I had the correct expression for this use case, but I keep getting different results than expected, specifically when I cross reference the output from regexr. Here is the expression re.compile(ur"[\s\S\]*<p.*>([\s\S]+?)<\/p>") And here is the html I am attempting to match Researchers at MIT and several other institutions have developed a method for making photonic ... It doesn't end up getting closed for some time, but the program doesn't grab this section at all, and only after the in ygen levels, and even blood pressure. does it begin to grab the html (EDIT: p elements). I guess I am confused by the inconsistencies with different regex engines, and I am trying to figure out when and where to modify my syntax, in this case to grab the entire p element, but also generally. This is my first time posting here, so I may have this formatted incorrectly, but thank you all in advance. Been lurking for a while now.
linked to: http://stackoverflow.com/q/1732348
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/81380298
has comment: http://stackoverflow.com/comment/81379947
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/47215333

http://stackoverflow.com/q/47182734
has comment: http://stackoverflow.com/comment/81316307
has comment: http://stackoverflow.com/comment/81316151
type: UnansweredQuestion
has body: I'm trying to create a python script that will log into an FTP server, change to a specific directory and download all files from that dir. The FTP server has directories created daily and the dir name matches the date. for example: drwxr-xr-x 2 user tenant 0 Nov 01 00:00 2017-11-01 drwxr-xr-x 2 user tenant 0 Nov 02 00:00 2017-11-02 drwxr-xr-x 2 user tenant 0 Nov 03 00:00 2017-11-03 drwxr-xr-x 2 user tenant 0 Nov 04 00:00 2017-11-04 drwxr-xr-x 2 user tenant 0 Nov 06 00:00 2017-11-06 drwxr-xr-x 2 user tenant 0 Nov 07 00:00 2017-11-07 I am able to get logged into the server but now how can I change into the directory that matches yesterday's date? For example, if today is 2017-11-07 I would need to change into 2017-11-06. I am using python 2.6.6. I'm using this which I found from another post: from datetime import date, timedelta yesterday = date.today() - timedelta(1) This works but how do I use 'yesterday' in my directory path? Any help is much appreciated.
tagged with: python
has comment: http://stackoverflow.com/comment/81315203
has comment: http://stackoverflow.com/comment/81317165
score: 0
has title: How to use ftplib in Python to change directories when directory name matches a date
linked to: http://stackoverflow.com/q/1712116
has comment: http://stackoverflow.com/comment/81319887
tagged with: date
duplicate of: http://stackoverflow.com/q/1712116
type: Question
tagged with: ftp
answer count: 0
tagged with: ftplib

http://stackoverflow.com/comment/81389105
has text: Better than my answer
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47219833

http://stackoverflow.com/q/47074958
has answer: http://stackoverflow.com/a/47075366
possible better answer: http://stackoverflow.com/a/47075366
type: AnsweredQuestion
score: 2
upvote count: 3
has body: I have a pandas dataframe like this: a b c foo bar baz bar foo baz foobar barfoo baz I've defined the following function in python: def somefunction (row): if row['a'] == 'foo' and row['b'] == 'bar': return 'yes' return 'no' It works perfectly fine. But I need to make a small tweak to the if function to take into account partial string matches. I've tried several combinations, but I can't seem to get it to work. I get the following error: ("'str' object has no attribute 'str'", 'occurred at index 0') The function Iv'e tried is: def somenewfunction (row): if row['a'].str.contains('foo')==True and row['b'] == 'bar': return 'yes' return 'no'
tagged with: pandas
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47075008
has title: Python function partial string match
accepted answer: http://stackoverflow.com/a/47075008
answer count: 2
tagged with: python

http://stackoverflow.com/a/47216661
accepted answer of: http://stackoverflow.com/q/47216177
has comment: http://stackoverflow.com/comment/81403456
type: Answer
score: 2
upvote count: 2
has body: Use np.concatenate + pd.DataFrame constructor. df col 0 [{'age': 10, 'name': 'Tom'}, {'age': 5, 'name'... 1 [{'age': 20, 'name': 'Ash'}, {'age': 54, 'name'... pd.DataFrame(np.concatenate(df.col).tolist()) age name 0 10 Tom 1 5 Mark 2 7 Pam 3 12 Dick 4 20 Ash 5 54 Jim 6 29 Sam 7 15 Poo If what you have is a series (not a dataframe), you can just to np.concat(s) where s is your pd.Series.
answers question: http://stackoverflow.com/q/47216177
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/tag/c
tags question: http://stackoverflow.com/q/47211132
tags question: http://stackoverflow.com/q/47103582
tags question: http://stackoverflow.com/q/47154532
tags question: http://stackoverflow.com/q/47194856
tags question: http://stackoverflow.com/q/47113107
tag name: c
type: Tag
tags question: http://stackoverflow.com/q/47160328
tags question: http://stackoverflow.com/q/47120907
tags question: http://stackoverflow.com/q/47117781
tags question: http://stackoverflow.com/q/47114939
tags question: http://stackoverflow.com/q/47124169
tags question: http://stackoverflow.com/q/47181635
tags question: http://stackoverflow.com/q/47086852
tags question: http://stackoverflow.com/q/47080411

http://stackoverflow.com/q/47067601
type: Question
tagged with: python-3.x
answer count: 2
possible better answer: http://stackoverflow.com/a/47067965
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/47067965
has answer: http://stackoverflow.com/a/47067828
accepted answer: http://stackoverflow.com/a/47067828
tagged with: http://stackoverflow.com/tag/json
has title: Can't dump JSON file, keep getting Type Error
has body: so I have a function for my object account that once it creates itself it logs itself to a file but it doesn't seem to work. I keep getting the error, TypeError: Object of type 'getset_descriptor' is not JSON serializable. Thanks in advance for any advice. import os import json import datetime clear = lambda: os.system("cls") now = datetime.date temp = 1 temp_intger = None class Account: def __init__(self , account_number , account_balance , account_creation , account_firstname , account_lastname): self.acc_number = account_number self.acc_balance = account_balance self.acc_creation = account_creation self.acc_firstname = account_firstname self.acc_lastname = account_lastname def account_creation(): acc = {} acc["account_firstname"] = input("Please enter the first name of the account") acc["account_lastname"] = input("Please enter the last name of the account") acc["account_balance"] = float(input("Please enter the balance of the account")) acc["account_creation"] = now.day while True: temp = input("Please enter a 4 pin number for your account!") if ((os.path.isfile("%s.json" %(temp))) == True): continue else: break with open("%s.json" % (temp) , "w") as fp: json.dump(acc,fp) print ("Done!") account_creation()
tagged with: python

http://stackoverflow.com/comment/81532468
has text: Why a server? Why not just mock the request library itself and avoid network connectivity entirely?
comment on: http://stackoverflow.com/q/47184906
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81222870
comment on: http://stackoverflow.com/q/47128948
score: 0
type: Comment
type: QuestionComment
has text: If you can create an [mcve](https://stackoverflow.com/help/mcve) of dask.dataframe ignoring the chunksize argument then I encourage you to [file a bug report](https://github.com/dask/dask/issues/new)

http://stackoverflow.com/comment/81284677
score: 0
has text: @DanielGee Thanks for the suggestion, unfortunately no change in runtime, but did condense the code.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47167148

http://stackoverflow.com/q/47150875
has title: Python, comparing two files
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47151913
has comment: http://stackoverflow.com/comment/81252118
answer count: 2
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81251408
possible better answer: http://stackoverflow.com/a/47151913
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47150979
has comment: http://stackoverflow.com/comment/81251837
has answer: http://stackoverflow.com/a/47150979
has body: Suppose I have two (huge) files. One contains a list of words. Another contains a list of words followed by some numbers; i.e., the format is like this: file 1: word1 word2 ... file 2: word1 n1 n2 n3 n4 n5.....n500 word2 n1 n2 n4 n5 .... n500 ... Using Python 3, what is the most efficient way of overlapping the files and extracting from file 2 only those lines that contain words also occurring in file 1? Creating a dictionary for file 2 and then going over it and checking membership using the words from file 1 is very slow.
tagged with: python

http://stackoverflow.com/a/47145774
score: 2
has body: I suppose the B list contains time intervals, right? In that case, you can do something like the following: updated = [x if any([start &lt;= x[0] end &lt;= for start, end in B]) else [x[0], 0] for x in A] That may be a bit too compact for some people, but it essentially does the same as the following: updated = [] for time, value in A: for start, end in B: if start &lt;= time and time &lt;= end: updated.append([time, value]) break updated.append([time, 0]) On a side note, if you are doing interval checking, this is probably not the most efficient way to do it. Take a look at interval trees, which is a data structure for performing various interval-related queries (yours included).
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47145424
upvote count: 2

http://stackoverflow.com/comment/81338540
comment on: http://stackoverflow.com/a/47194677
score: 0
type: Comment
type: AnswerComment
has text: @LawrenceMaizon The issue is: if the number displays as a float like 150.800000000003 - do you want it to be displayed as 150 or as 151?

http://stackoverflow.com/comment/81388524
comment on: http://stackoverflow.com/a/47219490
has text: Okay. So it is literally a RULE that all class inherited relationships MUST be is-a. (e.g. IF B inherits from A, B is an A) ...? I never knew this. In game playing, don't players inherit from a score or world class? I'd be interested in clarification of this
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47223143
tagged with: mocking
has comment: http://stackoverflow.com/comment/120912880
type: UnansweredQuestion
downvote count: 0
tagged with: python-unittest.mock
tagged with: python
tagged with: patch
has title: Python: patching function defined in same module of tested function
tagged with: unit-testing
favorite count: 0
upvote count: 17
has answer: http://stackoverflow.com/a/54083099
has answer: http://stackoverflow.com/a/62922356
score: 17
type: Question
has body: I have been working with Python's unittest.mock library quite a bit, but right now I'm struggling with a use case that may not be approached correctly. Consider a file mymodule/code.py containing the following snippet: def sum(): pass def mul(): pass def div(): pass def get_functions(): return [sum, mul, div] def foo(): functions = get_functions() for func in functions: func() I want to test the foo function, patching the sum function, and leaving mul and div as they are. This is what I tried initially: class TestFoo(unittest.TestCase): @mock.patch('mymodule.code.foo.sum') def test_foo(foo_sum_mock): foo() foo_sum_mock.assert_called_once() However, the patching approach illustrated above does not work. I believe that the sum function is patched correctly when loading mymodule.code.py, but redefined due to the def sum() block. By reading the official documentation, I also tried to use the start and stop functions of the unittest.mock library as follows: def test_foo(): patcher = mock.patch('module.code.sum') mocked_sum_fun = patcher.start() foo() mocked_sum_fun.assert_called_once() mock_sum_fun.stop() This approach also did not work. I was hoping it would avoid the sum function override after the modules/code.py file gets loaded. Is it possible to patch a local function such as sum? Or is moving the sum function to another file the only option for patching? Many thanks in advance!
answer count: 2

http://stackoverflow.com/a/47196030
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/47186313
has body: I found the solution some images are corrupted in dataset after removing them classifier is working perfectly
has comment: http://stackoverflow.com/comment/92612652
downvote count: 0
has comment: http://stackoverflow.com/comment/88701290
upvote count: 4
answers question: http://stackoverflow.com/q/47186313
type: AcceptedAnswer

http://stackoverflow.com/comment/81246253
score: 0
has text: Can you recreate the input generator? Otherwise I don't think there's any way to do what you want.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47146905

http://stackoverflow.com/a/47118728
has comment: http://stackoverflow.com/comment/81226700
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47118695
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/81226809
has comment: http://stackoverflow.com/comment/81226898
score: 4
has comment: http://stackoverflow.com/comment/81226931
has comment: http://stackoverflow.com/comment/81226608
accepted answer of: http://stackoverflow.com/q/47118695
has comment: http://stackoverflow.com/comment/81227284
has comment: http://stackoverflow.com/comment/81228399
has comment: http://stackoverflow.com/comment/81228159
downvote count: 0
has body: I think groupby + merge here is only overcomplicated way for this. So faster is use reindex by MultiIndex: mux = pd.MultiIndex.from_product([df['group'].unique(), categories], names=('group','cat')) df = df.set_index(['group','cat']).reindex(mux).swaplevel(0,1).reset_index() #add missing values to group column df['group'] = df['group'].mask(df['value'].isnull()) print (df) cat group value value2 0 a 1.0 0.0 0.0 1 b 1.0 1.0 2.0 2 c 1.0 2.0 4.0 3 d NaN NaN NaN 4 a 2.0 3.0 6.0 5 b NaN NaN NaN 6 c 2.0 4.0 8.0 7 d NaN NaN NaN Possible solution: df = df.groupby('group', group_keys=False) .apply(lambda x: pd.merge(categories, x, how = 'outer', on='cat')) cat group value value2 0 a 1.0 0.0 0.0 1 b 1.0 1.0 2.0 2 c 1.0 2.0 4.0 3 d NaN NaN NaN 0 a 2.0 3.0 6.0 1 b NaN NaN NaN 2 c 2.0 4.0 8.0 3 d NaN NaN NaN Timings: np.random.seed(123) N = 1000000 L = list('abcd') #235,94.1,156ms df = pd.DataFrame({'cat': np.random.choice(L, N, p=(0.002,0.002,0.005, 0.991)), 'group':np.random.randint(10000,size=N), 'value':np.random.randint(1000,size=N), 'value2':np.random.randint(5000,size=N)}) df = df.sort_values(['group','cat']).drop_duplicates(['group','cat']).reset_index(drop=True) print (df.head(10)) categories = ['a', 'b', 'c', 'd'] def jez1(df): mux = pd.MultiIndex.from_product([df['group'].unique(), categories], names=('group','cat')) df = df.set_index(['group','cat']).reindex(mux, fill_value=0).swaplevel(0,1).reset_index() df['group'] = df['group'].mask(df['value'].isnull()) return df def jez2(df): grouped = df.groupby('group') categories = pd.DataFrame(['a', 'b', 'c', 'd'], columns=['cat']) return grouped.apply(lambda x: pd.merge(categories, x, how = 'outer', on='cat')) def coldspeed(df): grouped = df.groupby('group') categories = pd.DataFrame(['a', 'b', 'c', 'd'], columns=['cat']) return pd.concat([g[1].merge(categories, how='outer', on='cat') for g in grouped]) def akilat90(df): grouped = df.groupby('group') categories = pd.DataFrame(['a', 'b', 'c', 'd'], columns=['cat']) merged_li…
has comment: http://stackoverflow.com/comment/81227977

http://stackoverflow.com/comment/81191178
score: 0
type: Comment
type: QuestionComment
has text: Why do you want that `buttonClicked` method to be in a separate class instead of in the GUI class?
comment on: http://stackoverflow.com/q/47120738

http://stackoverflow.com/comment/81237394
has text: I tried out the sample code from that blog post and it returns the same error ssl.SSLError: ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47142848

http://stackoverflow.com/a/47198629
has comment: http://stackoverflow.com/comment/81352513
has comment: http://stackoverflow.com/comment/81346373
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81346084
downvote count: 0
answers question: http://stackoverflow.com/q/47198378
upvote count: 1
has body: You can do something like as follows: input_list = [[0, 1], [1, 0], [2, 30], [3, 2], [4, 6], [5, 31], [6, 5], [7, 8], [8, 7], [9, 10], [10, 9], [11, 10], [12 , 1]] result = [] for i in range(len(input_list)): if not result: result.append(set(input_list[i])) else: flag = False last_merged_index = -1 j = 0 while j &lt; len(result): if not set(input_list[i]).isdisjoint(result[j]): result[j] |= set(input_list[i]) flag = True if last_merged_index != -1: result[j] |= result[last_merged_index] result.pop(last_merged_index) last_merged_index = j-1 else: last_merged_index = j j += 1 else: j += 1 if not flag: result.append(set(input_list[i])) print(result) Output: [{0, 1, 12}, {2, 3, 30}, {4, 5, 6, 31}, {8, 7}, {9, 10, 11}] For your second input: input_list = [[0, 1], [1, 0], [2, 30], [3, 2], [4, 6], [5, 31], [6, 5], [7, 8], [8, 7], [9, 10], [10, 9], [11, 10], [12 , 1], [13, 14], [14, 16], [15, 16], [16, 14], [17, 18], [18, 17], [19, 20], [20, 21], [21, 23], [22, 26], [23, 21], [24, 23], [25, 24], [26, 27], [27, 26], [28, 29], [29, 28], [30, 2], [31, 2]] You should get the following: [{0, 1, 12}, {2, 3, 4, 5, 6, 30, 31}, {8, 7}, {9, 10, 11}, {16, 13, 14, 15}, {17, 18}, {19, 20, 21, 23, 24, 25}, {26, 27, 22}, {28, 29}]
accepted answer of: http://stackoverflow.com/q/47198378
type: Answer

http://stackoverflow.com/a/47103023
type: AcceptedAnswer
downvote count: 0
score: 6
accepted answer of: http://stackoverflow.com/q/47102769
has comment: http://stackoverflow.com/comment/81163505
upvote count: 6
has body: Something like this would work: def no_arg(): return 5 def one_arg(x): return x def multiple_args(x, y): return x * y def function_results_sum(*args, **kwargs): result = 0 for func in args: result += func(*kwargs[func.__name__]) return result Output: function_results_sum( no_arg, one_arg, multiple_args, no_arg=(), one_arg=(23, ), multiple_args=(1,5)) 33 The only difference between what you are asking is that you have to put args in a tuple to then unpack as args to pass in later. If you dont want to have to supply anything for no argument functions, you can double check if the func name is in kwargs: def function_results_sum(*args, **kwargs): result = 0 for func in args: if func.__name__ i kwargs: result += func(*kwargs[func.__name__]) else: result += func() return result
answers question: http://stackoverflow.com/q/47102769
type: Answer

http://stackoverflow.com/a/47750437
type: Answer
accepted answer of: http://stackoverflow.com/q/47110762
has comment: http://stackoverflow.com/comment/82987594
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47110762
has body: This issue has been documented here, you can update to python 3.6 or install and enable the win_unicode_console package to solve it https://bugs.python.org/issue32245

http://stackoverflow.com/q/47129071
has body: The example given by the tensorflow tutorial shows that the mask can be created: tf.sequence_mask([1, 3, 2], 5) # [[True, False, False, False, False], # [True, True, True, False, False], # [True, True, False, False, False]] What if I would like to create a dynamic mask based on the values of my batches? Say if my input is [[1, 0, 2, 3, 4], [2, 3, 4, 4, 4], [2, 3, 4, 5, 4]], and I would like to mask everything up to the first 4 to be True and everything after the first 4 to be false, and the resulting mask should be: [[True, True, True, True, True], [True, True, True, False, False], [True, True, True, False, False]] I am trying to use this as weight to apply to my sequence_loss tensor
tagged with: python
has title: Creating a tf.sequence_mask based on input values
has comment: http://stackoverflow.com/comment/81208533
score: 0
answer count: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/81208373
has answer: http://stackoverflow.com/a/47129702
type: UnansweredQuestion

http://stackoverflow.com/comment/81119282
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47084949
has text: Here is a better picture of my dataframe.
score: 0

http://stackoverflow.com/comment/81155843
type: Comment
comment on: http://stackoverflow.com/q/47102808
type: QuestionComment
score: 0
has text: @SterlingArcher append you mean? add is a set method

http://stackoverflow.com/a/47147895
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47147749
type: Answer
accepted answer of: http://stackoverflow.com/q/47147749
has comment: http://stackoverflow.com/comment/81246382
has body: Your error has to do with pandas preferring bitwise operators and using the built in min function isn't going to work row wise. A potential solution would be to make two new calculated columns then using the pandas dataframe .min method. df['calc_col_1'] = df['Random data']-df['Average'] df['calc_col_2'] = (df['Random data2']-df['Stddev'])/(3.0*df['A2']) df['min_col'] = df'calc_col_1','calc_col_2'.min(axis=1) The method min(axis=1) will find the min between the two columns by row then assigned to the new column. This way is efficient because you're using numpy vectorization, and it is easier to read.
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/81322976
has text: We are upgrading, but I need to make it work on 2.2.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47185422
type: QuestionComment

http://stackoverflow.com/a/47146889
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81247355
has comment: http://stackoverflow.com/comment/81272620
has comment: http://stackoverflow.com/comment/81276498
has comment: http://stackoverflow.com/comment/81277044
has comment: http://stackoverflow.com/comment/81283727
has comment: http://stackoverflow.com/comment/81273908
type: Answer
has body: list_of_sports_in_category method seems to return the category name, rather than the list of sports. try replacing the second for-loop in your template with {% for sport in sport_list %}.
has comment: http://stackoverflow.com/comment/81275074
has comment: http://stackoverflow.com/comment/81244337
answers question: http://stackoverflow.com/q/47146497
score: 0
accepted answer of: http://stackoverflow.com/q/47146497

http://stackoverflow.com/a/47193014
downvote count: 0
answers question: http://stackoverflow.com/q/47192327
accepted answer of: http://stackoverflow.com/q/47192327
score: 3
has comment: http://stackoverflow.com/comment/81336267
upvote count: 3
has comment: http://stackoverflow.com/comment/81336340
type: Answer
has body: You need a <pk> to go with your url so it will match. I edited this part for you: {% for student in all_students %} {{ student.first_name }} {{ student.last_name }} ({{ student.course }}) Delete Update {% endfor%}
has comment: http://stackoverflow.com/comment/81336639
has comment: http://stackoverflow.com/comment/81336632
has comment: http://stackoverflow.com/comment/81336312
type: AcceptedAnswer

http://stackoverflow.com/q/47064968
tagged with: python-3.x
tagged with: nonetype
has comment: http://stackoverflow.com/comment/81078351
accepted answer: http://stackoverflow.com/a/47065049
has comment: http://stackoverflow.com/comment/81078253
has answer: http://stackoverflow.com/a/47065049
tagged with: python
type: AnsweredQuestion
tagged with: attributeerror
has body: I'm getting this error: [...], line 28, in &lt;module&gt; PlayerDamage = Dice * int(set_p_w.player_damage) AttributeError: 'NoneType' object has no attribute 'player_damage' When I run this code: import player Dice = random.randrange(1, 7) set_p_w = player.set_player_weapon() PlayerDamage = Dice * set_p_w.player_damage This is how player.set_player_weapon() looks like: def set_player_weapon(): import items player_weapon = items.WBrokenSword player_damage = player_weapon.damage I searched everywhere and tried a bunch of different solutions, but nothing helped me. What is wrong with my code?
score: 0
answer count: 1
has title: AttributeError: 'NoneType' object has no attribute 'foo'
has comment: http://stackoverflow.com/comment/81078227
has comment: http://stackoverflow.com/comment/81078276
type: Question

http://stackoverflow.com/a/47083306
score: 3
upvote count: 3
type: Answer
has body: You forgot to refresh the second figure after changing it. Add fig2.canvas.draw_idle() at the end. def mouse_move(event): x = event.xdata y = event.ydata if x is not None and y is not None: angle = x plot_ray(angle, y) fig2.canvas.draw_idle() Note that this would now create new circle and artist on every mouse_move event, which is rather inefficient. You would rather want to create those artists once and only update their properties. The following runs much more smoothly. import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots(dpi=100, figsize=(5, 5)) x = np.arange(0, 6, 0.1) plt.plot(x, np.sin(x), 'r') fig2, ax2 = plt.subplots(dpi=100, figsize=(5, 5)) circle = plt.Circle((0, 0), 1, color='b', fill=False) ax2.add_artist(circle) line, = ax2.plot([],[]) ax2.set_xlim(-2, 2) ax2.set_ylim(-2, 2) def plot_ray(angle, y): length = y / np.sin(angle) line.set_data([0, length * np.cos(angle)], [0, length * np.sin(angle)]) def mouse_move(event): x = event.xdata y = event.ydata if x is not None and y is not None: angle = x plot_ray(angle, y) fig2.canvas.draw_idle() cid = fig.canvas.mpl_connect('motion_notify_event', mouse_move) plt.show(block=True)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47078050
answers question: http://stackoverflow.com/q/47078050

getpass
tags question: http://stackoverflow.com/q/47213310
type: Tag
tag name: getpass

http://stackoverflow.com/comment/81217606
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47132729
has text: @amruta _"the code you provided did not make any changes as I wanted to have"_ You did not specify what you *wanted* to have in your original post. Learning how to read from a file or write to a file should be among the first things to learn in scripting. Anyway, I have added writing to a file for your pleasure.

http://stackoverflow.com/a/47167288
has body: Firstly, that's not JSON. Strings in JSON have double, not single quotes, and the unquoted tokens a and b are meaningless in JSON. Assuming that your actual document looks something like this: { "item1": { "value": ["a", "b"], "number": 1 }, "item2": { "value": ["a"], "number": 2 }, "item3": { "value": ["b"], "number": 3 } } … and you've loaded it into a Python dictionary data, you can get the output you want as follows: grouped = {} for key, subdict in data.items(): for value in subdict['value']: grouped.setdefault(value, []).append(key) Which will leave you with grouped looking like this: { 'a': ['item2', 'item1'], 'b': ['item3', 'item1'] }
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47166214
has comment: http://stackoverflow.com/comment/81326078
answers question: http://stackoverflow.com/q/47166214
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/47130632
has answer: http://stackoverflow.com/a/47131116
tagged with: anagram
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47130902
has comment: http://stackoverflow.com/comment/81211040
tagged with: substring
answer count: 4
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47130693
has comment: http://stackoverflow.com/comment/129278785
has title: How to check if a substring contains all of the letters in "apple"
has body: If I have string "axplpett" I would like to return true, because a substring of it "axplpe" contains all of the letters of apple. I was thinking of using the set method, but apple has repeating characters.
accepted answer: http://stackoverflow.com/a/47130760
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/3496518
possible better answer: http://stackoverflow.com/a/47130693
has answer: http://stackoverflow.com/a/47130760
upvote count: 2

http://stackoverflow.com/comment/81258345
score: 0
type: AnswerComment
has text: The first sentence of my answer explains why.
type: Comment
comment on: http://stackoverflow.com/a/47147865

http://stackoverflow.com/comment/81360123
score: 0
has text: Hold on, do you want a solution to type in the axis limits in the tk backend or a solution to set the window full size with Qt backend?
type: Comment
comment on: http://stackoverflow.com/a/47181267
type: AnswerComment

http://stackoverflow.com/q/47074208
type: AnsweredQuestion
tagged with: selenium-chromedriver
answer count: 1
has comment: http://stackoverflow.com/comment/81103355
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/81105204
tagged with: google-chrome
accepted answer: http://stackoverflow.com/a/47078460
favorite count: 0
has comment: http://stackoverflow.com/comment/81100168
has title: chrome fails to load with python selenium chromedriver
type: Question
has comment: http://stackoverflow.com/comment/81103389
score: 5
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/47078460
has body: I have tested the code on my PC with Ubuntu 17.10. Chrome launches with UI so everything is normal. The Vultr instasnce is with Ubuntu 16.04, Python 3, Selenium, Google-Chrome, Chromedriver and xvfb installed. Default user is root. chromedriver-2.33.506092 is on /usr/bin/chromedriver, while Google-Chrome-62.0.3202.75 is on /usr/bin/google-chrome However, running it on a Vultr instance, it gives this error: https://pastebin.com/RJX6Ynxe Below is part of the code. from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import Select from pyvirtualdisplay import Display display = Display(visible=0, size=(1024, 768)) display.start() chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') self.driver = webdriver.Chrome(chrome_options=chrome_options) This is the service-log: https://pastebin.com/s6Nw3Jxc Would anyone know how to fix this? Thanks!

http://stackoverflow.com/comment/81120920
type: QuestionComment
comment on: http://stackoverflow.com/q/47085244
has text: Have a look at this [curve fitting example](https://docs.scipy.org/doc/scipy-0.19.1/reference/generated/scipy.optimize.curve_fit.html) using `scipy`.
type: Comment
score: 1

http://stackoverflow.com/a/47207816
answers question: http://stackoverflow.com/q/47206742
type: Answer
accepted answer of: http://stackoverflow.com/q/47206742
score: 1
has body: One approach would be to prepend a datetime representation of the combined date elements to the start of each row. This would then make all of the elements correctly sortable. The list of rows can then be converted into a list of columns using *zip(): from datetime import datetime import csv data = [] with open('input.csv', newline='') as f_input: csv_reader = csv.reader(f_input) header = next(csv_reader) for row in csv_reader: data.append([datetime.strptime('{} {} {}'.format(*row[:3]), '%d %B %Y')] + row) sorted_cols = list(zip(*sorted(data))) print("Days", sorted_cols[1]) print("Months", sorted_cols[2]) print("Years", sorted_cols[3]) print("Debits", sorted_cols[4]) This would give you: Days ('6', '1', '1', '9') Months ('February', 'March', 'March', 'June') Years ('2016', '2016', '2016', '2017') Debits ('47.81', '27.48', '487.00', '218.55')
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47134556
has body: I am trying to integrate API gateway with Lambda proxy, The API server receives the request with these parameters i.e postcode and house https://api.domain.com/getAddressproxy?postcode=XX2YZ&amp;house=123 However tests from the API gateway to the Lambda proxy does not return values https://xxxxxxxxxx.execute-api.eu-west-1.amazonaws.com/Test/getaddressproxy?postcode=XX2YZ&amp;house=123 I think the issue is that the lambda function is not passing the query string parameters to the API server. Any idea how i can pass the query string parameters to the request object? Code: from __future__ import print_function import json import urllib2 import ssl print('Loading function') target_server = "https://api.domain.com" def lambda_handler(event, context): print("Got event\n" + json.dumps(event, indent=2)) ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE print("Event here: ") print(event['path']) print(event["queryStringParameters"]) req = urllib2.Request(target_server + event['path']) if event['body']: req.add_data(event['body']) # Copy only some headers copy_headers = ('Accept', 'Content-Type') for h in copy_headers: if h in event['headers']: req.add_header(h, event['headers'][h]) out = {} try: resp = urllib2.urlopen(req, context=ctx) out['statusCode'] = resp.getcode() out['body'] = resp.read() except urllib2.HTTPError as e: out['statusCode'] = e.getcode() out['body'] = e.read() return out
has answer: http://stackoverflow.com/a/47135019
type: AnsweredQuestion
answer count: 2
downvote count: 0
upvote count: 7
tagged with: aws-api-gateway
tagged with: amazon-web-services
tagged with: aws-lambda
favorite count: 0
accepted answer: http://stackoverflow.com/a/47134811
type: Question
has answer: http://stackoverflow.com/a/47134811
tagged with: python
score: 7
has title: python pass querystring parameters to API gateway
possible better answer: http://stackoverflow.com/a/47135019

http://stackoverflow.com/comment/81324680
type: QuestionComment
score: 2
has text: also you mighty want to use a dictionary instead
comment on: http://stackoverflow.com/q/47187642
type: Comment

http://stackoverflow.com/a/47220536
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47220355
has comment: http://stackoverflow.com/comment/81468548
answers question: http://stackoverflow.com/q/47220355
has body: Use os.path.normpath(path) or other helpful methods in os.path module.
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/81468379
has comment: http://stackoverflow.com/comment/81505367

http://stackoverflow.com/a/47114341
type: Answer
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81189566
has comment: http://stackoverflow.com/comment/81179152
has body: Install driver first and then try if it works. Download &amp; Install Python MySQL Connector driver from following link. https://dev.mysql.com/downloads/connector/c/6.0.html#downloads pip install MySQL-Python Refer: https://github.com/PyMySQL/mysqlclient-python/issues/142
answers question: http://stackoverflow.com/q/47114190

for-loop
tags question: http://stackoverflow.com/q/47212987
tags question: http://stackoverflow.com/q/47170102
tags question: http://stackoverflow.com/q/47190295
tags question: http://stackoverflow.com/q/47121135
tags question: http://stackoverflow.com/q/47104948
tags question: http://stackoverflow.com/q/47163992
tags question: http://stackoverflow.com/q/47172769
tags question: http://stackoverflow.com/q/47122752
tags question: http://stackoverflow.com/q/47198165
tags question: http://stackoverflow.com/q/47116080
type: Tag
tags question: http://stackoverflow.com/q/47213086
tags question: http://stackoverflow.com/q/47158642
tags question: http://stackoverflow.com/q/47072285
tags question: http://stackoverflow.com/q/47184124
tags question: http://stackoverflow.com/q/47146886
tags question: http://stackoverflow.com/q/47187764
tags question: http://stackoverflow.com/q/47154136
tags question: http://stackoverflow.com/q/47163008
tags question: http://stackoverflow.com/q/47210790
tags question: http://stackoverflow.com/q/47193665
tags question: http://stackoverflow.com/q/47180690
tags question: http://stackoverflow.com/q/47075370
tag name: for-loop
tags question: http://stackoverflow.com/q/47164494
tags question: http://stackoverflow.com/q/47078053
tags question: http://stackoverflow.com/q/47220993
tags question: http://stackoverflow.com/q/47183992
tags question: http://stackoverflow.com/q/47151148
tags question: http://stackoverflow.com/q/47084759
tags question: http://stackoverflow.com/q/47205055
tags question: http://stackoverflow.com/q/47131795
tags question: http://stackoverflow.com/q/47122028
tags question: http://stackoverflow.com/q/47096150

http://stackoverflow.com/comment/81293735
type: AnswerComment
has text: Sorry, I wasn't clear enough. The process is already running and I want to recover it from this running process.
comment on: http://stackoverflow.com/a/47172123
type: Comment
score: 0

http://stackoverflow.com/q/47219752
answer count: 1
has comment: http://stackoverflow.com/comment/81389753
accepted answer: http://stackoverflow.com/a/47219781
has comment: http://stackoverflow.com/comment/81389380
type: Question
has comment: http://stackoverflow.com/comment/81388968
has answer: http://stackoverflow.com/a/47219781
has comment: http://stackoverflow.com/comment/81389721
tagged with: python
has comment: http://stackoverflow.com/comment/81389473
has body: Working in an interactive mode, I input following assignments: item = ['keys', 'values', 'items'] get = ['get', 'setdefault'] pop = ['pop', 'popitem'] copy = ['copy', 'fromkeys'] update = ['update'] clear = ['clear'] # my intent result {'item': ['keys', 'values', 'items'], 'get': ['get', 'setdefault'], 'pop': ['pop', 'popitem'], 'copy': ['copy', 'fromkeys'], 'update': ['update'], 'clear': ['clear']}} I intend to fetch a dict of them from locals()with a dict comprehension and type checking. &gt;&gt;&gt; locals() {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': &lt;class '_frozen_importlib.BuiltinImporter'&gt;, '__spec__': None, '__annotations__': {}, '__builtins__': &lt;module 'builtins' (built-in)&gt;, 'item': ['keys', 'values', 'items'], 'get': ['get', 'setdefault'], 'pop': ['pop', 'popitem'], 'copy': ['copy', 'fromkeys'], 'update': ['update'], 'clear': ['clear']} my code: {k:v for k, v in locals().items if isinstance(v, list)} TypeError: 'builtin_function_or_method' object is not iterable I fixed it In [12]: {k:locals[k] for k in locals() if isinstance(locals()[k], list)} #Error reports again. KeyError: '__name__' How to fix it?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81389797
has comment: http://stackoverflow.com/comment/81389070
has title: isinstance() in dict comprehension

http://stackoverflow.com/a/47086111
answers question: http://stackoverflow.com/q/47084099
has body: You need to create an empty file called __init__.py in the app directory to make it into a package. If you don't have that file, you cannot perform submodule imports. touch /home/mike/CINS465/465proj/project/firstapp/collections/__init__.py
score: 0
has comment: http://stackoverflow.com/comment/81121841
has comment: http://stackoverflow.com/comment/81122122
type: Answer

http://stackoverflow.com/comment/81275156
has text: @Achaca Sure... `.rename(columns=lambda x: 'X')` instead of `.add_prefix(...)`
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47162294

http://stackoverflow.com/q/47175843
has answer: http://stackoverflow.com/a/47175951
has comment: http://stackoverflow.com/comment/81301620
has comment: http://stackoverflow.com/comment/81300844
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81302202
has body: I have a created a function to print out the statistics of a tokenized text: def print_statistics(text): print("\nThe total number of tokens is " +str(number_of_tokens(ny))+".") return ??? This function gives me two outputs (the second is "none"). But I want the function to give me the print output. Any idea how I can do this?
has title: Print function returns two values
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47175902
answer count: 4
has answer: http://stackoverflow.com/a/47175902
type: Question
possible better answer: http://stackoverflow.com/a/47175951
has answer: http://stackoverflow.com/a/47176019
has answer: http://stackoverflow.com/a/47176911
upvote count: 1
tagged with: python

http://stackoverflow.com/a/47067650
has body: I try to run your code: df = pd.read_clipboard(sep=',',engine='python') df DateTime open high low close 0 2016-01-04 00:36:18 1.08505 1.08505 1.08504 1.08504 1 2016-01-04 00:36:19 1.08505 1.08505 1.08504 1.08504 2 2016-01-04 00:36:20 1.08503 1.08503 1.08495 1.08495 and then use df.round(3) DateTime open high low close 0 2016-01-04 00:36:18 1.085 1.085 1.085 1.085 1 2016-01-04 00:36:19 1.085 1.085 1.085 1.085 2 2016-01-04 00:36:20 1.085 1.085 1.085 1.085 It works for me ,but as I df.astype(str).round(3) and then it will not work .So I recommend you to check the type of your data.
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47066858
score: 0
type: Answer

templating
type: Tag
tags question: http://stackoverflow.com/q/47158672
tag name: templating

http://stackoverflow.com/a/47173520
has comment: http://stackoverflow.com/comment/81305377
has comment: http://stackoverflow.com/comment/81305090
has comment: http://stackoverflow.com/comment/81304310
has comment: http://stackoverflow.com/comment/81305550
upvote count: 5
has comment: http://stackoverflow.com/comment/81306445
type: Answer
has comment: http://stackoverflow.com/comment/81304853
accepted answer of: http://stackoverflow.com/q/47173451
has comment: http://stackoverflow.com/comment/81305153
score: 5
has body: You can test the QuerySet directly using an if clause. This would cause the QuerySet to be evaluated. Empty QuerySets (or empty lists) are falsy: page = paginator.page(page_number) if page.object_list: ... If you want to iterate on the QuerySet, there's no need to test for emptiness. Just use the for clause: for obj in page.object_list: # empty QuerySet gets zero iterations ...
answers question: http://stackoverflow.com/q/47173451
type: AcceptedAnswer
downvote count: 0

pdf-parsing
type: Tag
tag name: pdf-parsing
tags question: http://stackoverflow.com/q/47148781

rss
type: Tag
tag name: rss
tags question: http://stackoverflow.com/q/47181567
tags question: http://stackoverflow.com/q/47213315

http://stackoverflow.com/comment/81236017
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47118933
has text: That's what this statement does.
type: Comment

http://stackoverflow.com/a/47205249
score: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47192677
has body: The use of the return keyword is different in a Python function vs. a MATLAB function. In a MATLAB function, the Left Hand Side (LHS) arguments define what needs to be defined within the function body prior to returning. function y = foo(x) y = 1; end If you use a return statement to end execution of the function early, you still are responsible for correctly populating the LHS argument list of the function function y = foo(x) y = 1; return; y = 2; end In this example, foo returns 1 as y because the function body defines y to be 1, before execution returns to the caller after the return statement. In python, the return statement ends execution AND also defines what (if any) values are returned by a function, there is no output argument list in a python function definition. def foo(x): return 1; Because you need to use the return keyword in python to return values from a function, return tends to be a more heavily used construct than return in MATLAB function definitions.
answers question: http://stackoverflow.com/q/47192677
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81300366
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47173904
has text: How can i share the file with you?

http://stackoverflow.com/q/47202265
linked to: http://stackoverflow.com/q/34931192
has title: Delete all files in a folder that doesn't have certain name
upvote count: 0
type: UnansweredQuestion
has body: So I have about 1200 folders with different content in each. In all of them there is one file that has a specific name, let's call it data.txt. Now, due to lack of hard drive space I need to remove/delete all data in each folder that is not that particular file, i.e. data.txt. Is this possible to do in python ? If so, how ? :)
has comment: http://stackoverflow.com/comment/81352910
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81352888
duplicate of: http://stackoverflow.com/q/34931192
answer count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47202466
type: Question

http://stackoverflow.com/a/47084171
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81117682
has comment: http://stackoverflow.com/comment/81121154
accepted answer of: http://stackoverflow.com/q/47084045
answers question: http://stackoverflow.com/q/47084045
type: Answer
has comment: http://stackoverflow.com/comment/81127641
score: 4
upvote count: 4
has body: We would look for differentiation values along rows and columns for zeros signalling repeated ones there. Thus, we could do - (np.diff(a,axis=0) == 0).any() | (np.diff(a,axis=1) == 0).any() Or with slicing for performance boost - (a[1:] == a[:-1]).any() | (a[:,1:] == a[:,:-1]).any() So, (a[1:] == a[:-1]).any() is the vertical adjacency, whereas the other one is for horizontal one. Extending to n adjacent ones (of same value) along rows or columns - from scipy.ndimage.filters import convolve1d as conv def vert_horz_adj(a, n=1): k = np.ones(n,dtype=int) v = (conv((a[1:]==a[:-1]).astype(int),k,axis=0,mode='constant')&gt;=n).any() h = (conv((a[:,1:]==a[:,:-1]).astype(int),k,axis=1,mode='constant')&gt;=n).any() return v | h Sample run - In [413]: np.random.seed(0) ...: a = np.random.randint(11,99,(10,4)) ...: a[[2,3,4,6,7,8],0] = 1 In [414]: a Out[414]: array([[55, 58, 75, 78], [78, 20, 94, 32], [ 1, 98, 81, 23], [ 1, 76, 50, 98], [ 1, 92, 48, 36], [88, 83, 20, 31], [ 1, 80, 90, 58], [ 1, 93, 60, 40], [ 1, 30, 25, 50], [43, 76, 20, 68]]) In [415]: vert_horz_adj(a, n=1) Out[415]: True # Because of first col In [416]: vert_horz_adj(a, n=2) Out[416]: True # Because of first col In [417]: vert_horz_adj(a, n=3) Out[417]: False In [418]: a[-1] = 10 In [419]: vert_horz_adj(a, n=3) Out[419]: True # Because of last row

http://stackoverflow.com/comment/81121271
comment on: http://stackoverflow.com/q/47085830
type: Comment
score: 1
type: QuestionComment
has text: it's not defined just under the if.. it's in the same scope as the rest of the code.. functions and classes create new scopes but just a conditional or loop **does not**

http://stackoverflow.com/comment/81181309
type: QuestionComment
has text: @charlietfl Is there a different way of sending emails than by HTML which allows movement?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47115583

http://stackoverflow.com/a/47193254
has comment: http://stackoverflow.com/comment/81335983
has body: It appears from the source code that luminoth trains until you stop it (locally that would be ctrl-c; on the cloud, manually cancelling the job). I suppose the idea is to monitor tensorboard while it's training and manually stop it when it looks good.
downvote count: 0
answers question: http://stackoverflow.com/q/47192902
has comment: http://stackoverflow.com/comment/81336118
upvote count: 1
has comment: http://stackoverflow.com/comment/81336152
has comment: http://stackoverflow.com/comment/81335902
has comment: http://stackoverflow.com/comment/81335745
has comment: http://stackoverflow.com/comment/81335839
has comment: http://stackoverflow.com/comment/81336243
score: 1
type: Answer

http://stackoverflow.com/comment/81365710
comment on: http://stackoverflow.com/q/47208048
score: 2
type: Comment
has text: You should probably find out what was the scaling used by preprocessing and perform your own manual scaling with the same parameters.
type: QuestionComment

http://stackoverflow.com/comment/81172555
comment on: http://stackoverflow.com/a/47110164
type: Comment
score: 0
type: AnswerComment
has text: Running `bytes` on `b` is a really cool idea, thanks. I did not know that this was possible on ctypes objects. What I do not see though is how I can take into account the length of the memory segment if it is not "obvious" like in your example (array of fixed length of known type). My `serialize_pointer` routine intentionally has a `size_bytes` parameter for this purpose (the `bytes` routine does not have such a parameter). After all, I want it to accept just any type of pointer regardless of the type of data it is pointing to.

http://stackoverflow.com/a/47139863
accepted answer of: http://stackoverflow.com/q/47136855
score: 5
answers question: http://stackoverflow.com/q/47136855
has body: It may not make too much sense to use seaborn here. Using usual matplotlib boxplots allows you to use the positions argument as expected. import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') df = pd.DataFrame({'A': pd.Series(np.random.uniform(0,1,size=10)), 'B': pd.Series(np.random.uniform(10,20,size=10)), 'C': pd.Series(np.random.uniform(10,20,size=10))}) fig, ax1 = plt.subplots(figsize=(7.8, 5.51)) props = dict(widths=0.7,patch_artist=True, medianprops=dict(color="gold")) box1=ax1.boxplot(df['A'].values, positions=[0], **props) ax2 = ax1.twinx() box2=ax2.boxplot(df'B','C'.values,positions=[1,2], **props) ax1.set_xlim(-0.5,2.5) ax1.set_xticks(range(len(df.columns))) ax1.set_xticklabels(df.columns) for b in box1["boxes"]+box2["boxes"]: b.set_facecolor(next(ax1._get_lines.prop_cycler)["color"]) plt.show()
has comment: http://stackoverflow.com/comment/81229467
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81229505
has comment: http://stackoverflow.com/comment/81229623
upvote count: 5
type: Answer

http://stackoverflow.com/comment/81257386
type: QuestionComment
has text: I've edited your question to have a (far) clearer MCVE, one that shows both the actual and the expected output. Note that for the `print ar` line I used `?`, because *you never supplied a value for that variable*. That's why I asked my question about the 3rd argument to `B`'s constructor, and what I used `42` for in my answer below.
comment on: http://stackoverflow.com/q/47153518
score: 0
type: Comment

http://stackoverflow.com/q/47135679
tagged with: python
score: -2
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81220622
has title: Summing up certain data from nested dictionaries python
has answer: http://stackoverflow.com/a/47135909
has answer: http://stackoverflow.com/a/47136178
has comment: http://stackoverflow.com/comment/81220993
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/47135928
answer count: 3
tagged with: nested
favorite count: 0
accepted answer: http://stackoverflow.com/a/47136178
has comment: http://stackoverflow.com/comment/81220729
has body: So I have the following code Filme = {'1': {'Titel': 'Titanic', 'Jahr': 1997, 'Wertung': 8, 'Preis': 30, 'Schauspielern': ["Adam Sandler", 'b', 'c']}, '2': {'Titel': 'Pulp Fiction', 'Jahr': 1994, 'Wertung': 9, 'Preis': 40, 'Schauspielern': ['']}, '3': {'Titel': 'Wings of Desire', 'Jahr': 1987, 'Wertung': 8, 'Preis': 40, 'Schauspielern': ['']}, '4': {'Titel': 'London Has Fallen', 'Jahr': 2016, 'Wertung': 6, 'Preis': 20, 'Schauspielern': ['']}, '5': {'Titel': 'Avatar', 'Jahr': 2009, 'Wertung': 8, 'Preis': 35, 'Schauspielern': ['']}, '6': {'Titel': 'The Devil Wears Prada', 'Jahr': 2006, 'Wertung': 7, 'Preis': 20, 'Schauspielern': ['']}, '7': {'Titel': 'Submarine', 'Jahr': 2010, 'Wertung': 7, 'Preis': 20, 'Schauspielern': ['']}, '8': {'Titel': 'About Time', 'Jahr': 2013, 'Wertung': 8, 'Preis': 37, 'Schauspielern': ['']}, '9': {'Titel': 'Love, Rosie', 'Jahr': 2014, 'Wertung': 7, 'Preis': 25, 'Schauspielern': ['']}, '10': {'Titel': 'Me Before You', 'Jahr': 2016, 'Wertung': 9, 'Preis': 45,'Schauspielern': ['']} } The task I have to do is to calculate the total price (the variable used is "Preis") I'd have by choosing different movies. For example, if I choose movies 1, 4, and 8, the output should be 87 (30 + 20 + 37) Is there anyway I can do this? Thanks
has comment: http://stackoverflow.com/comment/81220761
type: Question
downvote count: 2
possible better answer: http://stackoverflow.com/a/47135909
has comment: http://stackoverflow.com/comment/81221147
has comment: http://stackoverflow.com/comment/81221521

http://stackoverflow.com/q/47077180
type: AnsweredQuestion
score: 0
tagged with: sql
has title: Python Django Build Raw SQL Query From a Given List
answer count: 1
type: Question
tagged with: postgresql
has answer: http://stackoverflow.com/a/47078916
accepted answer: http://stackoverflow.com/a/47078916
has body: I try to get some information from my database backend by performing a raw SQL query. I need to do calculations (multiplying a field with a factor, truncating it) and to convert it in a performant way to JSON. That's the reason why I have chosen to not use the (Django) ORM here. with connection.cursor() as cursor: cursor.execute( ''' SELECT json_build_object( 'data', array_agg(r) ) FROM ( SELECT time, trunc(column1 * 100, 2) as COL1, trunc(column2 * 100, 2) as COL2, [...] FROM measurements WHERE device_id=%s ORDER BY time DESC LIMIT 5 ) r ''', [device_id] ) result = cursor.fetchall() I need to adapt the statement above from the following list: [ {'column': 'column1', 'factor': 100, 'description': 'COL1', 'trunc': 2}, {'column': 'column2', 'factor': 100, 'description': 'COL2', 'trunc': 2}, [..] ] Since I am not used to the python syntax yet I am wondering if there is an elegant solution for creating such a statement. I know I could just loop over the list of dicts and append the query but that doesn't feel good/right to me. Any suggestions would be appreciated. I am thinking about something like this: ['trunc({} * {}, {}) as {}'.format( d['column'], d['factor'], d['trunc'], d['description']) for d in l ]
tagged with: django
tagged with: python

http://stackoverflow.com/q/47213579
has answer: http://stackoverflow.com/a/47213720
possible better answer: http://stackoverflow.com/a/47213720
tagged with: python
has title: Pandas Group By - Separate by Time and Condition
accepted answer: http://stackoverflow.com/a/47213700
type: Question
score: 2
upvote count: 2
answer count: 2
tagged with: pandas-groupby
downvote count: 0
tagged with: pandas
has body: I have a data frame that I am trying to create sub event_ids based on two conditions - time and a flag. The flag is when people >= 600, create a new subgroup. The data looks something like this: | event_id | timestamp | people | | abc | 12:00 | 1 | | abc | 12:01 | 3 | | abc | 12:02 | 5 | | abc | 12:04 | 600 | | abc | 12:10 | 4 | | abc | 12:15 | 7 | | abc | 12:20 | 1700 | | abc | 12:30 | 1 | | abc | 12:31 | 1 | | xyz | 12:32 | 1 | | xyz | 12:40 | 750 | | xyz | 12:50 | 1 | and the result I would like would look like this: | event_id | timestamp | people | subgroup | | abc | 12:00 | 1 | A | | abc | 12:01 | 3 | A | | abc | 12:02 | 5 | A | | abc | 12:04 | 600 | A | | abc | 12:10 | 4 | B | | abc | 12:15 | 7 | B | | abc | 12:20 | 1700 | B | | abc | 12:30 | 1 | C | | abc | 12:31 | 1 | C | | xyz | 12:32 | 1 | A | | xyz | 12:40 | 750 | A | | xyz | 12:50 | 1 | B | So it needs some sort of group by to account for the different event_ids (here abc and xyz but there are millions in my real data set). The data is time ordered, and row order matters when determining the grouping - rows for a event_id between two flags are in one subgroup. Each subgroup belongs in a event_id and counting for the subgroups restarts for a new event_id. Would love to see any/all ideas, I'm stumped but playing with lambda functions now.
has answer: http://stackoverflow.com/a/47213700
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/q/47215391
has answer: http://stackoverflow.com/a/47220556
has comment: http://stackoverflow.com/comment/81386190
upvote count: 0
has comment: http://stackoverflow.com/comment/81382528
tagged with: tkinter
has comment: http://stackoverflow.com/comment/81380357
downvote count: 1
answer count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has title: How to turn the output of a function and pass it into a message widget in tkinter?
tagged with: python
score: -1
has body: I have been looking for answeres on this problem but came up with nothing so I might as well ask.So I am making this GUI with python and basically it's a little GUI that can find and add a customer to a csv file. This is what I have now: from tkinter import * import csv class guiVER1: def __init__(self, master): #Name of the GUI self.master = master master.title("Packa-Parker's App") master.configure(bg="#ffffff") self.label = Label(master, text="Packa-Parker's Bank App") self.label.configure(bg='white') self.label.grid(row=0, column=4) myImage = PhotoImage(file ="C:/Users/Shay/Documents/Notebooks/LOGO Term 4.gif") self.ImageLabel = Label(master, image=myImage) self.ImageLabel.image = myImage self.ImageLabel.grid(row=6, column=5) self.master.geometry("400x400") # Where it stores the Client number self.label_text = StringVar() self.label_text.set("Find user?") self.label = Label(master, textvariable=self.label_text) self.label.grid(row=8, column=4) #Incase the user inputs something other than an integer/number self.label = Label(master, text="Please Type a Valid ID") #The number the GUI Starts with self.clientNumber= 0 vcmd = master.register(self.validate) # we have to wrap the command self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P')) self.entry.grid(row=87, column=4) self.nameEntry = Entry(master, validate="key", validatecommand=(vcmd, '%P')) self.nameEntry.grid(row=4, column=6) # The Button to run the find function self.updatebutton = Button(master, text="Find", command=self.userFinder) self.updatebutton.grid(row=7600, column=2) # The button to close the GUI self.closedbutton = Button(master, text='close', command=master.quit) self.closedbutton.grid(row=7605, column=2) def update(self): # Updates the number self.label_text.set(self.clientNumber) self.entry.delete(0,END) def updateName(self): self.label_text.set(self.nameEntry) self.entry.delete(0,END) def validate(self, newText): # Validate's the number if not newText: self.clientNumber = 0 r…
has comment: http://stackoverflow.com/comment/81381692

http://stackoverflow.com/q/47201503
accepted answer: http://stackoverflow.com/a/47215003
has body: I'm using rrdtool library in python. Same python script returned data a day back, but now suddenly it's returning None object inside the tuples generated. The rrd files haven't been modified. Type of returned is tuple and even the rrdinfo if getting printed.Please spare some time to look into it. import sys import pprint sys.path.append('/opt/plexus-srv/rrdtool-1.4.9/lib64/python2.6/site- packages') import rrdtool rrd_file = sys.argv[1] rrd_info = rrdtool.info(rrd_file) data = rrdtool.fetch(rrd_file,"AVERAGE") print(type(data)) pp = pprint.PrettyPrinter(indent =4) pp.pprint(data) pp.pprint(rrd_info) Output is: &lt;type 'tuple'&gt; ('sum',) 1510142400 [(None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,), (None,),…
type: Question
tagged with: nonetype
tagged with: rrdtool
has answer: http://stackoverflow.com/a/47215003
has title: rrdtool fetch returns None object
tagged with: python
has answer: http://stackoverflow.com/a/47216134
possible better answer: http://stackoverflow.com/a/47216134
type: AnsweredQuestion
score: 0
tagged with: rrd
answer count: 2

http://stackoverflow.com/a/47211707
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47211128
has body: Here's a pretty simple approach using standard pandas methods. For brevity and convenience I'm making your data smaller and putting into dataframes, but the concept is the same. dr=pd.date_range('1-1-2017', periods=4, freq='d') df1=pd.DataFrame( np.random.randn(4), columns=['x'], index=dr) df2=pd.DataFrame( np.random.randn(4,2), columns=['y','z'], index=dr) So df1 &amp; df2 look like this: x 2017-01-01 -0.705449 2017-01-02 -0.597631 2017-01-03 -0.844197 2017-01-04 -1.063895 y z 2017-01-01 -0.288822 -0.343934 2017-01-02 1.072678 1.776767 2017-01-03 -0.606593 0.192280 2017-01-04 0.019401 2.007770 Re-configure like this: df = df1.stack().append(df2.stack()).sort_index() 2017-01-01 x -0.705449 y -0.288822 z -0.343934 2017-01-02 x -0.597631 y 1.072678 z 1.776767 2017-01-03 x -0.844197 y -0.606593 z 0.192280 2017-01-04 x -1.063895 y 0.019401 z 2.007770 And you can even convert from here to xarray with: df.to_xarray() Some quick notes: Panel is deprecated in favor of either xarrays or multi-indexes. I took the multi-index approach above but xarrays is another good option For a great theory of data organization, see Hadley Wickam's explanation of "tidy" data, which you can find here.
score: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47211128

http://stackoverflow.com/a/47117755
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47117743
score: 5
has body: 1. You can use all: if all(a[i] != 0 for i in [1,3,8,13]): # => a[i] != 0 for every i #do smth Or just the same with any: if not any(a[i] == 0 for i in [1,3,8,13]): # => there is no such i that a[i] == 0 #do smth # => a[i] != 0 for every i 2. Alternatively, you can use some functional programming stuff. For example, you can try filter: a = [1,0,6,9,6,0,6,0,1,4,0,7,5,0] idxs_to_check = [1,3,8,13] f = list(filter(lambda i: a[i] != 0, idxs_to_check)) if f == idxs_to_check: print('Meow') Or, a similar condition in one line: if not list(filter(lambda i: a[i] == 0, [1,3,8,13])): print('Meow') 3. Finally, in your particular case, you can use the fact that the product of a list containing zero is zero: from numpy import prod if prod([a[i] for i in [1,3,8,13]]): print("Woof")
upvote count: 5
answers question: http://stackoverflow.com/q/47117743
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/q/47183844
tagged with: tree
tagged with: recursion
has title: Python - Traverse lexical tree finding words in lexicon
type: Question
tagged with: python
type: UnansweredQuestion
score: 1
has body: Suppose we've got a tree structure where each node has 3 attributes: token, children, entries/ids. A visualized example of the tree (tokens) could look like this: Task: Given a context window, for example, ['take', 'a', 'long', 'bath', 'after', 'my', 'flight'] I'd like to generate all possible candidates relating to the first token take, which are [(take, a, bath), (take, after), (take, flight)] Note that, the following code is positioned to handle early stopping, see example 1, comic book and comic book art diff = len(node.entries) - len(node.children) if diff == 1 and node.children != {}: What I've done: def traverse(self, tokens, node, tokens_matched): diff = len(node.entries) - len(node.children) if diff == 1 and node.children != {}: yield tokens_matched if node.children == {}: yield tokens_matched for i in range(len(tokens)): if tokens[i] in node.children.keys(): tokens_matched += (tokens[i],) new_tokens = tokens[i+1:] new_node = node.children[tokens[i]] yield from self.traverse(new_tokens, new_node, tokens_matched) def generate_candidates(self, tokens): node = self.root results = [] if tokens[0] in node.children.keys(): new_node = node.children[tokens[0]] for i in range(1,len(tokens)): tokens_matched = (tokens[0],) new_tokens = tokens[i:] results.extend(list(iself.traverse(new_tokens, new_node, tokens_matched))) return results Example 1: tokens = ['comic', 'book', 'art', 'on', 'the', 'web'] and outputs of my algorithm (the output is correct) [('comic', 'book'), ('comic', 'book', 'art')] Example 2: Given tokens = ['write', 'a', 'review', 'about','my','book'] and outputs of my algorithm (the output is incorrect, correct output should be [('write', 'a', 'book'),('write', 'about'), ('write', 'book')]) [('write', 'a', 'book'), ('write', 'a', 'about'), ('write', 'a', 'about', 'book'),\ ('write', 'about'), ('write', 'about', 'book'), ('write', 'about'), ('write', 'about', 'book'),\ ('write', 'book'), ('write', 'book')] example 2 doesn't return the correct answer, ver…
tagged with: tree-traversal
downvote count: 0
answer count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/47205248
has title: ValueError when trying to set up a network with BasicLSTMCell and dynamic_rnn in TensorFlow
tagged with: lstm
type: AnsweredQuestion
tagged with: deep-learning
has body: I want to train a neural network that generates text character by character. After some research I have decided to use a LSTM network for this task. My input is structured as follows: I have a file full of text (roughly 90,000,000 characters), which I slice up into overlapping sequences of 50 characters. Consider this example sentence: The quick brown fox jumps over the lazy dog I split the text up into sequences: The quick brown he quick brown_ e quick brown f _quick brown fo quick brown fox I added underscores where the spaces wouldn't be displayed in these... These shall be the time steps for my input data. Output would be the character that comes next after each sequence, so _, f, o, x and _ for the sequences above. Characters are one-hot encoded in a vector with the length of all characters in the dictionary, so with an alphabet consisting of A B C D, the character C would be represented as [0 0 1 0] Because I can't fit all text vectorized in memory at once, im breaking it up into batches that contain only a small amount of generated sequences for the network to train on. With that I get my input placeholder: x = tf.placeholder(tf.float32, [batch_size, time_steps, char_size] In the example code below I'm using a batch_size of 128, time_steps of 50 and char_size of 48 to represent a standard alphabet with 50 letters upper- and lowercase. num_units passed to BasicLSTMCell was also arbitrarily chosen to be 256 (following some tutorials with my hyperparameters here) Here is the code: import tensorflow as tf batch_size = 128 time_steps = 50 char_size = 50 num_units = 256 sess = tf.InteractiveSession() X = tf.placeholder(tf.float32, [batch_size, time_steps, char_size]) cell = tf.contrib.rnn.BasicLSTMCell(num_units) cell = tf.contrib.rnn.MultiRNNCell([cell] * 2, state_is_tuple=True) output, state = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32) And this is the error message: Traceback (most recent call last): File ".\issue.py", line 16, in &lt;module&gt; output, state =…
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47207076
tagged with: python
has answer: http://stackoverflow.com/a/47207076

http://stackoverflow.com/comment/81235103
has text: Many thanks, this is technically the correct answer: the command now works. Unfortunately, I still cannot run the script due to `ImportError: No module named site`. This might be unrelated to the actual question, and more related to how the QGIS Python version is organized, but if you have any idea how to resolve this that'd be great!
type: AnswerComment
comment on: http://stackoverflow.com/a/47142405
score: 0
type: Comment

http://stackoverflow.com/q/47153134
tagged with: big-ip
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47200112
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47200112
has body: i am able to communicate with f5 box and creating single object called (virtual= VIP=Virtual server) with some basic profiles. Working code: from f5.bigip import ManagementRoot import urllib3 urllib3.disable_warnings() mgmt = ManagementRoot('13.126.189.103','admin','admin') ltm = mgmt.tm.ltm virtuals = mgmt.tm.ltm.virtuals virtual = mgmt.tm.ltm.virtuals.virtual virtual1 = mgmt.tm.ltm.virtuals.virtual.create(name='virtual3', description = 'testnew' , destination= '172.31.5.8:80', partition='Common') my requirement is , i will give input from CSV file , may be 100 VIP's. the above syntax has to run one by one row in imported CSV file. from f5.bigip import ManagementRoot import urllib3 import csv import sys import os urllib3.disable_warnings() mgmt = ManagementRoot('13.126.189.103','admin','admin') ltm = mgmt.tm.ltm virtuals = mgmt.tm.ltm.virtuals virtual = mgmt.tm.ltm.virtuals.virtual def configureVirtuals(bigip, virtualFile): # These are the fields in the file. The purpose of each field is obvious. See. Input from CSV file called 'virtualFile' and each row has config details # the BIG-IP iControl REST API for more information. fieldNames = ["name", "description", "ip", "port"] virtualReader = csv.DictReader(virtualFile, fieldnames=fieldNames, delimiter=",") # Create a virtual server, one per line. it will take input from CSV file by row one by one try: for row in virtualReader: myvirtual = mgmt.tm.ltm.virtuals.virtual.create(name=row["name"], description=row["description"], destination="%s:%s" % (row["ip"], row["port"]) I am getting error unexpected EOF while parsing i am f5 engineer and new to python. Building application for bulk changes. any one please help me?
tagged with: http://stackoverflow.com/tag/csv
has title: Syntax Error: unexpected EOF while parsing- F5 VIP creation using CSV file
tagged with: python
type: Question
tagged with: urllib2

http://stackoverflow.com/a/47206666
type: Answer
has body: Btw, I've figured out how to make it other way. After running command: ngrok http 5000 I get ngrok address thanks to this python script: import json import os def get_ngrok_address(): os.system("curl http://localhost:4040/api/tunnels &gt; tunnels.json") with open('tunnels.json') as data_file: datajson = json.load(data_file) return dict(zip(['http', 'https'], [i['public_url'] for i in datajson['tunnels']])) It just gets json object and converts it to python dict: 'http' -&gt; ngrok_http_address 'https' -&gt; ngrok_https_address Before server start I pass generated address to all html templates e.x.: &lt;body&gt; &lt;form action="{{ ngrok_address }}/login", method="post"&gt; &lt;input type="submit" value="submit"&gt; &lt;/body&gt;
score: 2
answers question: http://stackoverflow.com/q/47147492
downvote count: 0
upvote count: 2

http://stackoverflow.com/a/47169063
has comment: http://stackoverflow.com/comment/81288696
type: Answer
answers question: http://stackoverflow.com/q/47168821
has comment: http://stackoverflow.com/comment/81288106
score: 0
has body: In a basic way you can use this function: def concat_str(lst): newlst = [] newstr = "" length = len(lst) for index, elem in enumerate(lst): if(type(elem) is str): newstr = newstr + elem if(index == length -1): newlst.append(newstr) else: if(newstr): newlst.append(newstr) newlst.append(elem) newstr = "" return newlst
has comment: http://stackoverflow.com/comment/81288184

http://stackoverflow.com/comment/81209030
type: AnswerComment
score: 0
has text: It sounds like the input string might contain letters.
comment on: http://stackoverflow.com/a/47129408
type: Comment

http://stackoverflow.com/q/47136080
has comment: http://stackoverflow.com/comment/81223371
favorite count: 0
type: Question
has body: I have a list of word tokens, such as: my_list = [[('abc, 123'), ('def, 456')], [('ghi, 789'), ('abc, 456')]] and I want to do some preprocessing with regular expressions such as replacing ", " with a whitespace (eg. string = re.sub(r"(, )", " ", string). Afterwards, I want to append the strings again to another list. All in all, I want to get a preprocessed list which looks like that: my_list_preprocessed = [[('abc 123'), ('def 456')], [('ghi 789'), ('abc 456')]] Currently I tried to implement it like that: my_list_preprocessed = [] for string in my_list: string = re.sub(r"(, )", " ", str(string)) my_list_preprocessed.append(string) However, instead of getting the intended result. I am receiving a list of strings: my_list = ["['abc 123', 'def 456']", "['ghi 789', 'abc 456']"] What can I improve to get my intended result?
has title: List elements in a list instead of strings?
has comment: http://stackoverflow.com/comment/81221937
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81221453
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/47138154
has answer: http://stackoverflow.com/a/47136677
has answer: http://stackoverflow.com/a/47137871
answer count: 3
upvote count: 0
has comment: http://stackoverflow.com/comment/81222801
downvote count: 2

http://stackoverflow.com/comment/81277927
has text: If you're getting "no module named myclass", that just means that `myclass.py` isn't in your PYTHONPATH. This is all described in the robot user guide. See http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#configuring-where-to-search-libraries-and-other-extensions
comment on: http://stackoverflow.com/q/47163056
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81210313
has text: In my class, we haven't used enumerate yet so apparently there's a way to do it without using it and I need to find out since my midterm is tomorrow lol
comment on: http://stackoverflow.com/q/47130133
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81093153
score: 0
type: Comment
type: QuestionComment
has text: @Darien, can you clarify how exactly the boundaries are arranged? Can pairs intersect? From your example, Yn <= Xn+1. Is this always the case? If the answer is yes, then the optimal solution will be binary search
comment on: http://stackoverflow.com/q/47071235

http://stackoverflow.com/q/47166904
has body: I've written a Python 3.6 script that has the following line in it: os.chdir(os.path.dirname(os.path.abspath(__file__))) I call the script via a symbolic link and print(os.getcwd()) directly after it gives me the location of the link but I want the cwd to be where the .py file is. Every search I did brought me to questions where people had the issue that they wanted it the other way around so to not follow the link but that's what it's doing anyway. I'm a bit confused, since my searches gave me the impression that following the link should be the default behavior. Executing the script directly works perfectly. By the way, this on a Linux machine.
linked to: http://stackoverflow.com/q/3220755
has answer: http://stackoverflow.com/a/47166952
type: AnsweredQuestion
score: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/3220755
type: Question
has comment: http://stackoverflow.com/comment/81283787
has title: os.chdir doesnt follow symbolic links
tagged with: python
accepted answer: http://stackoverflow.com/a/47166952

http://stackoverflow.com/a/47212416
has comment: http://stackoverflow.com/comment/81376038
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/47212257
upvote count: 5
has body: I think one way is to find the date of the last comment for each conversation and then sort by that Conversation.objects.annotate(last_comment=Max('comment__submitted_date')) \ .order_by("last_comment")
type: Answer

http://stackoverflow.com/comment/81110370
has text: That is not a generator, that is a *list comprehension*
comment on: http://stackoverflow.com/q/47080479
type: QuestionComment
type: Comment
score: 4

http://stackoverflow.com/comment/81146060
type: AnswerComment
has text: i have tried this thank you but this returns the first instance of the least common number, im trying to make it return the last instance if there is say 2 numbers with the same lowest frequency
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47098115

http://stackoverflow.com/q/47183541
has title: low quality movie with avconv
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81327667
tagged with: python
has comment: http://stackoverflow.com/comment/81317390
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81316456
has comment: http://stackoverflow.com/comment/81317042
has comment: http://stackoverflow.com/comment/81316700
type: Question
tagged with: avconv
has body: I want to create a movie from a sequence of images. I used avconv (linux System in our Company has only avconv and not ffmpeg package). to do that first I creates 'fig%0d.png' Images and then by calling subprocess command I create a movie: subprocess.call('avconv -framerate 1 -f image2 -i fig%0d.png -c:v h264 -crf 1 Temp_electron1.mp4'.split()) but the Quality of the movie is not good and more importantly the movie doesn't Show the first Image and always starts from the second one. I appreciate any suggestion

http://stackoverflow.com/comment/81367972
comment on: http://stackoverflow.com/q/47208863
type: QuestionComment
score: 1
has text: Not sure why quit() does not close the instance, but you can possibly try a workaround by using os.system() to kill the chromedriver process
type: Comment

http://stackoverflow.com/q/47170119
has comment: http://stackoverflow.com/comment/81290859
score: 0
has comment: http://stackoverflow.com/comment/81290029
tagged with: python
has comment: http://stackoverflow.com/comment/81292251
has body: So I was just trying some random Django practicing, and after finishing I closed the server and command prompt and everything. Now when I go to open in again. when I run python manage.py runserver I get this error I don't know what to because everything worked fine before I closed the app, now nothing's opening.
type: Question
has comment: http://stackoverflow.com/comment/81290114
answer count: 0
has comment: http://stackoverflow.com/comment/81291105
type: UnansweredQuestion
has title: Django Python runserver not working after closing. ModuleNotFoundError
has comment: http://stackoverflow.com/comment/81292037

http://stackoverflow.com/comment/81351273
comment on: http://stackoverflow.com/q/47199759
has text: can you show how your are passing **kwargs to create_user?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47120680
answer count: 2
upvote count: 2
has title: Why can't the output of the network go through a softmax when using softmax_cross_entropy_with_logits?
downvote count: 0
linked to: http://stackoverflow.com/q/47034888
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/47120911
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: neural-network
possible better answer: http://stackoverflow.com/a/47120829
tagged with: python
has comment: http://stackoverflow.com/comment/81192956
has answer: http://stackoverflow.com/a/47120829
has body: I want to use the tensorflow built-in cross-entropy function. However, in the documentation, I'm reading Do not call this op with the output of softmax, as it will produce incorrect results. https://www.tensorflow.org/api_docs/python/tf/nn/softmax_cross_entropy_with_logits Like it is done often, I am using the softmax activation in my last output layer, however: result = tf.layers.dense(input=dropout, classes_num, tf.nn.softmax) Is it, therefore, incorrect to use this function, or is the documentation incorrect? I don't understand this, I would be thankful for a short explanation. (Which TensorFlow cost function would be correct to use for a softmax output layer then?)
has answer: http://stackoverflow.com/a/47120911
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/47216468
tagged with: pyqt
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/48082100
has comment: http://stackoverflow.com/comment/81411469
linked to: http://stackoverflow.com/q/22881888
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48082100
tagged with: qt
type: Question
has comment: http://stackoverflow.com/comment/81382502
has body: I am using pyqt and Python 3. I want to prevent a QGraphicsRectItem to cross the horizontal axis (y=0) in a QGraphicsScene when dragged with the mouse. I am using the following code (employing height() because the rectangle is in the upper half of the screen). See below a full example of the code. import sys from PyQt4.QtCore import Qt, QPointF from PyQt4.QtGui import QGraphicsRectItem, QGraphicsLineItem, QApplication, QGraphicsView, QGraphicsScene, QGraphicsItem class MyRect(QGraphicsRectItem): def __init__(self, w, h): super().__init__(0, 0, w, h) self.setFlag(QGraphicsItem.ItemIsMovable, True) self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.setFlag(QGraphicsItem.ItemIsFocusable, True) self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) def itemChange(self, change, value): if change == QGraphicsItem.ItemPositionChange: if self.y() + self.rect().height() &gt; 0: return QPointF(self.x(), -self.rect().height()) return value def main(): # Set up the framework. app = QApplication(sys.argv) gr_view = QGraphicsView() scene = QGraphicsScene() scene.setSceneRect(-100, -100, 200, 200) gr_view.setScene(scene) # Add an x-axis x_axis = QGraphicsLineItem(-100, 0, 100, 0) scene.addItem(x_axis) # Add the restrained rect. rect = MyRect(50, 50) rect.setPos(-25, -100) # &lt;--- not clear to me why I have to do this twice to get the rect.setPos(-25, -100) # item positioned. I know it has to do with my itemChanged above... scene.addItem(rect) gr_view.fitInView(0, 0, 200, 200, Qt.KeepAspectRatio) gr_view.show() sys.exit(app.exec_()) if __name__ == '__main__': main() In principle this is working, but when I keep dragging the mouse below the horizontal axis (y=0), the rectangle flickers and jumps back and forth between the mouse position and its restrained position in the upper hemiplane while dragging. So it looks like the drag first moves it to the mouse cursor, and only then the position is adjusted retroactively. I would like the adjustment to happen before the item is…
has comment: http://stackoverflow.com/comment/81411934
tagged with: python
has comment: http://stackoverflow.com/comment/81433066
score: 4
upvote count: 4
has title: Restraining a QGraphicsItem using itemChange()
tagged with: qgraphicsitem

http://stackoverflow.com/q/47119593
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81192197
tagged with: list
upvote count: 2
has answer: http://stackoverflow.com/a/47119647
downvote count: 0
has answer: http://stackoverflow.com/a/47119630
has comment: http://stackoverflow.com/comment/81189034
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47119649
has answer: http://stackoverflow.com/a/47119649
possible better answer: http://stackoverflow.com/a/47119612
has title: Lookup dictionary based on python key
has comment: http://stackoverflow.com/comment/81188900
tagged with: python
has answer: http://stackoverflow.com/a/47119612
has comment: http://stackoverflow.com/comment/81188901
tagged with: dictionary
answer count: 4
has body: I have a list of dictionaries in the format: mylist1 = [{'model': 'one'}, {'color': 'blue'}, {'age': 23}] Is there a way I can look up a dictionary based on its key? For something I want to do something like (pseudocode): mylist1['model'] #should return {'model': 'one'} The reason why I am not doing mylist[0]['model'] is because the list elements are not always in that order.
score: 2

http://stackoverflow.com/a/47314006
upvote count: 1
has comment: http://stackoverflow.com/comment/81623063
has body: 'conda install' command will resolve and install all dependencies automatically provided this was configured within the package. You can check package dependencies by running - conda info package_A=1.0.1=py36hafb9ca4_1 However, if you you install directly from tarballs there is no dependency check. To install local packages you can use the option "--use-local" conda install --use-local package_A=1.0.1=py36hafb9ca4_1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47185393
downvote count: 0

http://stackoverflow.com/q/47119450
answer count: 1
downvote count: 0
upvote count: 1
tagged with: django
score: 1
tagged with: variables
tagged with: string
type: AnsweredQuestion
tagged with: python
tagged with: image
favorite count: 0
type: Question
has title: Django passing variables into string
accepted answer: http://stackoverflow.com/a/47119465
has body: I'm trying to pass: &gt;img src="{% static '/static_dirs/images/itcg/01_{{ card_id }}.jpg' %}" alt="{{ card_id }}"&gt; to load image with file name 01_xx.jpg, but the result is just xx without image. Basically what happens is that {{ card_id }} works in alt but I can't load the image. I have tried to change 01_{{ card_id }}.jpg into 01_01.jpg and it works, so the static files can load properly but apparently 01_{{ card_id }}.jpg is not working as intended. I also tried to changing one of my image name from 01_01.jpg into 01.jpg and do the following: &gt;img src="{% static '/static_dirs/images/itcg/{{card_id}}.jpg' %}" alt="{{ card_id }}"&gt; The image still not loading, so I guess the problem is not in "01_" part either. Can someone help?
has answer: http://stackoverflow.com/a/47119465

http://stackoverflow.com/comment/89581773
type: AnswerComment
has text: Please try adding an explanation.
score: 1
comment on: http://stackoverflow.com/a/51302101
type: Comment

http://stackoverflow.com/comment/81162163
comment on: http://stackoverflow.com/a/47087118
score: 0
type: Comment
type: AnswerComment
has text: It's not a workaround but a necessary step in your algorithm. A better approach, I think, is to test every string character by character, without ever building a test string at all. I edited my solution to present this approach.

http://stackoverflow.com/comment/81388678
type: Comment
has text: They were not,will post a self answer in some time.thanks for your time.
type: QuestionComment
comment on: http://stackoverflow.com/q/47215744
score: 0

http://stackoverflow.com/a/47199620
has body: The basic idea of my solution is to create a column from a cumsum over non-zero values in order to get the zero values with the next non zero value into one group. Then you can use groupby + sum to get your the desired values. two_good = df.groupby((df['bad']!=0).cumsum().shift(1).fillna(0))['good'].sum() two_bad = df.groupby((df['good']!=0).cumsum().shift(1).fillna(0))['bad'].sum() two_good = two_good.loc[two_good!=0].reset_index(drop=True) two_bad = two_bad.loc[two_bad!=0].reset_index(drop=True) new_df = pd.concat([two_bad, two_good], axis=1).dropna() print(new_df) bad good 0 1 19.0 1 1 20.0 2 1 28.0 3 6 91.0 4 8 72.0 5 10 64.0 6 6 52.0 7 6 38.0 8 10 24.0 9 5 17.0 10 8 19.0 11 2 12.0 12 2 5.0 13 1 7.0 14 3 6.0 15 1 2.0 This code treats your etch case of trailing zeros different from your desired output, it simple cuts it off. You'd have to add some extra code to catch that one with a different logic.
score: 0
has comment: http://stackoverflow.com/comment/81348764
type: Answer
has comment: http://stackoverflow.com/comment/81348472
answers question: http://stackoverflow.com/q/47198514

http://stackoverflow.com/comment/81112072
score: 0
comment on: http://stackoverflow.com/q/47081439
has text: In a class, the first argument is the object itself, so when you're calling self.function(x), you're giving two arguments, self and x
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81384014
comment on: http://stackoverflow.com/a/47217226
type: Comment
has text: I think you cannot use `a.mul(b)`, because in pandas is not implemented multiple in lists. Need create 2d numpy array with lists and then here the `newaxis` index operator inserts a new `axis` into a, making it a two-dimensional `3x1 array`.
score: 0
type: AnswerComment

http://stackoverflow.com/q/47132864
tagged with: python
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/47133102
tagged with: django
has answer: http://stackoverflow.com/a/47133102
has title: Display specific table field (blog text) using Django
type: AnsweredQuestion
has body: Hopefully a simple one, but I can't find what's wrong myself. I have a simple blog app, and I can display the posts titles, in a weird format, but can't pull through the posts body/text - all I get is a blank row. /models.py from django.db import models from django.utils import timezone class Post(models.Model): title = models.CharField(max_length=200) body = models.TextField() pub_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title /views.py from django.shortcuts import render from .models import Post def index(request): posting = Post.objects.filter() context = { 'posting':posting, } return render(request, 'posts/index.html', context) /templates/posts/index.html {{posting}} {{posting.body}} test text The output to the page is similar to (apologies not exact due to html formatting, but note blank middle line) : QuerySet [Post: First Post>, Post: Second Post>, Post: Third Post>]> test text Thank you.
score: 0
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/a/47160853
accepted answer of: http://stackoverflow.com/q/47160822
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47160822
type: Answer
score: 2
upvote count: 2
has body: If what you have is a JSON string, load it into a list first: import json data = json.load(file) # or json.loads(json_str) Next, use a dict comp to convert your data to the form you want: data = [{'key' : 'key1', 'value' : 'value1'}, {'key' : 'key2', 'value' : 'value2'}] r = {d['key'] : d['value'] for d in data} r {'key1': 'value1', 'key2': 'value2'} Once done, you can just call json.dump and store it in a file. Obligatory disclaimer: Beware that dictionaries do not support duplicate keys (JSON strings do, iirc), so you might end up losing data if you have duplicate keys (the latter entry overwrites the former).

http://stackoverflow.com/q/47168683
upvote count: 1
has comment: http://stackoverflow.com/comment/81287423
tagged with: site-packages
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Missing 'utf' module
has answer: http://stackoverflow.com/a/47168783
has body: I am trying to install and use this Gmail library https://github.com/charlierguo/gmail I can successfully download and install the package using python3 setup.py install. However, when I go to import the module I receive the error Traceback (most recent call last): File "process.py", line 1, in &lt;module&gt; import gmail File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gmail-0.0.5-py3.6.egg/gmail/__init__.py", line 16, in &lt;module&gt; File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/gmail-0.0.5-py3.6.egg/gmail/gmail.py", line 5, in &lt;module&gt; ModuleNotFoundError: No module named 'utf' I inspect the site-packages folder and utf.py is there. I have reinstalled, changed names, and replaced this utf file, but it seems to be overlooked every time.
score: 1
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/81186995
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47118400
type: AnswerComment
has text: Hi Sandeep, thank you so much for your reply. I saved your code and ran it and got the issue you addressed in your first point. I was not getting that issue before. The code in the description of my main post has been updated with comments juanpa.arrivillaga made. It is returning the output with no system errors, but is not returning the correct numbers for the averages. I haven't learned the dictionary method yet, so I assume something with the way I wrote the initial code isn't agreeing with it?

http://stackoverflow.com/q/47128265
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I have been trying to access a specific row and column using indexes and I am not able to. I want to be able to give it two int's to say what row and column I am trying to return I am trying to find the max of a column and then in that row return a string in a different column but same row. I have already been able to calculate the max but I do not know how to access a row and column individually. I am not able to use pandas unfortunately '''Return the station ID of the station that has the most bikes available. If there is a tie for the most available, return the station ID that appears first in stations. Precondition: len(stations) &gt; 0 &gt;&gt;&gt; get_station_with_max_bikes(SAMPLE_STATIONS) 7088 ''' with open("stations.csv") as f: a1 = [row["num_bikes_available"] for row in DictReader(f)] max_index = a1.index(max(a1))
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81206616
answer count: 1
has title: how to specify a column and row to acess csv file Python
has comment: http://stackoverflow.com/comment/81206636
accepted answer: http://stackoverflow.com/a/47128311
type: Question
has answer: http://stackoverflow.com/a/47128311

http://stackoverflow.com/a/47219826
score: 3
type: Answer
has body: You can just do cart_ref = db.collection('carts').document(user_id).collection('books').document(book_id).set(cart); You can still store in sub collections even if the above collections don't exist anymore/yet.
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47217361

http://stackoverflow.com/a/61637761
downvote count: 0
upvote count: 1
has body: For me the process was timing out, had to change the default timeout
has comment: http://stackoverflow.com/comment/134520453
type: Answer
answers question: http://stackoverflow.com/q/47154856
has comment: http://stackoverflow.com/comment/120043224
score: 1

http://stackoverflow.com/comment/81095299
has text: what do u mean by symbols? Any character in unicode ? or just from ascii ?
comment on: http://stackoverflow.com/q/47073453
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81191820
comment on: http://stackoverflow.com/a/47117135
type: Comment
has text: Thanks for your answer : the problem is I just want to filter based on the result (append part) and do another filters . Recreate the queryset at each step is heavy
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81164308
type: Comment
type: QuestionComment
has text: Note that I've resolved this by using the namedtuple `_asdict` method, so that I'm *explicitly* returning dictionaries, but I am interested in whether this is version skew (it doesn't seem to correlate to flask 0.11.1 vs 0.12.2, for example) or something else.
score: 0
comment on: http://stackoverflow.com/q/47106862

http://stackoverflow.com/comment/81375283
type: AnswerComment
comment on: http://stackoverflow.com/a/47193790
type: Comment
has text: @jing Instance of a class.
score: 0

http://stackoverflow.com/comment/81128339
comment on: http://stackoverflow.com/a/47088892
type: AnswerComment
has text: This is similar to what I had in my question (which worked), but the above didn't (but looks like it should). Keep getting that same value error.
score: 0
type: Comment

http://stackoverflow.com/comment/81191696
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47121021
has text: `name` inside the function is local, it's the parameter. It's **not** the global `name`. I'd advise reading https://nedbatchelder.com/text/names.html to get a better idea of how scopes and identifiers work.
score: 2

attention-model
tags question: http://stackoverflow.com/q/47196299
tag name: attention-model
type: Tag

python-packaging
type: Tag
tags question: http://stackoverflow.com/q/47066676
tags question: http://stackoverflow.com/q/47125132
tag name: python-packaging

http://stackoverflow.com/q/47115436
has comment: http://stackoverflow.com/comment/81187751
tagged with: pysqlite
tagged with: python
type: AnsweredQuestion
score: 0
has body: I have following code to select rows from a SQLite database: #!/usr/bin/python3.4 # -*- coding: utf-8 -*- import sqlite3 as lite import sys csat = lite.connect('Tanuloim.db') with csat: hely = csat.cursor() for evflym in range (5, 6): hely.execute('select count() from tanulo where evf=? and tannyelv="Sr"', (evflym,)) xlegnagySr = (hely.fetchone()[0]) hely.execute('select count() from tanulo where evf=? and tannyelv="Hu"', (evflym,)) xlegnagyHu = (hely.fetchone()[0]) hely.execute('select count() from munkadbnevsora where evf=?', (evflym,)) ylegnagy = (hely.fetchone()[0]) print ('Ennyi magyar ötödikes tanuló van - xlegnagyHu:', xlegnagyHu) print ('Ennyi szerb ötödikes tanuló van - xlegnagySr:', xlegnagySr) print ('Ennyi munkadarab van az ötödikben - ylegnagy:', ylegnagy) print ('evfolyam:', evflym) hely.execute('select tanuloneve from tanulo where evf=? and tannyelv="Sr"', (evflym,)) """" This is returned as a tuple, let it named tuple1. """ for x in range (0, xlegnagySr): print (hely.fetchone()[0]) hely.execute('select munkdbnevesr from munkadbnevsora where evf=?', (evflym,)') """" This is returned as a tuple, let it named tuple2. """ for y in range (0, ylegnagy): print (hely.fetchone()[0]) Example for tuple1: [('tanulo1',), ('tanulo2',), ('tanulo3',), ... ('tanulo19',)] where the number of 19 in tanulo19 indicate that that xlegnagySr=19. Example for tuple2: [('munkdbnevesr1',), ('munkdbnevesr2',), ('munkdbnevesr3',),... ('munkdbnevesr13',)] where 13 indicate that that ylegnagy=13. The desired result should look like this: thirdtable = [('tanulo1','munkadbnevesr1'),('tanulo1','munkadbnevesr2'),.‌​..('tanulo1','munkad‌​bnevesr13'),('tanulo‌​2','munkadbnevesr1')‌​,('tanulo2','munkadb‌​nevesr2'),...,('tanu‌​lo2','munkadbnevesr1‌​3'), ...,('tanulo19','munkadbnevesr13')] where numbers 19 and 13 indicates that that xlegnagySr=19 and ylegnagy=13. So what I want is this: to insert into third database table some combined values from tuple1 and tuple2. I think the way for this…
tagged with: sqlite
answer count: 1
has comment: http://stackoverflow.com/comment/81214567
accepted answer: http://stackoverflow.com/a/47134148
has title: How to store selected rows into tuple?
type: Question
has answer: http://stackoverflow.com/a/47134148

http://stackoverflow.com/comment/81279501
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47164950
has text: Yeah, use `rolling.apply`.

http://stackoverflow.com/a/47202258
has body: of course: list1.append=tuple(line.values()) here you're trying to redefine the append method of list as a tuple. Fortunately for you, list members are protected against redefinition, which explains the error. This is a typo: you should have done: list1.append(tuple(line.values())) better: get rid of the loop and read list1 in one go using list comprehension: with open('cidades.csv', 'r') as f: list1 = [tuple(line.values()) for line in csv.DictReader(f)] but this approach still makes me dubious: reading the values loses infomation about the order (unless you're using Python 3.6 which uses OrderedDict for csv to fix this issue). I would drop DictReader and rely on the order of your csv using csv.reader, like this: with open('cidades.csv', 'r') as f: reader = csv.reader(f) next(reader) # skip the title line we don't need it list1 = [tuple(line) for line in reader]
answers question: http://stackoverflow.com/q/47202120
type: Answer
has comment: http://stackoverflow.com/comment/81367109
score: 0
accepted answer of: http://stackoverflow.com/q/47202120
type: AcceptedAnswer

http://stackoverflow.com/q/47126121
has answer: http://stackoverflow.com/a/47136804
upvote count: 2
tagged with: neural-network
tagged with: python
accepted answer: http://stackoverflow.com/a/47136804
has body: I'm trying to understand/run the code in Michael Neilsen's Neural Networks and Deep Learning chapter 2, on backpropagation: http://neuralnetworksanddeeplearning.com/chap2.html#the_code_for_backpropagation. At the start of the backward pass, it has: delta = self.cost_derivative(activations[-1], y) * \ sigmoid_prime(zs[-1]) nabla_b[-1] = delta nabla_w[-1] = np.dot(delta, activations[-2].transpose()) The forward pass creates the activations list, where activations[i] contains a vector of the activations of the neurons in layer i. So activations[-1] is the last layer. y is the desired output. cost_derivative is defined as: def cost_derivative(self, output_activations, y): """Return the vector of partial derivatives \partial C_x / \partial a for the output activations.""" return (output_activations-y) So that first line outputs a vector with the same shape as our output layer. So my question is how is that np.dot on the 4th line supposed to work? My understanding is that activations[-2] is a vector of the activations of the neurons in the 2nd-to-last layer, which can have any number of neurons, so I'm not sure how we can dot product it (or its transpose) with the delta, which has the shape of the output layer. I ran the code (https://github.com/mnielsen/neural-networks-and-deep-learning/blob/master/src/network.py) with some added debug lines to try to understand this, and it doesn't seem to work: &gt;&gt;&gt; from network import *; net = Network([2,1,2]) &gt;&gt;&gt; net.backprop([1,2], [3,4]) Activations[0] [1, 2] Activations[1] [[ 0.33579893]] Activations[2] [[ 0.37944698] [ 0.45005939]] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;snip&gt;/neural-networks-and-deep-learning/src/network.py", line 117, in backprop nabla_w[-1] = np.dot(delta, activations[-2].transpose()) ValueError: shapes (2,2) and (1,1) not aligned: 2 (dim 1) != 1 (dim 0) activations looks exactly as I'd expect - 2 activations, then 1, then 2. The failure …
has title: Understanding Michael Nielsen's backpropagation code
score: 2
type: AnsweredQuestion
tagged with: backpropagation
downvote count: 0
answer count: 1
tagged with: machine-learning
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/a/47116048
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47116015
has body: I'm assuming you don't mean an infinite list of numbers, that wouldn't fit into memory, but rather, an list of any possible size. Well, you always know the last position of a list in Python. It will always be the length of the list minus one: my_list[len(my_list) - 1] Python list objects also handily support negative indexing, so the above could be shortened to: my_list[-1] So to swap the first and last elements, simply do: my_list[0], my_list[-1] = my_list[-1], my_list[0] Note, the above is a nice little feature of python, often in languages you are forced to swap elements using a temporary variable: temp = my_list[0] my_list[0] = my_list[-1] my_list[-1] = temp
upvote count: 3
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/47116015

http://stackoverflow.com/a/70860726
answers question: http://stackoverflow.com/q/47164950
downvote count: 0
score: 1
type: Answer
has body: This can be solved in a single line of code. Given that s is the input series and wlen is the window length: zscore = s.sub(s.rolling(wlen).mean()).div(s.rolling(wlen).std()) If you need to shift the mean and std it can still be done: zscore = s.sub(s.rolling(wlen).mean().shift()).div(s.rolling(wlen).std().shift())
upvote count: 1

http://stackoverflow.com/q/47072627
tagged with: python
has answer: http://stackoverflow.com/a/47072777
tagged with: regex
type: AnsweredQuestion
score: 0
has title: How can I find the new match position converting an Unicode String to a Byte String?
answer count: 1
tagged with: pattern-matching
tagged with: python-3.x
type: Question
has body: I know I can convert an UnicodeString to a ByteString and vice versa using these commands: UnicodeStr = ByteStr.decode(encoding='UTF-8') ByteStr = UnicodeStr.encode(encoding='UTF-8') UTF-8 is multibyte character encoding. Characters can have 1 to 4 bytes, the position of a match changes converting from UnicodeStr to ByteStr. This is not a big problem using english text characters but it is using characters in the French, German, Spanish or Dutch language. p.e.: UnicodeStr = "Ça te changera les idées John!" (=That’ll take your mind off things John!) The match position of the word "idées" is: p=re.compile("idées") for m in p.finditer(UnicodeStr): print(m.span()) --> (19, 24) How can I find the new match position converting a UnicodeStr to ByteStr?
accepted answer: http://stackoverflow.com/a/47072777

http://stackoverflow.com/q/47121741
tagged with: pandas
answer count: 0
upvote count: 1
has body: I am trying to iteratively load a batch of images from a folder, process, then store the results of the batch to an hdf file. What's the best practice for batch reading images/files, and batch storing a resulting multi-dimensional array? First Part I start with a csv list of file names: file_list = [''.join(x) + '.png' for x in permutations('abcde')][:100] Say for example I want to process 5 images at a time. I currently grab 5 file names from the list, create an empty array to hold 5 images, then read each image one at a time to yield a batch. def load_images(file_list): for i in range(0, 100, 5): files_list = file_list[i, i + 5] image_list = np.zeros(shape=(5, 50, 50, 3)) for idx, file in enumerate(files_list): loaded_img = np.random.random((50, 50, 3)) # misc.imread(file) image_list[idx] = loaded_img yield image_list, files_list Question 1: Is there a way to eliminate the second for loop? Can I batch read in the images, or is the method above (one at a time) best practice? Second Part: After loading the images I do some processing on them. This results in a different size array def process_images(image_batch): result = image_batch[:, 5, 4, 3] # a novel down-sampling algorithm return result Now, I want to store the batch of images with their original file names. def store_images(data, file_names): with pd.HDFstore('output.h5') as hdf: pass Question 2: What is the best way to store a batch of multidimensional numpy arrays, while still referencing them with a key (such as the original file name)? I would like to explore using .h5 files, so if anyone knows how to batch process data to an .h5 and has advice on this, it would be most appreciated. Alternatively I think there is a way to save the numpy arrays as just .npy files to a folder, but I was having trouble with this and still wouldn't know how to do it other than one sample at a time (versus one batch at a time)
tagged with: batch-processing
tagged with: hdfs
has title: Batch processing: read image files, then write multidimensional numpy array to HDFS
favorite count: 0
type: Question
type: UnansweredQuestion
score: 1
tagged with: python
tagged with: numpy
has comment: http://stackoverflow.com/comment/131452988
downvote count: 0

http://stackoverflow.com/comment/81294976
comment on: http://stackoverflow.com/q/47168312
score: 0
has text: The reason I don't reshape prior to sorting is that it doesn't work. If I index a 500000x2 array with the result of argsorting that same array, it returns a 500000x2x2 array. The reason my array is 1000x500x2x2 in the first place is because it's more natural to express it that way. Basically, my goal is to obtain a vector field of 1000x500 vectors, made up by the eigenvectors associated with the smallest eigenvalue of the first array.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47208076
score: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47207032
has body: schema_name = 'my_schema' table_name = 'my_table' cur.execute(sql.SQL('SELECT col1, col2 FROM {}.{}').format( sql.Identifier(schema_name), sql.Identifier(table_name) ) ) or just table_name = 'my_table' cur.execute(sql.SQL('SELECT col1, col2 FROM my_schema.{}').format( sql.Identifier(table_name) ) )
accepted answer of: http://stackoverflow.com/q/47207032
upvote count: 2
has comment: http://stackoverflow.com/comment/81371890
downvote count: 0
type: Answer

http://stackoverflow.com/comment/81213165
has text: try `sudo -H pip3 install discord.py`
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47131857
type: QuestionComment

http://stackoverflow.com/comment/81318271
has text: you can implement `__str__` for your `Animal` object to return name. Then you can use it like: `print john.dog`. But in general what's you have implemented is ok. Probably you can make a class like `Nameble` or whatever where you have constructor with name + getter. Your objects just should extend from it.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47184192

documentation
tags question: http://stackoverflow.com/q/47111403
tag name: documentation
type: Tag

http://stackoverflow.com/comment/81327859
score: 0
type: QuestionComment
has text: @MichaelButscher - How do I fix it?
comment on: http://stackoverflow.com/q/47186213
type: Comment

http://stackoverflow.com/a/47217986
has comment: http://stackoverflow.com/comment/81393264
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/81386058
has comment: http://stackoverflow.com/comment/81386271
has comment: http://stackoverflow.com/comment/81385960
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81393038
has comment: http://stackoverflow.com/comment/81386676
has body: You can look at my answer here to know the proper usage of LabelEncoder for multiple columns:- Why does sklearn preprocessing LabelEncoder inverse_transform apply from only one column? The explanation is that LabelEncoder only supports single dimension as input. So for each column, you need to have a different labelEncoder object which can then be used to inverse transform that particular column only. You can use a dictionary of labelencoder objects for convertig multiple columns. Something like this: labelencoder_dict = {} for col in b.columns: labelEncoder = preprocessing.LabelEncoder() b[col] = labelEncoder.fit_transform(b[col]) labelencoder_dict[col]=labelEncoder While decoding, you can just use: for col in b.columns: b[col] = labelencoder_dict[col].inverse_transform(b[col]) Update:- Now that you have added the column which you are using as y, here's how you can decode it (assuming you have added the 'Predicted_Values' column to the dataframe): for col in b.columns: # Skip the predicted column here if col != 'Predicted_valu‌​es': b[col] = labelencoder_dict[col].inverse_transform(b[col]) # Use the original `y (Activity_Profile)` encoder on predicted data b['Predicted_valu‌​es'] = labelencoder_dict['Activity_Profile'].inverse_transfo‌​rm( b['Predicted_valu‌​es'])
has comment: http://stackoverflow.com/comment/81386775
has comment: http://stackoverflow.com/comment/81387140
has comment: http://stackoverflow.com/comment/81391549
has comment: http://stackoverflow.com/comment/81385701
has comment: http://stackoverflow.com/comment/81386447
has comment: http://stackoverflow.com/comment/81386563
accepted answer of: http://stackoverflow.com/q/47217821
type: Answer
has comment: http://stackoverflow.com/comment/81392994
answers question: http://stackoverflow.com/q/47217821
has comment: http://stackoverflow.com/comment/81385775

http://stackoverflow.com/comment/81164918
has text: @PM2Ring Done! And also convert to lowercase the whole input string in order to avoid converting it each time. Thank you!
comment on: http://stackoverflow.com/a/47107216
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47179464
type: Question
has comment: http://stackoverflow.com/comment/81308153
has body: I have a program using OpenCV 2 to do marker detection in an image (written in C, with a Python 2 ctypes wrapper), and I'm trying to get the output from a Raspberry Pi camera into that code. Essentially, I have a 2D numpy array image with the greyscale image data in (from cv2.imdecode); I then do this to get an empty IplImage: ipl_image = cv2.cv.CreateImageHeader((image.shape[1], image.shape[0]), cv2.cv.IPL_DEPTH_8U, 1) and then assign the actual image data to the IplImage like this: cv2.cv.SetData(ipl_image, image.tobytes(), image.dtype.itemsize * image.shape[1]) If I then call the image-analysing function (find_markers_fp), I get a segfault – through much printf debugging, I found out that the IplImage-&gt;imageData is 0, when it should be a pointer to the image data, despite the fact that I called SetData. This causes the C program to try to do a null pointer dereference, hence the segfault. Somehow, I figured out that calling ipl_image.tostring() before I call find_markers_fp will make it work, but this function isn't documented anywhere in the OpenCV 2.4 documentation, only in the version 2.1 documentation. I don't do anything with the result of the function, I just call it, and the C program starts returning valid results rather than segfaulting. Why does calling this function make the IplImage usable, or more importantly, how can I avoid using this undocumented function?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81311349
tagged with: python
tagged with: opencv
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/81311585
answer count: 0
has title: Why does OpenCV's SetData not actually set the image data?
tagged with: raspberry-pi3

http://stackoverflow.com/comment/81283368
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47164951
score: 0
has text: At this point, I don't think I've gotten that far? I get that error when starting the server. I have tried client side just to see if I can still connect, and I can, just not over ssl.

http://stackoverflow.com/q/47186213
has body: In my first attempt, I tried, failed, learned, and came back with the following attempt. I have a text file with the names parsed with commas that looks like this: Ann Marie,Smith,ams@companyname.com The list could have over 100+ names in it. I left out the code that generates all the other GUI components to focus on loading the combobox and the items. I'm trying to read a text and load the data into a combobox without blocking the main thread. I consulted a textbook and Pythons documentation, and this is what I came up with. Question: In my def read_employees(self,read_file): I return a list of the data I read. I'm aware that list isn't thread-safe, is it okay in the way i used it here? Same goes for the setting of the combobox in def textfilemanage(self): I set the combobox in that method by doing, self.combo = wx.ComboBox(self.panel, choices=data). Is that okay? import wx import concurrent.futures class Mywin(wx.Frame): def __init__(self, parent, title): super(Mywin, self).__init__(parent, title=title, size=(300, 200)) self.panel = wx.Panel(self) box = wx.BoxSizer(wx.VERTICAL) self.textfilemanage() self.label = wx.StaticText(self.panel, label="Your choice:", style=wx.ALIGN_CENTRE) box.Add(self.label, 0, wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 20) cblbl = wx.StaticText(self.panel, label="Combo box", style=wx.ALIGN_CENTRE) box.Add(cblbl, 0, wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 5) box.Add(self.combo, 1, wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 5) chlbl = wx.StaticText(self.panel, label="Choice control", style=wx.ALIGN_CENTRE) box.AddStretchSpacer() self.combo.Bind(wx.EVT_COMBOBOX, self.OnCombo) self.panel.SetSizer(box) self.Centre() self.Show() def read_employees(self,read_file): emp_list = [] with open(read_file) as f_obj: for line in f_obj: emp_list.append(line) return emp_list def textfilemanage(self): filename = 'employees.txt' with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: future_to_read = {executor.submit(se…
has answer: http://stackoverflow.com/a/47191608
has comment: http://stackoverflow.com/comment/81327859
type: Question
tagged with: python-multithreading
has comment: http://stackoverflow.com/comment/81332569
tagged with: python
has comment: http://stackoverflow.com/comment/81321636
linked to: http://stackoverflow.com/q/47184177
linked to: http://stackoverflow.com/q/54282226
tagged with: threadpool
tagged with: python-3.x
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/47290677
has title: Reading a File without block main thead in GUI
tagged with: wxpython
accepted answer: http://stackoverflow.com/a/47191608
answer count: 1

http://stackoverflow.com/comment/81182344
comment on: http://stackoverflow.com/q/47116080
type: QuestionComment
has text: Well that's idea, but you can't just write `x(i+1)` and `x(i)` obviously. One more time: You need to save the previous value, in a variable.
score: 0
type: Comment

http://stackoverflow.com/comment/81327455
type: AnswerComment
comment on: http://stackoverflow.com/a/47188957
score: 0
type: Comment
has text: +1 I agree, although this is not exactly what the OP wanted, I think its clearer and/or more Pythonic...

http://stackoverflow.com/comment/81108246
score: 0
has text: Thanks for this - I'll try it now! What are these parts for: '------'?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47079482

http://stackoverflow.com/comment/122282645
has text: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask).
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/69185815
score: 1

http://stackoverflow.com/q/47217718
has comment: http://stackoverflow.com/comment/81387161
tagged with: selenium
has comment: http://stackoverflow.com/comment/81389256
favorite count: 0
type: Question
has title: Python+selenium+firefox NTLM authentication with pop(alert) window issue
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82200974
has comment: http://stackoverflow.com/comment/81504043
type: UnansweredQuestion
tagged with: python
score: 4
upvote count: 4
tagged with: selenium-webdriver
has body: I've already tried three ways, and only the first way can work. Add user information in front of url, and this is the only way success. url_address = "http://username:passwd@abc.cde.com/" browser = webdriver.Firefox() browser.get(url_address) 2.Second way is use .switch_to_alert() to switch to pop window and use send_keys() to key in user information, it work just fine until send_key(Keys.TAB) have used; It will TAB the input maker into password field but when send_key("password") line, It jumps back to username field and then key in password! I have make a Demo gif link below. browser = webdriver.Firefox() browser.get(url_address) WebDriverWait(browser,10).until(EC.alert_is_present(),"wait for alert pop out") alert_window=browser.switch_to_alert() alert_window.send_keys("username") time.sleep(5) alert_window.send_keys(Keys.TAB) time.sleep(5) alert_windows.send_keys("passwd") time.sleep is in order to know if TAB really work or not. Same result if it removed Update 11/14 change send_keys to one line and it work as expect Like this alert_window.send_keys("username"+Keys.TAB+"passwd") 3.Third way is use alert_window.authenticate()but it return selenium.common.exceptions.WebDriverException: Message: POST /session/c7411dfa-5a0e-41e3-b8b3-e8f7d9dc9843/alert/credentials did not match a known command Any idea to fix issue on 2 and 3 ? tool list : python 3.6.2 selenium firefox 54.0.1 (32 bit)
has comment: http://stackoverflow.com/comment/81391199
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/81381347
type: AnswerComment
comment on: http://stackoverflow.com/a/47212410
has text: Thank you, that helped me get to a solution that worked perfectly.
type: Comment
score: 0

http://stackoverflow.com/comment/81112017
has text: Thanks for the clarification. Regarding the other patterns, my understanding is those strings are also being searched for. It works during searches, just doesn't work when I try including it with the others. I just need that line skipped if it ends in anything with an A or B and any number of digits at the end of the line (or in some cases with an additional rc); each of these are separated by underscores.
type: AnswerComment
comment on: http://stackoverflow.com/a/47080417
score: 0
type: Comment

http://stackoverflow.com/comment/81391704
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47221030
has text: so the list in this case is a list of all the filepaths/names.txt? it then compares every file with each other and puts all the duplicate ID's in a new file?
type: Comment

http://stackoverflow.com/q/47112249
tagged with: python
score: -1
tagged with: twitter
has comment: http://stackoverflow.com/comment/81174500
favorite count: 0
has answer: http://stackoverflow.com/a/47112342
type: Question
has comment: http://stackoverflow.com/comment/81174634
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81184161
has comment: http://stackoverflow.com/comment/81174661
has comment: http://stackoverflow.com/comment/81181468
has title: Cleaning out tweet json file using python
has body: I have twitter json file and want to extract specific info from here. Example of this json file can be found here, https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/intro-to-tweet-json { "created_at": "Thu Apr 06 15:24:15 +0000 2017", "id_str": "850006245121695744", "text": "1\/ Today we\u2019re sharing our vision for the future of the Twitter API platform!\nhttps:\/\/t.co\/XweGngmxlP", "user": { "id": 2244994945, "name": "Twitter Dev", "screen_name": "TwitterDev", "location": "Internet", "url": "https:\/\/dev.twitter.com\/", "description": "Your official source for Twitter Platform news, updates &amp; events. Need technical help? Visit https:\/\/twittercommunity.com\/ \u2328\ufe0f #TapIntoTwitter" }, "place": { }, "entities": { "hashtags": [ ], "urls": [ { "url": "https:\/\/t.co\/XweGngmxlP", "unwound": { "url": "https:\/\/cards.twitter.com\/cards\/18ce53wgo4h\/3xo1c", "title": "Building the Future of the Twitter API Platform" } } ], "user_mentions": [ ] } } I tried to remove some item that I don't need, like id_str. So I created a list that holds the name of keys I need, and iterate this json file(one file has more than a million tweets). I already searched similar questions and tried to implement what replies suggest. tags = ["created_at", "text", "retweet_count", "friends_count","followers_count","verified","place"] for line in json_file: try: data = json.loads(line) for i in data.keys(): if i not in tags: try: del data[i] except: continue except: continue for line in json_file: data = json.loads(line) print(data) However, my json_file is empty, it does not print out anything at the final. Instead of del data[i] I tried multiple different ways like del data[str(i)] data.pop(i) Thanks in advance!
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 1

http://stackoverflow.com/q/47119868
has answer: http://stackoverflow.com/a/47119960
has comment: http://stackoverflow.com/comment/81190072
has comment: http://stackoverflow.com/comment/81189952
has comment: http://stackoverflow.com/comment/81189780
tagged with: email
score: -1
type: Question
tagged with: python-3.x
has body: I am trying to send my exact error message via email however it does not seem to be sending anything. I have removed try blocks but no errors are displayed. I have tried the following: try: #Value here except OSError as e: traceback.print_exc() sender = "h####@gmail.com" receiver = ["a#####.com"] message = traceback.print_exc() try: session = smtplib.SMTP('smtp.gmail.com', 587) session.ehlo() session.starttls() session.ehlo() session.login(sender,'dadwadwa') session.sendmail(sender,receiver,message) session.quit() except smtplib.SMTPException as e: print(e)
has comment: http://stackoverflow.com/comment/81189892
has comment: http://stackoverflow.com/comment/81189589
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/81189807
answer count: 1
tagged with: error-handling
upvote count: 1
tagged with: python
has title: Email an error message with Python [Username and Password not accepted]
favorite count: 0

http://stackoverflow.com/comment/81324348
type: AnswerComment
has text: Well, `45.74` and `46` are both closest to `46.81`. Totally expected and valid result, no?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47186814

http://stackoverflow.com/comment/81377390
score: 0
has text: @pstatix I have just added it to the main post, thanks in advance
comment on: http://stackoverflow.com/q/47213823
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47079795
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81108586
has comment: http://stackoverflow.com/comment/81108924
has comment: http://stackoverflow.com/comment/81110047
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47079717
has comment: http://stackoverflow.com/comment/81108642
has body: use pd.cut() method: In [92]: bins = np.arange(0, df['wordcount'].max().round(-2) + 100, 100) In [94]: df.groupby(pd.cut(df['wordcount'], bins=bins, labels=bins[1:]))['Stats'].mean() Out[94]: wordcount 100 148765.0 200 18765.0 300 788765.0 400 12765.0 500 120349.5 600 NaN 700 NaN 800 NaN 900 10916.0 Name: Stats, dtype: float64
answers question: http://stackoverflow.com/q/47079717
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/81108619

http://stackoverflow.com/q/47163365
tagged with: restart
answer count: 0
has comment: http://stackoverflow.com/comment/81277654
has comment: http://stackoverflow.com/comment/81276718
has comment: http://stackoverflow.com/comment/81277176
type: Question
has title: Python restart program not working
has comment: http://stackoverflow.com/comment/81276885
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81276662
tagged with: python-2.7
has body: When creating a GUI using tkinter in python 2.7, i want the program to restart. It seemed simple enough, and after a short amoun of research I came upon the following code, which seemed to work: python = sys.executable os.execl(python, python, * sys.argv) however, it has just stopped working, as in, the program runs perfectly the first time around, but then when restarting it says: =============================== RESTART: Shell ============================== .>>> and nothing happens. If anyone knows any reason why i would be very appreciative, and any solutions to this problem would be a tremendous help. UPDATE: I tried running it in command line, however, the same issue occured however this time it said, "no such file or directory" when restarting, any ideas why?
score: 0

http://stackoverflow.com/comment/81260059
has text: cmd.exe is the name of Window's cmd. Use another name ...
type: QuestionComment
comment on: http://stackoverflow.com/q/47154508
score: 0
type: Comment

http://stackoverflow.com/a/47137170
has body: Yes, there is tf.train.StopAtStepHook: This hook requests stop after either a number of steps have been executed or a last step has been reached. Only one of the two options can be specified. You can also extend it and implement your own stopping strategy based on the step results. class MyHook(session_run_hook.SessionRunHook): ... def after_run(self, run_context, run_values): if condition: run_context.request_stop()
has comment: http://stackoverflow.com/comment/84714866
downvote count: 0
answers question: http://stackoverflow.com/q/47137061
has comment: http://stackoverflow.com/comment/81225388
type: Answer
has comment: http://stackoverflow.com/comment/81230148
score: 2
upvote count: 2

http://stackoverflow.com/q/47161939
upvote count: 5
tagged with: dataframe
tagged with: python
has title: How can I use a custom function within an expression using the eval dataframe method?
has body: I am using Python 3.X. With the builtin function eval() you can use a dictionaty of objects in order to use a custom function like this: from math import * def one(): # some operations return 1 functions = { '__builtins__': None, 'sqrt': sqrt, 'one': one, } variables = { '__builtins__': None, 'pi': pi, } expression = 'sqrt(34 * pi) + one()' eval(expression, variables, functions) But the eval() dataframe method does not work like that. You can only use these built-in functions: The supported math functions are sin, cos, exp, log, expm1, log1p, sqrt, sinh, cosh, tanh, arcsin, arccos, arctan, arccosh, arcsinh, arctanh, abs and arctan2 import pandas as pd import numpy as np from math import * df = pd.DataFrame({ 'A': [0, 10, 0, 10, 10, 30], 'B': [0, 0, 1000, 1000, 0, 0], 'C': [25, 25, 25, 25, 40, 40] }) def custom(): # some operations return 3 functions = { 'custom': custom } variables = { 'pi': pi } equation = 'D = sqrt(A) + B + custom()' df.eval( equation, global_dict=variables, local_dict=functions, engine='numexpr', inplace=True ) # ERROR: "custom" is not a supported function Is there a way to use a custom function in the expression? NOTE: I know it could bedangerous, but it is on me
type: AnsweredQuestion
score: 5
linked to: http://stackoverflow.com/q/47163401
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47162025
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47162025
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: eval

http://stackoverflow.com/comment/81287928
type: AnswerComment
comment on: http://stackoverflow.com/a/47168896
has text: I’ll check it as soon as I can.
type: Comment
score: 0

http://stackoverflow.com/q/47196917
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47197420
score: 0
has answer: http://stackoverflow.com/a/58343259
answer count: 3
has title: python bisection search exercise
accepted answer: http://stackoverflow.com/a/47197041
type: Question
has comment: http://stackoverflow.com/comment/81342795
tagged with: bisection
has body: I have been looking at it for a while and I cannot see what is wrong with my bisection search. If I run it, it says 'RecursionError: maximum recursion depth exceeded in comparison'. Could anybody have a look and see what is wrong below? Thank you! #Write a function called in_bisect #that takes a sorted list and a target value #and returns the index #of the value in the list if it’s there def in_bisect(t, word): if len(t) == 0: return False middle = len(t) // 2 if t[middle] == word: return middle elif t[middle] &gt; word: return in_bisect(t[:middle], word) else: return in_bisect(t[middle:], word) if __name__ == "__main__": fruits = ['apple', 'banana', 'kiwi', 'peach', 'watermelon'] in_bisect(fruits, 'banana') in_bisect(fruits, 'ewf')
tagged with: python
has comment: http://stackoverflow.com/comment/81342974
possible better answer: http://stackoverflow.com/a/47197420
has answer: http://stackoverflow.com/a/47197041

http://stackoverflow.com/comment/81249517
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47149509
type: Comment
has text: How are you suggesting this with shutil.move? The code does not append dir to filename,

http://stackoverflow.com/q/47215744
has body: I am trying to load some images,but when i try to do so, i get this error the code looks like this: color_me = [] for filename in os.listdir('/home/decentmakeover2/Coloring-greyscale-images-in-Keras/floydhub/Test/'): color_me.append(img_to_array(load_img('/home/decentmakeover2/Coloring- greyscale-images-in-Keras/floydhub/Test/'+filename))) color_me = np.array(color_me, dtype=float) color_me = rgb2lab(1.0/255*color_me)[:,:,:,0] color_me = color_me.reshape(color_me.shape+(1,)) but i get this error: ValueError Traceback (most recent call last) &lt;ipython-input-1-0650ed3793a3&gt; in &lt;module&gt;() 77 for filename in os.listdir('/home/decentmakeover2/Coloring- greyscale-images-in-Keras/floydhub/Test/'): 78 color_me.append(img_to_array(load_img('/home/decentmakeover2/Coloring-greyscale-images-in-Keras/floydhub/Test/'+filename))) ---&gt; 79 color_me = np.array(color_me, dtype=float) 80 color_me = rgb2lab(1.0/255*color_me)[:,:,:,0] 81 color_me = color_me.reshape(color_me.shape+(1,)) ValueError: setting an array element with a sequence. The color_me list has 2 images,any suggestions on what may be wrong? Thanks in advance.
answer count: 0
has comment: http://stackoverflow.com/comment/81388678
has title: image list giving, ValueError: setting an array element with a sequence
tagged with: keras
has comment: http://stackoverflow.com/comment/81387181
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81382715
has comment: http://stackoverflow.com/comment/81382486
tagged with: python
tagged with: numpy
has comment: http://stackoverflow.com/comment/81381427
score: 0

natural-logarithm
type: Tag
tag name: natural-logarithm
tags question: http://stackoverflow.com/q/47167490

http://stackoverflow.com/q/47110006
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81170392
has answer: http://stackoverflow.com/a/47110038
possible better answer: http://stackoverflow.com/a/47110038
has comment: http://stackoverflow.com/comment/81172039
has comment: http://stackoverflow.com/comment/81173015
tagged with: python
score: -1
has body: I am finding it increasingly difficult to find the letters from a word that the user generated. The code I am using is on linear searches and can only display letters I have inputed. Edit: To improve my question would like to know if I could search for a letter from the wordlist created in choice 1. if choice == "1": print ("Enter a Word") minput= input() wordList= list (minput) print (wordList) menu() if choice== 2 letter=('a,b,c,d,e,f,g,h,f,h') print () counter=0 searchLetter=input('Enter letter to find\t') while counter&lt;len(letter) and searchLetter!=letter[counter]: counter+=1 if counter &lt;len(letter): print(searchLetter,'found') else: print(searchLetter, ' Not found')
has title: How to use linear searches to search for letters in a user input word
type: AnsweredQuestion
upvote count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/81172833
downvote count: 1
linked to: http://stackoverflow.com/q/1155617
has answer: http://stackoverflow.com/a/47111134
accepted answer: http://stackoverflow.com/a/47111134
has comment: http://stackoverflow.com/comment/81172635

http://stackoverflow.com/comment/81283298
score: 0
has text: Can you use a basic bot from the discord.py github to test the connection to the server?
comment on: http://stackoverflow.com/q/47166585
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47131263
downvote count: 1
has body: How can I print below dictionary data in a more readable tree format like shown below using Python. This is my first time here so kindly pardon my ignorance. TempDict = {'outlook': {'sunny': {'humidity': {'high': 'no', 'normal': 'yes'}}, 'rainy': {'wind': {'strong': 'no', 'weak': 'yes'}}, 'overcast': 'yes'}} Output format required - outlook=sunny humidity=high:no humidity=normal:yes outlook=rainy wind=strong:no wind=weak:yes Class that is printing like this: class DecisionNode: def __init__(self, attribute): self.attribute = attribute self.children = {} # Visualizes the tree def display(self, level = 0): if self.children == {}: # reached leaf level print(": ", self.attribute, end="") else: for value in self.children.keys(): prefix = "\n" + " " * level * 4 print(prefix, self.attribute, "=", value, end="") self.children[value].display(level + 1)
favorite count: 0
has comment: http://stackoverflow.com/comment/81213191
score: 1
has comment: http://stackoverflow.com/comment/81212048
has comment: http://stackoverflow.com/comment/81212284
tagged with: python
has title: Python 3.6-Print dictionary data in readable tree structure
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81213263
has comment: http://stackoverflow.com/comment/81215726
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/47131907
has comment: http://stackoverflow.com/comment/81213030
has comment: http://stackoverflow.com/comment/81212657
has answer: http://stackoverflow.com/a/76175509
type: UnansweredQuestion

http://stackoverflow.com/q/47080329
tagged with: python
has comment: http://stackoverflow.com/comment/81110195
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/81109876
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: spectrogram
has title: How to extract the frequencies from spectrogram?
favorite count: 0
score: 2
has body: I got some code which takes wav songs from one folder and generates the corresponding spectrograms in another folder. However, I would like to extract the frequencies sampled each song when generating the spectogram, to eventually plot a histogram to represent the various frequency ranges in each song. How would I go about doing this? import cv2 import matplotlib.pyplot as plt import sys sys.path.append('/usr/local/lib/python2.7/site-packages') import glob, os import numpy as np import wave from scipy.io import wavfile import time results_dir = "/home/undead/Documents/MetricTestFolder/" for root, dirs, files in os.walk("/home/undead/ShareWindowsDesktop/SampleWavs"): #LOADS SONGS FROM DIRECTORY for file in files: if file.endswith(".wav"): filepath = os.path.join(root, file) fs, frames = wavfile.read(filepath) channels = [ np.array(frames[:, 0]), np.array(frames[:, 1]) ] fig, (ax2) = plt.subplots(nrows=1) data, freqs, bins, im = ax2.specgram(channels[0], NFFT=8192, Fs=44100, noverlap=int(8192 * 0.75)) start = time.time() ax2.pcolormesh(bins, freqs, 10. * np.log10(data)) ax2.axis('tight') plt.axis('off') plt.subplots_adjust(left=0.0, right=1.0, bottom=0.0, top=1.0) plt.xlim([0, 250]) plt.ylim([0, 15000]) plt.savefig(results_dir + "%s.png" % os.path.splitext(file)[0], dpi=450) plt.close("all") endt = time.time() print "%f" % (endt - start) #end
has comment: http://stackoverflow.com/comment/81109714

http://stackoverflow.com/q/47096887
has body: I've written a script in python to find the text within td tag which is the next sibling of first tdtag using BeautifulSoup in combination with css selectors. If i run the script, i find it working. However, when i do the same using lxml library, it no longer works. How can i get my latter script working? Thanks. This is the content: html_content=""" &lt;tr&gt; &lt;td width="25%" valign="top" bgcolor="lightgrey" nowrap=""&gt; &lt;font face="Arial" size="-1" color="224119"&gt; &lt;b&gt;Owner Address&amp;nbsp;&lt;/b&gt; &lt;/font&gt; &lt;/td&gt; &lt;td width="75%" valign="top" nowrap=""&gt; &lt;font face="Arial" size="-1" color="black"&gt; 1698 EIDER DOWN DR&lt;br&gt;SUMMERVILLE&amp;nbsp;SC&amp;nbsp;29483 &lt;/font&gt; &lt;/td&gt; &lt;/tr&gt; """ Working one with bs4: from bs4 import BeautifulSoup soup = BeautifulSoup(html_content,"lxml") item = soup.select("td")[0].find_next_sibling().text print(item) Result: 1698 EIDER DOWN DRSUMMERVILLE SC 29483 The below script can find the address string: from lxml.html import fromstring root = fromstring(html_content) item = root.cssselect("td b:contains('Address')")[0].text print(item) Result: Owner Address It doesn't work when it comes to find the next sibling (applied "+" sign to find the next sibling: from lxml.html import fromstring root = fromstring(html_content) item = root.cssselect("td b:contains('Owner Address')+td")[0].text print(item) Result: Traceback (most recent call last): File "C:\Users\ar\AppData\Local\Programs\Python\Python35-32\new_line_one.py", line 28, in &lt;module&gt; item = root.cssselect("td b:contains('Owner Address')+td")[0].text IndexError: list index out of range How can i make it work to find the next sibling? Btw, I'm only after css selectors not xpath. Thanks.
answer count: 1
tagged with: python-3.x
type: Question
accepted answer: http://stackoverflow.com/a/47099398
tagged with: lxml
has answer: http://stackoverflow.com/a/47099398
tagged with: python
has title: How to find certain text using selectors?
tagged with: css-selectors
type: AnsweredQuestion
score: 0
tagged with: web-scraping

http://stackoverflow.com/q/47082410
has comment: http://stackoverflow.com/comment/81114900
possible better answer: http://stackoverflow.com/a/47083805
accepted answer: http://stackoverflow.com/a/47083027
tagged with: duplicates
tagged with: python
has comment: http://stackoverflow.com/comment/81114555
tagged with: merge
has answer: http://stackoverflow.com/a/71227358
tagged with: dictionary
has comment: http://stackoverflow.com/comment/81114442
has comment: http://stackoverflow.com/comment/81114531
has answer: http://stackoverflow.com/a/47083027
has comment: http://stackoverflow.com/comment/81115632
has answer: http://stackoverflow.com/a/61111483
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81116014
has answer: http://stackoverflow.com/a/65783197
has comment: http://stackoverflow.com/comment/81116907
has title: keep highest value of duplicate keys in dicts
has comment: http://stackoverflow.com/comment/81114324
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81115508
answer count: 6
has answer: http://stackoverflow.com/a/47083805
has comment: http://stackoverflow.com/comment/81114703
has answer: http://stackoverflow.com/a/47086941
has comment: http://stackoverflow.com/comment/81114769
has comment: http://stackoverflow.com/comment/81114704
favorite count: 0
type: Question
has body: For school i am writing a small program for a rankinglist for a game. I am using dicts for this, with the name of the player as keyname, and the score as keyvalue. there will be 10 games, and each game will have an automatic ranking system which i print to file. ive already managed to code the ranking system, but now im facing a bigger challange which i cannot solve: I have to make an overall ranking, which means someplayername can be in several contests with several scores, but i need to only keep the highest score of a duplicate. In short: I need some help with keeping the duplicate key with the highest value: like this: dict1 = {"a": 6, "b": 4, "c": 2, "g": 1} dict2 = {"a": 3, "f": 4, "g": 5, "d": 2} dictcombined = {'a': 6, 'b': 4, 'c': 2, 'g': 5, 'f': 4, 'd': 2} the normal merge option just takes the second dict and thus that value. thnx in advance
has comment: http://stackoverflow.com/comment/81114224
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81115995
has comment: http://stackoverflow.com/comment/81114939
has comment: http://stackoverflow.com/comment/81115798
score: 3

http://stackoverflow.com/comment/81353908
type: Comment
has text: A quick question, which Java version did you install?
type: QuestionComment
comment on: http://stackoverflow.com/q/47198506
score: 0

http://stackoverflow.com/comment/81202251
type: QuestionComment
comment on: http://stackoverflow.com/q/47124800
score: 1
type: Comment
has text: Maybe this helps? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer The message suggests you could use a buffer object, that should be the way to go.

http://stackoverflow.com/a/53972653
has body: I have a File -&gt; Open menu item that displays an askopenfilename dialogue. I am finding that with python 2.7 and 3.6, the first time I use the dialogue and select Cancel or close the dialogue from the window border, it returns an empty tuple instead of ''. Every time thereafter the dialogue returns '' on Cancel or window close. Perhaps this is some sort of feature but it feels like a bug, particularly for this dialogue that doesn't support selection of multiple files. An empty tuple would make sense from askopenfilenames. I've settled on this simple test and cleanup for the file name returned by the askopenfilename dialogue: if str(filename) == '()': filename = ''
type: Answer
answers question: http://stackoverflow.com/q/47066606
score: 0
has comment: http://stackoverflow.com/comment/132174025

http://stackoverflow.com/q/47215682
has comment: http://stackoverflow.com/comment/81383086
has comment: http://stackoverflow.com/comment/81381473
type: UnansweredQuestion
score: 10
tagged with: python
linked to: http://stackoverflow.com/q/57854871
answer count: 0
has title: What type represents typing.Any except None?
downvote count: 0
upvote count: 10
tagged with: python-typing
duplicate of: http://stackoverflow.com/q/57854871
favorite count: 0
has body: I would like to annotate a variable such as it can be of any value except None, something like: x: typing.Required(typing.Any) = 42 The typing module has the Union function, but there is no counterpart that would allow to exclude.
type: Question

http://stackoverflow.com/comment/81125428
comment on: http://stackoverflow.com/a/47087886
has text: you can also use a built-in function here `divmod(x, y)` to get the division and remainder all in once, it could probably save a few lines or make the running slightly faster? But I don't think we need it for such a simple job.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/47093405
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47093583
has body: I have written a spider to fetch details from http://allevents.in. Every time I tried to scrap, I am getting a response body Too many requests, please try after some time or report this problem at contact@allevents.in I tried using the shell command also. scrapy shell 'http://allevents.in/new%20delhi/all' But still I am getting the same response for response.body. I have tried other websites like amazon which works fine. Also the above url can be fetched using requests as well as urllib.urlopen(). Here is my settings.py file # -*- coding: utf-8 -*- # Scrapy settings for tutorial project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html # http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html BOT_NAME = 'tutorial' SPIDER_MODULES = ['tutorial.spiders'] NEWSPIDER_MODULE = 'tutorial.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'tutorial (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = True # Configure maximum concurrent requests performed by Scrapy (default: 16) # CONCURRENT_REQUESTS = 1 # Configure a delay for requests for the same website (default: 0) # See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs DOWNLOAD_DELAY = 5 # The download delay setting will honor only one of: CONCURRENT_REQUESTS_PER_DOMAIN = 1 CONCURRENT_REQUESTS_PER_IP = 1 # Disable cookies (enabled by default) COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) # TELNETCONSOLE_ENABLED = False # Override the default request headers: # DEFAULT_REQUEST_HEADERS = { # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', # 'Accept-Language': 'en', # } # Enable or disable s…
has answer: http://stackoverflow.com/a/47099090
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81136835
tagged with: python
has comment: http://stackoverflow.com/comment/81136648
has title: Getting "Too many requests" error when scraping a particular website using scrapy
score: 2
answer count: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81136414
has answer: http://stackoverflow.com/a/55240311
tagged with: web-scraping
tagged with: python-requests
tagged with: scrapy

http://stackoverflow.com/q/47147948
has comment: http://stackoverflow.com/comment/81246170
has title: Infinite loop error python 3
type: AnsweredQuestion
score: 0
answer count: 3
has body: I am coding a simple chatbot for my computers class and I have run into a problem. I am trying to create a function that will ask for someone's name and then reply saying "Nice to meet you" and then their name. My function keep repeating "Hi Ii'm Bob. Whats your name?" over and over again. It works when its outside of the function but i cant figure out why it wont work when inside. def hello(): while True: print("Hi I'm Bob! What's your name?") name = input("Name:") print("Nice to meet you "+(name))
has answer: http://stackoverflow.com/a/47148000
has comment: http://stackoverflow.com/comment/81246165
upvote count: 1
has answer: http://stackoverflow.com/a/47147981
possible better answer: http://stackoverflow.com/a/47147981
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47147993
accepted answer: http://stackoverflow.com/a/47147993
tagged with: python

http://stackoverflow.com/q/47168056
has body: I feel like there has to be an easy solution to this, but I'm not too familiar with Numpy yet and couldn't find anything in the library fitting my needs. I feel like this is an obvious thing, but I couldn't find any similar question regarding this on StackOverflow. Basically, I want to create a 3-dimensional empty array. I tried it like this: matrix = np.array(None, ndmin=3). And now every time I have a new variable I want to append a dimension of the matrix I chose with the new value of the variable. How can I do that? I played around with np.append() and np.insert() but I couldn't come to a solution.
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47168284
answer count: 2
accepted answer: http://stackoverflow.com/a/47168330
downvote count: 2
upvote count: 5
tagged with: arrays
tagged with: python
has answer: http://stackoverflow.com/a/47168330
has title: Create empty 3D numpy array and append it with each new given value
possible better answer: http://stackoverflow.com/a/47168284
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1696135
score: 3
has comment: http://stackoverflow.com/comment/81286525

http://stackoverflow.com/q/47182284
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: environments
score: 2
tagged with: anaconda
answer count: 0
downvote count: 0
has title: python.exe running slower is custom Anaconda environment
has body: Can't find anyone else having the same problem as me online so here we go. I have Anaconda installed at work on my C: drive, but for certain reasons I now need to setup an environment on a shared network drive. To do this I ran the following in Anaconda prompt: conda create -n "M:\path\to\envFile" --no-default-packages python pyodbc xlwings ... ect activate "M:\path\to\envFolder" No problems so far! Some other people use my programs by running batch files e.g: C:\Anaconda3\python.exe M:\path\to\pythonFile.py Once my environment was setup I tried running some code calling the python.exe in my new environment i.e. M:\path\to\envFolder\python.exe M\path\to\pythonFile.py However the second method (using the environment python.exe) takes 120 seconds just to print "Hello world!" Seems like there's a lot more going on when I run from my environment but I don't have any idea what it is! Any information on what might be happening would be super useful. Ultimately I would like to be able to run my python from my new environment without the 2 minute wait! Thanks in advance for any help!
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/comment/81246823
has text: Fixed, sorry was from memory (defective)
type: Comment
comment on: http://stackoverflow.com/a/47147925
score: 0
type: AnswerComment

http://stackoverflow.com/comment/103177275
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47207569
has text: the more elegant does not print the same output.
type: Comment

http://stackoverflow.com/comment/81185035
comment on: http://stackoverflow.com/a/47117477
type: AnswerComment
score: 0
has text: It would also be nice to have the argument `names` with the list (time, text, retweet_count...) in the dataframe constructor, so that you have named columns.
type: Comment

http://stackoverflow.com/comment/124384920
score: 0
comment on: http://stackoverflow.com/a/50073238
type: Comment
type: AnswerComment
has text: `pip install --ignore-installed --upgrade "https://github.com/lakshayg/tensorflow-build/releases/download/tf2.2.1-py3.8-macos/tensorflow-2.2.1-cp38-cp38-macosx_10_15_x86_64.whl"` -> `ERROR: tensorflow-2.2.1-cp38-cp38-macosx_10_15_x86_64.whl is not a supported wheel on this platform.`

http://stackoverflow.com/q/47204012
type: UnansweredQuestion
tagged with: cpython
upvote count: 1
tagged with: python
tagged with: visual-studio-2012
score: 1
has answer: http://stackoverflow.com/a/47204547
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has body: There's a doc ex.doc with contents like The doctor set a due date of August 17th. Now i want to read this line by line using CPython 2.7 and divide them into arrays of words like , as follow: ['The','doctor','set','a','due','date','of','August','17th','.'] If we can get special characters and numbers separate it will be better . Then i would like to compare each words to existing set of data like ['January'..........} To know which month / ( profession like i can search doctor from list of professions ) the given line is talking about . Please try to help by easier and cleaner code. Here's my progress : with open("ex.doc") as file: my_list = file.readlines() my_list = [x.strip() for x in my_list] mt = ['Jan','Feb'] mtPresent=0 for lines in my_list: for words in lines: if words in mt: mtPresent=1 if mtPresent == 1: print(rows) #if line contains jan or feb then only line will be displayed mtPresent = 0 We should be able to compare word ':' among the list of ['is',':']. Thanks !
has title: Read lines from doc using python and compare to a set of words

http://stackoverflow.com/comment/81125219
type: QuestionComment
comment on: http://stackoverflow.com/q/47087757
has text: If I use your first regex with `re.findall` on the text I get `['Company', 'Inc.', 'Conner', 'Corporation ', 'Maxtor', 'The ', 'Applieds ', 'Systems ']`. This does not really match what you stated you wanted to match in the question, but you also said the regex works well. Am I missing something?
score: 0
type: Comment

http://stackoverflow.com/comment/81182314
comment on: http://stackoverflow.com/q/47116080
type: Comment
has text: Thanks, so instead of `(x**(i+1) - x**i)` I'd put `(x(i+1) - x(i))` then?
score: 0
type: QuestionComment

http://stackoverflow.com/q/47166090
has comment: http://stackoverflow.com/comment/81282223
has body: I exported variable in local environment, and need to pass that variable into bash script, which in turn will need to run python script using that env. #!/usr/bin/env bash export API_TOKEN=836176e9b6ce sudo python script.py --pretty Right now I am getting following: Could not find values for Program api_token. They must be specified via either ini file, command line argument (--api-token), or environment variables (API_TOKEN) Is it possible to achieve?
has title: Using environmental variables in bash while executing python script?
tagged with: python
score: 0
tagged with: bash
has comment: http://stackoverflow.com/comment/81282115
has answer: http://stackoverflow.com/a/47166128
type: UnansweredQuestion
tagged with: environment-variables
answer count: 1
type: Question

http://stackoverflow.com/comment/81280395
comment on: http://stackoverflow.com/q/47165314
has text: How to get Permissions ? I am logged in Windows as Admin + there is no password on the admin user
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81157169
has text: @wim Yeah ok I'm an idiot... wouldn't have expected `def f(): return []` to always return the same one. Something about `defaultdict(lambda: [])` somehow threw me off. I guess because it looks too similar to parameter default notation.
type: Comment
comment on: http://stackoverflow.com/a/47102108
score: 0
type: AnswerComment

http://stackoverflow.com/q/47177493
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/40970478
downvote count: 0
has comment: http://stackoverflow.com/comment/81306419
upvote count: 7
favorite count: 0
linked to: http://stackoverflow.com/q/32281168
has answer: http://stackoverflow.com/a/47198877
has comment: http://stackoverflow.com/comment/81304211
has comment: http://stackoverflow.com/comment/81305400
linked to: http://stackoverflow.com/q/33311616
score: 7
has comment: http://stackoverflow.com/comment/81304070
tagged with: python
has title: Python: point on a line closest to third point
has answer: http://stackoverflow.com/a/47177763
has answer: http://stackoverflow.com/a/47178534
type: Question
tagged with: numpy
tagged with: python-3.x
has body: I have a line/vector between two XY points (p1 and p2) and a third XY point (p3) that is outside the line. According to this post I know how to get the distance of that point to the line. But what I'm actually looking for is a point (p4) on that line that is in a minimum distance (d) to the third point (p3). I found this post, but I feel it's not the correct solution. Maybe there's something included in Numpy or Python? According to @allo I tried the following. You can download my code as Python file or Jupyter Notebook (both Python3). points = [[1, 1], [3, 1], [2.5, 2], [2.5, 1]] import matplotlib.pyplot as plt %matplotlib inline fig, ax = plt.subplots() fig.set_size_inches(6,6) x, y = zip(*points[:2]) l1, = ax.plot(x,y, color='blue') scatter1 = ax.scatter(x=x,y=y, color='blue', marker='x', s=80, alpha=1.0) x, y = zip(*points[2:]) l2, = ax.plot(x,y, color='red') scatter2 = ax.scatter(x=x,y=y, color='red', marker='x', s=80, alpha=1.0) p1 = Vector2D(*points[0]) p2 = Vector2D(*points[1]) p3 = Vector2D(*points[2]) p1p2 = p2.sub_vector(p1) p1p3 = p3.sub_vector(p1) angle_p1p2_p1p3 = p1p2.get_angle_radians(p1p3) length_p1p3 = p1p3.get_length() length_p1p2 = p1p2.get_length() p4 = p1.add_vector(p1p2.multiply(p1p3.get_length()/p1p2.get_length()).multiply(math.cos(p1p2.get_angle_radians(p1p3)))) #p4 = p1 + p1p2 * length(p1p3)/length(p1p2)*cos(angle(p1p2, p1p3)) p4 = p1.add_vector(p1p2.multiply(length_p1p3/length_p1p2*math.cos(angle_p1p2_p1p3))) p4 Which results in p4 = (1.8062257748298551, 1.0) but should obviously be (2.5, 1.0).
answer count: 3

http://stackoverflow.com/a/47091899
score: 2
upvote count: 2
has body: curly brackets {, } should be doubled to print them literally: token_found = ["abcdxyz", "1234567"] user_creds_string = """ UserA_A: - name: 'Abcd' value: '{0}' UserB_B: - name: 'Abcd' value: '{1}' headers: - name: 'Abcd' value: 'Kota %(xyz)' inputs: apop: {{'type':'hex-64', 'required': True}} - name: 'X-Broke' value: '%(BId) %(blahId)' inputs: UkID: {{'type':'hex-16', 'required': True}} blahId: {{'type':'hex-64', 'required': True}} apis: """.format(token_found[0],token_found[1]) print(user_creds_string) The output: UserA_A: - name: 'Abcd' value: 'abcdxyz' UserB_B: - name: 'Abcd' value: '1234567' headers: - name: 'Abcd' value: 'Kota %(xyz)' inputs: apop: {'type':'hex-64', 'required': True} - name: 'X-Broke' value: '%(BId) %(blahId)' inputs: UkID: {'type':'hex-16', 'required': True} blahId: {'type':'hex-64', 'required': True} apis:
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47091727
answers question: http://stackoverflow.com/q/47091727
has comment: http://stackoverflow.com/comment/81133972
type: Answer
has comment: http://stackoverflow.com/comment/81133684

http://stackoverflow.com/a/47192983
has comment: http://stackoverflow.com/comment/81335441
type: Answer
score: -1
upvote count: 0
downvote count: 1
has body: Is there anything in common between these two implementations? embedding_lookup is just a lookup, it just extract information from m based on index x. But keras.layers.Embedding is a computation. Just check official documentation: https://keras.io/layers/embeddings/
answers question: http://stackoverflow.com/q/47192887

http://stackoverflow.com/q/47105276
type: UnansweredQuestion
tagged with: python
has body: I am using an IDE so hacks like sys.path.append() are somewhat undesirable, because static type checker can hardy see modules imported like this, so I was wondering what is a conventional way of referring to and managing your personal library of small utility scripts that are shared among a bunch of different projects. I can think of following: Using a git submodule that reffers to a git repo with 'personal utils shared among projects' A symlink to a shared project, though it leads to duplicate code in github A proper package with setup and everything, but it seems like an overkill to me in terms of the amount of work required to maintain and sync versions between projects, even if that is just a folder with a setup.py script Copy-pasting scripts between project utils subfolders on demand - that is what I do now, but it leads to some weird conflicting version of same utils in different projects A bit of context: I am the only person who actively makes changes to these projects, so trickery with git might be okay, though other people might also need to have to run that code at some point in the future.
tagged with: git
has title: Best practices to maintain often changing set of utils within multiple projects?
score: 0
has comment: http://stackoverflow.com/comment/81161833
has comment: http://stackoverflow.com/comment/81163749
answer count: 0
has comment: http://stackoverflow.com/comment/81163564
tagged with: project
has comment: http://stackoverflow.com/comment/81161670
linked to: http://stackoverflow.com/q/37006114
has comment: http://stackoverflow.com/comment/81161402
type: Question
tagged with: utility
has comment: http://stackoverflow.com/comment/81161484

http-redirect
tags question: http://stackoverflow.com/q/47150962
tag name: http-redirect
type: Tag

http://stackoverflow.com/a/47196831
answers question: http://stackoverflow.com/q/47196719
has body: I think you need a bit maths: a = df['date'].astype(int) print (a) 0 1960 1 1960 2 1960 3 1960 4 1960 5 1960 Name: date, dtype: int32 b = df['date'].sub(a).add(1/12).mul(12).round(0).astype(int) print (b) 0 7 1 8 2 9 3 10 4 11 5 12 Name: date, dtype: int32 c = pd.to_datetime(a.astype(str) + '.' + b.astype(str), format='%Y.%m') print (c) 0 1960-07-01 1 1960-08-01 2 1960-09-01 3 1960-10-01 4 1960-11-01 5 1960-12-01 Name: date, dtype: datetime64[ns] Solution with map: d = {'500':'7','583':'8','667':'9','750':'10','833':'11','917':'12'} #if necessary #df['date'] = df['date'].astype(str) a = df['date'].str[:4] b = df['date'].str[5:].map(d) c = pd.to_datetime(a + '.' + b, format='%Y.%m') print (c) 0 1960-07-01 1 1960-08-01 2 1960-09-01 3 1960-10-01 4 1960-11-01 5 1960-12-01 Name: date, dtype: datetime64[ns]
type: Answer
upvote count: 3
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47196719
has comment: http://stackoverflow.com/comment/81343458
score: 3
has comment: http://stackoverflow.com/comment/81343085

http://stackoverflow.com/q/47120973
has title: how to use StanfordParser on Heroku with Python?
type: UnansweredQuestion
tagged with: python
tagged with: cloud9
has answer: http://stackoverflow.com/a/47171099
has body: I'm trying to use Stanford Parser on Heroku with Python. But I get this error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.5/site-packages/nltk/parse/stanford.py", line 150, in raw_parse_sents return self._parse_trees_output(self._execute(cmd, '\n'.join(sentences), verbose)) File "/usr/local/lib/python3.5/site-packages/nltk/parse/stanford.py", line 216, in _execute stdout=PIPE, stderr=PIPE) File "/usr/local/lib/python3.5/site-packages/nltk/internals.py", line 134, in java raise OSError('Java command failed : ' + str(cmd)) OSError: Java command failed : ['/usr/bin/java', '-mx1000m', '-cp', 'stanford-parser-3.4.1-models.jar', 'edu.stanford.nlp.parser.lexparser.LexicalizedParser', '-model', 'edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz', '-sentences', 'newline', '-outputFormat', 'penn', '-encoding', 'utf8', '/var/folders/vy/rll459h54ts7pt6l0hs62nth0000gr/T/tmpffdpj0v5'] Is there anyone who has any idea on how to solve this? I think it's a problem with Heroku because this works in my local environment on cloud9.
score: 0
answer count: 1
type: Question
tagged with: heroku

http://stackoverflow.com/q/47066734
favorite count: 0
tagged with: class
type: Question
score: 2
has comment: http://stackoverflow.com/comment/81081635
upvote count: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81081611
has answer: http://stackoverflow.com/a/47066848
has body: I am learning classes and I have an exercise to create a class that does some string function. One should get a string and the other should print the string but I was wondering if you really need to create the variable under def __init__: This is what the answer is supposed to look like: class InputOutString(object): def __init__(self): self.s = "" def getString(self): self.s = raw_input() def printString(self): print self.s.upper() I was thinking that it would be a lot more convenient to just create the variable when you get the raw input.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81081679
has title: Do all variables in a class have to be created in the initialization
accepted answer: http://stackoverflow.com/a/47066848
has comment: http://stackoverflow.com/comment/81081991
has comment: http://stackoverflow.com/comment/81081607
tagged with: python
linked to: http://stackoverflow.com/q/12274179

http://stackoverflow.com/q/47114208
tagged with: python
type: AnsweredQuestion
score: 2
has body: I have a matrix named v1 and I want to create another matrix named matriz1 that has only the items of the length of v1*2/3 v1=np.matrix('1,2;3,4;2,6;4,5') distancia=len(v1) distancia=distancia*2/3 matriz1=np.matrix print(distancia) k=0 print() print() print('matriz1') for k in range(0,(int(distancia))): matriz1[k]=v1[k] k=k+1 print(matriz1) The error is: TypeError Traceback (most recent call last) &lt;ipython-input-206-1ed800e332a1&gt; in &lt;module&gt;() 77 print('matriz1') 78 for k in range(0,(int(distancia))): ---&gt; 79 matriz1[k]=v1[k] 80 k=k+1 81 print(matriz1) TypeError: 'type' object does not support item assignment I know I am not defining a length for that matrix. What can I do to solve it?
tagged with: matrix
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/81178586
has title: Assign rows of a Matrix to a new Matrix
favorite count: 0
has comment: http://stackoverflow.com/comment/81178246
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81178280
upvote count: 2
accepted answer: http://stackoverflow.com/a/47114375
has answer: http://stackoverflow.com/a/47114375

http://stackoverflow.com/comment/81211572
has text: @Bryan Oakley ..can you suggest how can i invoke a terminal or cmd (os indepenedent) , run the command "appium -p 4723 " on it and then terminate the terminal or cmd after use.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47091374
score: 0

http://stackoverflow.com/q/47221651
tagged with: python
score: -1
duplicate of: http://stackoverflow.com/q/6531482
tagged with: python-2.7
has title: python - if statement with logical OR condition
answer count: 1
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/15112125
type: Question
has answer: http://stackoverflow.com/a/47221686
has body: I'm a beginner in python and trying to achieve the following - need help pls... In the below code snippet, it matches for ab but not for remaining two matches...Can anyone pls point what I'm missing. I've a txt input which is captured in text. for line in text: parse = re.split('\s+', line) print(parse) if ("ab" or "yx" or "12") in line: print("success") continue else: print("failure") The above code matches just "ab", it doesn't work for other matches like "yx" and "12". Don't know what I'm missing. Thanks
type: UnansweredQuestion
downvote count: 2
duplicate of: http://stackoverflow.com/q/15112125

http://stackoverflow.com/q/47169618
downvote count: 0
tagged with: coordinate-transformation
has body: I'm using python3 I have just started learning openGL and I need some help turning the camera of your view with a mouse (Like a FPS game). Right now my program looks like i'm moving but i'm just moving the object so if you could tell me how to move the camera(forward, backwards, etc) too that would be nice. Thanks in advance My Code: import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * vertices = ( (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, -1), (1, -1, 1), (1, 1, 1, ), (-1, -1, 1), (-1, 1, 1), ) edges = ( (0,1), (0,3), (0,4), (2,1), (2,3), (2,7), (6,3), (6,4), (6,7), (5,1), (5,4), (5,7), ) surfaces = ( (0,1,2,3), (3,2,7,6), (6,7,5,4), (4,5,1,0), (1,5,7,2), (4,0,3,6), ) colors = ( (1,1,1), (0,0,0), (0,1,1), (0,0,0), (0,1,1), (1,0,1), (0,0,0), (1,1,1), (0,0,0), (0,1,1), ) def Cube(): glBegin(GL_QUADS) for surface in surfaces: x = 0 for vertex in surface: x += 1 glColor3fv(colors[x]) glVertex3fv(vertices[vertex]) glEnd() glBegin(GL_LINES) for edge in edges: for vertex in edge: glVertex3fv(vertices[vertex]) glEnd() def main(): pygame.init() x = 0 y = 0 z = 0 display = (800,600) pygame.display.set_mode(display, DOUBLEBUF|OPENGL|RESIZABLE) pygame.event.set_grab(True) pygame.mouse.set_visible( False ) gluPerspective(45, (display[0]/display[1]), 0.1, 50.0) glTranslatef(0, 0, -5) glRotatef(0, 0, 0, 0) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() quit() if event.key == pygame.K_a: x = 0.1 elif event.key == pygame.K_d: x = -0.1 elif event.key == pygame.K_w: z = 0.1 elif event.key == pygame.K_s: z = -0.1 elif event.type == pygame.KEYUP: if event.key == pygame.K_a and x &gt; 0: x = 0 elif event.key == pygame.K_d and x &lt; 0: x = 0 if event.key == pygame.K_w and z &gt; 0: z = 0 if event.key == pygame.K_s and z &lt; 0: z = 0 glTranslatef(x,y,z) #glRotatef(1, 2, 3, 4) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUF…
favorite count: 0
tagged with: pyopengl
has answer: http://stackoverflow.com/a/47173089
linked to: http://stackoverflow.com/q/46008171
type: AnsweredQuestion
tagged with: opengl
tagged with: python
accepted answer: http://stackoverflow.com/a/47173089
tagged with: pygame
type: Question
upvote count: 2
score: 2
has title: how to modify the view of the camera with pygame and openGL
answer count: 1

http://stackoverflow.com/comment/81334961
type: Comment
comment on: http://stackoverflow.com/a/47190264
type: AnswerComment
has text: Hmm. When I run your code with `x=.81`, I get this: `8100000000000001.0` Python3 demo: https://ideone.com/Mwl0KL Python2 demo: https://ideone.com/E2T6xH
score: 0

http://stackoverflow.com/q/47173925
upvote count: 4
score: 4
accepted answer: http://stackoverflow.com/a/47176403
tagged with: pandas
type: AnsweredQuestion
has body: Sorry if this seems like a stupid question, I have a dataset which looks like this type time latitude longitude altitude (m) speed (km/h) name desc currentdistance timeelapsed T 2017-10-07 10:44:48 28.750766667 77.088805000 783.5 0.0 2017-10-07_10-44-48 0.0 00:00:00 T 2017-10-07 10:44:58 28.752345000 77.087840000 853.5 7.8 198.70532 00:00:10 T 2017-10-07 10:45:00 28.752501667 77.087705000 854.5 7.7 220.53915 00:00:12 Im not exactly sure how to approach this,calculating acceleration requires taking difference of speed and time,any suggestions on what i may try? Thanks in advance
has comment: http://stackoverflow.com/comment/81297252
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81297327
tagged with: data-science
favorite count: 0
has comment: http://stackoverflow.com/comment/81297460
has comment: http://stackoverflow.com/comment/81297757
has comment: http://stackoverflow.com/comment/81297538
type: Question
has comment: http://stackoverflow.com/comment/81297211
has comment: http://stackoverflow.com/comment/81300514
tagged with: physics
has answer: http://stackoverflow.com/a/47176403
tagged with: datetime
has comment: http://stackoverflow.com/comment/81297035
has title: calculate acceleration given speed
tagged with: python

http://stackoverflow.com/comment/81318568
type: Comment
comment on: http://stackoverflow.com/a/47144791
score: 0
type: AnswerComment
has text: Thank you for your help. Nevertheless, in the case to count the spaces, it is not necessary to specify Python not to count spaces in the first line just after \n? Thanks in advance

http://stackoverflow.com/a/47085609
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/81120976
has comment: http://stackoverflow.com/comment/81121069
type: Answer
answers question: http://stackoverflow.com/q/47085552
has body: Use a list comprehension: string = "Create your own function that takes in a sentence and replaces every second word with the word “Hello”" hello = " ".join(["{} hello".format(word) for idx, word in enumerate(string.split()) if idx % 2 == 0]) print(hello) # Create hello own hello that hello in hello sentence hello replaces hello second hello with hello word hello The key point here is to use the enumerate() function and the modulo operator (%). As @darksky points out in the comment section, this might be hard to grasp when trying to learn Python. Instead you could very well use a longer function like lst = [] for idx, word in enumerate(string.split()): if idx % 2 == 0: lst.append(word) lst.append("hello") words = " ".join(lst) print(words) Which prints out exactly the same.
score: 2
has comment: http://stackoverflow.com/comment/81121170

http://stackoverflow.com/q/47191412
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/81332506
has answer: http://stackoverflow.com/a/73177322
has title: pySerial AttributeError: module 'serial' has no attribute 'Serial'
has comment: http://stackoverflow.com/comment/137063463
has answer: http://stackoverflow.com/a/68896422
answer count: 3
tagged with: python-module
tagged with: python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47562659
has body: I have windows 7 64 bit and Python 3.6 I literally dig entire web for solving this - and nothing works sadly. AttributeError Traceback (most recent call last) &lt;ipython-input-150-80ee8bd5f0f2&gt; in &lt;module&gt;() ----&gt; serial.Serial() AttributeError: module 'serial' has no attribute 'Serial' I tried solve this by: - checking if my file is named serial.py - reinstalling module - at first, entire module didn't work, now only it's functions. - I can't use any of its features, checking ports don't work, nothing works literally. - I checked my pip - everything is fine, module is in folder site-pacages. - If I execute some code inside pySerial files - it works. But there is no serial.Serial or connecting with COM ports (which I try to do.)
score: 5
has comment: http://stackoverflow.com/comment/81367718
tagged with: pyserial
type: UnansweredQuestion

http://stackoverflow.com/q/47101947
linked to: http://stackoverflow.com/q/38987
has title: Python merging dictionary of dictionaries into one dictionary by summing the value
has answer: http://stackoverflow.com/a/47102108
answer count: 3
tagged with: addition
downvote count: 0
has answer: http://stackoverflow.com/a/47102041
type: Question
has comment: http://stackoverflow.com/comment/81153937
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47102009
has body: I want to merge all the dictionaries in a dictionary, while ignoring the main dictionary keys, and summing the value of the other dictionaries by value. Input: {'first':{'a': 5}, 'second':{'a': 10}, 'third':{'b': 5, 'c': 1}} Output: {'a': 15, 'b': 5, 'c': 1} I did: def merge_dicts(large_dictionary): result = {} for name, dictionary in large_dictionary.items(): for key, value in dictionary.items(): if key not in result: result[key] = value else: result[key] += value return result Which works, but I don't think it's such a good way (or less "pythonic"). By the way, I don't like the title I wrote. If anybody thinks of a better wording please edit.
has answer: http://stackoverflow.com/a/47102009
tagged with: python
tagged with: merge
tagged with: dictionary
favorite count: 0
score: 4
upvote count: 4
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47102108

http://stackoverflow.com/a/63971195
downvote count: 0
has body: I had the same issue with the correct path. What worked for me is to create the .docx file with an empty Document(). document = docx.Document() document.save('your_doc_name.docx') So you can do something like : try: document = docx.Document('your_doc_name.docx') except: document = docx.Document() document.save('your_doc_name.docx') print("Previous file was corrupted or didn't exist - new file was created.")
has comment: http://stackoverflow.com/comment/126765905
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/47199300
type: Answer
has comment: http://stackoverflow.com/comment/125706799

http://stackoverflow.com/q/47104627
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81159840
accepted answer: http://stackoverflow.com/a/47104823
tagged with: python
has answer: http://stackoverflow.com/a/47104823
has body: I'm studying Python and creating a simple chat bot. Consider I have a module with main function: # bot.py class QueueWrapper: pass wrapper = QueueWrapper() # also tried with dict def main(): wrapper.queue = init_queue() if __name__ == '__main__': main() And consider there is an another module where i want to access queue from bot module, but function from this module gets invoked some time after bot.py module got invoked: # another_module.py from bot import wrapper def create_job(): wrapper.queue.do_smth() # &lt;- error. object has no attribute ... And when I try to access queue that should be in wrapper object I get and error saying there is no queue in wrapper. But if I run in debug mode over bot module I can clearly see that wrapper.queue contains object. But when create_job function from another_module.py is invoked it doesn't know that there were a queue in wrapper. The problem here in my opinion is that var queue from bot.py gets initialized after main() and init_queue() had finished working but module itself gets imported into another_module before that. What am I doing wrong (probably missing something about variable scope) and how can I get my wrapper.queue initialized in when create_job() is invoked? Thanks in advance!
has comment: http://stackoverflow.com/comment/81240319
type: AnsweredQuestion
tagged with: python-import
has comment: http://stackoverflow.com/comment/81159877
has title: Access variable that was changed from another module

http://stackoverflow.com/comment/81299488
has text: Thanks for the reply. I already went through that link and that section. Need to know how to implement it.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47175087
type: Comment

http://stackoverflow.com/q/47078310
tagged with: amazon-cloudwatch
type: Question
has comment: http://stackoverflow.com/comment/81107374
accepted answer: http://stackoverflow.com/a/47079569
has answer: http://stackoverflow.com/a/47079569
has comment: http://stackoverflow.com/comment/81106156
has comment: http://stackoverflow.com/comment/81105673
tagged with: amazon-ec2
has body: I can see events for every 5 minutes using the AWS console for CloudWatch, however when using the following query: import boto3 from pprint import pprint from datetime import timedelta from datetime import datetime stats = cloudwatch.get_metric_statistics( Namespace='AWS/EC2', MetricName='CPUUtilization', StartTime=datetime(2017, 11,1), EndTime=datetime(2017, 11,2), Statistics=['Maximum'], Period=300 ], ) pprint(stats) I don't get any data points: {'Datapoints': [], 'Label': 'CPUUtilization', 'ResponseMetadata': {'HTTPHeaders': {'content-length': '337', 'content-type': 'text/xml', 'date': 'Thu, 02 Nov 2017 15:01:42 GMT', 'x-amzn-requestid': 'xxxxxx'}, 'HTTPStatusCode': 200, 'RequestId': 'xxxxxx', 'RetryAttempts': 0}} Any idea what I'm doing wrong here? I've even been careful to specify the correct region.
tagged with: python
tagged with: boto3
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81105461
score: 0
has comment: http://stackoverflow.com/comment/81106613
answer count: 1
has title: Empty data set for CloudWatch EC2 CPUUtilization request

http://stackoverflow.com/q/47152334
has title: Zero Division error,float division by zero
answer count: 1
accepted answer: http://stackoverflow.com/a/47152407
has comment: http://stackoverflow.com/comment/81254310
has comment: http://stackoverflow.com/comment/81254093
has answer: http://stackoverflow.com/a/47152407
has comment: http://stackoverflow.com/comment/81254085
has comment: http://stackoverflow.com/comment/81254177
has comment: http://stackoverflow.com/comment/81254782
has body: This is My code for i in range(len(speed)): for j in range(len(time_two)): new.append((speed[i] - speed[i-1])/(time_two[j] - time_two[j-1])) I get this error: ZeroDivisionError Traceback (most recent call last) &lt;ipython-input-7-9cdf386300d7&gt; in &lt;module&gt;() 4 for i in range(len(speed)): 5 for j in range(len(time_two)): ----&gt; 6 new.append((speed[i] - speed[i-1])/(time_two[j] - time_two[j-1])) ZeroDivisionError: float division by zero Here speed and time_two are a list of floats, There are no 0's in the lists. Any suggestions as to what i may change? Any help is appreciated ! Thank you in advance EDIT: speed = [14.13102608620676, 6.111463527087486, 5.593147106275493, 4.854037993898749,...] time_two = [2.0, 14.0, 15.0, 17.0, 15.0, 15.0...]
has comment: http://stackoverflow.com/comment/81254197
type: AnsweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81254175
has comment: http://stackoverflow.com/comment/81254224
type: Question
score: 0

http://stackoverflow.com/comment/81116375
comment on: http://stackoverflow.com/q/47083451
type: QuestionComment
type: Comment
has text: @TristanForward so why did you not mention that? You explicitly said that you want a string `'[FacilityID] & " " & [DIAMETER]'`. If you want anything else, you need to specify what characters the brackets can contain.
score: 2

http://stackoverflow.com/q/47075622
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81109142
tagged with: arrays
has title: numpy.savetxt format specifier for array
answer count: 1
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
tagged with: format
has comment: http://stackoverflow.com/comment/81104176
tagged with: python
has answer: http://stackoverflow.com/a/47080866
has comment: http://stackoverflow.com/comment/81107784
has body: I'm using numpy.savetxt to save my matrix of dtype=[('time','S8'),('channels', 'float16', 2)] A row of this matrix looks like: (b'12:31:24', [ 1.20019531, 4. ]) Is there any way to specify this format? I was trying to use fmt='%s %.3f %.3f' but it's not working. numpy.savetxt requires pythonic format specifier, not numpy dtype and I can't figure out how to specify array. If I use different dtype=[('time','S8'),('channel0', 'float16'),('channel1', 'float16')] everything works fine, since I get rid of this array and get only columns with floats but I would like to use the dtype with one string and array per row (there are more channels in my device and having data stored in an array simplifies iterating)
tagged with: numpy

http://stackoverflow.com/q/47154704
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/45621722
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/47154971
has comment: http://stackoverflow.com/comment/81259050
tagged with: python
has body: import os from fnmatch import fnmatch root = 'Directory' for path, subdirs, file in os.walk(root): for files in file : with open(files) as f: contents = f.read() if 'Search_string' in contents: print os.path.join(path, files) It is giving me below error : for files in file : ^ IndentationError: expected an indented block Please help.
tagged with: string-search
linked to: http://stackoverflow.com/q/45621722
upvote count: 0
downvote count: 2
answer count: 1
has title: Python Script to Search String in all file contents and also in subfolder

http://stackoverflow.com/a/47200170
has comment: http://stackoverflow.com/comment/135651830
score: 84
type: Answer
has comment: http://stackoverflow.com/comment/103547408
has body: Ok I was very close to the solution. Seaborn pairplots have plot_kws that takes as arguments a dictionary of the kind of modifications you would do in a regplot. The following line is exactly what I needed: g = sns.pairplot(df, kind='reg', plot_kws={'line_kws':{'color':'red'}, 'scatter_kws': {'alpha': 0.1}}) And this is the outcome: If you don't do the regression but just the scatter plot (kind='scatter'), within plot keywords you don't have to do the division between line and scatter keywords: g = sns.pairplot(df, kind='scatter', plot_kws={'alpha':0.1})
has comment: http://stackoverflow.com/comment/97519075
has comment: http://stackoverflow.com/comment/109498162
accepted answer of: http://stackoverflow.com/q/47200033
upvote count: 85
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/110328780
answers question: http://stackoverflow.com/q/47200033
downvote count: 1

http://stackoverflow.com/comment/81241755
type: Comment
has text: Typically a page will have a INPUT button that the user clicks, the File | Open dialog launches, the user chooses a file, and then clicks Open. You can see this on this test page: http://the-internet.herokuapp.com/upload. You would get the "Choose File" INPUT (id: file-upload) and send_keys the file path to that INPUT and then click on the Upload button. The File | Open dialog should never open.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47117698

http://stackoverflow.com/q/47105525
tagged with: pymongo
favorite count: 0
accepted answer: http://stackoverflow.com/a/47106054
type: Question
tagged with: mongodb
has answer: http://stackoverflow.com/a/47106054
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has body: I have a lot of documents like: { _id: something date: 2017-10-23 20:05:00.000 (Date) qty: 400.41 (Double) weight: 100.44 (Double) } I need to update each document by adding 2 fields: qty_avg and weight_avg that are calculated by the average of the elements that are at maximum 5 minutes behind the date. The tools I have at my disposal are python, or mongo console, the latter would be preferable if possible
has comment: http://stackoverflow.com/comment/81161774
has title: Update Document - Average of Previous Documents Filtered by Date
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81161714
tagged with: aggregation-framework
score: 1

http://stackoverflow.com/a/47110106
has comment: http://stackoverflow.com/comment/81170401
downvote count: 0
has body: There is no urllib.request.post. You are maybe confusing the usage of requests package with the inbuilt urllib library module. &gt;&gt;&gt; from urllib import request &gt;&gt;&gt; request.post Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: module 'urllib.request' has no attribute 'post'
answers question: http://stackoverflow.com/q/47109988
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/81170604
score: 4

http://stackoverflow.com/a/47115237
downvote count: 0
score: 4
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/47115063
has body: You shouldn't need to do anything. Cython accepts an argument language_level (see http://cython.readthedocs.io/en/latest/src/reference/compilation.html#compiler-directives) which controls where it interprets the code as Python 2 or Python 3 (for example print as a function or as a statement). Whichever you do the code it generates should be compilable to use with Python 2 or Python 3 (this is determined by what headers you include, which is largely arranged by the build process). There are a lot of preprocessor #if PY_MAJOR_VERSION &gt;= 3 sections in the generated C code to ensure this. I suspect that there are some limitations on this compatibility, and I certainly wouldn't expect all Python 3 features to work perfectly when compiled against Python 2, but as a general rule you should be able to take your existing Cython code, run Cython on it with language_level=2 (the default) and then compile it using the Python 3 headers/libraries (which setup.py should take care of by default) and it should work. There may be small, specific issues you have to work round though.

http://stackoverflow.com/comment/81384086
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47217252
has text: I can understand that the train or test data should be shaped like this, but the embedding layer required the input be 2D tensor. Besides, I was wondering why if we set return_sequence as False and only return the last output and the model can compile and go through the fitting.
score: 0

http://stackoverflow.com/comment/81261228
type: Comment
comment on: http://stackoverflow.com/a/47109399
type: AnswerComment
has text: Done! Thanks again.
score: 0

http://stackoverflow.com/comment/81538945
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47160407
has text: so i did introduce `time.sleep(5); ser.read_all()` and I am okay now.
type: QuestionComment

http://stackoverflow.com/comment/81120948
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47085402
has text: I'll accept this since you posted it as a formal answer...thanks. It along with a comment under my question have provided fixes for both versions. Guess I keep mixing-up the closing of the `mmap` object and the closing the file associated with it.
type: Comment

http://stackoverflow.com/q/47123009
type: AnsweredQuestion
score: 0
tagged with: random
has answer: http://stackoverflow.com/a/47123054
has title: Generate random RNA transcripts with ending condition
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47123054
has body: I am trying to write a program that generates random RNA transcripts: all 4 RNA nucleotides are of equal probability, each sequence begins with a start codon, ends only when a stop codon is introduced. import random def random_rna(): rna = 'AUG' stop_codon = ['UAG','UAA','UGA'] while rna[-3:] not in stop_codon: rna += (random.choice('AUCG'))*3 return rna random_rna() it does not generate a sequence and python is not presenting any errors...
has comment: http://stackoverflow.com/comment/81195766
tagged with: python
tagged with: dna-sequence

http://stackoverflow.com/comment/81273442
type: AnswerComment
score: 1
has text: @Dasho exactly. But use `if word` it's more idiomatic.
type: Comment
comment on: http://stackoverflow.com/a/47161537

http://stackoverflow.com/comment/81237251
type: QuestionComment
comment on: http://stackoverflow.com/q/47142665
has text: ...what the heck is up with all that hex stuff? The `struct.pack` output should already be what you need. Everything else in `process_value` is redundant.
type: Comment
score: 2

http://stackoverflow.com/q/47077805
has comment: http://stackoverflow.com/comment/81104967
has body: I have scripts I would like to execute in sequence with a time delay between the each of them. The intention is to run the scripts which scan for an string in file names and imports those files into a folder. The time delay is to give the script the time to finish copying the files before moving to the next file. I have tried the questions already posed on Stackoverflow: Running multiple Python scripts Run a python script from another python script, passing in args But I'm not understanding why the lines below don't work. import time import subprocess subprocess.call(r'C:\Users\User\Documents\get summary into folder.py', shell=True) time.sleep(100) subprocess.call(r'C:\Users\User\Documents\get summaries into folder.py', shell=True) time.sleep(100) The script opens the files but doesn't run.
tagged with: python
linked to: http://stackoverflow.com/q/24163962
type: Question
has title: Running multiple python scripts in a sequence
linked to: http://stackoverflow.com/q/3781851
score: 0
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47078156

http://stackoverflow.com/comment/81298176
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47173459
has text: have you tried after adding it into environment path ?

http://stackoverflow.com/comment/81365841
comment on: http://stackoverflow.com/q/47207713
score: 0
has text: @ScottBoston i assume that you are suggesting sth like that `df.loc[:, ('PACKETS')].drop()` maybe ?
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47149914
has body: I'm trying to build a messaging app, here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") ... created_at = models.DateTimeField(auto_now_add=True) I wants to order the Users based upon who sent a message to request.user &amp; to whom request.user sent a message most recently! As we see on social networks. This is what I tried, users = User.objects.filter( Q(sender__receiver=request.user) | Q(receiver__sender=request.user) ).annotate(Max('receiver')).order_by('-receiver__max') This code is working fine only when request.user sends someone a message (It re-orders their name &amp; place it to the top). But, It's not changing the order of users in case if someone sends a message to request.user. I also tried, users = Message.objects.filter( Q(sender=request.user) | Q(receiver=request.user) ).order_by("created_at") But, I could't filter out the distinct users. It's showing equal number of users as messages. Also, I have to use {{ users.sender }} OR {{ users.receiver }} in order to print the users name which is a problem itself in case of ordering &amp; distinct users. Please help me, how can I do that?
has answer: http://stackoverflow.com/a/47152091
score: 0
has comment: http://stackoverflow.com/comment/81253026
answer count: 1
has comment: http://stackoverflow.com/comment/81252977
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/81253714
has title: Messaging App With Django
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/comment/81176196
score: 0
has text: https://pythonhosted.org/Flask-Classy/
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47113190

http://stackoverflow.com/comment/81328562
score: 0
type: Comment
has text: A complete explanation of list comprehension seems a little beyond the scope of an SO answer. That's what the docs are for. All this was meant to do was help him figure it out himself.
type: AnswerComment
comment on: http://stackoverflow.com/a/47189511

http://stackoverflow.com/comment/81310164
type: Comment
score: 0
type: AnswerComment
has text: No. Use the `os` module. The code won't be portable if you hardcode the separator.
comment on: http://stackoverflow.com/a/47180665

http://stackoverflow.com/a/47074456
type: Answer
answers question: http://stackoverflow.com/q/47066449
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: From draft 4 and on, "required" should be an array not a boolean. Also "maximum" and "minimum" should be integers, not strings. Try like this: { "$schema": "http://json-schema.org/draft-06/schema#", "title": "AP Scores", "type": "array", "items": { "type": "object", "properties": { "exam": { "type": "string" }, "score": { "type": "integer", "minimum": 1, "maximum": 5 } }, "required": [ "exam" ] } }
has comment: http://stackoverflow.com/comment/81106264
has comment: http://stackoverflow.com/comment/81104628
accepted answer of: http://stackoverflow.com/q/47066449

http://stackoverflow.com/comment/81277827
type: QuestionComment
comment on: http://stackoverflow.com/q/47161832
type: Comment
has text: @BrunoMiguelGonçalves Can you show an example of what your text files look like?
score: 0

http://stackoverflow.com/a/47142514
has comment: http://stackoverflow.com/comment/81236083
type: Answer
has body: Consider pandas' to_sql method layered on the SQLAlchemy API where you can append or replace data in database table. SQLAlchemy interfaces with a standard Python-SQL Sever DB-API such as pyodbc or pymssql. So install either before use. import pyodbc import sqlalchemy engine = sqlalchemy.create_engine("mssql+pyodbc://user:pwd@server/database", echo=False) mydataframe.to_sql('mytable', con=engine, if_exists='replace') engine.dispose() Unlike various import wizards, this method does a straight SQL connection between pandas dataframe and your SQL Server database table. With replace, the method actually runs DROP TABLE ..., then CREATE TABLE ..., finally INSERT INTO ... using data types of pandas dataframe or as specified by user in dtype argument of to_sql.
has comment: http://stackoverflow.com/comment/81237435
has comment: http://stackoverflow.com/comment/81795918
has comment: http://stackoverflow.com/comment/81235634
has comment: http://stackoverflow.com/comment/81237525
score: 0
has comment: http://stackoverflow.com/comment/81237517
has comment: http://stackoverflow.com/comment/81795973
has comment: http://stackoverflow.com/comment/81236159
has comment: http://stackoverflow.com/comment/81235102
answers question: http://stackoverflow.com/q/47141836

http://stackoverflow.com/comment/81159205
has text: @user2357112: `_saved_reference` is needed because of something Python 2 does. See the accepted answer to [this question](https://stackoverflow.com/questions/5365562/why-is-the-value-of-name-changing-after-assignment-to-sys-modules-name) of mine that discusses it.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47104046

http://stackoverflow.com/comment/81203861
comment on: http://stackoverflow.com/a/47124735
has text: Oh that may be, but that would still then be a related problem to misuse of Pool.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47087380
has comment: http://stackoverflow.com/comment/81124711
has title: Writing a str and float into a file
has comment: http://stackoverflow.com/comment/81124660
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47087603
tagged with: python
has comment: http://stackoverflow.com/comment/81124709
has body: For some reason I can't test my function. I get this error. print(write_avg(out_file('grades.csv'))) Traceback (most recent call last): Python Shell, prompt 3, line 1 builtins.NameError: name 'out_file' is not defined Can anyone please help me fix this? Here is my function. def write_avg(L, out_file): '''(list, file) -&gt; NoneType Given a list of lists where each inner list consists of a string and a float,and an open file for writing, write the contents of each inner list as a line in the file. Each line of the file should be the string followed by the float separated by a comma. Close the file when done. ''' for line in out_file: L.append(',') output_line = L out_file.write(output_line) out_file.close()
has comment: http://stackoverflow.com/comment/81124625
has comment: http://stackoverflow.com/comment/81124675
answer count: 1
has comment: http://stackoverflow.com/comment/81124542
downvote count: 1
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/81124489
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/47100105
has comment: http://stackoverflow.com/comment/81150548
has comment: http://stackoverflow.com/comment/81150375
tagged with: python
score: 4
has body: I am trying to emulate something written in Java in python. There is a symmetric encryption algorithm in the Java part, where key generation relies on Java long integers overflowing. I now need to do this in Python to be able to decrypt there. I did not write the encryption algorithm, and I cannot change that. This is part of the key generator function in Java: long a; long b; ... for (...) ... a = b + ((b &lt;&lt; 1) + (b &lt;&lt; 4) + (b &lt;&lt; 7) + (b &lt;&lt; 8) + (b &lt;&lt; 35)); Now when I copy this as it is to Python, I will receive massive numbers, as Python does what it is supposed to do and adds more bytes to my integer, while in Java the integers just keep overflowing and eventually a 64 bit key is returned. This is not the entirety of the code, it is actually a loop that keeps doing this and other things to a and b, so I cannot just take the highest 64 bits or something like that and treat that as my new a. However, I now need to emulate this behaviour in Python to get my decryption key. How do I do this in Python? Is it even possible, or do I need to rely on a C function for this part, and do the key generation there?
has answer: http://stackoverflow.com/a/47100158
has title: Forcing integer overflow in Python
has comment: http://stackoverflow.com/comment/81150428
has comment: http://stackoverflow.com/comment/81150771
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81150394
has answer: http://stackoverflow.com/a/47100309
possible better answer: http://stackoverflow.com/a/47100309
downvote count: 0
has comment: http://stackoverflow.com/comment/81150373
has comment: http://stackoverflow.com/comment/81150205
accepted answer: http://stackoverflow.com/a/47100158
favorite count: 0
type: Question
upvote count: 4
answer count: 2

http://stackoverflow.com/q/47100945
tagged with: python
tagged with: mouseevent
upvote count: 2
score: 2
downvote count: 0
has body: I am building a UI in Maya that when a button is clicked will generate a bunch of horizontal layouts containing widgets inside of a QScrollArea. I am trying to figure out how to get each row to recognize a single / double click. When a particular row is clicked, I would like it to return the widget that was clicked so that I can do something with it. I am thinking I will probably have to attach a container widget to the row layouts to recognize the mouse clicks? I have figured out how in general to recognize single and double clicks and have it print something - but I am having a hard time figuring out how to link that to a widget.
answer count: 1
tagged with: user-interface
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47102713
type: UnansweredQuestion
has title: Pyside: detecting single and double clicks on a QWidget
tagged with: pyside

http://stackoverflow.com/comment/81317740
score: 0
has text: You may want to look into a pivot query: http://buysql.com/mysql/12-how-to-pivot-tables.html
type: Comment
comment on: http://stackoverflow.com/q/47184102
type: QuestionComment

http://stackoverflow.com/comment/81409463
score: 0
type: AnswerComment
has text: Thanks ....But I know about the way you mentioned above like making a dictionary and pass all the values at one of key of the dictionary. I want only one dictionary to be passed in the function with many key and values and I can get all of them in a single variable in my template file. I don't know wheather it is possible or not ?
type: Comment
comment on: http://stackoverflow.com/a/47208143

http://stackoverflow.com/comment/81237108
type: Comment
comment on: http://stackoverflow.com/a/47143492
type: AnswerComment
has text: Great answer. Simple and intuitive.
score: 4

http://stackoverflow.com/a/55643196
score: 10
upvote count: 11
answers question: http://stackoverflow.com/q/47147328
downvote count: 1
has body: I'm not 100% certain it's the reason you're seeing this as you are using Windows, but I encountered this on Linux with Python 3.6 in a similar scenario. I was using .shutdown() on a concurrent.futures.ThreadPoolExecutor and the program would seem to hang up. Sometimes it would finally exit after 30-60 seconds. Ctrl-C always resulted in a traceback showing it was sitting in _wait_for_tstate_lock() Note: in Python 3 a second Ctrl-C actually exits My problem occurred when the function submitted was using time.sleep() in a loop. Looking at the HtmlFileTracer implementation in current nodepy code on github I see a similar scenario to what I was doing, (continuously loop and sleep for an interval unless some sort of flag was set)
type: Answer

http://stackoverflow.com/q/47165402
has answer: http://stackoverflow.com/a/47168501
has body: I am loading in a picture into a QGraphicsScene then when you click on the photo it will place circles in the area that is clicked. Then I am adding a custom widget that will keep a list of the points. This widget has a couple of buttons. one of them will be able to move the circle and the other will be to delete it. I am currently stuck on the delete part. Problem I can delete the circle just fine and I can delete the widget from the list. The problem is there is still a space in the list from where the widget once was and since I'm using the button from the widget and not selecting the item I'm not sure how to delete that spot. Also if I delete a bunch and then try and add some Python its self will crash and I have no idea why. I'm not sure if what I want can be done since there really is no reference or if I'm better off moving the buttons to the main window and removing them from the custom widget. If it is possible I would like to keep it the way I have it. There are a few files so I will put it on GitHub so I am not to take up a ton of space. Any help is much appreciated. GitHub Link Link to GitHub Project The relevant code (from Main.py): class MainWindow(QMainWindow, Ui_MainWindow): ... def Add_History(self,pos): self.HistoryWidget = HistoryList() self.HistoryWidget.setObjectName("HistoryWidget_"+ str(Constents.analysisCount)) myQListWidgetItem = QListWidgetItem(self.History_List) myQListWidgetItem.setSizeHint(self.HistoryWidget.sizeHint()) self.History_List.addItem(myQListWidgetItem) self.History_List.setItemWidget(myQListWidgetItem, self.HistoryWidget) self.HistoryWidget.buttonPushed.connect(self.deleteObject) self.HistoryWidget.setXpoint(str(pos.x())) self.HistoryWidget.setYpoint(str(pos.y())) self.HistoryWidget.setHistoryName("Point "+ str(Constents.analysisCount)) Constents.analysisCount = Constents.analysisCount + 1 def deleteObject(self): sender = self.sender() #var of object that sent the request row_number = sender.objectName().split("_") number = r…
type: AnsweredQuestion
tagged with: pyqt
has title: PyQt: removing custom widgets from a QListWidget
downvote count: 0
answer count: 1
tagged with: pyqt5
score: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: qlistwidget
accepted answer: http://stackoverflow.com/a/47168501
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/81383875
score: 0
has text: @Babaramdev, will you please try out mine snippet same way ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47216947

http://stackoverflow.com/q/47220115
has answer: http://stackoverflow.com/a/47452436
answer count: 1
has title: How to create Oracle database table with so many columns and same column datatype in python
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
upvote count: 0
tagged with: oracle-database
tagged with: database
tagged with: python
has body: I could not solve this problem for a week. I have a python list which containing headers. I would like to use these headers to create a table in Oracle database. The problem is that there are more than 50 headers. Also, there are more than 400 lists that I need to use to create tables. Also, all headers have same column datatype. I know how to do this job manually. However, if I do it manually, I am too stupid. So, I am looking for some ways that can do it automatically. I have been searched for one week. But I still could not find a solution. Please help me. Thank youuuuuuuuu.
score: -1
has comment: http://stackoverflow.com/comment/81429662
has comment: http://stackoverflow.com/comment/81390176
has comment: http://stackoverflow.com/comment/81389809

http://stackoverflow.com/comment/81242726
type: Comment
comment on: http://stackoverflow.com/a/47129693
type: AnswerComment
score: 1
has text: If you want to add the option to take input arguments that could be a list vs. various strings, you need to add logic that checks the length of args: `len(args)` and the type of args: `type(args[0]).__name__` in that order.

http://stackoverflow.com/comment/81193795
has text: This doesn't answer your question about growing a list, but `trainingSet1 = [random.choice(trainingSet) for _ in range(30)]` will do the same as your code.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47121745
type: QuestionComment

http://stackoverflow.com/q/47194496
downvote count: 0
upvote count: 1
answer count: 1
has body: I am trying to colour the points of a scatter graph with the data sourced from a pandas dataframe as follows: x = [5,7,12,0,19,56,40,16,36,17,81,50] y = [20,26,37,40,8,63,13,28,47,91,26,2] letter = ['A','B','C','D','E','F','E','B','A','C','F','D'] df = pd.DataFrame({'x' : x, 'y' : y,'letter' : letter}) I have also set up a lookup dictionary, to decide which colour is assigned to which value in the 'letter' column: letter_col = {'A':'blue', 'B':'red', 'C':'green', 'D':'yellow', 'E':'orange', 'F':'pink'} Using the colour argument (c=) of the pyplot scatter function, how do I set the colour of the point, using letter_col?
duplicate of: http://stackoverflow.com/q/27318906
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81338373
has answer: http://stackoverflow.com/a/47194748
type: AnsweredQuestion
has title: Python - Use lookup dictionary to set colour of pyplot scatter
score: 1
tagged with: matplotlib
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/27318906
accepted answer: http://stackoverflow.com/a/47194748

http://stackoverflow.com/a/47069555
answers question: http://stackoverflow.com/q/47069508
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: You can use dateutil.parser to parse dates and a min to compare them. Here is an example: In [1]: from dateutil.parser import parse In [4]: dates = ['2016-11-30T13:27:04-05:00', '2016-11-30T13:27:41-05:00', '2017-03-01T22:16:35-05:00'] In [5]: min([parse(s) for s in dates]) Out[5]: datetime.datetime(2016, 11, 30, 13, 27, 4, tzinfo=tzoffset(None, -18000))

http://stackoverflow.com/comment/81286342
type: Comment
has text: Thank you very much, I had not thought about it, you helped me a lot Thanks
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47164476

http://stackoverflow.com/comment/81119722
comment on: http://stackoverflow.com/q/47085092
type: Comment
type: QuestionComment
score: 0
has text: I found this issue when I trying practice something. I just can't find out what its mean.

http://stackoverflow.com/a/47125094
score: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47125076
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47125076
has body: df[df['ids'].str.contains("ball")] Would become: df[df['ids'].str.contains("ball") &amp; df['ids'].str.contains("field")] If you are into neater code: contains_balls = df['ids'].str.contains("ball") contains_fields = df['ids'].str.contains("field") filtered_df = df[contains_balls &amp; contains_fields]

http://stackoverflow.com/q/47211810
type: AnsweredQuestion
has title: How can `sdl2.SDL_GetKeyboardState` be used correctly?
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question
tagged with: pysdl2
tagged with: keyboard-input
tagged with: python
has answer: http://stackoverflow.com/a/47213235
has body: I'm attempting to use the python library pysdl2 to construct an emulator. The library has been working well so far, however I've been having problems receiving keyboard input. What I essentially needed to do is test if certain keys are pressed. After doing a bit of research, I discovered sdl2.SDL_GetKeyboardState which supposedly is the same SDL function as SDL_GetKeyboardState. Following the previously linked documentation and this article on the Lazy Foo' Productions website, I constructed the following script: import sdl2 sdl2.ext.init() window = sdl2.ext.Window('Test', size=(640, 480)) window.show() key_states = sdl2.SDL_GetKeyboardState(None) running = True while running: for event in sdl2.ext.get_events(): if event.type == sdl2.SDL_QUIT: running = False break if key_states[sdl2.SDL_SCANCODE_A]: print('A key pressed') window.refresh() The above code is suppose to detect if the a key is pressed and if so print a message out. When the above program is run, a window does appear, but when the a key is pressed, 'A key pressed' is printed over four thousand times. It does not continue to print the message, it only prints it once thousands of times, then stops. At first, I consider that the problem may have been that the key deduction code (lines 15-16) should be inside of the the event loop (lines 11-14). It worked to some degree. Rather than 'A key pressed' being printed out thousands of times per key press, it was only being printed out twice per key press. Is there a problem with my code? Am I missing something about how to correctly use the sdl2.SDL_GetKeyboardState function? How can I properly detect key presses?
tagged with: sdl-2
accepted answer: http://stackoverflow.com/a/47213235

http://stackoverflow.com/a/47187166
has body: It seems that some path is not set, but I'm not able to figure out which one. When you use Jython standalone jar, python.home should point to your Lib folder. Extract the Jython standalone jar, copy the 'Lib' folder to some location and point the python.home to that path. props.put("python.home", "/path/to/folder/Lib"); In order to install packages, copy it to the root of the Lib folder. Example in order to use package 'test_framework' paste it into Lib folder and use import test_framework to import the package. Also when you are using standalone jar, you don't need to set jython.home property
downvote count: 0
answers question: http://stackoverflow.com/q/47124649
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/81335642
score: 0
type: AnswerComment
has text: To see how this works out in your example, add `print('{0:.40f}'.format(x))` to your loop.
comment on: http://stackoverflow.com/a/47190264
type: Comment

http://stackoverflow.com/comment/81421884
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47173904
has text: Thanks a lot, Jezrael!!! I just tried your edited code and it works! I am very grateful to you!
type: Comment

http://stackoverflow.com/comment/81284298
score: 0
type: Comment
has text: Although looking in my python folders there's only 'C:\Python27\Lib\site-packages\pocketsphinx\model\en-us' - one en-us, but even changing to this path for the model doesn't work
comment on: http://stackoverflow.com/a/47122732
type: AnswerComment

http://stackoverflow.com/q/47158370
type: UnansweredQuestion
has title: Jupyter notebook cannot connect to Python kernel
has comment: http://stackoverflow.com/comment/81297116
tagged with: azure
tagged with: python
has comment: http://stackoverflow.com/comment/81276381
tagged with: jupyter-notebook
has body: Just created a Jupyter notebook on https://notebooks.azure.com for trying it out. When opening it, it seems the notebook cannot connect to the kernel (Python 3.6). I get the error: "A connection to the notebook server could not be established. The notebook will continue trying to reconnect. Check your network connection or notebook server configuration." When opening the browser (Chrome) console it says something like: "WebSocket connection failed: Error during WebSocket handshake: Incorrect 'Sec-WebSocket-Accept' header value" Any clues as to what this could be all about?
type: Question
score: 0
answer count: 0

http://stackoverflow.com/comment/81338979
has text: I used '~/Desktop/py.csv' and it works now thanks for suggestion
type: AnswerComment
comment on: http://stackoverflow.com/a/47194737
score: 0
type: Comment

http://stackoverflow.com/a/47280363
has comment: http://stackoverflow.com/comment/81551480
has body: Alright, first create a specific project directory for your docker image. For example: mkdir /home/pi/Desktop/teasr/capturing Copy your dockerfile and script in there and change the current context to this directory. cp /home/pi/Desktop/teasr/capturing.py /home/pi/Desktop/teasr/dockerfile /home/pi/Desktop/teasr/capturing/ cd /home/pi/Desktop/teasr/capturing This is for best practice, as the first thing the docker-engine does on build, is read the whole current context. Next we'll take a look at your dockerfile. It should look something like this now: FROM python:latest WORKDIR /usr/local/bin COPY capturing.py . CMD ["capturing.py", "-OPTIONAL_FLAG"] The next thing you need to do is build it with a smart name. Using dots is generally discouraged. docker build -t pulkit/capturing:1.0 . Next thing is to just run the image like you've done. docker run -ti --name capturing pulkit/capturing:1.0 The script now get executed inside the container and will probably exit upon completion. Edit after finding the problem that created the following error: standard_init_linux.go:195: exec user process caused "exec format error" There's a different architecture beneath raspberry pi's (ARM instead of x86_64), which COULD'VE BEEN the problem, but wasn't. If that would've been the problem, a switch of the parent image to FROM armhf/python would've been enough. Source BUT! The error kept occurring. So the solution to this problem is a simple missing Sha-Bang on top of the python script. The first line in the script needs to be #!/usr/bin/env python and that should solve the problem. Source
has comment: http://stackoverflow.com/comment/81642080
has comment: http://stackoverflow.com/comment/81519305
accepted answer of: http://stackoverflow.com/q/47202705
has comment: http://stackoverflow.com/comment/81519173
score: 34
downvote count: 1
has comment: http://stackoverflow.com/comment/81555151
has comment: http://stackoverflow.com/comment/81517146
has comment: http://stackoverflow.com/comment/81513976
has comment: http://stackoverflow.com/comment/81522775
has comment: http://stackoverflow.com/comment/81554217
has comment: http://stackoverflow.com/comment/81556615
answers question: http://stackoverflow.com/q/47202705
has comment: http://stackoverflow.com/comment/81643151
type: Answer
has comment: http://stackoverflow.com/comment/81515024
has comment: http://stackoverflow.com/comment/81554355
has comment: http://stackoverflow.com/comment/81555233
has comment: http://stackoverflow.com/comment/81513696
has comment: http://stackoverflow.com/comment/81562153
has comment: http://stackoverflow.com/comment/81522520
upvote count: 35
has comment: http://stackoverflow.com/comment/81639364
has comment: http://stackoverflow.com/comment/81519378
has comment: http://stackoverflow.com/comment/81518285
type: AcceptedAnswer

http://stackoverflow.com/comment/91393470
score: 0
comment on: http://stackoverflow.com/q/47120637
has text: Here is detailed example with latest tensorflow version 1.7 https://stackoverflow.com/a/52222383/5904928
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/81862679
score: 0
has text: Thanks the_storyteller for your contribution. But please note that the program isn't designed to output statements with regards to the input, be it integers or strings. If I cast it the way you said, it throws an error.
comment on: http://stackoverflow.com/a/47113727
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47124032
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81198473
has comment: http://stackoverflow.com/comment/81198130
has comment: http://stackoverflow.com/comment/81198393
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81198401
has comment: http://stackoverflow.com/comment/81198431
answers question: http://stackoverflow.com/q/47124007
has comment: http://stackoverflow.com/comment/81198276
has body: Create boolean mask and count it - Trues are process like 1: m1 = df == 1 m0 = df == 0 m_1 = df == -1 df['Sum1'] = m1.sum(1) df['Sum0'] = m0.sum(1) df['Sum_1'] = m_1.sum(1) print (df) a b c d e Sum1 Sum0 Sum_1 0 0 0 -1 1 -1 1 2 2 1 0 1 -1 1 -1 2 1 2 2 -1 0 -1 1 1 2 1 2 3 -1 1 1 -1 1 3 0 2 4 1 0 1 -1 1 3 1 1 5 1 0 0 0 1 2 3 0 6 1 1 0 0 -1 2 2 1 7 1 1 -1 0 0 2 2 1 General solution with get_dummies: df1 = (pd.get_dummies(df.astype(str), prefix='', prefix_sep='') .sum(level=0, axis=1) .add_prefix('Sum')) print (df1) Sum-1 Sum0 Sum1 0 2 2 1 1 2 1 2 2 2 1 2 3 2 0 3 4 1 1 3 5 0 3 2 6 1 2 2 7 1 2 2 df = df.join(df1) print (df) a b c d e Sum-1 Sum0 Sum1 0 0 0 -1 1 -1 2 2 1 1 0 1 -1 1 -1 2 1 2 2 -1 0 -1 1 1 2 1 2 3 -1 1 1 -1 1 2 0 3 4 1 0 1 -1 1 1 1 3 5 1 0 0 0 1 0 3 2 6 1 1 0 0 -1 1 2 2 7 1 1 -1 0 0 1 2 2 Idea for better performance of Zero solution - compare numpy array and instead static values is possible use unique values by numpy.unique: all_vals = np.unique(df.values) arr = df.values df1 = df.join(pd.DataFrame({'Sum{}'.format(v):(arr == v).sum(1) for v in all_vals})) print (df1) a b c d e Sum-1 Sum0 Sum1 0 0 0 -1 1 -1 2 2 1 1 0 1 -1 1 -1 2 1 2 2 -1 0 -1 1 1 2 1 2 3 -1 1 1 -1 1 2 0 3 4 1 0 1 -1 1 1 1 3 5 1 0 0 0 1 0 3 2 6 1 1 0 0 -1 1 2 2 7 1 1 -1 0 0 1 2 2 Timings np.random.seed(234) N = 100000 df = pd.DataFrame(np.random.randint(3, size=(N,5)), columns=list('abcde')) - 1 print (df) #wen's solution 1 In [49]: %timeit pd.concat([df,pd.get_dummies(df.astype(str).stack()).sum(level=0).add_prefix('Sum')],1) 1 loop, best of 3: 2.21 s per loop #wen's solution 2 In [56]: %timeit df.apply(lambda x : x.value_counts(),1).fillna(0) 1 loop, best of 3: 1min 35s per loop #jezrael's solution 2 In [50]: %timeit df.join((pd.get_dummies(df.astype(str), prefix='', prefix_sep='').sum(level=0, axis=1).add_prefix('Sum'))) 1 loop, best of 3: 2.14 s per loop #jezrael's solution 1 In [55]: %%timeit ...: m1 = df == 1 ...: m0 = df == 0 ...: m_1 = df == -1 ...: df['Sum1'] = m1.sum(1) ...: df['Sum…

http://stackoverflow.com/comment/81295669
comment on: http://stackoverflow.com/a/47172348
type: Comment
has text: It works! Thank you! And plt.pause(0.001), how can I change the 0.001 to make the real time faster?
type: AnswerComment
score: 0

http://stackoverflow.com/q/47142665
type: AnsweredQuestion
tagged with: performance
has title: How to improve performance when having a huge list of bytes to be written to file?
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81235747
has comment: http://stackoverflow.com/comment/81278876
type: Question
has answer: http://stackoverflow.com/a/47143238
has comment: http://stackoverflow.com/comment/81237374
has body: In python, I have a huge list of floating point values(nearly 30 million values). I have to convert each of them as 4 byte values in little endian format and write all those to a binary file in order. For a list with some thousands or even 100k of data, my code is working fine. But if the data increases, it is taking time to process and write to file. What optimization techniques can I use to write to file more efficiently? As suggested in this blog , I am replacing all the small writes to a file by the use of bytearray. But still, the performance is not satisfiable. Also I have tried multiprocessing (concurrent.futures.ProcessPoolExecutor()) to utilize all the cores in the system instead of using a single CPU core. But still it is taking more time to complete the execution. Can anyone give me more suggestions on how to improve the performance(in terms of time and memory) for this problem. Here is my code: def process_value (value): hex_value = hex(struct.unpack('&lt;I', struct.pack('&lt;f', value))[0]) if len(hex_value.split('x')[1]) &lt; 8: hex_value = hex_value[:2] + ('0' * (8 - len(hex_value.split('x')[1]))) + hex_value[2:] dec1 = int( hex_value.split('x')[1][0] + hex_value.split('x')[1][1], 16) dec2 = int(hex_value.split('x')[1][2]+hex_value.split('x')[1][3],16) dec3 = int(hex_valur.split('x')[1][4]+hex_value.split('x')[1][5],16) dec4 = int(hex_value.split('x')[1][6]+hex_value.split('x')[1][7],16) msg = bytearray( [dec4,dec3,dec2,dec1] ) return msg def main_function(fp, values): msg = bytearray() for val in values: msg.extend (process_value(val)) fp.write(msg)
upvote count: 0
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/81235515
has comment: http://stackoverflow.com/comment/81237020
accepted answer: http://stackoverflow.com/a/47143238
favorite count: 0
tagged with: optimization
has comment: http://stackoverflow.com/comment/81237251

http://stackoverflow.com/comment/81198301
type: Comment
score: 0
type: AnswerComment
has text: Thank you!! But actually I need distinct location visited (Latitude, Longitude) VS time.. not ID
comment on: http://stackoverflow.com/a/47123747

http://stackoverflow.com/a/47111123
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47110884
has body: What is the port number you are using , you should use 21 as port number. Then client can detect it as FTP If you are using other than 21 , in wireshark you have to decode port number as 21(Wireshark --> Analyze --> Decode as --> Give your port number and decode as which protocol)
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/47110884

http://stackoverflow.com/a/47242300
answers question: http://stackoverflow.com/q/47094900
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/47094900
has body: In your customScrape function, you can do this for every link: ref_html = requests.get(link).text to get the complete text from link (you don't need a Session unless you want to save cookies and other stuff between subsequent requests). You can then parse ref_html to find title or first heading or whatever you like. Your function could look like this: import requests, requests.exceptions from bs4 import BeautifulSoup def custom_scrape(wikipedia_url): wikipedia_html = requests.get(wikipedia_url).text refs = BeautifulSoup(wikipedia_html, 'html.parser').find('ol', { 'class': 'references' }) refs = refs.select('a["class"]') for ref in refs: try: ref_html = requests.get(ref['href']).text title = heading = BeautifulSoup(ref_html, 'html.parser') title = title.select('title') title = title[0].text if title else '' heading = heading.select('h1') heading = heading[0].text if heading else '' except requests.exceptions.RequestException as e: print(ref['href'], e) # some refs may contain invalid urls title = heading = '' yield title.strip(), heading.strip() # strip whitespace You can then go through the results: for title, heading in custom_scrape('https://en.wikipedia.org/wiki/Stack_Overflow'): print(title, heading)
type: Answer
upvote count: 4

http://stackoverflow.com/comment/81267709
type: AnswerComment
score: 1
has text: ``np.random.shuffle`` is in-place, so is likely better if you have a big array to reorder. However if you cannot make it work for mutiple arrays, the in-place bonus doesn't help. For the records: also the solution from @cardamom is not in-place.
type: Comment
comment on: http://stackoverflow.com/a/47156309

http://stackoverflow.com/a/47181204
upvote count: 1
has comment: http://stackoverflow.com/comment/81311674
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81311308
has body: This one should work, if you had issue with yours: [(+\d]\d[-\d\s()]*\d
answers question: http://stackoverflow.com/q/47181008
has comment: http://stackoverflow.com/comment/81311574
downvote count: 0

http://stackoverflow.com/comment/81171191
comment on: http://stackoverflow.com/a/47107064
score: 1
type: Comment
type: AnswerComment
has text: Thanks. Same problem. I copied your code as is, removing comments. It's working when I visit the actual `CreateView` URL (displays error, redirects on success, saves model), but when invoking the modal it doesn't display at all, get the same screen as before.

http://stackoverflow.com/comment/81270416
type: QuestionComment
score: 0
has text: Sample pareto value, multiply by Xm
comment on: http://stackoverflow.com/q/47158685
type: Comment

http://stackoverflow.com/comment/92501957
type: AnswerComment
comment on: http://stackoverflow.com/a/47070974
score: 0
type: Comment
has text: What if I don't want to groupby ?

http://stackoverflow.com/comment/81084527
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47068261
has text: it should be; `for currlist in mylist: for i in currlist: if i in stops:` right? :)

http://stackoverflow.com/comment/81120341
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47085392
type: QuestionComment
has text: there's an else without an if statement to start....

http://stackoverflow.com/comment/81111727
type: AnswerComment
comment on: http://stackoverflow.com/a/47069463
score: 0
type: Comment
has text: Oh my. I would bet large amounts of money that this is not the best solution to OP's problem.

http://stackoverflow.com/comment/81102166
has text: What is the output of `ls directory/*.jpg` ? What's the directory name where the files reside?
comment on: http://stackoverflow.com/q/47076736
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47081841
has body: Yes, but by using __format__, not __fstr__. f-strings were not an overhaul of the previous methods to format strings. Instead, it built on the protocols already in place. From PEP 0498 that introduced them, in Code equivalence: The exact code used to implement f-strings is not specified. However, it is guaranteed that any embedded value that is converted to a string will use that value's __format__ method. This is the same mechanism that str.format() uses to convert values to strings. and then again, in Format Specifiers: Once expressions in a format specifier are evaluated (if necessary), format specifiers are not interpreted by the f-string evaluator. Just as in str.format(), they are merely passed in to the __format__() method of the object being formatted. So, there's no new special method for them. You need to define a __format__ method that takes the spec and returns an appropriately formatted string. As the docs on __format__ also describe: Called by the format() built-in function, and by extension, evaluation of formatted string literals and the str.format() method, to produce a “formatted” string representation of an object.
answers question: http://stackoverflow.com/q/47081521
downvote count: 0
type: AcceptedAnswer
score: 14
upvote count: 14
accepted answer of: http://stackoverflow.com/q/47081521
type: Answer

http://stackoverflow.com/comment/93187323
comment on: http://stackoverflow.com/a/49787479
type: Comment
type: AnswerComment
score: 0
has text: I think you should upgrade from using the packages tensorflow.contrib.learn such as Experiment, and use Estimators or Keras. These packages will be deprecated soon. Then it will make more sense where to insert his snipped or when to use tf.summary.scalar in general.

http://stackoverflow.com/q/47114257
linked to: http://stackoverflow.com/q/15773868
type: UnansweredQuestion
tagged with: python
score: 0
has title: Check multiple users for being admin in windows
answer count: 1
has answer: http://stackoverflow.com/a/47114316
type: Question
has body: I have a list of users and I want to create a python script to check if any of the users has windows admin privileges. I have tried the ctypes lib but apparently it only checks for the current user. import ctypes lst = ['Administrator','test','Guest'] for i in lst: print ctypes.windll.shell32.IsUserAnAdmin(i) Thanks.

http://stackoverflow.com/a/47065107
type: Answer
answers question: http://stackoverflow.com/q/47064885
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/47064885
has body: You can refer this code: def find_factor(n): factor_values = [] for i in range(1, n + 1): if n % i == 0: factor_values.append(i) values = "" for v in factor_values: values += str(v) + " " return values The function will return 1 2 3 6

http://stackoverflow.com/q/47091529
has answer: http://stackoverflow.com/a/47095939
tagged with: apache-spark
downvote count: 0
has body: Suppose I have a SparseVector and I want to sum its values, e.g. v = SparseVector(15557, [3, 40, 45, 103, 14356], np.ones(5)) v.values.sum() 5.0 This works well. Now I want to do the same thing by means of a udf, because I have a DataFrame with a column of SparseVector. Here I get an error I don't understand: from pyspark.sql import functions as f def sum_vector(vector): return vector.values.sum() sum_vector_udf = f.udf(lambda x: sum_vector(x)) sum_vector_udf(v) ---- AttributeError Traceback (most recent call last) &lt;ipython-input-38-b4d44c2ef561&gt; in &lt;module&gt;() 1 v = SparseVector(15557, [3, 40, 45, 103, 14356], np.ones(5)) 2 ----&gt; 3 sum_vector_udf(v) 4 #v.values.sum() ~/anaconda3/lib/python3.6/site-packages/pyspark/sql/functions.py in wrapper(*args) 1955 @functools.wraps(f) 1956 def wrapper(*args): -&gt; 1957 return udf_obj(*args) 1958 1959 wrapper.func = udf_obj.func ~/anaconda3/lib/python3.6/site-packages/pyspark/sql/functions.py in __call__(self, *cols) 1916 judf = self._judf 1917 sc = SparkContext._active_spark_context -&gt; 1918 return Column(judf.apply(_to_seq(sc, cols, _to_java_column))) 1919 1920 ~/anaconda3/lib/python3.6/site-packages/pyspark/sql/column.py in _to_seq(sc, cols, converter) 58 """ 59 if converter: ---&gt; 60 cols = [converter(c) for c in cols] 61 return sc._jvm.PythonUtils.toSeq(cols) 62 ~/anaconda3/lib/python3.6/site-packages/pyspark/sql/column.py in &lt;listcomp&gt;(.0) 58 """ 59 if converter: ---&gt; 60 cols = [converter(c) for c in cols] 61 return sc._jvm.PythonUtils.toSeq(cols) 62 ~/anaconda3/lib/python3.6/site-packages/pyspark/sql/column.py in _to_java_column(col) 46 jcol = col._jc 47 else: ---&gt; 48 jcol = _create_column_from_name(col) 49 return jcol 50 ~/anaconda3/lib/python3.6/site-packages/pyspark/sql/column.py in _create_column_from_name(name) 39 def _create_column_from_name(name): 40 sc = SparkContext._active_spark_context ---&gt; 41 return sc._jvm.functions.col(name) 42 43 ~/anaconda3/lib/python3.6/site-packages/py4…
upvote count: 1
answer count: 1
favorite count: 0
type: Question
has title: Pyspark: sum error with SparseVector
tagged with: user-defined-functions
type: UnansweredQuestion
score: 1
tagged with: pyspark
tagged with: python
tagged with: numpy

http://stackoverflow.com/q/47065468
answer count: 1
linked to: http://stackoverflow.com/q/15112125
has comment: http://stackoverflow.com/comment/81079258
accepted answer: http://stackoverflow.com/a/47065493
type: AnsweredQuestion
has body: i am new with python and i am trying to make a survey but when i write this code things don't go well this is the first part of my very long survey: #a program to test your adhd yes=1 YES=1 Yes=1 no=0 NO=0 No=0 print("please honestly answer the following questions","\n" "with \"yes\" or \"no\" ") a=input("1. do you have difficulty getting organized ?")#q1 if a==yes or YES or Yes or no or NO or No: b=input("2. When given a task, you usually procrastinate rather than doing it right away")#q2 else: print("wrong answer") a=input("1. do you have difficulty getting organized ?")#q1 the idea of this is when the user write one of the true answers the program move to the next question. and if he wrote other things the program print wrong answer and repeat the question. but when tested with python shell and c.m.d it never consider the (else statement) note that: i don't know many things in python (besides if and else statements) yet as i am at the very beginning on learning steps.
tagged with: if-statement
tagged with: python
has title: What is wrong with these if and else statements?
type: Question
has answer: http://stackoverflow.com/a/47065493
score: 0
has comment: http://stackoverflow.com/comment/81079223
duplicate of: http://stackoverflow.com/q/15112125
has comment: http://stackoverflow.com/comment/81079262

http://stackoverflow.com/a/47068882
has comment: http://stackoverflow.com/comment/81099706
has body: Using pdfimages from poppler-utils You might want to take a look at pdfimages from the poppler-utils package. I have taken the sample pdf from - Sample PDF On running the following command, images present in the pdf are extracted - pdfimages /home/tata/Desktop/4555c-5055cBrochure.pdf image Some of the images extracted from this brochure are - Extracted Image1 Extracted Image 2 So, you can use python's subprocess module to execute this command, and then extract all the images. Note: There are some drawbacks to this method. It generates images in ppm format, not jpg. Also, some additional images might be extracted, which might actually not be images in the pdf. Using pdfminer If you want to do this using pdfminer, take a look at this blog post - Extracting Text &amp; Images from PDF Files Pdfminer allows you to traverse through the layout of a particular pdf page. The following image shows the layout objects as well as the tree structure generated by pdfminer - Layout Objects and Tree Structure Image Source - Pdfminer Docs Thus, extracting LTFigure objects can help you extract / count images in the pdf document. Note: Please note that both of these methods might not be accurate, and their accuracy is highly dependent on the type of pdf document you are dealing with.
type: Answer
has comment: http://stackoverflow.com/comment/81094390
answers question: http://stackoverflow.com/q/47067456
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/47119960
has body: Fairly certain easier way to do what you are asking. Something along the lines of: def raise_email(self, e): SendEmail() raise e
score: 0
answers question: http://stackoverflow.com/q/47119868
type: Answer

http://stackoverflow.com/a/47103531
has body: You can simply use regex : Short: import re string = """'['1' ,'2', '3']'""" pattern=r'(\d.*?)' match=re.finditer(pattern,string) print([int(integer.group()) for integer in match]) Detailed: import re string = """'['1' ,'2', '3']'""" pattern=r'(\d.*?)' int_list=[] match=re.finditer(pattern,string) for integer in match: int_list.append(int(integer.group())) print(int_list) output: [1, 2, 3] and as you said: so I can add each int together in the list to get an output of 6 then: print(sum([int(integer.group()) for integer in match])) output: 6
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47103377
type: Answer

http://stackoverflow.com/a/47071931
has comment: http://stackoverflow.com/comment/81093125
has comment: http://stackoverflow.com/comment/81092461
accepted answer of: http://stackoverflow.com/q/47071869
has comment: http://stackoverflow.com/comment/81092224
has comment: http://stackoverflow.com/comment/81092787
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81092187
answers question: http://stackoverflow.com/q/47071869
downvote count: 0
upvote count: 7
has comment: http://stackoverflow.com/comment/81091954
has comment: http://stackoverflow.com/comment/81092134
has body: You can use the built-in sum() function like this: num = int(input("Insert number: ")) s = sum(range(1, num+1, 2)) range() takes start (inclusive), end (exclusive), and step (In our case: start=1, end=num+1 and step=2) Output: &gt;&gt;&gt; num = 9 &gt;&gt;&gt; s = sum(range(1, num+1, 2)) &gt;&gt;&gt; s 25 If using while is a requirement, then you can achieve the same result with: &gt;&gt;&gt; s = 0 &gt;&gt;&gt; i = 1 &gt;&gt;&gt; while i &lt; num + 1: ... if i % 2: # Or: i % 2 != 0, which means we only consider odd nums ... s += i ... i += 1 ... &gt;&gt;&gt; s 25
has comment: http://stackoverflow.com/comment/81092188
has comment: http://stackoverflow.com/comment/81093271
score: 7
type: Answer

http://stackoverflow.com/comment/81194051
score: 0
has text: @Miraj50 This is just a part of the question.There can be any number of values in the list
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47122201

http://stackoverflow.com/comment/81078276
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47064968
has text: `return set_player_weapon() [Previous line repeated 995 more times] RecursionError: maximum recursion depth exceeded`
score: 0

http://stackoverflow.com/comment/89489388
score: 1
type: Comment
type: QuestionComment
has text: Yeah, haha. Guess my silly question helps someone.
comment on: http://stackoverflow.com/q/47117884

http://stackoverflow.com/q/47132104
has title: Django - runserver error- value error: source code string cannot contain null bytes
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/108413191
has comment: http://stackoverflow.com/comment/81214577
has body: I just started learning django and I was trying out some tutorials online. Please help. This is just a small web app the accepts user input and displays it on the message board. I am using windows and django 1.11.7. I use sublime text editor for python. I am not sure whAt the error means. If somebody could help, it would be of great help. This is the error that I got: ` Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x03BF8F18&gt; Traceback (most recent call last): File "C:\dev\message_board\mb\lib\site-packages\django\utils\autoreload.py", l ine 228, in wrapper fn(*args, **kwargs) File "C:\dev\message_board\mb\lib\site-packages\django\core\management\command s\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\dev\message_board\mb\lib\site-packages\django\core\management\base.py ", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\dev\message_board\mb\lib\site-packages\django\core\management\base.py ", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\dev\message_board\mb\lib\site-packages\django\core\checks\registry.py ", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\dev\message_board\mb\lib\site-packages\django\core\checks\urls.py", l ine 16, in check_url_config return check_resolver(resolver) File "C:\dev\message_board\mb\lib\site-packages\django\core\checks\urls.py", l ine 26, in check_resolver return check_method() File "C:\dev\message_board\mb\lib\site-packages\django\urls\resolvers.py", lin e 254, in check for pattern in self.url_patterns: File "C:\dev\message_board\mb\lib\site-packages\django\utils\functional.py", l ine 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\dev\message_board\mb\lib\site-packages\django\urls\resolvers.py", lin e 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\dev\message_board\mb\lib\sit…
has comment: http://stackoverflow.com/comment/81213937
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/81213699
upvote count: 4
has comment: http://stackoverflow.com/comment/81213769
answer count: 0

http://stackoverflow.com/a/55815126
score: 2
has body: This is a very late answer so I assume is no longer relevant to the Original Poster but I came across the post whilst trying to find an existing implementation of what I describe below. It sounds like you are looking for something like a Latin Hypercube: https://en.wikipedia.org/wiki/Latin_hypercube_sampling. Essentially if I have n variables and I want 10 samples then the range of each variable is split into 10 intervals and the possible values for each variable are (e.g.) the middle points of each interval. A Latin hypercube algorithm picks samples at random in such a way that each of the 10 values for each variable appears only once. The example in Warren's answer is an example of a Latin Hypercube. This doesn't help to cover the search space as well as possible (or in other words to check if the design is space filling). There is a criterion from Morris and Mitchell's 1995 paper Exploratory designs for computational experiments which calculates how space filling a sample is by looking at the distance between points. You can create a large number of different Latin Hypercube Designs and then use the criterion to choose the best, or take an initial design and manipulate it to give a better design. The latter is implemented in the algorithm here: https://github.com/1313e/e13Tools/blob/master/e13tools/sampling/lhs.py They give some examples in the code, e.g. for 5 points and 2 variables: import numpy as np np.random.seed(0) lhd(5, 2, method='fixed') returns something like array([[ 0.5 , 0.75], [ 0.25, 0.25], [ 0. , 1. ], [ 0.75, 0.5 ], [ 1. , 0. ]]) This will give the Latin Hypercube scaled on the interval [0, 1] so you would need to unscale to the range of your parameters using, for example https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html Here's an example of one of the outputs I get when I run the above code: This one is pretty good at space-filling according to the Morris-Mitchell criterion.
downvote count: 0
answers question: http://stackoverflow.com/q/47139515
upvote count: 2
type: Answer

http://stackoverflow.com/a/70601744
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47193745
has body: It is response from HTTP request. If this is a REST API that you are making a call to, you can convert the response to JSON by calling r.json().
has comment: http://stackoverflow.com/comment/124875697

wcf
tags question: http://stackoverflow.com/q/47143037
type: Tag
tag name: wcf

http://stackoverflow.com/comment/81337492
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47193745
has text: `r` is of type `requests.models.Response`... what is your question?
score: 0

http://stackoverflow.com/a/47114728
answers question: http://stackoverflow.com/q/47114687
downvote count: 0
upvote count: 1
score: 1
has body: don't ever use regexes to parse structured data like this. Once parsed with proper means (json.loads or ast.literal_eval both work here), they become native python structure, trivial to access to. In your case, using json.loads in one line: import json print(json.loads('{"address": "1GocfVCWTiRViPtqZetcX4UiCxnKxgTHwK", "balance": 1234, "pending_balance": 0, "paid_out": 0}')["balance"]) result: 1234 (same method applies for your second question)
type: Answer

http://stackoverflow.com/q/47100107
tagged with: web-scraping
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81150419
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47100534
downvote count: 2
tagged with: pytest
has body: I am building a web scraper in Python. So far I've been testing it with a real website, but I'd like to have a proper test suite, ideally run via pytest. Any ideas/examples how to do it? I imagine the test would spin up a mini http server serving a couple of pages (presumably in a separate process), run my scraper by calling one of its API functions, check the results and then shut down the server. What's the easiest way to achieve that? EDIT: I will describe the specific solution here that I found in case it is useful for somebody (certainly not the moderators who closed the question as too broad without trying to discuss or ask for details, they're not interested). In my (Python 3) code I was initially using urllib.request. After spending some time searching on the internets I found the excellent httmock, but that library mocks requests, it doesn't work with urllib.request. So, I reworked my code to use requests and then I could happily use httmock in my tests. Both requests and httmock are absolutely brilliant, highly recommended.
has comment: http://stackoverflow.com/comment/105153747
upvote count: 1
answer count: 1
has title: Python: functional testing of a web scraper

http://stackoverflow.com/comment/139492596
type: Comment
has text: As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
type: AnswerComment
comment on: http://stackoverflow.com/a/79099565
score: 0

http://stackoverflow.com/q/47201227
linked to: http://stackoverflow.com/q/16424493
tagged with: python
tagged with: jupyter-notebook
type: Question
linked to: http://stackoverflow.com/q/11707586
downvote count: 0
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/47201262
has title: Jupyter Notebook Ipython: Groupby based on the values alphabetically
accepted answer: http://stackoverflow.com/a/47201262
favorite count: 0
type: AnsweredQuestion
has body: I am using jupyter notebook first time. I tried to groupby one column of csv and get the count of the values. i got the below result with this code. import pandas pandas.read_csv('a.csv', sep=',') df.groupby('name').name.count() name >Aa 4 >Aachen 5 >Aartselaar 1 >Abadan 1 >Abaya 1 >Abba 12 >Abbey 2 >Abbeydale 1 >Abbot 2 >Abbots 3 >Abbotsford 22 >Abbotsinch 5 >Abbotts 1 >Abel 1 >Aberchirder 2 >Aberdare 3 >Aberdeen 1 >Aberdeen 163 >Aberdeenshire 286 >Aberdour 9 >Aberfan 1 >Aberfeldy 16 >Abergavenny 4 >Aberlady 1 >Aberlady 3 >Abernethy 1 >Abertay 1 >Abertillery 6 >Abha 2 >Abidjan 10 ... >Zakho 20 >Zakopane 1 >Zambezi 2 >Zambezi 8 >Zambia 19 >Zamboanga 4 >Zandak 3 >Zanzibar 11 >Zaragosa 1 >Zaragoza 4 >Zeebrugge 28 >Zeeland 2 >Zemun 1 >Zenica 12 >Zermatt 5 >Zetland 1 >Zhizhong 1 >Zhongshan 2 >Zhuhai 1 >Zimbabwe 377 >Znamenskoye 1 >Zoetermeer 1 >Zola 1 >Zomba 3 >Zulu 1 >Zululand 2 >Zuni 2 >Zurich 86 >Zvornik 3 >Zwolle 1 Name: name, Length: 8585, dtype: int64 is it possible to get the counts alphabet by alphabet, first I should run the command with alphabet a and it should give all values with a then next b and so on. or if it's possible to get the values skipping starting 100 values. My real data looks like this: Aldershot Amiens Alaska Amiens Amsterdam Alabama Ally Algiers Amsterdam Amsterdam
tagged with: pandas-groupby
tagged with: pandas
score: 1

http://stackoverflow.com/q/47152691
score: 630
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/74190430
linked to: http://stackoverflow.com/q/28337117
tagged with: pandas
tagged with: pivot
linked to: http://stackoverflow.com/q/34702815
has answer: http://stackoverflow.com/a/73060100
has answer: http://stackoverflow.com/a/62219652
upvote count: 636
linked to: http://stackoverflow.com/q/44229489
has title: How can I pivot a dataframe?
linked to: http://stackoverflow.com/q/42708193
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/131718268
has comment: http://stackoverflow.com/comment/130971141
accepted answer: http://stackoverflow.com/a/47152692
answer count: 5
tagged with: pivot-table
possible better answer: http://stackoverflow.com/a/62219652
tagged with: group-by
has answer: http://stackoverflow.com/a/47152692
has comment: http://stackoverflow.com/comment/132326656
has answer: http://stackoverflow.com/a/66237613
tagged with: python
linked to: http://stackoverflow.com/q/11400181
has body: How do I pivot the pandas dataframe df defined at bottom such that the col values become columns, row values become the index, and mean of val0 becomes the values? (in some cases this is called transforming from long-format to wide-format) (See note at bottom: Why is this question not a duplicate? and why this is thematically one question and not too broad.) Subquestions (How to avoid getting ValueError: Index contains duplicate entries, cannot reshape?) How do I pivot df defined at bottom, such that the col values become columns, row values become the index, and mean of val0 are the values? col col0 col1 col2 col3 col4 row row0 0.77 0.605 NaN 0.860 0.65 row2 0.13 NaN 0.395 0.500 0.25 row3 NaN 0.310 NaN 0.545 NaN row4 NaN 0.100 0.395 0.760 0.24 How do I pivot... ... so that missing values are 0? col col0 col1 col2 col3 col4 row row0 0.77 0.605 0.000 0.860 0.65 row2 0.13 0.000 0.395 0.500 0.25 row3 0.00 0.310 0.000 0.545 0.00 row4 0.00 0.100 0.395 0.760 0.24 ... to do an aggregate function other than mean, like sum? col col0 col1 col2 col3 col4 row row0 0.77 1.21 0.00 0.86 0.65 row2 0.13 0.00 0.79 0.50 0.50 row3 0.00 0.31 0.00 1.09 0.00 row4 0.00 0.10 0.79 1.52 0.24 ... to do more that one aggregation at a time? sum mean col col0 col1 col2 col3 col4 col0 col1 col2 col3 col4 row row0 0.77 1.21 0.00 0.86 0.65 0.77 0.605 0.000 0.860 0.65 row2 0.13 0.00 0.79 0.50 0.50 0.13 0.000 0.395 0.500 0.25 row3 0.00 0.31 0.00 1.09 0.00 0.00 0.310 0.000 0.545 0.00 row4 0.00 0.10 0.79 1.52 0.24 0.00 0.100 0.395 0.760 0.24 ... to aggregate over multiple 'value' columns? val0 val1 col col0 col1 col2 col3 col4 col0 col1 col2 col3 col4 row row0 0.77 0.605 0.000 0.860 0.65 0.01 0.745 0.00 0.010 0.02 row2 0.13 0.000 0.395 0.500 0.25 0.45 0.000 0.34 0.440 0.79 row3 0.00 0.310 0.000 0.545 0.00 0.00 0.230 0.00 0.075 0.00 row4 0.00 0.100 0.395 0.760 0.24 0.00 0.070 0.42 0.300 0.46 ... to subdivide by multiple columns? (item0,item1,item2..., col0,col1,col2...) item item0 item1 item2 col col2 co…
downvote count: 6

http://stackoverflow.com/comment/81173908
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47112019
has text: You are really good at this kind of answers. This one `df.gt(0).diff().ne(0).cumsum()` alone deserves more votes

http://stackoverflow.com/q/47206593
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47206594
type: UnansweredQuestion
has title: Scrapy interpreting html entities on extract
tagged with: python
score: 1
downvote count: 0
answer count: 1
has body: During a crawling, I captured links usually that way: response.xpath("//a[contains(@class, something)/@href").extract() But for some reason in that specific page was not working. What I was receiving in the array was something like this: ['details?lm==true=1=A43', (...)] The correct output should be: ['details?lm=&amp;printerView=true&amp;accessType=1&amp;id=A43', (...)]
upvote count: 1
tagged with: scrapy

http://stackoverflow.com/q/47113190
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81176250
tagged with: flask
score: 0
has title: Linking a route to a class in Flask
answer count: 0
has comment: http://stackoverflow.com/comment/81176358
has comment: http://stackoverflow.com/comment/81176196
type: Question
has body: I'm looking at an open source app https://github.com/AlvinCJin/deepfit-app/tree/master/app This is using flask-admin for admin purposes/ On the page https://github.com/AlvinCJin/deepfit-app/blob/master/app/main/views.py: # admin management setup admin.add_view(ModelView(User, db.session)) admin.add_view(ModelView(Post, db.session)) path = op.join(os.path.abspath(__file__ + "/../../"), 'static') # need to get parent path of this code admin.add_view(FileAdmin(path, '/static/', name='Static Files')) This works fine as far as producing a helpful dashboard but is unsecured. I have flask-login installed and I read the section http://flask-admin.readthedocs.io/en/latest/introduction/#rolling-your-own , but it is unclear to me how to link the class discussed: class MicroBlogModelView(sqla.ModelView): def is_accessible(self): return login.current_user.is_authenticated def inaccessible_callback(self, name, **kwargs): # redirect to login page if user doesn't have access return redirect(url_for('login', next=request.url)) with the admin route. I'm used to the idea of linking routes to module functions in flask , but not classes. How can this be done?
has comment: http://stackoverflow.com/comment/81184573

http://stackoverflow.com/comment/81217765
comment on: http://stackoverflow.com/q/47130865
score: 0
type: Comment
type: QuestionComment
has text: Good and think to add your solution bellow.

http://stackoverflow.com/comment/81160251
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47104697
has text: Ok, I get histogram in this way. I also fixed FutureWarning: sort(columns=....) is deprecated, use sort_values(by=.....) part.

http://stackoverflow.com/a/64156572
answers question: http://stackoverflow.com/q/47202705
downvote count: 0
has body: its very simple 1- go to your Python script directory and create a file with this title without any extension Dockerfile 2-now open the docker file and write your script name instead of sci.py ( content of Dockerfile ) FROM python:slim #i choice slim version you can choose another tag for example python:3 WORKDIR /usr/local/bin COPY sci.py . #replace you scrip name with sci.py CMD [ "python", "sci.py" ] #replace you scrip name with sci.py save it and now you should create image file from this dockerfile and script py and next run it 3-in path address folder write CMD and press Enter key : 4-When the cmd window opens for you, type in it : docker build -t my-python-app . #this create image in docker by this title my-python-app 5- and findly run image: docker run -it --rm --name my-running-app my-python-app
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/47090329
score: 11
upvote count: 11
has comment: http://stackoverflow.com/comment/138530319
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47090309
has body: Need DataFrame from Series by to_frame and transpose: a = pd.concat([df, sr.to_frame(1).T]) print (a) a b 1 1 2 Detail: print (sr.to_frame(1).T) a b 1 1 2 Or use setting with enlargement: df.loc[1] = sr print (df) a b 1 1 2
answers question: http://stackoverflow.com/q/47090309
type: Answer

http://stackoverflow.com/comment/81324382
comment on: http://stackoverflow.com/q/47187441
score: 0
type: Comment
type: QuestionComment
has text: `con.rollback()` and `render_template("result.html",msg = msg)` *is* calling another function ;)

http://stackoverflow.com/a/47136484
has body: Use rename_axis for name of column from index and reset_index: df = df.value_counts().rename_axis('unique_values').reset_index(name='counts') print (df) unique_values counts 0 2 3 1 1 2 Or if need one column DataFrame use Series.to_frame: df = df.value_counts().rename_axis('unique_values').to_frame('counts') print (df) counts unique_values 2 3 1 2
answers question: http://stackoverflow.com/q/47136436
accepted answer of: http://stackoverflow.com/q/47136436
has comment: http://stackoverflow.com/comment/124468059
has comment: http://stackoverflow.com/comment/98674504
type: Answer
score: 242
has comment: http://stackoverflow.com/comment/139147512
upvote count: 242
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47220475
upvote count: 1
answers question: http://stackoverflow.com/q/47217219
score: 1
type: Answer
has body: Check this if this gives correct result (result may be in different format) for you I am not sure btw :) z = {} q1 = OrderExtra.objects.all() for q in q1: # Get time difference in minutes for this order diff = q.order.datetime_end - q.order.datetime_begin diffm = diff.seconds / 60 #check if store is already updated to z check = z.get(q.store.title, 'error') # if NOT add storeName as key and c= Counter, a = Avg date-time diff if check == 'error': z.update({q.store.title:{'c':1, 'd':diffm, 'a': diffm}}) # If Available calculate avg with counter and total diff else: avgm = (( diffm + z[q.store.title]['d'] ) // (z[q.store.title]['c'] + 1)) z[q.store.title]['a'] = avgm z[q.store.title]['d'] = diffm + z[q.store.title]['d'] z[q.store.title]['c'] = z[q.store.title]['c'] + 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47217219
downvote count: 0

http://stackoverflow.com/comment/81125521
has text: You should probably outsource this task to ImageMagick.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47087953
type: QuestionComment

http://stackoverflow.com/comment/81268727
has text: separate by comma and the perform cleaning to each element... I thing this work for you.
comment on: http://stackoverflow.com/q/47159416
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81312954
score: 0
has text: If you're asking a debugging question then you must provide an example which is the **smallest amount of code which can reliably produce the problem**, please review [this guide](https://stackoverflow.com/help/mcve) and amend.
comment on: http://stackoverflow.com/q/47182049
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47167874
type: UnansweredQuestion
has title: Python Tkinter return menu label as string
answer count: 1
tagged with: python
score: -1
tagged with: label
has answer: http://stackoverflow.com/a/47168344
upvote count: 0
tagged with: return-value
downvote count: 1
has body: I am trying to somehow return the value of the current menu label using tkinter and python code. I want to dynamically update editmenu depending on the number of serial ports being used, but I am not sure what to do. I have tried using list[x].device already, but when the function is called, it uses a past value of x (as expected really, so this doesn't work). Does anyone have any ideas? Thanks! editmenu = Menu(menubar, tearoff=0) list = serial.tools.list_ports.comports() for x in range(0, len(list)): editmenu.add_command(label=list[x].device, command=lambda:app.setPort()) menubar.add_cascade(label="Port", menu=editmenu)
tagged with: menu
favorite count: 0
type: Question
tagged with: tkinter

http://stackoverflow.com/q/47211584
accepted answer: http://stackoverflow.com/a/47289777
has answer: http://stackoverflow.com/a/47289777
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81435210
has title: Signed URLs on GAE with Python for GCS PUT request
tagged with: google-app-engine
upvote count: 5
tagged with: python
tagged with: google-cloud-storage
has body: I'm trying to create a signed URL to be used for uploading files directly to Google Cloud Storage (GCS). I had this working using POST using this Github example, which makes use of a policy. Per best practice, I'm refactoring to use PUT and getting a SignatureDoesNotMatch error: <?xml version='1.0' encoding='UTF-8'?> <Code>SignatureDoesNotMatch The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method. PUT 123456789 /mybucket/mycat.jpg Per the docs on creating a signed URL with a program and the GCP example Python code, I am doing this process: building my Signature string signing it base64 encoding it url encoding the result (the python example doesn't do this though... Since this is running on a Google App Engine (GAE) App, I shouldn't need to get a JSON key file for my service account user, but rather use App Identity Services to sign it. Here's my code within a Flask project: google_access_id = app_identity.get_service_account_name() expires = arrow.utcnow().replace(minutes=+10).replace(microseconds=0).timestamp resource = '/mybucket/mycat.jpg' args = self.get_parser.parse_args() signature_string = 'PUT\n' # take MD5 of file being uploaded and its content type, if provided content_md5 = args.get('md5') or '' content_type = args.get('contenttype') or '' signature_string = ('PUT\n' '{md5}\n' '{content_type}\n' '{expires}\n' '{resource}\n').format( md5=content_md5, content_type=content_type, expires=expires, resource=resource) log.debug('signature string:\n{}'.format(signature_string)) _, signature_bytes = app_identity.sign_blob(signature_string) signature = base64.b64encode(signature_bytes) # URL encode signature signature = urllib.quote(signature) media_url = 'https://storage.googleapis.com{}'.format(resource) return dict(GoogleAccessId=google_access_id, Expires=expires, Signature=signature, bucket='mybucket', media_url='{}?GoogleAccessId={}&Expires={}&Signature={}'.format(media_url, google_acce…
has comment: http://stackoverflow.com/comment/81377979
type: AnsweredQuestion
tagged with: python-2.7
score: 5

http://stackoverflow.com/q/47086112
answer count: 0
downvote count: 0
has body: I'm creating several subplots in python 3 (I think) with matplotlib in a for loop, and I want to set the NUMBER of yticks/ xticks, because the max and min values vary with each loop. I've tried using the MaxNLocator as suggested in this answer change ticks number on a subplot (I'm sorry to ask another question about this now, but I couldn't comment on the answer given there): from matplotlib import ticker M = 3 yticks = ticker.MaxNLocator(M) ax.yaxis.set_major_locator(yticks) But this doesn't work for me. The yticklabels and yticks just vanish completely on the subplots in the for loop and I get two xticks although I requested five. The one subplot outside the for loop still has yticklabels but a different number of ticks than requested. And I am NOT using a logarithmic axis on either! I'd be great, if anyone had an idea, how to fix this! :) The structure of my code is: f = plt.figure(figsize =(13,10),dpi=300) yticks = ticker.MaxNLocator(4) # number of yticks xticks = ticker.MaxNLocator(5) # number of xticks yfmt = md.DateFormatter('%d.%m.\n%H:%M') # format of date for n,m in enumerate (['20-25cm','15-20cm','10-15cm','5-10cm','0-5cm']): ax = f.add_subplot(6,1,-n+6) # subplots number 6 to number 2 ax.yaxis.set_major_locator(yticks) # &lt;-- ? ax.xaxis.set_major_locator(xticks) # &lt;-- ? ax.xaxis.set_major_formatter(yfmt) # format for date on xaxis ax.xaxis.set_tick_params(labelsize=20) ax.yaxis.set_tick_params(labelsize=20) if n !=0: ax.set_xticklabels([]) # only put xtlabels at the bottom subplot Y = dictionary[data][n][:] #Y is a np.array with floats from a dictionary X = dictionary[date][n][:] #X is a np.array containing datetime objects from the same dictionary plt.plot(X[-250:-1],Y[-250:-1], label = m) ax1 = f.add_subplot(6,1,1) # subplot number 1 outside the loop ax1.xaxis.set_major_formatter(yfmt) ax1.xaxis.set_tick_params(labelsize=20) ax1.yaxis.set_tick_params(labelsize=20) ax1.yaxis.set_major_locator(yticks) # &lt;-- ? ax1.xaxis.set_major_locator(xticks) #…
score: 1
upvote count: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81122023
tagged with: axis-labels
has title: Change ticks number on a subplot with MaxNLocator - ticks vanish
linked to: http://stackoverflow.com/q/27425974
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: subplot
tagged with: python

http://stackoverflow.com/q/47103811
downvote count: 0
has comment: http://stackoverflow.com/comment/112691685
has body: I know I can use: nltk.download() But I really don't want to waste time letting the whole thing download. How do I just install the vader_lexicon
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/47107019
duplicate of: http://stackoverflow.com/q/22211525
tagged with: nltk
tagged with: python
tagged with: jupyter
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/112691903
has title: How do I download vader_lexicon through NLTK in jupyter
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/22211525
has answer: http://stackoverflow.com/a/47107599

http://stackoverflow.com/q/47106364
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
has answer: http://stackoverflow.com/a/56661161
has body: I want to stream the audio of my microphone (that is being recorded via pyaudio) via Flask to any client that connects. This is where the audio comes from: def getSound(self): # Current chunk of audio data data = self.stream.read(self.CHUNK) self.frames.append(data) wave = self.save(list(self.frames)) return data Here's my flask-code: @app.route('/audiofeed') def audiofeed(): def gen(microphone): while True: sound = microphone.getSound() #with open('tmp.wav', 'rb') as myfile: # yield myfile.read() yield sound return Response(stream_with_context(gen(Microphone()))) And this is the client: &lt;audio controls&gt; &lt;source src="{{ url_for('audiofeed') }}" type="audio/x-wav;codec=pcm"&gt; Your browser does not support the audio element. &lt;/audio&gt; It does work sometimes, but most of the times I'm getting "[Errno 32] Broken pipe" When uncommenting that with open("tmp.wav")-part (the self.save() optionally takes all previous frames and saves them in tmp.wav), I kind of get a stream, but all that comes out of the speakers is a "clicking"-noise. I'm open for any suggestions. How do I get the input of my microphone live-streamed (no pre-recording!) to a webbrowser? Thanks!
has answer: http://stackoverflow.com/a/54686096
has answer: http://stackoverflow.com/a/51099584
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Stream audio from pyaudio with Flask to HTML5
has answer: http://stackoverflow.com/a/51057856
tagged with: python
upvote count: 7
tagged with: flask
answer count: 4
tagged with: audio
tagged with: pyaudio
score: 7

http://stackoverflow.com/a/47127454
score: 1
type: Answer
has body: Categorise the numbers as small, valid and large (S,V and L) and further index the valid numbers: V_1, V_2, V_3 etc. Let us start off by assuming there are no large numbers. Consider the list A = [S,S,…,S,V_1, X,X,X,X,…X] .If V_1 has index n, there are n+1, subsets of the form [V_1], [S,V_1], [S,S,V_1] and so on. And for each of these n+1 subsets, we can append the len(A)-n-1 sequences: [X], [XX], [XXX] and so on. Giving a total of (n+1)(len(A)-n) subsets containing V_1. But we can partition the set of all subsets by those containing V_k but no V_n for n less than k. Hence we must then, simply perform the same calculation on the remaining XXX…X part of the list using V_2 and itterate. This would require something like this: def query(sliced,left,right,total): index=0 while index&lt;len(sliced): if sliced[index]&gt;=left: total+=(index+1)*(len(sliced)-index) return total+query(sliced[index+1:],left,right,0) else: index+=1 return total To incorporate the large numbers, we can just partition the whole set according to where the large numbers occur and add the total number of sequence for each. If we call our first function, sub_query, then we arrive at the following: def sub_query(sliced,left,right,total): index=0 while index&lt;len(sliced): if sliced[index]&gt;=left: total+=(index+1)*(len(sliced)-index) return total+sub_query(sliced[index+1:],left,right,0) else: index+=1 return total def query(sliced,left,right): index=0 count=0 while index&lt;len(sliced): if sliced[index]&gt;right: count+=sub_query(sliced[:index],left,right,0) sliced=sliced[index+1:] index=0 else: index+=1 count+=sub_query(sliced,left,right,0) print (count) This seems to run through the list and check for max/min values fewer times. Note it doesn’t distinguish between sub-lists that are the same but from different positions in the original list (as would arise from a list such as [0,1,0,0,1,0]. But the code from the original post wouldn’t do that either, so I am guessing this is not a requirement.
upvote count: 1
has comment: http://stackoverflow.com/comment/81205091
has comment: http://stackoverflow.com/comment/81221891
answers question: http://stackoverflow.com/q/47126987
downvote count: 0

http://stackoverflow.com/q/47069454
has title: How to fetch records from gpudb(kinetica) tables using command line interface
accepted answer: http://stackoverflow.com/a/52362155
score: 2
type: AnsweredQuestion
tagged with: kinetica
has comment: http://stackoverflow.com/comment/81115053
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81101158
has answer: http://stackoverflow.com/a/52362155
has comment: http://stackoverflow.com/comment/111363714
has body: I am trying to connect to gpudb tables but getting below exception. The command which i used to connect to gpudb tables is: python gpudb_cmd.py --gpudb < ip >:< port > --username < username > --ask-password --query 'select * from collectionname.tablename' Exception: Traceback (most recent call last): File "gpudb_cmd.py", line 248, in <module> gpudb_cmd( sys.argv ) File "gpudb_cmd.py", line 81, in gpudb_cmd gpudb = GPUdb( encoding = encoding, host = GPUdb_IP, port = GPUdb_Port, username = args.username, password = password ) File "/home/test/GIT/kinetica-api/kinetica-api-python/gpudb/gpudb.py", line 1531, in __init__ server_status_response = self.show_system_status() File "/home/test/GIT/kinetica-api/kinetica-api-python/gpudb/gpudb.py", line 9585, in show_system_status return AttrDict( self.__post_then_get( REQ_SCHEMA, REP_SCHEMA, obj, '/show/system/status' ) ) File "/home/test/GIT/kinetica-api/kinetica-api-python/gpudb/gpudb.py", line 1840, in __post_then_get return self.__read_datum(REP_SCHEMA, response, None, response_time) File "/home/test/GIT/kinetica-api/kinetica-api-python/gpudb/gpudb.py", line 1777, in __read_datum resp = self.__read_orig_datum(REP_SCHEMA, encoded_datum, encoding) File "/home/test/GIT/kinetica-api/kinetica-api-python/gpudb/gpudb.py", line 1756, in __read_orig_datum return _Util.decode_binary_data( SCHEMA, encoded_datum ) File "/home/test/GIT/kinetica-api/kinetica-api-python/gpudb/gpudb.py", line 280, in decode_binary_data out = reader.read( bd ) # read, give a decoder File "/home/test/GIT/kinetica-api/kinetica-api-python/gpudb/packages /avro/avro_py2/io.py", line 451, in read return self.read_data(self.writers_schema, self.readers_schema, decoder) File "/home/test/GIT/kinetica-api/kinetica-api-python/gpudb/packages /avro/avro_py2/io.py", line 496, in read_data return self.read_record(writers_schema, readers_schema, decoder) File "/home/test/GIT/kinetica-api/kinetica-api-python/gpudb/packages /avro/avro_py2/io.py", line 696, in read_record fie…
upvote count: 2
downvote count: 0
answer count: 1
tagged with: python

http://stackoverflow.com/comment/81332046
has text: What is the output of `QtGui.QFontInto(font).family()`?. It looks like Qt isn't finding the correct font. Are you sure you installed it properly?
comment on: http://stackoverflow.com/q/47182539
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47215704
tagged with: python
tagged with: post
has comment: http://stackoverflow.com/comment/81381674
type: Question
has comment: http://stackoverflow.com/comment/81381130
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python-requests
has title: Unable to login to a site with requests
favorite count: 0
tagged with: get
has comment: http://stackoverflow.com/comment/81381028
has answer: http://stackoverflow.com/a/47216276
score: 1
has body: For fun, I'm trying to use Python requests to log on to my school's student portal. This is what I've come up with so far. I'm trying to be very explicit on the headers, because I'm getting a 200 status code (the code you also get when failing to login) instead of a 302 (successful login). import sys import os import requests def login(username, password): url = '(link)/home.html#sign-in-content' values = { 'translator_username' : '', 'translator_password' : '', 'translator_ldappassword' : '', 'returnUrl' : '', 'serviceName' : 'PS Parent Portal', 'serviceTicket' : '', 'pcasServerUrl' : '\/', 'credentialType' : 'User Id and Password Credential', 'account' : username, 'pw' : password, 'translatorpw' : password } headers = { 'accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'accept-encoding' : 'gzip, deflate, br', 'accept-language' : 'en-US,en;q=0.9', 'cache-control' : 'max-age=0', 'connection' : 'keep-alive', 'content-type' : 'application/x-www-form-urlencoded', 'host' : '(link)', 'origin' : '(link)', 'referer' : '(link)guardian/home.html', 'upgrade-insecure-requests' : '1' } with requests.Session() as s: p = s.post(url, data=values) if p.status_code == 302: print(p.text) print('Authentication error', p.status_code) r = s.get('(link)guardian/home.html') print(r.text) def main(): login('myname', 'mypass') if __name__ == '__main__': main() Using Chrome to examine the network requests, all of these headers are under 'Request Headers' in addition to a long cookie number, content-length, and user-agent. The forms are as follows: pstoken:(token) contextData:(text) translator_username: translator_password: translator_ldappassword: returnUrl:(url)guardian/home.html serviceName:PS Parent Portal serviceTicket: pcasServerUrl:\/ credentialType:User Id and Password Credential account:f pw:(id) translatorpw: Am I missing something with the headers/form names? Is it a problem with cookies? If I look at p.requests.headers, this is wha…

http://stackoverflow.com/a/47203968
has body: You can use the built-in any to test if the list contains at least one non-Falsy/non-zero element. Zero is falsy, in fact the only falsy number: &gt;&gt;&gt; bool(0) False So you can easily do: for lst in (l1, l2): if any(lst): print(lst) This would provide correct results as long as your lists contains only numericals and you're not willing to make an expcetion of non numericals.
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47203741
type: Answer

http://stackoverflow.com/q/47163279
has comment: http://stackoverflow.com/comment/81276823
has answer: http://stackoverflow.com/a/47163356
favorite count: 0
type: AnsweredQuestion
tagged with: list
downvote count: 3
tagged with: python
has title: Python: Array out of bounds?
has comment: http://stackoverflow.com/comment/81276253
type: Question
has body: Effectively, whenever I use this code: elif mSelect == 3: score = [[],[],[],[],[],[]] scoreTwo = [] for x in range(0,6): file = open("./couple"+str(x+1)+"/tScore.txt","r") score[x].append(str(x+1)) score[x].append(str(file.read())) scoreTwo.append(str(score[x+1])) print("Couple"+str(x)+": "+str(score[x])+" points.") file.close() score = sorted(score) I get an error stating that an array was out of bounds. I'm trying to write a piece of code that takes information from text files and ranks users based on the score saved there, but for starters being able to assign these variables properly would be nice... Thanks.
upvote count: 0
accepted answer: http://stackoverflow.com/a/47163356
answer count: 1
score: -3

http://stackoverflow.com/q/47085092
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81119732
linked to: http://stackoverflow.com/q/15112125
has comment: http://stackoverflow.com/comment/81119722
type: Question
has body: What does this mean in Python: if x == (1 or 2): I know it's different to: if x == 1 or x == 2: if x in (1,2):
score: 0
has title: What does if x == ( 1 or 2 ): mean?
linked to: http://stackoverflow.com/q/18212574
duplicate of: http://stackoverflow.com/q/15112125
tagged with: python
has comment: http://stackoverflow.com/comment/81119591
has comment: http://stackoverflow.com/comment/81119767
tagged with: python-3.x

http://stackoverflow.com/q/47143461
type: Question
has comment: http://stackoverflow.com/comment/81237030
type: UnansweredQuestion
tagged with: python
score: 4
upvote count: 4
tagged with: word-cloud
has answer: http://stackoverflow.com/a/47143672
has comment: http://stackoverflow.com/comment/81237212
has title: Python wordcloud color by term frequency
downvote count: 0
has comment: http://stackoverflow.com/comment/81241988
answer count: 1
has body: I new in python and I a using wordcloud pkg. I generated a word cloud by frequencies that I have in a dict frequencies with keys=words and values=frequencies of the words. The wordcloud can receive a function in the color_funct parameter. Such function can be used to make your own colormap for the words on the cloud. As example I used my_tf_color_func. wordcloud = WordCloud(background_color="white", max_words=1000, mask=motog3_coloring, max_font_size=1000, random_state=1, relative_scaling=.6, regexp="\w[\%\-\(\)\w']+", collocations=False, color_func=my_tf_color_func) In my_tf_color_func I want to color each word according to its frequency in the attribute frequencies. I now that I can do something like bellow in my_tf_color_func, given the report on this issue def my_tf_color_func(word, font_size, position, orientation, random_state=None, **kwargs): return "hsl(%d, 80%%, 50%%)" % (360 * frequencies[word]) But the dict frequencies has to be passed, how can I do that? Where and how I must pass the dict frequencies to be able to use it in my_tf_color_func. I tried in some ways but I could not. Many Thanks
has comment: http://stackoverflow.com/comment/81237448
tagged with: keyword-argument
has comment: http://stackoverflow.com/comment/81239244
favorite count: 0

http://stackoverflow.com/comment/81322853
comment on: http://stackoverflow.com/q/47186807
type: QuestionComment
has text: have you tried the [`datetime64[ns]`](https://pandas.pydata.org/pandas-docs/stable/timeseries.html) type?
score: 0
type: Comment

http://stackoverflow.com/comment/81130258
score: 2
comment on: http://stackoverflow.com/q/47088992
type: Comment
has text: And besides the question formatting: that's not how IP addresses work. An IPv6 address is 128 bits and an IPv4 address is 32 bits, so what you're asking is impossible.
type: QuestionComment

http://stackoverflow.com/q/47133398
answer count: 1
downvote count: 0
has body: I am very new to leaflet, and I'm trying to workout how to return the lat and lng from a onMapClick event in leaflet to the flask server app, to allow me to use the coordinates t perform a spatial search on my database. The event currently only shows the lat long in a pop-up on the web app. I've had a search around, but I guess my knowledge is so basic I don't know what functions I'm searching for. My web map Demo <!-- Leaflet CSS file (style sheets)>--> <!--leaflet java script file>--> and the server app from flask import Flask, render_template app = Flask(__name__) @app.route('/demo') def webMap(): return render_template('demo.html') if __name__ == '__main__': app.run(host='0.0.0.0', port=8090) EDIT I have attempted using an ajax call but getting a 405 error $.ajax('demo/data/', { type: 'GET', data: { lat: e.latlng.lat, lng: e.latlng.lng } }); }; Flask app @app.route('/demo/data/') def demoData(): return request.form['lng'], request.form['lat']
has answer: http://stackoverflow.com/a/47144046
accepted answer: http://stackoverflow.com/a/47144046
has title: How do I return latitude and longitude to flask server after clicking on a leaflet web app?
favorite count: 0
type: Question
tagged with: ajax
tagged with: python
tagged with: flask
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: leaflet
linked to: http://stackoverflow.com/q/978061
has comment: http://stackoverflow.com/comment/127856476

http://stackoverflow.com/comment/81392587
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47200367
has text: @HakariDo: done. try it again...

http://stackoverflow.com/comment/81195775
has text: this assignment needs to be in the block where you handle the error, otherwise there is no traceback
comment on: http://stackoverflow.com/a/47122870
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81141333
comment on: http://stackoverflow.com/q/47095841
has text: What is your input data? What would you like your plot to look like? Please read [ask] and [mcve].
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/81113076
comment on: http://stackoverflow.com/a/47081811
has text: Oh sorry for the misunderstanding. In the end I only need the Continents as indices 'size', 'sum', 'mean', 'std' with respect to the 'PopEst' Btw I still try to understand what your code does.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81332940
score: 0
has text: That's a nice insight, thank you. It's strange I didn't think of that myself.
type: Comment
comment on: http://stackoverflow.com/a/47176249
type: AnswerComment

http://stackoverflow.com/a/47069435
score: 0
type: AcceptedAnswer
has body: Use below xpath (//td[contains(@class, 'odds-nowrp')]/a)[1] for Home_odds (//td[contains(@class, 'odds-nowrp')]/a)[2] for Draw_odds (//td[contains(@class, 'odds-nowrp')]/a)[3] for Away_odds you can also use findelements also and store the results in List. then use list index to iterate for 1st, 2nd and 3rd index
type: Answer
answers question: http://stackoverflow.com/q/47067720
accepted answer of: http://stackoverflow.com/q/47067720

http://stackoverflow.com/q/47085362
has body: I'm using xlwings to control a workbook because I need to keep existing charts in tact (otherwise I'd use openpyxl). Is there a way to make the sheets hidden and to open a book within an app that is not visible? to hide a sheet I've tried: wb.sheets[ws].Visible = False wb.sheets[ws].hidden= True wb.sheets[ws].Visible= xlveryhidden #vba syntax - bombs The top two run, but don't do anything, the third bombs out. I can create a new excel app and I can create a new book (which creates is new app). However, I want to open a specific book, but Book doesn't take a visible parameter - how do I open an existing workbook and not have it be visible? excel = xw.App(visible = False) #creates a new app that is visible wb= xw.Book(filepath) #opens the already existing workbook, but it is visible - how do I make it part of the app above?
has title: xlwings hide worksheets from python and book not visible
tagged with: python
tagged with: xlwings
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47096350
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/81102708
comment on: http://stackoverflow.com/q/47077125
has text: `pd.read_csv(InFiles[i], dtype=str, nrows=1)`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47489166
score: 1
answers question: http://stackoverflow.com/q/47221562
downvote count: 0
has body: I think could have been a problem with the conda-forge feedstock for fiona: https://github.com/conda-forge/fiona-feedstock/issues/62 I had the same problem a few days ago but it seems to have been resolved now. Have you tried again?
type: Answer
upvote count: 1

http://stackoverflow.com/comment/81377903
type: QuestionComment
has text: It looks like praw is timing out on authenticating with reddit (see the last line in your traceback). That could absolutely be related to site problems.
type: Comment
comment on: http://stackoverflow.com/q/47213930
score: 0

http://stackoverflow.com/q/47219727
type: Question
score: 2
linked to: http://stackoverflow.com/q/11699298
linked to: http://stackoverflow.com/q/35242735
upvote count: 2
tagged with: video-capture
type: UnansweredQuestion
has body: I've been having issues getting OpenCV 2.4.9 to read (and show) a video file using python. I know it's not a problem with finding the file because I was able to get cv2.imread() to read an image from the same directory. It's definitely a problem with cv2.VideoCapture(). Here's the code and output I've been getting: import cv2 import numpy as np testvid = cv2.VideoCapture('testvid.avi') while(1): ret, frame = testvid.read() print ret cv2.imshow('frame',frame) k = cv2.waitKey(30) &amp; 0xff if k == 27: break testvid.release() cv2.destroyAllWindows() Output: False error: C:\pisi\tmp\opencv-2.4.9-5\work\opencv-2.4.9\modules\highgui\src\window.cpp:261: error: (-215) size.width&gt;0 &amp;&amp; size.height&gt;0 in function cv::imshow OpenCV Error: Assertion failed (size.width&gt;0 &amp;&amp; size.height&gt;0) in cv::imshow, file C:\pisi\tmp\opencv-2.4.9-5\work\opencv-2.4.9\modules\highgui\src\window.cpp, line 261 I know there's been several people who have had the same problem. This thread and this tread both address the issue by saying that you have to rename the opencv_ffmpeg.dll file to fit your version and copy it to the main python directory or directory in your path (or something to that effect). However, I'm using Python 2.7.13 through Enthought (by recommendation from my professor), and the paths and way libraries and packages are set up seem completely different from how they are in the other threads. Enthought uses a package manager that automatically downloaded and setup OpenCV for me. There is no Python directory. Everything is through Enthought. After some digging, I found where all of the OpenCV .dlls are located, including opencv_ffmpeg249_64.dll: C:\Users\USERNAME\AppData\Local\Enthought\Canopy\edm\pkgs\03\9d58e152b8f411718220c30639b8448585cb7d9a82de662c7e34b35d9ec1f6 So what do I do with this? Where do I copy the .dll? Is the .dll even the problem here? I've tried so many things, including copying it to all sorts of places and renaming the .dll, and nothin…
downvote count: 0
has answer: http://stackoverflow.com/a/47241610
favorite count: 0
tagged with: opencv
tagged with: python-2.7
tagged with: enthought
answer count: 3
has answer: http://stackoverflow.com/a/47225453
has title: OpenCV 2.4.9 VideoCapture() won't Read Video File in Enthought Python 2.7 Environment
tagged with: python
has answer: http://stackoverflow.com/a/47220372

if-statement
tags question: http://stackoverflow.com/q/47135539
tags question: http://stackoverflow.com/q/47111779
tags question: http://stackoverflow.com/q/47180646
tag name: if-statement
type: Tag
tags question: http://stackoverflow.com/q/47065468
tags question: http://stackoverflow.com/q/47142190
tags question: http://stackoverflow.com/q/47154136
tags question: http://stackoverflow.com/q/47082204
tags question: http://stackoverflow.com/q/47169971
tags question: http://stackoverflow.com/q/47189048
tags question: http://stackoverflow.com/q/47214185
tags question: http://stackoverflow.com/q/47122936
tags question: http://stackoverflow.com/q/47109769
tags question: http://stackoverflow.com/q/47191226
tags question: http://stackoverflow.com/q/47096150
tags question: http://stackoverflow.com/q/47080315
tags question: http://stackoverflow.com/q/47203240
tags question: http://stackoverflow.com/q/47117743
tags question: http://stackoverflow.com/q/47074966
tags question: http://stackoverflow.com/q/47188473
tags question: http://stackoverflow.com/q/47158741

http://stackoverflow.com/a/64096276
type: Answer
score: 0
has body: In case it benefits anyone else. In the event you are willing to create a grid and draw at the per pixel level, I wrote a function that will sort through a list of lists (or tuple of tuples) which represent a graphical image. It draws a single pixel at a time, at whichever coordinates you input, and it centers the image to the provided coordinates. This is not an optimal solution for real-world use, but is a fully functioning proof of concept nonetheless # Snake head made from drawing pixel by pixel, with optional directionality import turtle import time screen = turtle.Screen() screen.bgcolor("#000000") screen.tracer(0) # 0 = black 1 = green 2 = Yellow 3 = red head_colors = ["#000000", "#00AA66", "#FFFF00", "#FF0033"] head_pixels = [ [0,0,0,0,0,0,0,1,0,3,3,3,0,1,0,0,0,0,0,0,0], [0,0,0,0,0,0,1,1,1,0,0,0,1,1,1,0,0,0,0,0,0], [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0], [0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0], [0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0], [0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0], [0,0,1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,0,0], [0,1,1,1,0,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,0], [0,1,1,0,0,2,2,0,0,1,1,1,0,0,2,2,0,0,1,1,0], [0,1,1,0,0,2,2,0,0,1,1,1,0,0,2,2,0,0,1,1,0], [1,1,1,1,0,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] ] def turtle_graphic(colors, pixel_data, turt, go=(0,0), d="up"): turt.hideturtle() y = len(pixel_data) / 2 x = len(pixel_data[0]) / 2 turt.clear() if d == "left": turt.left(90) elif d == "right": turt.right(90) elif d == "down": turt.left(180) for row in range(len(pixel_data)): if d == "down": turt.goto(go[0]+x-1,go[1]-y+row) elif d == "left": turt.goto…
answers question: http://stackoverflow.com/q/47144177

http://stackoverflow.com/q/47085573
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: Python script file containing parameters fails to execute in batch file
tagged with: batch-file
has answer: http://stackoverflow.com/a/47085752
has comment: http://stackoverflow.com/comment/81121433
score: 1
tagged with: windows
has comment: http://stackoverflow.com/comment/81124823
has body: I'm trying to run a simple Windows batch file containing just one line: python c:\temp\script.py The input file to be executed by python, script.py, contains these lines: # This Python file uses the following encoding: utf-8 import os os.chdir("C:/Program Files/QGIS 2.18/apps/Python27/Scripts") code = "python –m pip install –U pip setuptools" os.system(code) Script.py of course executes fine on its own, but when run from within the setup.bat file, the following error results: python: can't open file 'ΓÇôm': [Errno 2] No such file or directory It is stumbling on the "-m" option in the script.py command line, because if a command without signed options is passed in the script.py file (i.e., "code=pip install setuptools"), it works just fine. Any substring with a "-" character messes the batch file execution up. Any thoughts are welcome.
tagged with: python
tagged with: cmd
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/81143362
has text: Why is count 1. Aint that suppose to be 2 ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47096797

http://stackoverflow.com/comment/81081574
type: QuestionComment
has text: What's inaccurate about these numbers?
score: 0
comment on: http://stackoverflow.com/q/47066690
type: Comment

comparison-operators
tags question: http://stackoverflow.com/q/47146149
type: Tag
tag name: comparison-operators

http://stackoverflow.com/q/47149756
has title: Remove punctuations except intra-digit punctuations
tagged with: python
has comment: http://stackoverflow.com/comment/81253948
downvote count: 1
type: AnsweredQuestion
score: 2
upvote count: 3
tagged with: regex
favorite count: 0
accepted answer: http://stackoverflow.com/a/47149786
type: Question
possible better answer: http://stackoverflow.com/a/47149918
answer count: 2
has answer: http://stackoverflow.com/a/47149786
has body: Is there a way to remove all punctuations in a string, but retaining hyphen and intra-digit punctuations? Hello! this episode is thirty-five minutes long, 35.26 mins to be precise. should be: Hello this episode is thirty-five minutes long 35.26 mins to be precise
has answer: http://stackoverflow.com/a/47149918

http://stackoverflow.com/q/47110639
tagged with: python-multithreading
has comment: http://stackoverflow.com/comment/81180042
tagged with: python
has title: How to send jobs from multiple client threads to a pool of multiprocessor workers and get results returned (python)?
type: Question
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/81172930
answer count: 0
upvote count: 3
type: UnansweredQuestion
tagged with: multithreading
downvote count: 0
has body: I need to compute an expensive to compute function many times and want to use all processor cores for it. That would be relatively simple if I had all function argument sets at once: I could use multiprocessing pool.map . However I don't have them all at once, and also would like to avoid starting a separate process for each function computation. Therefore I want to start a pool of workers (no problems), send them the jobs from the clients (use queue, no problems), and then get the results back to the client (but how?). More specifically, I need to compute my function on a multi-dimensional mesh array of arguments. In my case it is possible to avoid the computation for every array point by using two specific propeties of my function: it is monotonously nondecreasing for all arguments, and it can take only a few discrete values. Thus, if the function value is equal for two separate points on the mesh, it will be the same for all points in-between. Now we divide our mesh into parts and use recursion. Using recursion however means I cannot easily use pool.map Actually I found a working solution, but guess there could be a more straightforward and reliable way. I set up a separate dispatcher thread. It gets ALL results from the workers through a results queue, and then lets clients to pick up their results. Below the code for a simplified (2d) case. EDIT: to the comment by Shihab Shahriar. Large part of the code needed to make the whole work, but do not directly relate to the question. Specifically: contpl(), sample_f() are auxillary functions. In the real problem, instead of sample_f() there would be a complex and expensive simulation. recfill() is the recursive function. It needs the resuls from the expensive calculation, and receives them via calling getz() . It would recursively start instances of itself in separate threads. Other details here unimportant. getz() is an important part of my solution: It is a proxy between the above recursive function, and the workers…
favorite count: 0
tagged with: recursion
score: 3

http://stackoverflow.com/comment/81122312
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47086186
has text: Note: This will error if any line lacks a space character. If you want to handle such lines by pairing a key (the contents of the line) with the empty string, you can do: `dict(line.partition(' ')[::2] for line in f)`. `partition` always returns exactly three values, so taking even index values always gets you exactly two (the middle value is the partition character if found, which you don't care about here).

http://stackoverflow.com/comment/103317235
has text: Did you put absolutely different column names in both tables intentionally?
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47113813

http://stackoverflow.com/q/47105869
has comment: http://stackoverflow.com/comment/99506394
downvote count: 0
has body: Here is the code: from pyemd import emd print("sentence 1:") print(input_document_lower[0]) print("sentence 2:") print(input_document_lower[1]) print("similarity:") model_w2v.wmdistance(input_document_lower[0], input_document_lower[1]) Here's the error: sentence 1: incorrect batch number printed primary label pbn sentence 2: unconfirmed oos met vial washing qualification sample per similarity: ImportErrorTraceback (most recent call last) &lt;ipython-input-201-50af089a2354&gt; in &lt;module&gt;() 4 print(input_document_lower[1]) 5 print("similarity:") ----&gt; 6 model_w2v.wmdistance(input_document_lower[0], input_document_lower[1]) C:\ProgramData\Anaconda2\lib\site-packages\gensim\models\word2vec.pyc in wmdistance(self, document1, document2) 1308 Refer to the documentation for `gensim.models.KeyedVectors.wmdistance` 1309 """ -&gt; 1310 return self.wv.wmdistance(document1, document2) 1311 1312 def most_similar_cosmul(self, positive=None, negative=None, topn=10): C:\ProgramData\Anaconda2\lib\site-packages\gensim\models\keyedvectors.pyc in wmdistance(self, document1, document2) 386 387 if not PYEMD_EXT: --&gt; 388 raise ImportError("Please install pyemd Python package to compute WMD.") 389 390 # Remove out-of-vocabulary words. ImportError: Please install pyemd Python package to compute WMD. It is being installed properly so I really have no clue as to what is going wrong. Have any of your encountered this?
has answer: http://stackoverflow.com/a/52854212
answer count: 7
has answer: http://stackoverflow.com/a/66560482
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/54004639
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52425653
has answer: http://stackoverflow.com/a/54112595
upvote count: 6
score: 6
tagged with: word2vec
tagged with: python
tagged with: gensim
has answer: http://stackoverflow.com/a/49127438
has answer: http://stackoverflow.com/a/47733434
has title: Getting an error to install pyemd even though I just installed it
tagged with: installation

http://stackoverflow.com/comment/81312768
has text: Then (assuming the symptom is still the same - page refreshes instead) the problem is vbery probably in the part of the view you didn't post, and no one can help you without seeing that code. Hint : add a new view that only handles this exact part of the code and post your form to this new view's url. This should make clear whether there's a bug in your original 800-pounds-gorilla view (which is probably doing way to many things from what you describe) or the problem is elsewhere.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47176064
score: 0

http://stackoverflow.com/comment/81353336
type: AnswerComment
comment on: http://stackoverflow.com/a/47200317
score: 0
type: Comment
has text: I forgot to change colspecs=a in the edit. Everything else works well. Thanks for your solution.

http://stackoverflow.com/a/61654362
score: 0
answers question: http://stackoverflow.com/q/47181268
type: Answer
has body: building upun @thaavik's answer- in modern peewee (im using 3.13) the dict name was changed to __data__ so you need to use m1.__dict__['__data__'] somthing else you can do is use dict's .items() method and the ^ operator (Exclusive Or) to get the difference between the two item sets a = {"a": 1, "c": 1} b= {"b": 1, "c":2} print(a.items()^ b.items()) &gt; {('c', 1), ('c', 2), ('a', 1), ('b', 1)}

http://stackoverflow.com/q/47066728
has title: Combine @property with another decorator
has comment: http://stackoverflow.com/comment/81082872
has comment: http://stackoverflow.com/comment/81081659
has answer: http://stackoverflow.com/a/47087826
possible better answer: http://stackoverflow.com/a/47087826
tagged with: python
has answer: http://stackoverflow.com/a/47089791
tagged with: properties
accepted answer: http://stackoverflow.com/a/47089791
tagged with: python-decorators
type: Question
score: 2
has body: I have these decorators that work with @property def android(**params): def deco(f): def wrap(*args, **kwargs): if is_android: return params return f() return wrap return deco def ios(**params): def deco(f): def wrap(*args, **kwargs): if not is_android: return params return f() return wrap return deco And defined class: class Foo: @property @android(foo=1) @ios(foo=2) def foo(self): pass f = Foo() print(f.foo) I have to repeat again and again the @property every time I want to use. Is there any way to combine the @property into @android and @ios? I mean just need to use @android and @ios without @property but I am able to call f.foo
answer count: 2
has comment: http://stackoverflow.com/comment/81082286
upvote count: 3
downvote count: 1
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion

http://stackoverflow.com/comment/81155377
type: Comment
type: QuestionComment
has text: You need to read a getting started with Python type of guide.
comment on: http://stackoverflow.com/q/47102613
score: 0

http://stackoverflow.com/comment/81150771
has text: It does not matter as it is just a bit field used for AES. Java shows numbers as signed but it does not matter what the numerical representation is as long as bits are correct. numpy.int64() seemed to do the trick.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47100105

http://stackoverflow.com/comment/81188611
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47119406
type: AnswerComment
has text: @user2357112 Thanks, I'll add that info to my answer.

http://stackoverflow.com/comment/81122583
type: Comment
comment on: http://stackoverflow.com/q/47086380
has text: Also, if your Python3 instance has to be called with "python3", you would use "pip3 install Pillow".
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81367587
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47209173
type: AnswerComment
has text: I'm new to the django and at first i created the frontend to site now i'm converting it to django templates etc. and my question is should i create a model for for the images for each option? Just a example what i'm trying to do. [link](https://imbaboost.com/rank-boost.html)

http://stackoverflow.com/comment/81400029
comment on: http://stackoverflow.com/a/47215106
type: Comment
type: AnswerComment
score: 0
has text: @whisperstream yw have a nice day

http://stackoverflow.com/comment/81198401
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47124032
type: AnswerComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ - and removeing stack ;)

http://stackoverflow.com/comment/81159279
type: AnswerComment
has text: Correct. It performs a pixel-wise kernel based comparison, so the images would need to be registered first.
type: Comment
comment on: http://stackoverflow.com/a/47100835
score: 0

http://stackoverflow.com/comment/81327667
type: QuestionComment
has text: can you repeat your test with another video? (http://distribution.bbb3d.renderfarming.net/video/mp4/bbb_sunflower_1080p_60fps_normal.mp4) maybe the problem it's your source video.
comment on: http://stackoverflow.com/q/47183541
score: 0
type: Comment

http://stackoverflow.com/q/47169858
accepted answer: http://stackoverflow.com/a/47169902
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47169902
tagged with: ordereddictionary
has body: I have list of tuples with 3 elements. I want to convert it into a dict with preserved order. &gt;&gt;&gt; a = [('one', '0', '1'), ('two', '0', '0'), ('three', '1', '1')] &gt;&gt;&gt; x = OrderedDict({sb[0]: sb[1:] for sb in a}) &gt;&gt;&gt; x OrderedDict([('three', ('1', '1')), ('two', ('0', '0')), ('one', ('0', '1'))]) I see order getting changed, not sure why. Can someone please help me fix this issue?
score: 1
linked to: http://stackoverflow.com/q/15711755
tagged with: python
has title: Convert list of tuples with 3 elements into ordered dictionary
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/15733558
answer count: 1
downvote count: 0
upvote count: 1
duplicate of: http://stackoverflow.com/q/15711755

http://stackoverflow.com/comment/81582799
type: Comment
type: AnswerComment
has text: Thank you! I'll try to get around a bit more before making a new answer, but I'll let you know if I'm in trouble ;)
comment on: http://stackoverflow.com/a/47224176
score: 0

http://stackoverflow.com/comment/81246587
comment on: http://stackoverflow.com/q/47093294
has text: Did you provide a zone and a region flag for this? And if so, which ones did you provide?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81258556
has text: *'Return the lowest index in the string where substring sub is found within the slice s[start:end]'*
type: AnswerComment
comment on: http://stackoverflow.com/a/47154455
score: 0
type: Comment

http://stackoverflow.com/comment/81110433
type: QuestionComment
comment on: http://stackoverflow.com/q/47080079
score: 0
has text: Probably relevant: https://stackoverflow.com/questions/36939063/matplotlib-colorbar-ticks-on-left-opposite-side. Also note that the API for the `colorbar()` method can be found here: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.colorbar.html#matplotlib.pyplot.colorbar (the link was in your link to the Colorbar API)
type: Comment

http://stackoverflow.com/comment/81411638
score: 0
has text: The answer [here](https://stackoverflow.com/questions/46943061/how-to-iterate-over-and-download-each-image-in-an-image-collection-from-the-goog/46961005#46961005) solves your map() issue.
comment on: http://stackoverflow.com/q/47149216
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47103836
score: 1
answers question: http://stackoverflow.com/q/47103742
downvote count: 0
upvote count: 1
type: Answer
has body: You might want to use itertools.groupby(): In [15]: {k: [list(x[1:]) for x in g] ....: for k,g in itertools.groupby(s1, key=lambda x: x[0])} Out[15]: {1L: [['R', 4], ['D', 3], ['I', 10], ['K', 0.0]], 2L: [['R', 11], ['D', 13], ['I', 1], ['K', 6]], 3L: [['R', 12], ['D', 17], ['I', 23], ['K', 10]]}

http://stackoverflow.com/q/47067036
type: Question
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47067264
has comment: http://stackoverflow.com/comment/81082172
has title: getting data from nested Dictionary in Python
tagged with: python
tagged with: dictionary
has body: I have been trying to extract data from a multi level dictionary in python example of dictionary i am extracting from is: {"family": { "name": "Mary", "age": "32", "sex": "female", "kids": [ { "name": "jim", "age": "10", "sex": "male", "dob_year": "2007", "ssn": "123-23-1234" }, { "name": "jill", "age": "6", "sex": "female", "dob_year": "2011", "ssn": "123-23-1235" }]}} ss = test0["family"]["kids"] def search(values, lookup): for k in values: for v in values: if lookup in v: return k return None print search(ss, '201') my goal is for it to search keywords (not exact) in the values of the nested dictionary and return either the full dictionary or a value of a particular key like "23-23-1235" if ssn is asked for. need it to return {"name": "jill","age": "6","sex": "female","dob_year": "2011","ssn": "123-23-1235"} of a request value in the different levels. Right now it only shows:{"name": "jim","age": "10","sex": "male", "dob_year": "2007","ssn": "123-23-1234"}
score: 0
has answer: http://stackoverflow.com/a/47075566

http://stackoverflow.com/a/47127538
score: -2
has comment: http://stackoverflow.com/comment/134995689
has body: Is postgresql installed on your machine? Apart from: pip install psycopg2 you need to install postgresql (on Ubuntu): sudo apt install postgresql
type: Answer
answers question: http://stackoverflow.com/q/47124297
upvote count: 0
downvote count: 2

http://stackoverflow.com/comment/81350562
type: AnswerComment
score: 0
has text: It looks like you have cuda-9.0 installed, and not cuda-8.0
type: Comment
comment on: http://stackoverflow.com/a/47200772

http://stackoverflow.com/a/47200177
upvote count: 1
has body: ** note, I edited the markup to include what you specified ** I just compiled some code and I can confirm that this outputs the correct string. See the code below: from bs4 import BeautifulSoup string = """ Every quadratic polynomial can have at most (a) three zeros (b) one zero (c) two zeros (d) none of these """ soup = BeautifulSoup(string, "html.parser") text = soup.get_text().replace("\n", "") print(text) This will output Every quadratic polynomial can have at most (a) three zeros(b) one zero(c) two zeros(d) none of these I am not sure of the exact format you are wanting, so tweaking yourself will have to be done.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47199211
downvote count: 0

http://stackoverflow.com/q/47197062
score: 0
has title: Predicting a single value in classification network
answer count: 1
type: Question
has body: I am currently trying to get into machine learning and neural networks, but my lack of programming skills is kind of hindering me at the moment. I am following an online tutorial in which these lines of code were made to evaluate the created model: pred_fn = tf.estimator.inputs.pandas_input_fn(x=X_test,batch_size=len(X_test),shuffle=False) predictions = list(model.predict(input_fn=pred_fn)) predictions[0] final_preds = [] for pred in predictions: final_preds.append(pred['class_ids'][0]) final_preds[:10] from sklearn.metrics import classification_report print(classification_report(y_test,final_preds)) This works very well for me an tells me the precision I achieved on these 10 inputs I chose from X_test. Unfortunately, I can't really figure out how to be able to predict a particular, single value from X_test or maybe even a manually input value that has the same dimensions as an element of X_test. X_test is a pandas.core.frame.DataFrame and includes 15 columns and thousands of rows. Therefore, I would find it helpful to maybe predict or evaluate a certain value. If I missed any essential information, that I should have included, let me know. Thanks in advance!
tagged with: classification
type: UnansweredQuestion
tagged with: neural-network
tagged with: python
has answer: http://stackoverflow.com/a/47197226

http://stackoverflow.com/comment/81304881
score: 0
has text: You can use multiple condtions like `((df['inc_cr_date_day'] == 'Saturday') & (df['inc_cr_date_day'].dt.hour > 9) & (df['inc_cr_date_day'].dt.hour < 20))`
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47177396

http://stackoverflow.com/a/47212404
score: 1
has body: I answered in the comments because i was unsure if it returned an object or a string. Getting it like it was an object worked for the thread starter. So the correct answer to the question was to get it like client.get_buy_price().amount
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47211186
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47211186

http://stackoverflow.com/comment/81142155
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47096320
has text: so, return means "end all loops", basically, and works like that? Because, if I adjust my code this way and try to print(validationHelper.true), I get the following error: print(validationHelper.true) AttributeError: 'function' object has no attribute 'true'

http://stackoverflow.com/a/47200647
downvote count: 0
answers question: http://stackoverflow.com/q/47200538
type: AcceptedAnswer
has body: For more advanced usage, use PairGrid instead of pairplot. Basically, PairGrid allows you to control which function is used to plot the upper, lower and diagonal plots independently. Check out the documentation for PairGrid for more details. To answer your specific question: iris = sns.load_dataset("iris") g = sns.PairGrid(iris) g = g.map_upper(sns.regplot, lowess=True, scatter_kws={'alpha':0.15}, line_kws={'color': 'red'})
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47200538

http://stackoverflow.com/q/47173204
type: Question
has comment: http://stackoverflow.com/comment/81295954
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81295726
answer count: 1
tagged with: web-applications
tagged with: django
tagged with: python
has body: The purpose is to implement a pool like database connection pool in my web application. My application is write by Django. The problem is that every time a http request come, my code will be loaded and run through. So if I write some code to initiate a pool. These code will be run per http request. And the pool will be initiated per request. So it is meaningless. So how should I write this?
tagged with: connection-pool
has answer: http://stackoverflow.com/a/47176595
score: 0
has title: How to implement a connection pool in web application like django?
has comment: http://stackoverflow.com/comment/81296245

opencsv
tag name: opencsv
type: Tag
tags question: http://stackoverflow.com/q/47167659

http://stackoverflow.com/a/47203940
has body: You can use the built-in function any(): From Python's documentation: any(iterable) Return True if any element of the iterable is true. If the iterable is empty, return False Here's a code: for l in [l1,l2, ..., ln]: if any(l): print(l)
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47203741
type: Answer
score: 1

http://stackoverflow.com/a/47068045
score: 3
answers question: http://stackoverflow.com/q/47067985
type: Answer
has body: Try this way: listOne = ['hello','hi','bye'] listTwo = ['goodbye','by'] for x in listTwo: if any(x in e for e in listOne): print(x) it will print 'by', as 'by' is part of 'bye' in listOne .
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/47200642
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81350176
has body: bool(input("Enter input :")) when the input is null, this will output False. But when we give any value it gives out True. Why is that?
has title: Why the output is the same for every input value except null in python?
tagged with: boolean
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81349702
duplicate of: http://stackoverflow.com/q/39983695
has comment: http://stackoverflow.com/comment/81349710
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81350757

http://stackoverflow.com/q/47181844
has title: Python 2D list of numbers to csv
has comment: http://stackoverflow.com/comment/81312617
answer count: 1
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47182109
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: Im looking for the best way to convert a 2D list to csv file containing the coordinates (xyz) for every point. The 2D-list has this format: ['586.732'], ['626.012'], ['496.778'] ['597.422'], ['536.778'], ['586.056'] ['597.422'], ['536.778'], ['586.056'] Using: with open("output.csv", "w") as csvfile: writer = csv.writer(csvfile) writer.writerows([x, y, z]) will return a transposed list of objects, that cannot be plotted easily. I would be happy if anyone could suggest a way to solve this.
has comment: http://stackoverflow.com/comment/81313048
linked to: http://stackoverflow.com/q/4937491
has comment: http://stackoverflow.com/comment/81312524
score: 0

http://stackoverflow.com/comment/81342816
score: 0
type: AnswerComment
has text: Here is the second query ` cursor.execute("select t1.id as pid,pxval,pyval from table2 t1 left join (select * from table3 where clubid=?) t2 on t1.id=t2.pid where t1.cityid in (SELECT cityid FROM table1 WHERE domid = ? group by cityid) and t1.pxval>0 and t2.distance is null order by pid",(dom_id[i],dom_id[i]))`
type: Comment
comment on: http://stackoverflow.com/a/47196606

http://stackoverflow.com/comment/81319090
type: Comment
has text: Ajax, this question is substantially different than that question. See that part I bolded.
score: 0
comment on: http://stackoverflow.com/q/47184806
type: QuestionComment

http://stackoverflow.com/comment/81336506
type: QuestionComment
comment on: http://stackoverflow.com/q/47193509
has text: you are trying to read all rows from the `word.csv` file, form the 2nd and 3rd column value to a tuple, then count all of them. The Counter will count duplicated tuple, and increase the count.
score: 0
type: Comment

http://stackoverflow.com/comment/81368718
type: Comment
score: 4
type: QuestionComment
has text: I'm pretty sure you don't have a set of lists.
comment on: http://stackoverflow.com/q/47209786

http://stackoverflow.com/comment/81286140
type: Comment
has text: Ah, in that case I'm not sure you can use a custom Jinja2 filter. You'd probably need to iterate over the items manually in the template. This wouldn't look as nice though, and the templating logic can only go so far.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47167994

http://stackoverflow.com/comment/81369614
comment on: http://stackoverflow.com/q/47205160
type: Comment
has text: Did you activate tensorflow eager mode by calling `tfe.enable_eager_execution()` before running this code block? Eager mode is disabled by default.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81249473
score: 0
comment on: http://stackoverflow.com/q/47149820
has text: im asking how to parse JSON in python not javascript?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47087737
downvote count: 0
has body: You only want to groupby 'A': In [11]: df.groupby(['A'])['VAL'].shift(1) Out[11]: 0 NaN 1 1.0 2 NaN 3 1.0 4 2.0 Name: VAL, dtype: float64 It might be what you want is to shift by offset rather than by position: In [21]: df1 = df.set_index("DT") In [22]: df1.groupby(['A'])['VAL'].shift(freq=pd.offsets.YearBegin(1)) Out[22]: A DT 1 2018-01-01 1 2019-01-01 2 2 2018-01-01 1 2019-01-01 2 2020-01-01 3 Name: VAL, dtype: int64
answers question: http://stackoverflow.com/q/47087671
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/47089802
tagged with: recommendation-engine
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47137435
downvote count: 0
accepted answer: http://stackoverflow.com/a/47137435
tagged with: matrix
score: 1
upvote count: 1
answer count: 1
has body: I want to construct train data matrix and test data matrix for book crossing dataset. But the Book Ids which are ISBN code may contain characters. So, I cannot apply this code (from a tutorial): #Create two user-item matrices, one for training and another for testing train_data_matrix = np.zeros((n_users, n_items)) for line in train_data.itertuples(): train_data_matrix[line[1]-1, line[2]-1] = line[3] print (line) test_data_matrix = np.zeros((n_users, n_items)) for line in test_data.itertuples(): test_data_matrix[line[1]-1, line[2]-1] = line[3] line[2]-1 will cause a type error: unsupported operand type(s) for -: 'str' and 'int'. I need to find another way to build train test matrix. Any other way to build train/test matrix? Example of printed line when iterating over train_data: Pandas(Index=874192, user_id=20859, ISBN='3442248876X', rating=0, title='Die Krieger der Drachenlanze 06. Die Ritter des Schwerts.', Location='tübingen, baden-württemberg, germany', Age=0.0) Note: I thought about creating a new column called book_id which is mapped to book ISBN but containing only integers so that the code works, but I don't know how to do it.
tagged with: train-test-split
favorite count: 0
type: Question
has title: Train/Test Matrix Book Crossing Recommender System
tagged with: python

http://stackoverflow.com/q/47183377
has title: Keep smallest keys for distinct values in Python dictionary
has body: I have a dictionary with distinct, integer keys and potentially duplicated values, like this: my_data = {5:1,2:2,3:2,4:2,1:1} I know how to get the distinct values using set() but what I'd like to do is to select the distinct values with their key pairs, where the small occurring key among the duplicated values, like this: {1:1, 2:2}
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/47183687
has answer: http://stackoverflow.com/a/47183706
score: 1
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/47183706
type: Question
has answer: http://stackoverflow.com/a/47183687
has comment: http://stackoverflow.com/comment/81315841
has comment: http://stackoverflow.com/comment/81315794
upvote count: 1
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/47194502
type: Question
has body: I have a code with add a column to a existing csv file. When i run it for the first time it works well but when i re-run the code it creates two new column SupplyDelay_x and SupplyDelay_y but i want it to overwrite the existing column only. Is this possible? import math supply_delay = abs(purchase_data['DeliveryDate'] - purchase_data['Date']) SupplyDelay= pd.DataFrame({'SupplyDelay': supply_delay}) purchase_data = purchase_data.merge(SupplyDelay, left_index = True, right_index = True) purchase_data.to_csv('Lokad_PurchaseOrders.csv') purchase_data Expected Output
tagged with: http://stackoverflow.com/tag/csv
tagged with: math
accepted answer: http://stackoverflow.com/a/47194633
tagged with: python
has answer: http://stackoverflow.com/a/47194633
type: AnsweredQuestion
score: 0
answer count: 1
has title: How to overwrite a column added to a existing csv file

http://stackoverflow.com/a/47084751
upvote count: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47084641
has comment: http://stackoverflow.com/comment/81118956
has comment: http://stackoverflow.com/comment/81118912
downvote count: 0
has comment: http://stackoverflow.com/comment/81118834
answers question: http://stackoverflow.com/q/47084641
type: Answer
has body: You can get a histogram by turning your data into a pandas.DataFrame: a = [['ID1', 922.63, 'Product 1'], ['ID1', 1001, 'Product 2'], ['ID1', 800, 'Product 1'], ['ID1', 922.63, 'Product 1'], ['ID1', 1001, 'Product 2'], ['ID2', 800, 'Product 1'], ['ID2', 922.63, 'Product 1'], ['ID2', 1001, 'Product 2'], ['ID3', 800, 'Product 1'], ['ID3', 700.63, 'Product 1'], ['ID3', 1200, 'Product 2'], ['ID3', 850, 'Product 1']] q=pd.DataFrame(a,columns=['id','price','product']) q.hist(column='price',bins=100) You can specify the number of bins you want with the bins parameter: q.hist(column='price', bins=100) If you want to group it by product use the by parameter: q.hist(column='price', bins=100,by='product')
score: 4

http://stackoverflow.com/comment/81142530
type: QuestionComment
comment on: http://stackoverflow.com/q/47096228
score: 0
has text: This sounds like you might be better served doing a left join from a dataframe made from mymap?
type: Comment

http://stackoverflow.com/comment/81196669
type: Comment
comment on: http://stackoverflow.com/a/47120353
score: 0
type: AnswerComment
has text: Works great. Thanks.

http://stackoverflow.com/q/47106385
has answer: http://stackoverflow.com/a/47106424
has title: Determine WHY Features Are Important in Decision Tree Models
upvote count: 12
score: 10
tagged with: python
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/47123331
has body: Often-times stakeholders don't want a black-box model that's good at predicting; they want insights about features to have a better understanding about their business, and so they can explain it to others. When we inspect the feature importance of an xgboost or sklearn gradient boosting model, we can determine the feature importance... but we don't understand WHY the features are important, do we? Is there a way to explain not only what features are important but also WHY they're important? I was told to use shap but running even some of the boilerplate examples throws errors so I'm looking for alternatives (or even just a procedural way to inspect trees and glean insights I can take away other than a plot_importance() plot). In the example below, how does one go about explaining WHY feature f19 is the most important (while also realizing that decision trees are random without a random_state or seed). from xgboost import XGBClassifier, plot_importance from sklearn.datasets import make_classification import matplotlib.pyplot as plt X,y = make_classification(random_state=68) xgb = XGBClassifier() xgb.fit(X, y) plot_importance(xgb) plt.show() Update: What I'm looking for is a programmatic procedural proof that the features chosen by the model above contribute either positively or negatively to the predictive power. I want to see code (not theory) of how you would go about inspecting the actual model and determining each feature's positive or negative contribution. Currently, I maintain that it's not possible so somebody please prove me wrong. I'd love to be wrong! I also understand that decision trees are non-parametric and have no coefficients. Still, is there a way to see if a feature contributes positively (one unit of this feature increases y) or negatively (one unit of this feature decreases y). Update2: Despite a thumbs down on this question, and several "close" votes, it seems this question isn't so crazy after all. Partial dependence plots might be the answer. …
downvote count: 2
tagged with: machine-learning
has answer: http://stackoverflow.com/a/47123331
has answer: http://stackoverflow.com/a/47106639
tagged with: scikit-learn
tagged with: decision-tree
tagged with: xgboost
possible better answer: http://stackoverflow.com/a/47106424
favorite count: 0
type: Question

http://stackoverflow.com/comment/81116984
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47076457
has text: Hi Bruno, I finally went for an Ajax POST to get the button registering towards the views.py and went for cache with 30 seconds timeout. having a specific timeout for one specific sessions variable would not work out. regarding the navigating to another page: that was only relevant when I was using a specific url toward a similar html.
score: 0

http://stackoverflow.com/comment/81192914
type: Comment
comment on: http://stackoverflow.com/a/47120536
score: 0
type: AnswerComment
has text: How are you checking that?

http://stackoverflow.com/comment/81188705
has text: The Javascript code only changes the status of the buttons on the page, it does not alter the GPIO pins at all. The PHP program is the only part which changes the status of the GPIO pins so they will only change when the php code executes, which will only happen when you load the buttons web page. You need to modify the pins in the Javascript program and not the php
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47109633

http://stackoverflow.com/comment/81259004
has text: You could just use `loc`.... `df.loc[index, 'order_num'] = 'somestr'`
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47154694

http://stackoverflow.com/comment/81141113
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47094603
has text: There is a difference between using 64-bit-FP-based linear-algebra tools (speed!) and all kinds of extended precision methods or even symbolic-calculation. Your question then is hard to answer without a very specific case of data and algorithm in mind. ```1/3``` won't give you an accurate result either (for the former 2 approaches)!
type: QuestionComment

http://stackoverflow.com/comment/127630732
score: 2
has text: IMO `pprint` is the best solution, I would not have known about it had I not found this thread. The name doesn't exactly make its function obvious.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47131907

http://stackoverflow.com/comment/81271250
has text: Delete the mysql-connector " pip uninstall mysql-connector " download the latest version of https://dev.mysql.com/downloads/connector/python/
comment on: http://stackoverflow.com/a/47160108
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81127348
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47088524
has text: Thank you :) It would be great
type: AnswerComment

http://stackoverflow.com/a/47153540
has comment: http://stackoverflow.com/comment/81278547
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You'll want to define the quote character, setting the delimiter will not get you the desired results. import csv with open('a.csv', 'r') as f: reader = csv.reader(f, delimiter=',', quotechar='"') for row in reader: print row Edit: As for changes to your code, it would look somewhat like this: with open('a.csv', 'r') as infile, open('reordered.csv', 'a') as outfile: fieldnamesout = ['B', 'C', 'A', 'D'] fieldnamesin = ['A', 'B', 'C', 'D'] reader = csv.DictReader(infile, delimiter=',', quotechar='"', fieldnames=fieldnamesin) writer = csv.DictWriter(outfile, delimiter=',', quotechar='"', fieldnames=fieldnamesout, quoting=csv.QUOTE_ALL) for row in reader: writer.writerow(row) Note the quoting=csv.QUOTE_ALL, which instructs the writer to quote all fields according to the quotechar, this may or may not be what you want, other options would be quoting=csv.QUOTE_NONNUMERIC.
answers question: http://stackoverflow.com/q/47153385
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47153385
has comment: http://stackoverflow.com/comment/81256882

http://stackoverflow.com/q/47110775
has comment: http://stackoverflow.com/comment/81171736
has body: I'm following a tutorial for calculating cosine similarity for user-user collaborative filtering and user-item collaborative filtering. I don't understand why we are using transpose for user similarity denominator while we don't use transpose for item similarity. As follow the python code: ratings = np.zeros((n_users, n_items)) for row in df.itertuples(): ratings[row[1]-1, row[2]-1] = row[3] def predict_fast_simple(ratings, similarity, kind='user'): if kind == 'user': return similarity.dot(ratings) / np.array([np.abs(similarity).sum(axis=1)]).T elif kind == 'item': return ratings.dot(similarity) / np.array([np.abs(similarity).sum(axis=1)]) Can anyone explain to me by example because I don't see a difference between both formula (user-based vs item-based): the denominator is the squared sum of ratings for item i and item j by similar users who rated both items. (for user-based squared sum of ratings of intersection of items rated by both users).
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/81171709
answer count: 0
has comment: http://stackoverflow.com/comment/81171625
has title: difference in calculating cosine similarity user/item collaborative filtering
has comment: http://stackoverflow.com/comment/81171592
type: Question
tagged with: cosine-similarity
has comment: http://stackoverflow.com/comment/81171519
type: UnansweredQuestion
tagged with: math
tagged with: python
has comment: http://stackoverflow.com/comment/81171858
has comment: http://stackoverflow.com/comment/81172165

http://stackoverflow.com/comment/81312881
score: 0
has text: I will defer to your answer (if I can give you enough info to post one); and delete my answer. I solved it by deleting my client certs (they had the wrong permissions on them, and since I regenerated my certs 8123847124 times, they were wrong), I turrned off all the host entries in my conf file in favor of hostssl ones.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47164951

http://stackoverflow.com/q/47121675
type: Question
has title: Filtering overlapped rows in data frame based on majority count of labels
accepted answer: http://stackoverflow.com/a/47121740
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47121740
score: 2
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
upvote count: 2
downvote count: 0
answer count: 1
has body: How to filter duplicated rows with overlapped labels? I need a subset of Dataframe where duplicated rows are replaced with one row for which label count is max. Consider a dataframe df: df = pd.DataFrame({ 'X' : [1, -1, 1, 1, 3, -2, -1, -1], 'Y' : [2, 3, 2, 2, 2, -1, 3, 3], 'label' : [0, 1, 1, 0, 2, 1, 2, 2] }) After filtering, the following subset df_output is expected df_output = pd.DataFrame({ 'X' : [1, -1, 3, -2], 'Y' : [2, 3, 2, -1], 'label' : [0, 2, 2, 1] })
favorite count: 0

http://stackoverflow.com/a/47076457
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81141671
accepted answer of: http://stackoverflow.com/q/47075629
answers question: http://stackoverflow.com/q/47075629
has comment: http://stackoverflow.com/comment/81116984
has comment: http://stackoverflow.com/comment/81142098
type: Answer
has body: "How do I prevent the task from firing up each time on refresh" First make sure you use the "POST/redirect/GET" pattern: your view should only fire the task on a "POST" request (GET request must not have side-effects), and then return a HttpResponseRedirect. This won't prevent the user from firing a second task while the first is still running, but it does prevent re-submitting the form each time you refresh ("GET") the page... Ideally, a user can only run one task of this particular type. When firing a task, store it's id in the session, and before firing a task check the session for a task id. If there's one, use it to check the task's state. If it's done (whatever the result), remove the task id and proceed with the new task, else just display a message telling your user he already has a task running. Just make sure you correctly handle the case of a "ghost" task_id in the session (it might be a long finished task for which celery already discarded the results, or a task that got lost in a worker or broker crash - yeah, sh!t happens - etc). A working solution is to actually store a (timestamp, task_id) pair and if celery has no state for the task_id - actually "no state" is (mis)named celery.states.PENDING, which really means "I don't have a clue about this task's state ATM" - check the timestamp. If it's way older than it should then you can probably consider it as long dead and 6 feets under. and prevent navigating to another page. Why would you want to prevent your user to do something else in the meantime, actually ? From a UI/UX point of view, once the task is fired, your user should be redirected to a "please wait" page with (as much as possible) some progress bar or similar feedback. The simple (if a bit heavy) solution here is to do some polling using ajax : you setup a view that takes a task_id, check results / progress and returns them as json, and the 'please wait' page calls this views (using ajax) every X seconds to update itself (and possibly redire…
score: 2
upvote count: 2

http://stackoverflow.com/comment/81155088
has text: after the little change ` df1 = df[df["c"] >= theta] temp=[] for ind,row in df1.iterrows(): temp.append(df[(df["x"] == row["x"]+1) & (df["c"] < theta)]) temp = pd.concat(temp) df_final=pd.concat([df1,temp]) print(df_final)` its work. Thanks @Srinivas V
comment on: http://stackoverflow.com/a/47089982
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81325024
score: 0
has text: Probably a dup of this https://stackoverflow.com/questions/36628847/keep-double-quotes-in-a-text-file-using-csv-reader
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47187792

http://stackoverflow.com/a/47154275
type: Answer
has comment: http://stackoverflow.com/comment/81299700
answers question: http://stackoverflow.com/q/47153182
score: 0
has body: I think its because of the Tesorflow version that you have installed. Update to Tensorflow version 1.4.0 and should work fine.
accepted answer of: http://stackoverflow.com/q/47153182
type: AcceptedAnswer
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/81171609
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47110630
score: 0
has text: @JonClements Yeah, I wasn't optimizing, just doubling the situation. But now I think it's something like the restaurant has five extra chairs, that would explain an overall up to five extra people.

http://stackoverflow.com/q/47176470
tagged with: tkinter
answer count: 3
score: 0
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47184875
accepted answer: http://stackoverflow.com/a/47289000
has answer: http://stackoverflow.com/a/47184875
has comment: http://stackoverflow.com/comment/81302393
has answer: http://stackoverflow.com/a/47289000
has answer: http://stackoverflow.com/a/47176891
tagged with: python
has body: I want to read the content of the selected file by opening with tk filedialog. When i select the file and click on open button the file doesn't open but rather close the dialog box .How can i open the selected file with notepad so i can be able to read the content in the file. from tkinter import * from tkinter import filedialog def my_file(): filename = filedialog.askopenfile(mode="r", initialdir="/", title="select file", filetypes=(("text files", "*.txt"), ("all files", "*.*"))) root = Tk() root.geometry("300x300") #open the selected txt file with notepad to read the content b = Button(root, text="open text file", command = my_file).pack() root.mainloop() EDIT With hint from @PM 2RING and @Erik i changed the filedialog.askopenfile to filedialog.askopenfilename to return it to open with notepad.exe when i select the file. THis is the code: from tkinter import * from tkinter import filedialog import os def my_file(): filename = filedialog.askopenfilename( initialdir="C:/", title="select file", filetypes=(("text files", "*.txt"), ("all files", "*.*"))) for f in filename: return f os.system(r"C:/notepad.exe" + f) root = Tk() root.geometry("300x300") #open the selected txt file with notepad to read the content b = Button(root, text="open text file", command = my_file).pack() root.mainloop() it output this error : Blockquote'C:/notepad.exet' is not recognized as an internal or external command, operable program or batch file. Blockquote but when i changed the return to print it print the directory to terminal.I tried to open with subprocess subprocess.Popen([r'C:\Program Files (x86)\Notepad.exe' + f]) it also doesn't open with this one to.
type: AnsweredQuestion
has title: How to open file with tkfiledialog and read the content with notepad

http://stackoverflow.com/q/47185380
has body: I am trying to create a number of tables with different names (of course) but sharing the same schema. For this purpose, I am using executemany on a Cursor object as follows: tables = ['Meanings', 'Synonyms', 'Antonyms', 'Examples', 'Phrases', 'Pronunciations', 'Hyphenations'] create_table_query = '''CREATE TABLE (?) ( id INTEGER NOT NULL, text TEXT, word_id INTEGER NOT NULL, PRIMARY KEY id, FOREIGN KEY(word_id) REFERENCES Word(id) )''' cursor.executemany(create_table_query, tables) When I execute this snippet, I get the following error message: OperationalError: near "(": syntax error I am having trouble fixing the bug here with my SQL since I find the error message to be not descriptive enough. I have tried the following queries but I am unable to develop the understanding of their success and my query's failure: create_table_query_1 = '''CREATE TABLE {} ( id INTEGER NOT NULL, text TEXT, word_id INTEGER NOT NULL, PRIMARY KEY id, FOREIGN KEY(word_id) REFERENCES Word(id) )''' # Syntax error near "id" create_table_query_2 = '''CREATE TABLE (?) ( id INTEGER PRIMARY KEY, text TEXT, word_id INTEGER NOT NULL, FOREIGN KEY(word_id) REFERENCES Word(id) )''' # Syntax error near "(" create_table_query_1 = '''CREATE TABLE {} ( id INTEGER PRIMARY KEY, text TEXT, word_id INTEGER NOT NULL, FOREIGN KEY(word_id) REFERENCES Word(id) )''' # works with string formatting Also, what are other efficient(in terms of time) ways to achieve the same?
has comment: http://stackoverflow.com/comment/81320189
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/47185912
tagged with: sqlite
answer count: 1
tagged with: string
has title: SQL for creating tables in a database using Python sqlite3
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81319873
has comment: http://stackoverflow.com/comment/81319973
tagged with: python

http://stackoverflow.com/comment/81326815
type: AnswerComment
score: 0
type: Comment
has text: Just based the OP's original code. Clearly an easy fix. I love f-strings.
comment on: http://stackoverflow.com/a/47188275

http://stackoverflow.com/q/47110755
has answer: http://stackoverflow.com/a/47110872
possible better answer: http://stackoverflow.com/a/47110838
type: Question
has comment: http://stackoverflow.com/comment/81171517
tagged with: python
has comment: http://stackoverflow.com/comment/81171896
accepted answer: http://stackoverflow.com/a/47110910
has title: Using string.replace(x, y) to replace all
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47110827
has answer: http://stackoverflow.com/a/47110919
has answer: http://stackoverflow.com/a/47110844
has answer: http://stackoverflow.com/a/47110790
has comment: http://stackoverflow.com/comment/81171473
has body: I have just started to learn python and would like help using string.replace(x,y). Specifically, replacing all to X's and x's depending whether the letter was originally capitalized or not. e.g. John S. Smith -> Xxxx X. Xxxxx What I have created currently is below. print("Enter text to translate:", end ="") sentence = input () replaced = sentence.replace("", "x") print(replaced) However when I input text like "John Smith". I am returned with "xJxoxhxnx xSx.x xSxmxixtxhx". Thank you in advance! Edit: Although string.replace(x,y) may be longer to perform, I'd like to slowly build on my knowledge before finding faster and shorter ways to perform the same operation. I'd highly appreciate it if it was explained in terms of string.replace(x, y) instead of re.sub Edit2: I have been notified that string.replace is the wrong tool to use. Thank you for your help! I will be reading into re.sub instead.
answer count: 7
has answer: http://stackoverflow.com/a/47110910
has answer: http://stackoverflow.com/a/47110838
linked to: http://stackoverflow.com/q/5658369
tagged with: str-replace

http://stackoverflow.com/q/47212747
has answer: http://stackoverflow.com/a/47220080
has title: global name 'fetch' is not defined (GUI TKINTER PYTHON)
upvote count: 1
has comment: http://stackoverflow.com/comment/81375026
favorite count: 0
type: Question
has body: my professor assigned us a GUI programming question for our INTRO TO PYTHON CLASS. I keep getting "global name 'fetch' is not defined" as an error code. How can I resolve this error code? The question: Create an investment-value calculator) Write a program that calculates the future value of an investment at a given interest rate for a specified number of years. The formula for the calculation is as follows: futureValue = investmentAmount * (1 + monthlyInterestRate) ^ years * 12 Use text fields for users to enter the investment amount, years, and interest rate. Display the future amount in a text field when the user clicks the Calculate button. This is what I have so far: from Tkinter import * fields = ('Investment Amount', 'Years', 'Interest Rate', 'Future Value') def future_value(entries): # period rate: r = float(int(entries['Investment Amount'].get())*(1+int(entries['Interest Rate'].get()))^int(entries['Years'].get())*12) entries['Future Value'].delete(0,END) entries['Future Value'].insert(0, r) def makeform(root, fields): entries = {} for field in fields: row = Frame(root) lab = Label(row, width=22, text=field+": ", anchor='w') ent = Entry(row) ent.insert(0,"0") row.pack(side=TOP, fill=X, padx=5, pady=5) lab.pack(side=LEFT) ent.pack(side=RIGHT, expand=YES, fill=X) entries[field] = ent return entries if __name__ == '__main__': root = Tk() ents = makeform(root, fields) root.bind('&lt;Return&gt;', (lambda event, e=ents: fetch(e))) b1 = Button(root, text='Calculate', command=(lambda e=ents: future_value(e))) b1.pack(side=LEFT, padx=5, pady=5) b3 = Button(root, text='Quit', command=root.quit) b3.pack(side=LEFT, padx=5, pady=5) root.mainloop()
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81376924
tagged with: python
downvote count: 5
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/81375338
tagged with: tkinter
score: -4
answer count: 1

http://stackoverflow.com/q/47116912
score: 4
tagged with: flask
accepted answer: http://stackoverflow.com/a/47117043
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/47117025
tagged with: mysql
upvote count: 4
has answer: http://stackoverflow.com/a/47117025
has answer: http://stackoverflow.com/a/47117043
favorite count: 0
type: Question
answer count: 2
has title: Python flask.ext.mysql is deprecated?
has body: When I run from flask.ext.mysql import MySQL I get the warning Importing flask.ext.mysql is deprecated, use flask_mysql instead. So I installed flask_mysql using pip install flask_mysql,installed it successfully but then when I run from flask_mysql import MySQL I get the error No module named flask_mysql. In the first warning I also get Detected extension named flaskext.mysql, please rename it to flask_mysql. The old form is deprecated. .format(x=modname), ExtDeprecationWarning. Could you please tell me how exactly should I rename it to flask_mysql? Thanks in advance.
tagged with: python

http://stackoverflow.com/q/47102382
has comment: http://stackoverflow.com/comment/81155896
has comment: http://stackoverflow.com/comment/81155430
has title: How to pass table name dynamically to sql query in cursor.execute in Python?
type: UnansweredQuestion
tagged with: python
has body: cur.execute("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME LIKE [{}]".format(tableName)) This is my code, but table names are not displaying. Maybe the problem here is in format.
score: 0
has comment: http://stackoverflow.com/comment/81155719
has answer: http://stackoverflow.com/a/47102430
tagged with: sql
answer count: 1
tagged with: cursor
type: Question

http://stackoverflow.com/q/47066711
has title: SVG does not display when embedded in HTML. Displays just fine on its own
has body: I am making a web app using Flask. I have created the following function to dynamically render SVG icons with different colors. All testing is done in the latest Google Chrome on Mac OSX. @app.route("/testicon") def testicon(): return render_template("icons/test.svg", primary="ff0000") (Obviously the primary parameter is not hardcoded in practice. This is just a demonstration) This function renders the following SVG file: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <path id="path3800" class="icon-primary" d="m 32.745902,139.71585 -0.385246,-80.002735 31.333333,-41.349727 z" style="fill:#{{ primary }};stroke:none;" /> (Again, this is simplified for this demonstration.) When I fire up the Flask server and visit localhost:5000/testicon, the SVG displays exactly as it should. However, I created the following function and accompanying template: @app.route("/test") def test(): return render_template("test.html") test.html: Title When visiting localhost:5000/test, nothing shows up. I can inspect the img element and find that its src attribute is, indeed, /testicon, but the SVG does not display. It instead shows the standard "image not found" icon. However, I can right click on that and select "open image in new tab", and the image, once again, displays just fine. The Google Chrome console shows no errors like it would if I put a bad link in the image's src. What do I have to do to get this image to properly display?
type: Question
tagged with: http://stackoverflow.com/tag/svg
accepted answer: http://stackoverflow.com/a/47066712
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/47066712
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/html
answer count: 1

http://stackoverflow.com/a/47134171
downvote count: 0
has comment: http://stackoverflow.com/comment/81218070
upvote count: 2
type: Answer
has body: l=['ID|number1|number2|+|name|location','ID2|number3|number4|-|name2|location2'] j=[] for i in l: i=i.replace("|","=",1) j.append(i) print(j) Output ['ID=number1|number2|+|name|location', 'ID2=number3|number4|-|name2|location2']
answers question: http://stackoverflow.com/q/47134099
score: 2

http://stackoverflow.com/a/47119406
upvote count: 4
answers question: http://stackoverflow.com/q/47119332
has comment: http://stackoverflow.com/comment/81188583
has comment: http://stackoverflow.com/comment/81188611
has comment: http://stackoverflow.com/comment/81188597
downvote count: 1
has comment: http://stackoverflow.com/comment/81188444
score: 3
type: Answer
has body: You can use an mgrid class instance for this. import numpy as np y, x = np.mgrid[:60:10, :6] a = y + x print(a) output [[ 0 1 2 3 4 5] [10 11 12 13 14 15] [20 21 22 23 24 25] [30 31 32 33 34 35] [40 41 42 43 44 45] [50 51 52 53 54 55]] A minor variation is to use the Numpy sum function to perform the addition of the two arrays: a = np.sum(np.mgrid[:60:10, :6], axis=0) However, as user2357112 mentions in the comments, it's more efficient to just do the addition with the +operator rather than calling a function. He also mentions that we can use ogrid to create column and row arrays, which consumes less RAM for y and x. And it's faster too. import numpy as np y, x = np.ogrid[:60:10, :6] a = y + x print(y, x, a, sep='\n\n') output [10] [20] [30] [40] [50]] [[0 1 2 3 4 5]] [[ 0 1 2 3 4 5] [10 11 12 13 14 15] [20 21 22 23 24 25] [30 31 32 33 34 35] [40 41 42 43 44 45] [50 51 52 53 54 55]]

http://stackoverflow.com/comment/81390420
type: Comment
comment on: http://stackoverflow.com/a/47219531
type: AnswerComment
score: 1
has text: @Miraj50 It's difficult to get perfect timings on a multitasking OS, since there are other user programs (like your Web browser) and various system tasks using the CPU(s), and it's not really possible to correctly compensate for them. The best we can do is to do lots of loops to average out those effects.

http://stackoverflow.com/q/47198948
has body: I have a bytearray and want to convert into a buffered reader. A way of doing it is to write the bytes into a file and read them again. sample_bytes = bytes('this is a sample bytearray','utf-8') with open(path,'wb') as f: f.write(sample_bytes) with open(path,'rb') as f: extracted_bytes = f.read() print(type(f)) output: &lt;class '_io.BufferedReader'&gt; But I want these file-like features without having to save bytes into a file. In other words I want to wrap these bytes into a buffered reader so I can apply read() method on it without having to save to local disk. I tried the code below from io import BufferedReader sample_bytes=bytes('this is a sample bytearray','utf-8') file_like = BufferedReader(sample_bytes) print(file_like.read()) but I'm getting an attribute error AttributeError: 'bytes' object has no attribute 'readable' How to I write and read bytes into a file like object, without saving it into local disc ?
duplicate of: http://stackoverflow.com/q/25116
type: AnsweredQuestion
tagged with: arrays
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47199135
favorite count: 0
has comment: http://stackoverflow.com/comment/81346747
tagged with: buffer
tagged with: file-io
type: Question
tagged with: io
linked to: http://stackoverflow.com/q/25116
accepted answer: http://stackoverflow.com/a/47199135
tagged with: python
has title: Convert bytes into BufferedReader in python
score: 27
upvote count: 27

http://stackoverflow.com/a/47087033
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47064885
has body: This is the total code I have come up with. Thank you for all the help. def findFactor(n): factorValues = [] for i in range(1, n + 1): if n % i == 0: factorValues.append(i) values = "" for v in factorValues: values += str(v) + " " print values.count(" ") # prints the number of factors print values findFactor(21) It will print the number of factors, and then the factors on the next line.

optimization
tags question: http://stackoverflow.com/q/47147813
tags question: http://stackoverflow.com/q/47184148
tags question: http://stackoverflow.com/q/47100679
tags question: http://stackoverflow.com/q/47098571
tags question: http://stackoverflow.com/q/47154136
tags question: http://stackoverflow.com/q/47178793
tags question: http://stackoverflow.com/q/47102190
tag name: optimization
tags question: http://stackoverflow.com/q/47192792
tags question: http://stackoverflow.com/q/47115448
tags question: http://stackoverflow.com/q/47138394
tags question: http://stackoverflow.com/q/47202575
tags question: http://stackoverflow.com/q/47142665
tags question: http://stackoverflow.com/q/47125697
tags question: http://stackoverflow.com/q/47072143
tags question: http://stackoverflow.com/q/47126987
tags question: http://stackoverflow.com/q/47174627
tags question: http://stackoverflow.com/q/47081663
tags question: http://stackoverflow.com/q/47115281
type: Tag
tags question: http://stackoverflow.com/q/47154903

http://stackoverflow.com/a/47143492
answers question: http://stackoverflow.com/q/47143361
upvote count: 72
has comment: http://stackoverflow.com/comment/81237672
accepted answer of: http://stackoverflow.com/q/47143361
type: Answer
has comment: http://stackoverflow.com/comment/81237939
has body: A 2D array is a matrix : an array of arrays. A 4D array is basically a matrix of matrices: Specifying one index gives you an array of matrices: &gt;&gt;&gt; x[1] array([[[-0.37387191, -0.19582887], [-2.88810217, -0.8249608 ], [-0.46763329, 1.18628611]], [[-1.52766397, -0.2922034 ], [ 0.27643125, -0.87816021], [-0.49936658, 0.84011388]], [[ 0.41885001, 0.16037164], [ 1.21510322, 0.01923682], [ 0.96039904, -0.22761806]]]) Specifying two indices gives you a matrix: &gt;&gt;&gt; x[1, 1] array([[-1.52766397, -0.2922034 ], [ 0.27643125, -0.87816021], [-0.49936658, 0.84011388]]) Specifying three indices gives you an array: &gt;&gt;&gt; x[1, 1, 1] array([ 0.27643125, -0.87816021]) Specifying four indices gives you a single element: &gt;&gt;&gt; x[1, 1, 1, 1] -0.87816021212791107 x[1,1] gives you the small matrix that was saved in the 2nd column of the 2nd row of the large matrix.
has comment: http://stackoverflow.com/comment/81238232
has comment: http://stackoverflow.com/comment/81237874
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81237370
has comment: http://stackoverflow.com/comment/81237108
score: 72

http://stackoverflow.com/q/47119712
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/47119736
has body: I'm trying to print a table of my database using : pd.read_sql_query("SELECT name,duration FROM activity where (strftime('%W', date) = strftime('%W', 'now'))", conn)) and it work it prints : name duration 0 programmation 150 1 lecture 40 2 ctf 90 3 ceh 90 4 deep learning 133 5 vm capture the flag 100 but I would like to use my function minuteToStr who translate the duration to string likes "1h30" on the duraton colowns. I tried this code but it does'nt work : tableau = str(pd.read_sql_query("SELECT name,duration FROM activity\ where (strftime('%W', date) = strftime('%W', 'now'))", conn)) tableau = re.sub("([0-9]{2,})", minuteToStr(int("\\1")), tableau) print(tableau) Thanks
has answer: http://stackoverflow.com/a/47119745
type: AnsweredQuestion
score: 2
answer count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/47078034
has title: regex replace using function python
has comment: http://stackoverflow.com/comment/81189134
possible better answer: http://stackoverflow.com/a/47119745
favorite count: 0
type: Question
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47119736
has answer: http://stackoverflow.com/a/47119814

http://stackoverflow.com/q/47216415
has comment: http://stackoverflow.com/comment/81404424
has answer: http://stackoverflow.com/a/47217858
type: Question
tagged with: lxml
has body: Input Html Hey This is XXX Im using using lxml xpath to extract Data xpath_paragraph = '//section[@id="article"]/p//text()' items = mydoc.xpath(xpath_paragraph) The Result i got is: Hey This is XXX Expected Result : Hey This is XXX The Result is understandable that i'm extracting text, i have also tried it with node(). its not working either. I need to extract the data with Tags.
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: UnansweredQuestion
has title: HTMl Xpath that return with tags /mark up
has comment: http://stackoverflow.com/comment/81382850
tagged with: http://stackoverflow.com/tag/xml
tagged with: xpath
score: 0
linked to: http://stackoverflow.com/q/6123351
answer count: 2
has answer: http://stackoverflow.com/a/47218871

http://stackoverflow.com/q/47153105
has title: Add borders of table sent by email via Python
has answer: http://stackoverflow.com/a/47178467
favorite count: 0
type: Question
tagged with: smtplib
has body: Currently I use this solution Send table as an email body (not attachment ) in Python for sending tables in emails via Python: import smtplib from smtplib import SMTPException import csv from tabulate import tabulate text = """ Hello, Friend. Here is your data: {table} Regards, Me""" html = """ Hello, Friend. Here is your data: {table} Regards, Me """ with open('result.csv') as input_file: reader = csv.reader(input_file) data = list(reader) text = text.format(table=tabulate(data, headers="firstrow", tablefmt="grid")) html = html.format(table=tabulate(data, headers="firstrow", tablefmt="html")) message = MIMEMultipart( "alternative", None, [MIMEText(text), MIMEText(html,'html')]) message['Subject'] = "Your data" message['From'] = 'a@abc.com' message['To'] = 'b@abc.com' sender = "a@abc.com" receivers = ['b@abc.com'] try: smtp_obj = smtplib.SMTP('mail.abc.com') smtp_obj.sendmail(sender, receivers, message.as_string()) print ("Successfully sent email") except SMTPException: print ("Error: unable to send email") Data is loaded from csv file. But I need to add borders to the table to make it look like pandas DataFrame.
possible better answer: http://stackoverflow.com/a/47445584
accepted answer: http://stackoverflow.com/a/47178467
linked to: http://stackoverflow.com/q/38275467
type: AnsweredQuestion
upvote count: 3
score: 3
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47445584
tagged with: http://stackoverflow.com/tag/html
tagged with: email
tagged with: python
has answer: http://stackoverflow.com/a/47153241

http://stackoverflow.com/comment/81092555
has text: If i'm not wrong, django doesn't let your `STATIC_URL` and `STATIC_ROOT` name be the same. meaning you can't have your static files in a folder called "static" and set url to "static" too. so i think if you change the url or static folder it should work. in production nginx handle this and it won't get to django so i think that's why it works there. try it out and let me know.
type: QuestionComment
comment on: http://stackoverflow.com/q/47072004
score: 0
type: Comment

http://stackoverflow.com/comment/81092134
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47071931
has text: @KristenL Just edited my answer to add a second solution using `while`.
score: 0

http://stackoverflow.com/a/47092414
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81135398
has body: If you want to have squared axes you might want to give adequate figsize instead of playing with gridspecs: fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(600/dpi, 300/dpi), dpi=dpi) Note that x dim in figsize should be y * 2. This would fill the whole fig space and keep the squared proportions of axes.
accepted answer of: http://stackoverflow.com/q/47091592
answers question: http://stackoverflow.com/q/47091592
type: Answer
has comment: http://stackoverflow.com/comment/81135454
score: 2
upvote count: 2

rgb
tags question: http://stackoverflow.com/q/47145311
tag name: rgb
tags question: http://stackoverflow.com/q/47069058
tags question: http://stackoverflow.com/q/47117179
type: Tag

http://stackoverflow.com/a/47180723
has comment: http://stackoverflow.com/comment/81311514
type: Answer
answers question: http://stackoverflow.com/q/47180690
has comment: http://stackoverflow.com/comment/81312193
has comment: http://stackoverflow.com/comment/81337685
has comment: http://stackoverflow.com/comment/81310378
score: 0
has body: If you are using python2.x Use xrange instead of range. xrange is more memory efficient and faster than range Reason: When you do range(1,100000) it will return an array of 100000 elements which is created in memory, where as xrange(1,100000) will generate the number at runtime using the current value and the step value provided to the function.

http://stackoverflow.com/comment/130796633
has text: This should be the accepted answer. The desired functionality is already there automatically in pytest when you assert that two dictionaries are equal. There's no need either to write dedicated logic or to import anything from unittest.
type: Comment
comment on: http://stackoverflow.com/a/68001205
type: AnswerComment
score: 4

http://stackoverflow.com/comment/102119078
has text: `text.contains(regex)` looks suspicious, are you sure that it works correctly (unless `regex` is just string, not `QRegExp`)? btw here is my a bit more advanced version https://stackoverflow.com/a/57845903/964478
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47203950

http://stackoverflow.com/comment/81082344
comment on: http://stackoverflow.com/q/47066858
score: 0
type: Comment
type: QuestionComment
has text: @Wen Did you try it with the rows I provided? I tried with only those 5 rows, and I ecounter the same problem, it doesn't round the values (I added it in the question)

http://stackoverflow.com/q/47124801
tagged with: python-3.x
answer count: 2
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47124871
has title: Itertools permutation
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81199776
tagged with: python-itertools
has comment: http://stackoverflow.com/comment/81199899
score: -3
has comment: http://stackoverflow.com/comment/81199797
tagged with: python
downvote count: 5
has answer: http://stackoverflow.com/a/63115064
has body: I want to find total number of sub-lists from a given list that doesn't contain numbers greater than a specified upper bound number say 10 .suppose my list is: x=[2, 0, 11, 3, 0] and upper bound for sub-list elements is 10 then my sub-lists can be [[2],[2,0],[3],[3,0]].Now when i use itertools for this i am facing an issue from itertools import permutations x=[2, 0, 11, 3, 0] y=[i for i in permutations(x) if max(i)&lt;=10 ] But solution doesn't work.

http://stackoverflow.com/comment/81295846
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47130850
has text: @asakryukin After changing `dtype` back to `int32`, the problem is back... This is probably a bug in Tensorflow?
type: Comment

http://stackoverflow.com/a/47153961
type: Answer
accepted answer of: http://stackoverflow.com/q/47153151
score: 0
has comment: http://stackoverflow.com/comment/81296681
has body: It's better to use coalesce() if we are decreasing the partitions as it more optimized version of repartition(), as it avoids full shuffling of data. df.coalesce(1).write.mode("overwrite").format("json").save("test_file") For more details on repartition and coalesce,check this, Spark - repartition() vs coalesce()
answers question: http://stackoverflow.com/q/47153151
has comment: http://stackoverflow.com/comment/81258941
type: AcceptedAnswer

http://stackoverflow.com/comment/81123755
comment on: http://stackoverflow.com/q/47085527
type: Comment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/158125/discussion-between-maximtitarenko-and-sara).
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81080604
comment on: http://stackoverflow.com/q/47066119
score: 3
type: Comment
type: QuestionComment
has text: This looks like a homework problem. What have you tried so far?

http://stackoverflow.com/a/47161682
accepted answer of: http://stackoverflow.com/q/47161480
answers question: http://stackoverflow.com/q/47161480
type: Answer
has comment: http://stackoverflow.com/comment/81272916
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81273202
score: 1
has body: data['dt']=pd.to_datetime(data['dt'], format = '%Y-%m-%d %H:%M:%S +%f %Z')
type: AcceptedAnswer

http://stackoverflow.com/a/62705441
answers question: http://stackoverflow.com/q/47119987
score: 0
has body: The form loads after the page is loaded so here's how I did it : from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Firefox() driver.get("https://instagram.com") time.sleep(4) driver.find_element_by_name("username").send_keys("foobar") driver.find_element_by_name("password").send_keys("pass") driver.find_element_by_name("password").send_keys(Keys.ENTER) A bit hacky at the end
type: Answer

http://stackoverflow.com/comment/81256531
comment on: http://stackoverflow.com/q/47097803
type: QuestionComment
has text: I'm using TestCase. Also your link is not working.
score: 0
type: Comment

http://stackoverflow.com/q/47104894
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81160401
has answer: http://stackoverflow.com/a/47104968
has body: Im trying to generate from random variables for an inserting in a database but I'm always getting the same string when i try to iterate thru the widgetname list. I'm getting gadget all the 5 iterations. How do i get different string? output Im getting wd name: gadget 91 9 wd name: gadget 87 1 wd name: gadget 41 10 wd name: gadget 16 10 wd name: gadget 50 4 my code: widgetname=['sprocket', 'gizmo', 'gadget'] price=0 design_date='2010-02-10' version=0 design_comment='design comment goes here' count = 0 while (count &lt; 5): count += 1 for widget in widgetname: widget_name = widget for i in range(count): price=random.randint(1.0, 100.0) for j in range(count): version=random.randint(1.0, 10.0) print('wd name: '+widget_name) print(price) print(version)
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81160441
has comment: http://stackoverflow.com/comment/81160461
accepted answer: http://stackoverflow.com/a/47104968
has comment: http://stackoverflow.com/comment/81160445
answer count: 1
has title: python, iterate through a list in a nested for loop
has comment: http://stackoverflow.com/comment/81161178
has comment: http://stackoverflow.com/comment/81160419

http://stackoverflow.com/q/47205433
answer count: 1
has title: SQLAlchemy table reflection - remove duplicate source column references
has answer: http://stackoverflow.com/a/51024467
tagged with: sqlalchemy
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
has body: I am trying to reflect a table using sqlalchemy by executing: PilotCycle = Table('PilotCycle', pr_meta, schema='dbo', autoload=True, autoload_with=pr_engine) However, I receive an error: "ArgumentError: ForeignKeyConstraint with duplicate source column references are not supported." I think I figured out what's causing this by inspecting the table's foreign keys. from sqlalchemy import inspect insp = inspect(pr_engine) fks = insp.get_foreign_keys('PilotCycle') print(fks) This returns a list of dicts with each element being a foreign key constraint. I found one foreign key, 'FK_PilotCycle_Equipment', that has duplicate constrained columns (EquipmentID) and duplicate referred columns (ID). Here is the dict in the list that I am referring to: { 'name': 'FK_PilotCycle_Equipment', 'constrained_columns': ['EquipmentID', 'EquipmentID'], 'referred_schema': None, 'referred_table': 'Equipment', 'referred_columns': ['ID', 'ID'] } I have read only access to the database. How can I fix this?
upvote count: 1
tagged with: python
score: 1

http://stackoverflow.com/a/47143321
has comment: http://stackoverflow.com/comment/81238672
has comment: http://stackoverflow.com/comment/81238913
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/81238082
has comment: http://stackoverflow.com/comment/81239077
has comment: http://stackoverflow.com/comment/81238035
accepted answer of: http://stackoverflow.com/q/47142950
score: 1
has comment: http://stackoverflow.com/comment/81238724
answers question: http://stackoverflow.com/q/47142950
has body: To give some example of what we mean, I think this is kind of alright import random import pickle class BaseCharacter: def __init__(self): self.gold = random.randint(25, 215) * 2.5 self.currentHealth = 100 self.maxHealth = 100 self.stamina = 10 self.resil = 2 self.armor = 20 self.strength = 15 self.agility = 10 self.criticalChance = 25 self.spellPower = 15 self.speed = 5 # set gold as random gold determined from before self.first_name = 'New' self.last_name = 'Player' self.class_ = None def update(self, attrs, factors): # Maybe a try except would be nice here for attr, fac in zip(attrs, factors): val = getattr(self, attr) setattr(self, attr, val * fac) def show_stats(self): for attr in self.__dict__: # Don't do this... but meh print(attr, getattr(self, attr)) def save(self): with open(self.first_name+'_'+self.last_name, 'wb') as f: pickle.dump(self, f) @staticmethod def load(filename): with open(filename, 'rb') as f: return pickle.load(f) class WarriorCharacter(BaseCharacter): def __init__(self, first_name, last_name): super().__init__() self.class_ = 'Warrior' self.first_name = first_name self.last_name = last_name self.update(['stamina', 'resil', 'armor'], [1.25, 1.25, 1.35]) w = WarriorCharacter('Jon', 'Snow') w.show_stats() w.save() loadedW = WarriorCharacter.load('Jon_Snow') print(loadedW.class_)

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/47109343
tags question: http://stackoverflow.com/q/47190486
tags question: http://stackoverflow.com/q/47163614
tags question: http://stackoverflow.com/q/47189009
tags question: http://stackoverflow.com/q/47083201
tags question: http://stackoverflow.com/q/47067510
tags question: http://stackoverflow.com/q/47213310
tags question: http://stackoverflow.com/q/47075946
type: Tag

http://stackoverflow.com/a/47165943
upvote count: 2
has body: You can't remove lines from a file, per se. Rather, you have to rewrite the file, including only the valid lines. Either close the file after you've read all the data, and reopen in mode "w", or write to a new file as you process the lines (which takes less memory in the short term. Your main problem with detecting line validity seems to be handling the input. You want to convert the input text to a list of values; this is a skill you should get from learning your tools. The ones you need here are split to divide the line, and int to convert the values. For instance: line_vals = line.split(',') Now iterate through line_vals, and convert each to integer with int. Validity: you need to count the quantity of each value you have in this list. You should be able to count things by value; if not back up to your prior lessons and review basic logic and data flow. If you want the advanced method for this, use collections.Counter, which is a convenient type of dictionary that accumulates counts from any sequence. Does that get you moving? If you're still lost, I recommend some time with a local tutor.
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47165807

http://stackoverflow.com/comment/81358068
comment on: http://stackoverflow.com/a/47203792
type: Comment
score: 0
has text: Thanks for all the responses. I think I'll try to move the voted items to another table and choose only one item from the non-voted items' table.
type: AnswerComment

http://stackoverflow.com/comment/81926446
has text: Yeah, it's a bit unfortunate that you can edit answers posts on SO, but the comments stay the same. They should either force user to add a new answer, or mark comments which relate to the previous answer.
comment on: http://stackoverflow.com/a/47207166
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/a/47197987
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47197463
has comment: http://stackoverflow.com/comment/82850830
has body: See if the below code works for your scenario: import os import shutil for root, subdirs, files in os.walk('C:/directory'): for d in subdirs: if d == "old data": shutil.rmtree(os.path.join(root, d)) shutil.rmtree will delete the entire "old data" directory
score: 7
upvote count: 7

http://stackoverflow.com/comment/81131112
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47090886
score: 1
has text: @paraxod And how is that a problem?

http://stackoverflow.com/comment/81203278
comment on: http://stackoverflow.com/q/47126370
type: Comment
type: QuestionComment
has text: You can convert the opencv image to PIL image. https://stackoverflow.com/questions/10965417/how-to-convert-numpy-array-to-pil-image-applying-matplotlib-colormap
score: 0

aes
tag name: aes
tags question: http://stackoverflow.com/q/47070678
type: Tag

http://stackoverflow.com/comment/81308751
score: 0
has text: Where's your data?
type: QuestionComment
comment on: http://stackoverflow.com/q/47179799
type: Comment

http://stackoverflow.com/q/47148872
has answer: http://stackoverflow.com/a/65851049
has answer: http://stackoverflow.com/a/59688162
has answer: http://stackoverflow.com/a/59707105
upvote count: 51
has answer: http://stackoverflow.com/a/73411809
tagged with: python
has answer: http://stackoverflow.com/a/65435541
has answer: http://stackoverflow.com/a/62512171
has answer: http://stackoverflow.com/a/67847167
type: Question
accepted answer: http://stackoverflow.com/a/47150939
has answer: http://stackoverflow.com/a/58636683
tagged with: selenium-chromedriver
has answer: http://stackoverflow.com/a/63174205
has answer: http://stackoverflow.com/a/47255840
has answer: http://stackoverflow.com/a/69585561
has answer: http://stackoverflow.com/a/56559669
has answer: http://stackoverflow.com/a/47150939
has answer: http://stackoverflow.com/a/57345688
answer count: 21
has answer: http://stackoverflow.com/a/67349388
tagged with: selenium
has answer: http://stackoverflow.com/a/69342331
has answer: http://stackoverflow.com/a/71319500
has answer: http://stackoverflow.com/a/69351553
has title: 'Webdrivers' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home
tagged with: google-chrome
downvote count: 1
has answer: http://stackoverflow.com/a/60581559
has answer: http://stackoverflow.com/a/60469050
possible better answer: http://stackoverflow.com/a/47255840
favorite count: 0
has body: I've looked around checked both documentations and have found no answer. I've been trying to use InstaPy a instagram api for python. After failing with multiple errors and assuming InstaPy is just having some issues so i tried to raw code it using selinium. after inserting the example code and alter it to my liking i just made sure this one would work. I received a new error instead of the old one saying the permissions may not be right. I have tried reinstall and running as admin but nothing works. how do i fix this and/or what does this mean Code: import time from selenium import webdriver driver = webdriver.Chrome('C:\Webdrivers') # Optional argument, if not specified will search path. driver.get('http://www.google.com/xhtml'); time.sleep(5) # Let the user actually see something! search_box = driver.find_element_by_name('q') search_box.send_keys('ChromeDriver') search_box.submit() time.sleep(5) # Let the user actually see something! driver.quit() Error: Traceback (most recent call last): File "C:\Program Files (x86)\Python36-32\lib\site-packages\selenium\webdriver\common\service.py", line 74, in start stdout=self.log_file, stderr=self.log_file) File "C:\Program Files (x86)\Python36-32\lib\subprocess.py", line 707, in __init__ restore_signals, start_new_session) File "C:\Program Files (x86)\Python36-32\lib\subprocess.py", line 990, in _execute_child startupinfo) PermissionError: [WinError 5] Access is denied During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Webdrivers\RawBot.py", line 5, in &lt;module&gt; driver = webdriver.Chrome('C:\Webdrivers') # Optional argument, if not specified will search path. File "C:\Program Files (x86)\Python36-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 62, in __init__ self.service.start() File "C:\Program Files (x86)\Python36-32\lib\site-packages\selenium\webdriver\common\service.py", line 86, in start os.path.basename(self.path), self.start_error_me…
tagged with: selenium-webdriver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65892950
score: 50

http://stackoverflow.com/comment/81312878
comment on: http://stackoverflow.com/a/47181675
type: AnswerComment
score: 0
type: Comment
has text: that's a classic: I _never_ use conditions in `while` because you end up copying/pasting the same condition or call twice. Check my oneliner if you have aspirin handy :)

http://stackoverflow.com/a/47193410
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47193173
answers question: http://stackoverflow.com/q/47193173
type: Answer
has body: It looks like using the fileinput module in the standard library is the way to go. You can simplify your code to: import fileinput import re import sys regex = re.compile(r'&lt;pattern&gt;') for line in fileinput.input(file_in_read, inplace=True): sys.stdout.write(line) if regex.search(line): sys.stdout.write(additional_lines)
score: 0

http://stackoverflow.com/comment/81161229
type: Comment
type: QuestionComment
score: 2
has text: Given that `python3` runs 3.5, `python3 -m pip install lxml` should install lxml in the 3.5 site-packages. I have no idea about 2.7.
comment on: http://stackoverflow.com/q/47105185

http://stackoverflow.com/q/47180499
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/28947607
has title: python 3 not recognizing vertical bar character
has body: I had the following code but python 3 is not recognizing the vertical pipe as a unicode character. m_cols = ['movie_id', 'title', 'release_date', 'video_release_date', 'imdb_url'] movies = pd.read_csv( 'http://files.grouplens.org/datasets/movielens/ml-100k/u.item', sep='|', names=m_cols, usecols=range(5)) movies.head() and I get the following error UnicodeDecodeError Traceback (most recent call last) pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._convert_tokens (pandas\_libs\parsers.c:14858)() pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._convert_with_dtype (pandas\_libs\parsers.c:17119)() pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._string_convert (pandas\_libs\parsers.c:17347)() pandas\_libs\parsers.pyx in pandas._libs.parsers._string_box_utf8 (pandas\_libs\parsers.c:23041)() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: invalid continuation byte During handling of the above exception, another exception occurred: UnicodeDecodeError Traceback (most recent call last) &lt;ipython-input-15-72a8222212c1&gt; in &lt;module&gt;() 4 movies = pd.read_csv( 5 'http://files.grouplens.org/datasets/movielens/ml-100k/u.item', ----&gt; 6 sep='|', names=m_cols, usecols=range(5)) 7 8 movies.head() What could be the possible reason behind this, and how can I fix this?
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81309819
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/47180704
accepted answer: http://stackoverflow.com/a/47180704

http://stackoverflow.com/comment/81232434
comment on: http://stackoverflow.com/q/47141264
type: Comment
has text: In my code I don't use _. I am using it in this question for clarity.
score: 1
type: QuestionComment

http://stackoverflow.com/q/47098395
has comment: http://stackoverflow.com/comment/81146551
score: 3
has comment: http://stackoverflow.com/comment/81147030
tagged with: python
has body: def findEquals(words, word): wordCounts = sorted(Counter(word).values()) equals = [] for word in words: wordsCounts = sorted(Counter(word).values()) if wordCounts == wordsCounts: equals.append(word) return equals So I have this loop inside my code where words is a list of words. For each word in the list, I store the frequency of letters in a Counter as values which is then sorted using the method sorted(). I know that sorted() has a worst time complexity of O(nlog(n)). Am I right to say that the worst time complexity of the whole code is O(n^2 log(n)) since sorted() is used inside a for loop?
type: Question
has answer: http://stackoverflow.com/a/47098577
answer count: 2
has comment: http://stackoverflow.com/comment/81146578
has comment: http://stackoverflow.com/comment/81146786
upvote count: 3
tagged with: time-complexity
has answer: http://stackoverflow.com/a/47098527
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/81146947
has title: Time complexity of python sorted method inside a loop
has comment: http://stackoverflow.com/comment/81147101
favorite count: 0

http://stackoverflow.com/comment/137189462
has text: @WaterBoy Re: solution 2, I believe it is already optimal for large dataframes. If concatenating the dataframes then writing, it would require an additional copy which is slower and doubles RAM usage. For example, if the dataframe was 10 columns of 50 million rows each, the act of first concatenating (which creates another copy) will take longer than flushing the first part to disc, then the second part, then closing. However, for smaller dataframes, a cleaner parquet file may result from concatenating first as columns would be stored in one contiguous memory array rather than two.
type: Comment
comment on: http://stackoverflow.com/a/70817689
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81196953
type: AnswerComment
has text: I tried it. The error still persists. I receive a "'QuerySet' object has no attribute 'objects'" error. Does the error has anything to do with the form (how I am trying to load the user information in the init function?)
comment on: http://stackoverflow.com/a/47122497
type: Comment
score: 0

http://stackoverflow.com/comment/81233586
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47140810
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/158339/discussion-between-aaron-and-lester-burnham).

http://stackoverflow.com/comment/81257809
has text: What is unclear about that error message?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47153937
type: QuestionComment

http://stackoverflow.com/comment/81419842
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47219705
has text: Thanks for responding back, we are close I just cannot figure out how to call it properly.. aim_mouse.thompsonAimer.handle_click(x, y) find the positions perfectly, however Its not clicking....

http://stackoverflow.com/a/47159784
accepted answer of: http://stackoverflow.com/q/47159646
score: 2
answers question: http://stackoverflow.com/q/47159646
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81269310
downvote count: 0
has body: Try moving out the p.join(). That will wait for the process to complete which effectively makes this a serial process as you kick off the process (i.e. start) and then wait for each one (i.e. join). Instead you can try something like this: # construct the workers workers = [multiprocessing.Process(target=worker, args=(file_location_ + filename,)) for filename in os.listdir(file_location_)] # start them for proc in workers: proc.start() # now we wait for them for proc in workers: proc.join() (I didn't try running this in your code but something like that should work.) EDIT If you want to limit the number of workers/processes then I'd recommend just using a Pool. You can specify how many processes to use and then map(..) the arguments to those processes. Example: # construct a pool of workers pool = multiprocessing.Pool(6) pool.map(worker, [file_location_ + filename for filename in os.listdir(file_location_)]) pool.close()
upvote count: 2
type: Answer

http://stackoverflow.com/q/47189009
score: 0
tagged with: spyder
favorite count: 0
type: Question
has body: I would how to run a script using a remote kernel ? I have everything set and did connect successfully to the kernel from Spyder but I'm getting an error when executing the script. It says file (script file) not found. Is there a way to just run the script without copying it and all the data files ? Just use the remote kernel for calculation ? Thanks !
tagged with: remote-server
upvote count: 2
type: UnansweredQuestion
tagged with: remote-access
downvote count: 2
answer count: 1
tagged with: python
has title: Run script on remote kernel
tagged with: anaconda
has answer: http://stackoverflow.com/a/47190182

http://stackoverflow.com/a/47090260
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47090039
downvote count: 0
answers question: http://stackoverflow.com/q/47090039
type: AcceptedAnswer
type: Answer
has body: What you need is not a Tk class but a Frame instead : import tkinter as tk # CLASS FOR OWN PANEL: class Mypanel(tk.Frame): def __init__(self, master=None, **kwargs): super().__init__(master, kwargs) self.label = tk.Label(self, text="Enter here:") self.entry = tk.Entry(self) self.label.pack() self.entry.pack() # def on_button(self): # print(self.entry.get()) # FN FOR BUTTON: def adder(): main_label.set((panel1.entry.get() + panel2.entry.get())) # CREATE GUI ELEMENTS: main_window = tk.Tk() # CREATE MAIN WINDOW panel1 = Mypanel(main_window) # CREATE A PANEL panel2 = Mypanel(main_window) # CREATE ANOTHER PANEL main_label = tk.Label(main_window, text="Press button to get values.") main_button = tk.Button(main_window, text="Get values.", command=adder) # PACK ALL GUI ELEMENTS IN main WINDOW panel1.pack() panel2.pack() main_label.pack() main_button.pack() # SHOW MAIN WINDOW: main_window.mainloop() You can see the class Tk as the main application, and you put widgets inside. There should be only one Tk in a code.

http://stackoverflow.com/a/47354243
has body: As best I can tell a metaclass can do this. You somehow need to get the decorators available to the metaclass, possibly by importing, and then you can include them in the prepared namespace: class includewraps(type): def prepare(*args): from functools import wraps return {'wraps': wraps} class haswraps (metaclass = includewraps): # wraps is available in this scope
downvote count: 0
type: Answer
score: 3
answers question: http://stackoverflow.com/q/47112884
upvote count: 3

http://stackoverflow.com/q/47205335
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81359634
has body: I have a string like 76/,2., 115., 12, 5/e12, .111 107,/1, 108/61a, f457f/3 11/150 and I would like to find the following values inside: 76/2, 115, 12, 5/12, 111, 107/1, 108/61, 457/3 and 11/150 Note, that for 107,/1 I want 107/1, but for 107, /1 I would want 107 and 1, same for 76/,2. I try with this regex, but I don't know how to keep only numeric and (if there is) a slash character inside results. Is it possible? I can just iterate over results and check if each one contains unwanted chars and remove them, but I hoped to find a regex way to do it.
has comment: http://stackoverflow.com/comment/81359749
accepted answer: http://stackoverflow.com/a/47205976
has answer: http://stackoverflow.com/a/47205976
has title: Omit unwanted char in each regex result
downvote count: 0
has comment: http://stackoverflow.com/comment/81359481
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/81361916
has comment: http://stackoverflow.com/comment/81359536
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81359926
has comment: http://stackoverflow.com/comment/81360824
answer count: 1
tagged with: regex
score: 1

http://stackoverflow.com/a/47079228
type: Answer
answers question: http://stackoverflow.com/q/47078948
upvote count: 2
score: 2
downvote count: 0
has body: Look at this Elasticsearch python API, you have from_ and size parameters to perform your request.
has comment: http://stackoverflow.com/comment/81107987
has comment: http://stackoverflow.com/comment/81107467
has comment: http://stackoverflow.com/comment/81108379

http://stackoverflow.com/q/47101515
upvote count: 0
answer count: 1
tagged with: scipy
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81155477
has comment: http://stackoverflow.com/comment/81176679
tagged with: python
score: -1
has body: I have a dataset of 60,000 examples of the form: mu1 mu2 std1 std2 0 -0.745 0.729 0.0127 0.0149 1 -0.711 0.332 0.1240 0.0433 ... They are essentially parameters of 2-dimensional normal distributions. What I want to do is create a (NxN) matrix P such that P_ij = Normal( mu_i | mean=mu_j, cov=diagonal(std_j)), where mu_i is (mu1, mu2) for data 'i'. I can do this with the following code for example: from scipy import stats import numpy as np mu_all = data'mu1', 'mu2' std_all = data'std1', 'std2' P = [] for i in range(len(data)): mu_i = mu_all[i,:] std_i = std_all[i,:] prob_i = stats.multivariate_normal.pdf(mu_all, mean=mu_i, cov=np.diag(std_i)) P.append(prob_i) P = np.array(P).T But this is too expensive (my machine freezes). How can I do this more efficiently? My guess is that scipy cannot handle computing pdf of 60000 at once. Is there an alternative?
tagged with: vectorization
accepted answer: http://stackoverflow.com/a/47113447
linked to: http://stackoverflow.com/q/1053928
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47113447
has title: creating a large pdf matrix efficiently

http://stackoverflow.com/q/47115719
downvote count: 0
answer count: 1
tagged with: selenium
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47132508
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47132508
score: 1
has title: Open an accordion with selenium in python
tagged with: python
has body: I'm trying to open an accordion link with selenium in python. The element looks like this when closed: &lt;div class="crm-accordion-body" style="display: none;"&gt; and this when open: &lt;div class="crm-accordion-body" style="display: block;"&gt; The code I'm trying to use to change the style is: driver.execute_script("document.getElementsByClassName('crm-accordion-body').style.display = 'block';") This produces the following error: WebDriverException: Message: unknown error: Cannot set property 'display' of undefined (Session info: chrome=61.0.3163.100) (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 6.1.7601 SP1 x86_64) Anyone know what I'm doing wrong? Thanks.

http://stackoverflow.com/comment/81174462
type: QuestionComment
has text: No, they cannot be sorted. What do you mean by is A < B is valid operation?
comment on: http://stackoverflow.com/q/47112109
score: 0
type: Comment

http://stackoverflow.com/q/47073231
score: 0
has answer: http://stackoverflow.com/a/47074677
tagged with: pandas
has title: Code understanding python
answer count: 1
tagged with: set
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47074677
type: Question
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/81094545
has body: I am having a hard time to understand this line of code written in python: drop_index = assets_df[assets_df['id']==Id].sort_values(['date_signed_contract','start_date'], ascending = False)[1::].index.tolist() Does ascending = False mean it's descending? Also the [1::] refers to what here? Just trying to get the right idea.
type: AnsweredQuestion

http://stackoverflow.com/q/47203254
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47203531
tagged with: tqdm
has title: How to update N lines on screen with Python?
score: 2
upvote count: 3
tagged with: printing
has comment: http://stackoverflow.com/comment/81356829
tagged with: tui
downvote count: 1
answer count: 1
has body: I have spawned N processes and monitoring their statuses. So, I would like to print N lines on screen with changing statuses on each. How to do this with python? I don't wan't vizible re-prints. Is there any library like tqdm for such updates?
favorite count: 0
type: Question

http://stackoverflow.com/q/47182641
answer count: 1
tagged with: data-mining
tagged with: dataset
has title: Decision tree implementation in python for dataset error
upvote count: 1
tagged with: decision-tree
downvote count: 1
favorite count: 0
type: Question
has body: I have done the following code for python decision tree algorithm implementation: from csv import reader def load_csv(filename): file = open(filename, "rb") lines = reader(file) dataset = list(lines) return dataset # Split a dataset based on an attribute and an attribute value def test_split(index, value, dataset): left, right = list(), list() for row in dataset: if row[index] &lt; value: left.append(row) else: right.append(row) return left, right # Calculate the Gini index for a split dataset def gini_index(groups, classes): # count all samples at split point n_instances = float(sum([len(group) for group in groups])) # sum weighted Gini index for each group gini = 0.0 for group in groups: size = float(len(group)) # avoid divide by zero if size == 0: continue score = 0.0 # score the group based on the score for each class for class_val in classes: p = [row[-1] for row in group].count(class_val) / size score += p * p # weight the group score by its relative size gini += (1.0 - score) * (size / n_instances) return gini # Select the best split point for a dataset def get_split(dataset): class_values = list(set(row[-1] for row in dataset)) b_index, b_value, b_score, b_groups = 999, 999, 999, None for index in range(len(dataset[0])-1): for row in dataset: groups = test_split(index, row[index], dataset) gini = gini_index(groups, class_values) if gini &lt; b_score: b_index, b_value, b_score, b_groups = index, row[index], gini, groups return {'index':b_index, 'value':b_value, 'groups':b_groups} # Create a terminal node value def to_terminal(group): outcomes = [row[-1] for row in group] return max(set(outcomes), key=outcomes.count) # Create child splits for a node or make terminal def split(node, max_depth, min_size, depth): left, right = node['groups'] del(node['groups']) # check for a no split if not left or not right: node['left'] = node['right'] = to_terminal(left + right) return # check for max depth if depth &gt;= max_depth: node['left'], node['right'] = to_terminal(le…
tagged with: python
has answer: http://stackoverflow.com/a/47188331
score: 0
type: UnansweredQuestion
tagged with: classification

http://stackoverflow.com/comment/81229417
has text: That sounds like it should work, but I'd need to see a full reproduction to make sure. Can you either post a complete example and the error message as an edit to the question, or in a [GitHub issue](https://github.com/tensorflow/tensorflow/issues)? Thanks!
score: 0
comment on: http://stackoverflow.com/q/47103249
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81189433
has text: Thank's for your help, but it doesnt work ... I got : ` name duration 0 programmation NaN 1 lecture NaN 2 ctf NaN 3 ceh NaN 4 deep learning NaN 5 vm capture the flag NaN 6 programmation NaN `
type: Comment
comment on: http://stackoverflow.com/a/47119814
score: 0
type: AnswerComment

http://stackoverflow.com/q/47139930
tagged with: python
type: AnsweredQuestion
tagged with: while-loop
has title: Sorting output from a while loop in Python 3
score: 1
has answer: http://stackoverflow.com/a/47140211
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47140211
has body: The following code prints out number sequences up to around 100 from a list. A fair amount of the sequences print out above 100. I want to know how to only print out the numbers that add up to 100 on the button. I have tried printing the results to a list without luck. I tried putting in if and else statements to filter the results but with no luck. I looked at list comprehensions but I know those don't use while loops and so I don't know how to get the same results with a for loop. The only information I can seem to find online is basic lessons on how to use a while loop and just printing a list of numbers out. I could not find anything about how to sort a list of numbers printed. Here is the code: import itertools list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in list1: a = 0 num1 = 2 num2 = i seq = ([a]) it = itertools.cycle((num1,num2)) while a &lt; 100: a += next(it) print(a, end = " ") seq.append(a) print() print("Here are the numbers", num1, "&amp;", num2, "added together in a sequence") print() Output: 2 3 5 6 8 9 11 12 14 15 17 18 20 21 23 24 26 27 29 30 32 33 35 36 38 39 41 42 44 45 47 48 50 51 53 54 56 57 59 60 62 63 65 66 68 69 71 72 74 75 77 78 80 81 83 84 86 87 89 90 92 93 95 96 98 99 101 Here are the numbers 2 &amp; 1 added together in a sequence 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100 Here are the numbers 2 &amp; 2 added together in a sequence 2 5 7 10 12 15 17 20 22 25 27 30 32 35 37 40 42 45 47 50 52 55 57 60 62 65 67 70 72 75 77 80 82 85 87 90 92 95 97 100 Here are the numbers 2 &amp; 3 added together in a sequence 2 6 8 12 14 18 20 24 26 30 32 36 38 42 44 48 50 54 56 60 62 66 68 72 74 78 80 84 86 90 92 96 98 102 Here are the numbers 2 &amp; 4 added together in a sequence 2 7 9 14 16 21 23 28 30 35 37 42 44 49 51 56 58 63 65 70 72 77 79 84 86 91 93 98 100 Here are the numbers 2 &amp; 5 added together in a sequence 2 8 10 16 18 24 26 32 34 40 4…

http://stackoverflow.com/comment/81182063
comment on: http://stackoverflow.com/a/47116068
type: Comment
score: 2
type: AnswerComment
has text: This answer is (probably) correct, but the OP seems to struggle with basic notions of programming: what's does it mean to "return", to "print", to iterate using `for`, etc. I doubt these can be taught in a SO answer.

http://stackoverflow.com/comment/81276149
type: AnswerComment
comment on: http://stackoverflow.com/a/47157180
type: Comment
has text: It gives this error: ImportError: No module named proxies
score: 0

http://stackoverflow.com/a/48912788
has body: Use pyi-makespec --onefile yourprogram.py to generate a sample spec file for onefile mode. https://pyinstaller.readthedocs.io/en/stable/man/pyi-makespec.html There is no COLLECT call, and the EXE call is different. Example: exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='main', debug=False, strip=False, upx=True, runtime_tmpdir=None, console=True )
score: 50
type: Answer
downvote count: 0
upvote count: 50
accepted answer of: http://stackoverflow.com/q/47143315
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47143315

http://stackoverflow.com/q/47183762
type: UnansweredQuestion
has title: graph-tool graph_draw plot a colorbar legend
has answer: http://stackoverflow.com/a/47237441
answer count: 1
tagged with: python
score: 1
upvote count: 1
tagged with: graph-tool
has body: So I have a graph and I draw this graph to a PDF using this command: graph_draw(G_Sub, vertex_fill_color=pr, vertex_size=prop_to_size(pr, mi ...: =5, ma=15), vorder=pr, vcmap=matplotlib.cm.gist_heat, output="G_Sub_pr. ...: pdf", vertex_text=G_Sub.vp['name'], vertex_font_size=0.5) Now, I want the colorbar used to generate node colors to be plotted next to the graph. Is there a way to do this in graph-tool?
favorite count: 0
type: Question
downvote count: 0

http://stackoverflow.com/a/47145464
accepted answer of: http://stackoverflow.com/q/47145305
has comment: http://stackoverflow.com/comment/81241822
answers question: http://stackoverflow.com/q/47145305
type: Answer
has comment: http://stackoverflow.com/comment/81241971
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: You first need to convert the values associated with each key in your dict to lists: You can accomplish this via dict comprehension. Afterwards, it's simply a matter of appending items to the list at the desired key in the dictionary. The following code would work: dictionary = {"dog" : "bark", "cat" : "kitten"} dictionary = {key : [value] for key, value in dictionary.items()} dictionary["dog"].append("woof") dictionary["dog"].append("speak") At which point, if you print dictionary, the output will be: {'dog': ['bark', 'woof', 'speak'], 'cat': ['kitten']}

button
tags question: http://stackoverflow.com/q/47205538
tags question: http://stackoverflow.com/q/47156055
tags question: http://stackoverflow.com/q/47082319
tag name: button
type: Tag
tags question: http://stackoverflow.com/q/47119431

http://stackoverflow.com/q/47074836
answer count: 0
type: UnansweredQuestion
has title: Encoding in query sql in python script
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: parameters
tagged with: sql
score: 1
tagged with: python
has body: Hello I have a problem I want to put parameter in a sql query but it's difficul because of the encoding, params = {'external_id': external_id, 'source': source, 'distance': distance, 'date1': date1, 'date2': date2, 'date3': date3, 'date4': date4, 'date5': date5, 'date6': date6, 'date7': date7, 'date8': date8 } sql_pays = """ SELECT adm_country_code, adm_region_code, adm_city_code FROM Product WHERE external_id = {external_id} AND source = '{source}' AND product_language = 'fr' """.format(**params) I want to get the destination of the id localisation = executor.query_to_df(sql_pays%params) series1 = localisation.iloc[0,:] def get_localisation(): if series1["adm_city_code"] == "Paris" or series1["adm_city_code"] == "Lyon" or series1["adm_city_code"] == "Marseille" : return series1.iloc[2,] elif series1["adm_country_code"] == "Espagne" or series1["adm_country_code"] == "Italie" or series1["adm_country_code"] == "France": return series1.iloc[1,] else: return series1.iloc[0,]; loca = get_localisation() loca I obtain this : 'Tha\xc3\xaflande' Then I use loca in an sql query query_vues = """ SELECT email FROM table WHERE member_language = 'fr' AND event_type IN ('View') AND adm_country_code in ('{loca}') AND (timestamp&gt;='{date4}' OR (timestamp&gt;='{date5}' AND timestamp&lt;='{date6}')) """.format(**params) what could I do to have Thaïlande in loca ? thank you very much N
type: Question

http://stackoverflow.com/comment/81159500
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47097811
score: 0
has text: Thanks. Any alternatives that I can use?

http://stackoverflow.com/q/47200104
has title: Get only declared methods of a class (excluding inherited classes' methods)
downvote count: 0
has comment: http://stackoverflow.com/comment/81349044
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/47200448
has body: I got a problem in Python 3.5. I have a class (B) which inherits from another one (A). I'm trying get only declared methods in B but it returns the declared methods in class B and also inherited methods from class A. Here the code: class A: def a_method_1(self): """ WILL BE OVERRIDEN """ return True def a_method_2(self): """ WON'T BE OVERRIDEN """ return True class B(A): def b_method_1(self): """ NOT OVERRIDEN """ return True def get_methods(self): """ NOT OVERRIDEN This function filters special python methods. """ methods = [method for method in dir(self) if callable(getattr(self, method)) and not method[:2] == '__'] return methods def a_method_1(self): """ OVERRIDEN """ return True if __name__ == "__main__": B_obj = B() print(B_obj.get_methods()) Returns : &gt;&gt;&gt; ['a_method_1', 'a_method_2', 'b_method_1', 'get_methods'] And I would want : &gt;&gt;&gt; ['a_method_1', 'b_method_1', 'get_methods'] How can I modify get_methods to filter inherited methods? Have a good day, Thank you.
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81349108
has answer: http://stackoverflow.com/a/47200448
tagged with: python
tagged with: inheritance
type: AnsweredQuestion

http://stackoverflow.com/q/47125884
has answer: http://stackoverflow.com/a/47126419
accepted answer: http://stackoverflow.com/a/47125913
has title: How to insert zeros between elements in a numpy array?
has answer: http://stackoverflow.com/a/47125913
has answer: http://stackoverflow.com/a/78307670
favorite count: 0
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/53179919
has body: I have an nd array, for example this: x = np.array([[1,2,3],[4,5,6]]) I would like to double the size of the last dimension, and insert zeroes between the elements to fill the space. The result should look like this: [[1,0,2,0,3,0],[4,0,5,0,6,0]] I tried to solve it using expand_dims and pad. But the pad function inserts zeroes not just after each value in the last dimension. The shape of it's result is (3, 4, 2), but it should be (2,3,2) y = np.expand_dims(x,-1) z = np.pad(y, (0,1), 'constant', constant_values=0) res = np.reshape(z,[-1,2*3] Result of my code: array([[1, 0, 2, 0, 3, 0], [0, 0, 4, 0, 5, 0], [6, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]) How is it possible with pad to insert zeroes in the last dimension after each element? Or is there any better way to solve the problem?
has answer: http://stackoverflow.com/a/53179919
has answer: http://stackoverflow.com/a/73994667
tagged with: arrays
downvote count: 0
score: 16
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/70585083
upvote count: 16
type: AnsweredQuestion

http://stackoverflow.com/comment/81274644
type: AnswerComment
comment on: http://stackoverflow.com/a/47161797
type: Comment
has text: Oh I see. And you were probably getting the keyerror:'mytab' message as with some of the other methods you'd tried.
score: 1

http://stackoverflow.com/a/47180880
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47179497
type: Answer
accepted answer of: http://stackoverflow.com/q/47179497
has body: So this is a better way of doing this as i mentioned it in comment section: 1 - You don't need Settings and SettingChoices. They are basically the same so you can combine them into one model called Setting: class Setting(models.Model): name = models.CharField(max_length=200) # if you need anything that you might think you need another model for, # just think this way, add a BooleanField. # for example if you have a setting available only for admins: only_admin = models.BooleanField(default=False) # then when you're going to make a from, just filter the options; # options = setting.objects.filter(only_admin=False) class Meta: verbose_name = "Settings" verbose_name_plural = "Settings" def __str__(self): return self.name 2 - And for Circuits model you just need a simple ForeignKey field: class Circuits(models.Model): site_data = models.ForeignKey(SiteData, verbose_name="Site", on_delete=models.PROTECT) order_no = models.CharField(max_length=200, verbose_name="Order No") expected_install_date = models.DateField() install_date = models.DateField(blank=True, null=True) circuit_type = models.ForeignKey(Setting, null=False, blank=False) Now when you want to make a form for users to fill: forms.py: class CircuitsForm(forms.ModelForm): class Meta: model = Circuits fields = ('install_date', 'circuit_type') # or other fields. # and to filter which choices are available to choose from: def __init__(self, *args, **kwargs): super(CircuitsForm, self).__init__(*args, **kwargs) self.fields["circuit_type"].queryset = setting.objects.filter(only_admin=False) This way you have a safe and easy way to make forms for both users and your admins. You can edit the admin panel itself or just make a url just for admin users with a form like this. Also if you aren't that kind of people who uses django to render their form you can simply get the available choices in your view and pass it to the template like this: settings = setting.objects.filter(only_admin=False) and render it in a template lik…
score: 0

http://stackoverflow.com/comment/81324558
type: QuestionComment
has text: " but since range is not iterable i cant use it" .... uh, nope. `range` objects are iterable, that's their whole *raison d'etre*. `int` objects, on the other hand, are not...
score: 3
type: Comment
comment on: http://stackoverflow.com/q/47187607

http://stackoverflow.com/a/47070218
has body: a = ['2016-11-30T13:27:04-05:00', '2016-11-30T13:27:41-05:00','2017-03-01T22:16:35-05:00'] &gt;&gt;&gt; min(a) '2016-11-30T13:27:04-05:00 It works, just try it as normal strings. You can avoid importing time Do you want to convert them datetime objects and then find the minimum? use the method specified here https://stackoverflow.com/a/12282040/5334188 to datetime objects and find minimum
answers question: http://stackoverflow.com/q/47069508
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/q/47178272
has body: While saving jpg thumbnails from tiff (CMYK) file I'm encountering the following problem: Thumbnail created with color mode conversion from CMYK to RGB gets blue hue: Thumbnail created from the same tiff in photoshop (no ICC profile, not converted to sRGB, RGB only) get the colors the right way: Thumbnails created without color mode conversion (jpeg with CMYK) gets similar results to the photoshopped ones but are not usable for the web (still blue). Code snippet: img = Image.open(img_tiff) img.thumbnail(size) img.convert("RGB").save(img_jpg, quality=70, optimize=True) Also, when trying to include tiff's ICC profile it gets corrupted in some way, and photoshop is complaining about the profile being corrupted. I was including the profile in the save function using: icc_profile=img.info.get('icc_profile') What am I doing wrong / missing here? EDIT: Searching for the solution I found that the problem was linked to the icc profiles. Tiff file has FOGRA profile, jpeg should have some sRGB. Couldn't get to work profile transformation from within Pillow (ImageCms.profileToProfile() was throwing PyCMSError cannot build transform ,'ImageCmsProfile' object is not subscriptable, 'PIL._imagingcms.CmsProfile' object is not subscriptable ). Found a workaround to the problem using ImageMagick@7 convert: com_proc = subprocess.call(['convert', img_tiff, '-flatten', '-profile', 'path/to/sRGB profile', '-colorspace', 'RGB', img_jpeg]) The result of conversion is very good, file size is quite small and most important of all, colours are matching the original tiff file. Still would like to know how to do it properly from within Pillow (ICC profile reading and applying). Python 3.6.3, Pillow 4.3.0, OSX 10.13.1
has title: Hue Tint Color error converting tiff to jpg in python3 with pillow
type: Question
score: 2
accepted answer: http://stackoverflow.com/a/47262412
tagged with: python-3.x
answer count: 2
upvote count: 2
downvote count: 0
tagged with: http://stackoverflow.com/tag/jpeg
favorite count: 0
tagged with: tiff
type: AnsweredQuestion
tagged with: python-imaging-library
possible better answer: http://stackoverflow.com/a/47255080
has answer: http://stackoverflow.com/a/47262412
has answer: http://stackoverflow.com/a/47255080
tagged with: python

http://stackoverflow.com/comment/81138232
score: 0
has text: I see the output in this way
comment on: http://stackoverflow.com/q/47094142
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81263984
has text: @SayliJawale Check https://stackoverflow.com/a/11146645/4909087 for various cartesian product alternatives.
comment on: http://stackoverflow.com/a/47156863
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/81370410
has text: just added it. thanks for looking.
type: QuestionComment
comment on: http://stackoverflow.com/q/47210402
score: 0
type: Comment

http://stackoverflow.com/a/47074794
has comment: http://stackoverflow.com/comment/81103607
score: 1
has body: If you want to change an option in a widget object you could use: lblpay.configure(text="ILERI") or if you want to create all over again you need to call geometry manager function(s) again after creation like: ... else: print ('PARK HALINDE\n') lblpay = tk.Label(text="PARK HALINDE") lblpay.grid() as in your 'relative' code pieces should look either, and for the better, like: if(args[0] == 1): print ('ACIL DURUM FRENI\n') lblpay.configure(text="ACIL DURUM FRENI") elif self.alpha/4 &gt; 0.20: print ('ILERI\n') + str(self.alpha/4) lblpay.configure(text="ILERI") elif self.z &gt; 200: print ('SAG\n') lblpay.configure(text="SAG") elif self.z &lt; -200 : print ('SOL\n') lblpay.configure(text="SOL") elif self.x &lt; -200: print ('GERI\n') lblpay.configure(text="GERI") else: print ('PARK HALINDE\n') lblpay.configure(text="PARK HALINDE") or like: if(args[0] == 1): print ('ACIL DURUM FRENI\n') lblpay = tk.Label(text="ACIL DURUM FRENI") elif self.alpha/4 &gt; 0.20: print ('ILERI\n') + str(self.alpha/4) lblpay = tk.Label(text="ILERI") elif self.z &gt; 200: print ('SAG\n') lblpay = tk.Label(text="SAG") elif self.z &lt; -200 : print ('SOL\n') lblpay = tk.Label(text="SOL") elif self.x &lt; -200: print ('GERI\n') lblpay = tk.Label(text="GERI") else: print ('PARK HALINDE\n') lblpay = tk.Label(text="PARK HALINDE") lblpay.grid(row=4, column=1, columnspan=2)
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47074502
type: Answer

http://stackoverflow.com/a/47085861
upvote count: 1
score: 1
type: AcceptedAnswer
has body: You probably need to upgrade your version of XlsxWriter to >= 1.0.0 where that feature was added.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47085618
accepted answer of: http://stackoverflow.com/q/47085618

http://stackoverflow.com/comment/81183958
has text: Indeed, `__get__` has an unusual status as working in a way as both an instance method and a class method depending on how the descriptor is accessed.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47116881
type: Comment

http://stackoverflow.com/q/47116814
has comment: http://stackoverflow.com/comment/81183774
has title: regex findall() only returning []
tagged with: python
score: -1
tagged with: regex
has comment: http://stackoverflow.com/comment/81183605
has answer: http://stackoverflow.com/a/47116837
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47116837
downvote count: 2
has comment: http://stackoverflow.com/comment/81184129
upvote count: 1
has comment: http://stackoverflow.com/comment/81183707
answer count: 1
has body: I am trying to run the following lines, and expected Python to return ['402-292-2345'], but all I am getting from the Shell is '[]' like the final line below. What am I doing wrong? (note: I edited the original code below to reflect the missing dash.) LATER EDIT: Additional problem came up that I think is related to using IDLE's text editor and running the Shell from there. After a couple of your comments, I ran the lines below directly in the Shell, and returned #2 below Ran this from the text editor: phoneRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') resume = '''IM A SAMPLE 1234 North 55 Street Bellevue, Nebraska 68005 402-292-­2345 iasample@aol.com PROFESSIONAL REFERENCES Name Attaboy Company''' phoneRegex.findall(resume) [] then #2 I ran this directly in the Shell: phoneRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') resume = '''IM A SAMPLE 1234 North 55 Street Bellevue, Nebraska 68005 402-292-2345 iasample@aol.com PROFESSIONAL REFERENCES Name Attaboy Company''' phoneRegex.findall(resume) which returned ['402-292-2345'] as expected. So, this ran as expected directly in the Shell, but not in IDLE's text editor.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81183713

http://stackoverflow.com/a/47169340
type: Answer
answers question: http://stackoverflow.com/q/47169221
downvote count: 0
has body: I would suggest taking a look at the Klein web micro-framework which runs on Twisted Python. It's similar to Flask and may suit your needs and will allow you to run it all in a single process. You can integrate it with the event loop of various UI toolkits, including tkinter.
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/136483703

http://stackoverflow.com/comment/81530909
has text: That's a different question, please raise a new question.
type: Comment
comment on: http://stackoverflow.com/a/47289000
type: AnswerComment
score: 0

http://stackoverflow.com/a/47083151
has body: Use virtualenvs to reduce package clash between independent projects. After activating the venv use pip to install packages. This way each project has an independent view of the package space. I use brew to install both Python 2.7 and 3.6. The venv utility from each of these will build a 2 or 3 venv respectively. I also have pyenv installed from brew which I use if I want a specific version that is not the latest in brew. After activating a specific version in a directory, I will then create a venv and use this to manage the package isolation. I can't really say what is best. Let's see what other folks say.
type: Answer
accepted answer of: http://stackoverflow.com/q/47082736
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47082736

http://stackoverflow.com/comment/81106574
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47078562
type: Comment
has text: can you show us what the runtime error looks like?

http://stackoverflow.com/a/47087240
has comment: http://stackoverflow.com/comment/81158896
has comment: http://stackoverflow.com/comment/81167194
has comment: http://stackoverflow.com/comment/81149116
answers question: http://stackoverflow.com/q/47085244
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81149931
has comment: http://stackoverflow.com/comment/81156032
has comment: http://stackoverflow.com/comment/81159802
has body: Well, if you used lmfit setting up and running your fit would look like this: xdeg = [70.434654, 37.147266, 8.5787086, 161.40877, -27.31284, 80.429482, -81.918106, 52.320129, 64.064552, -156.40771, 12.37026, 15.599689, 166.40984, 134.93636, 142.55002, -38.073524, -38.073524, 123.88509, -82.447571, 97.934402, 106.28793] y = [86683.961, -40564.863, 50274.41, 80570.828, 63628.465, -87284.016, 30571.402, -79985.648, -69387.891, 175398.62, -132196.5, -64803.133, -269664.06, 36493.316, 22769.121, 25648.252, 25648.252, 53444.855, 684814.69, 82679.977, 103244.58] import numpy as np from lmfit import Model import matplotlib.pyplot as plt def sinefunction(x, a, b, c): return a + b * np.sin(x*np.pi/180.0 + c) smodel = Model(sinefunction) result = smodel.fit(y, x=xdeg, a=0, b=30000, c=0) print(result.fit_report()) plt.plot(xdeg, y, 'o', label='data') plt.plot(xdeg, result.best_fit, '*', label='fit') plt.legend() plt.show() That is assuming your X data is in degrees, and that you really intended to convert that to radians (as numpy's sin() function requires). But that just addresses the mechanics of how to do the fit (and I'll leave the display of results up to you - it seems like you may need the practice). The fit result is terrible, because these data are not sinusoidal. They are also not well ordered, which isn't a problem for doing the fit, but does make it harder to see what is going on.
has comment: http://stackoverflow.com/comment/81156047
has comment: http://stackoverflow.com/comment/81152108
has comment: http://stackoverflow.com/comment/81170495
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47085244
type: Answer

http://stackoverflow.com/q/47086468
has title: Count elements in pandas dataframe columns
favorite count: 0
type: Question
has body: Any suggestions for elegant ways to make the following counts for each column in my dataframe: Count of elements in the column which are numeric (any value) Count of elements in the column which are numeric and nonzero Here's some code to generate a dataframe like mine (but much smaller): import pandas as pd import numpy as np import matplotlib.pyplot as plt #from matplotlib import style import seaborn as sns df = pd.DataFrame(data=np.random.random_integers(low=0,high=10,size=(50,1)), columns=['all'] ) # set up the grouping g = df.groupby(pd.cut(df['all'],[-1,2,4,6,8,10])) for name, data in g.groups.items(): df[name] = df.loc[data]['all'] This produces a dataframe that looks like the following:
score: 3
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/81123265
has answer: http://stackoverflow.com/a/47086871
answer count: 2
tagged with: pandas
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47086931

http://stackoverflow.com/a/47235744
has body: I don't believe there is any way to invoke the __enter__ method of a Python class from MATLAB, but the __exit__ method might be implicitly called (I'll address this further below). It's important to first consider the purpose of context managers (via the __enter__ and __exit__ methods), which is to provide a way to allocate and release resources in a scope-limited fashion, whether or not that scope is exited normally or via an error. MATLAB has a more limited means of "scoping": each function has its own workspace, and control structures like loops, conditional statements, etc. within that function all share that workspace (unlike many languages in which these control structures have their own sub-scopes). When a workspace is exited in MATLAB, the variables it contains are cleared, but any resources that were allocated may still need to be released. This can be achieved with onCleanup objects. When they are cleared from memory, they invoke a given function for managing existing resources. An example would be opening and reading from a file: function openFileSafely(fileName) fid = fopen(fileName, 'r'); c = onCleanup(@() fclose(fid)); s = fread(fid); ... end Here, a file is opened and subsequently read from. An onCleanup object c is created that will close the file when c is cleared from memory upon exit from the function. If the file were simply closed with fclose(fid) at the end of the function, then an error exit from the function (such as during the course of reading data) would cause the file to still remain opened. Using an onCleanup object ensures that the file will be closed regardless of how the function exits. Here's an example of how this could be handled in Python: with open('some_file', 'w') as opened_file: opened_file.write('Hola!') Since MATLAB has a different means of "context management" than Python, this may explain why it's not possible to access the __enter__ method. I tried with a class I knew had one: the io.FileIO class. I first looked for help:…
downvote count: 0
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47192413
score: 5

http://stackoverflow.com/comment/81368427
type: AnswerComment
comment on: http://stackoverflow.com/a/47198754
score: 0
has text: the num of classes is the number of breeds?
type: Comment

http://stackoverflow.com/comment/81601611
type: QuestionComment
has text: Yes @Trilliput, with the mentioned version it was not working. I changed the version of django-mssql==1.8 to 1.6 after that it worked :)
comment on: http://stackoverflow.com/q/47156702
score: 0
type: Comment

http://stackoverflow.com/comment/81276295
has text: When you fix the typo in the code in your question, it works just fine. So, the answer to your question is "fix the typo". If your question has no relationship to your real problem, there's nothing we can do about that.
comment on: http://stackoverflow.com/q/47163056
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81115778
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47082599
has text: Humm so there is no way to revert re.sub operation. Ok, I am going to try re.search. I was creating an example to show the expected output but I will try re.search before.
score: 0

http://stackoverflow.com/q/47078585
has title: Python f.write() is not taking more arguments
has comment: http://stackoverflow.com/comment/81105867
possible better answer: http://stackoverflow.com/a/47078659
tagged with: file
has comment: http://stackoverflow.com/comment/81105935
has answer: http://stackoverflow.com/a/47078785
has answer: http://stackoverflow.com/a/47078659
score: 4
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81106047
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47078697
has answer: http://stackoverflow.com/a/47079106
upvote count: 5
accepted answer: http://stackoverflow.com/a/47078639
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/47078639
has body: I am having a python code like this f=open('nv.csv','a+') a=10+3 b=3+12 c=3+13 f.write(a,b,c) This returns the output as f.write(a,b,c) TypeError: function takes exactly 1 argument (3 given) Kindly help me to solve this problem. I wish to enter every data into my file.
has answer: http://stackoverflow.com/a/47079616

http://stackoverflow.com/q/47086372
has comment: http://stackoverflow.com/comment/81122479
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81122418
linked to: http://stackoverflow.com/q/1732348
score: 0
has comment: http://stackoverflow.com/comment/81122495
has comment: http://stackoverflow.com/comment/81122446
answer count: 1
upvote count: 1
downvote count: 1
tagged with: parsing
has title: parsing huge XML in python when needing only one attribute
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/4683046
has comment: http://stackoverflow.com/comment/81122392
has body: I am trying to parse an xml file, and i only need one attribute. Is there any easy way to get to said attribute? The file looks like this: <?xml version="1.0" encoding="UTF-8"?> testowy testowy adj:sg:nom:m3:pos 1358 1358/1.0000000000 próbny.1(42:jak) testowy.1(42:jak) plik plik subst:sg:nom:m3 35864 35864/0.6075684112 2248/0.3924315888 plik.2(7:por) And it will have variable number of branches, and each branch might have different number of keys. The only attribute that i need to extract is syns_id. It will probably be one HUGE xml file, im thinking few hundred megabytes. Or about 100k of small ones, with just around 5-10 's. What i need, is a list containing all of these syns_id's. How should i approach this? I think regexes would solve it, but i have not used them yet. Or is there any faster/better way?
accepted answer: http://stackoverflow.com/a/47086448
has answer: http://stackoverflow.com/a/47086448
tagged with: python
has comment: http://stackoverflow.com/comment/81122411
tagged with: regex
has comment: http://stackoverflow.com/comment/81122445
has comment: http://stackoverflow.com/comment/81122454

http://stackoverflow.com/q/47158642
has comment: http://stackoverflow.com/comment/81266589
tagged with: python
has comment: http://stackoverflow.com/comment/81266570
has body: I would like to start threads in turns in a for loop, but the next thread should not start until the current one is completed. Please help me with this issue. I want to achieve this, because I have a GUI, and for each loop a progress bar will appear and run, and the GUI will not be locked (it won't give that ugly "Not Responding" error) for op in ["op1", "op2"]: start_thread() def start_thread(): display_and_run_progress_bar() do_the_operation() when_op_is_completed_destroy_progress_bar()
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81266701
has title: How to start threads in turn in python in a for loop?
tagged with: multithreading
answer count: 1
has answer: http://stackoverflow.com/a/47158974
accepted answer: http://stackoverflow.com/a/47158974
type: Question
has comment: http://stackoverflow.com/comment/81266522
tagged with: for-loop

http://stackoverflow.com/a/61031945
answers question: http://stackoverflow.com/q/47219846
upvote count: 2
type: Answer
score: 2
has body: This is a bit older but I ran into the same issue. What I wanted was basically an iterator that i could use to go through all aggregations that i got back (i also have a lot of unique results). The best thing i found is to create a python generator like this def scan_aggregation_results(): i=0 partitions=20 while i &lt; partitions: s = Search(using=elastic, index='my_index').extra(size=0) agg = A('terms', field='my_field.keyword', size=999999, include={"partition": i, "num_partitions": partitions}) s.aggs.bucket('my_agg', agg) result = s.execute() for item in result.aggregations.my_agg.buckets: yield my_field.key i = i + 1 # in other parts of the code just do for item in scan_aggregation_results(): print(item) # or do whatever you want with it The magic here is that elastic will automatically partition the number of results by 20, ie the number of partitions i define. I just have to set the size to something large enough to hold a single partition, in this case the result can be up to 20 million items large (or 20*999999). If you have much less items, like me, to return (like 20000) then you will just have 1000 results per query in your bucket, regardless that you defined a much larger size. Using the generator construct as outlined above you can then even get rid of that and create your own scanner so to speak, iterating over all results individually, just what i wanted.
downvote count: 0

http://stackoverflow.com/a/47118693
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: Use div + shift: df['C'] = df.B / df.B.shift(-1) df year A B C 0 2000 101 20 2.0 1 2001 102 10 2.0 2 2002 103 5 2.5 3 2003 250 2 0.5 4 2004 500 4 NaN
has comment: http://stackoverflow.com/comment/81187204
accepted answer of: http://stackoverflow.com/q/47118559
type: Answer
answers question: http://stackoverflow.com/q/47118559

http://stackoverflow.com/comment/81233461
type: QuestionComment
has text: thanks a lot really appreciate it
type: Comment
comment on: http://stackoverflow.com/q/47141600
score: 0

http://stackoverflow.com/a/47140412
has comment: http://stackoverflow.com/comment/81230751
has body: Try using this to create your table: self.cur.execute('CREATE TABLE IF NOT EXISTS cards(ID INTEGER PRIMARY KEY, date TEXT,card TEXT,serial_card TEXT,statuscard TEXT)') This will mean that ids of deleted rows can occur again, if you want it so that once an ID has been assigned it can never be assigned again even if the row using it no longer exists in the table, use this line: self.cur.execute('CREATE TABLE IF NOT EXISTS cards(ID INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT,card TEXT,serial_card TEXT,statuscard TEXT)')
score: 0
has comment: http://stackoverflow.com/comment/81232337
type: Answer
answers question: http://stackoverflow.com/q/47139645
has comment: http://stackoverflow.com/comment/81231542
has comment: http://stackoverflow.com/comment/81231039
has comment: http://stackoverflow.com/comment/81230709
has comment: http://stackoverflow.com/comment/81231149
has comment: http://stackoverflow.com/comment/81233104
has comment: http://stackoverflow.com/comment/81231180

http://stackoverflow.com/a/47220053
answers question: http://stackoverflow.com/q/47219993
score: 3
upvote count: 3
has body: If I've understood you correctly, you can cycle over indices using itertools.cycle. from itertools import cycle source = [1,2,3] additions = [1, 2, 3, 4, 5, 6, 7, 8] for i, j in zip(cycle(range(len(source))), additions): source[i] += j print(source) [13, 17, 12]
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81389783
accepted answer of: http://stackoverflow.com/q/47219993
type: Answer

http://stackoverflow.com/a/47199841
downvote count: 0
has comment: http://stackoverflow.com/comment/134106110
has body: The object is not saved to the database until form.save() is called in form_valid() method. If you override the method and save with instance = form.save(commit=False), it is not saved to the database until you call instance.save(). However, when form.is_valid() is called in the post() method, this immediately updates self.object with the new values. Therefore, if you access self.object in the form_valid() method, it already has the new values. You could refetch the original object from the database: original_object = MyModel.objects.get(pk=self.object.pk) If you just want to know which fields changed, form.changed_data might be enough for you.
answers question: http://stackoverflow.com/q/47199579
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/q/47145002
has body: I have a django project and I am trying to integrate SynapsePay Api. I sent a request that returned a class as a response. I am trying to figure out how to cycle or parse the response to get to the json so that I can grab certain values from the response that was returned. I have looked everywhere and cant seem to find a solution or a way to get into a class objects and reach the json part of the return. Here is the response that I am getting... I want to grab the _id from both of the objects returned in the object response below. Does anyone know how I can do this?? [ &lt;class 'synapse_pay_rest.models.nodes.ach_us_node.AchUsNode'&gt;( { 'user':"&lt;class 'synapse_pay_rest.models.users.user.User'&gt;(id=...49c04e1)", 'json':{} } ) ]
tagged with: python
has answer: http://stackoverflow.com/a/47145147
accepted answer: http://stackoverflow.com/a/47145147
type: AnsweredQuestion
tagged with: synapsepay
answer count: 1
tagged with: django
type: Question
score: 0
tagged with: django-views
has title: Iterating through a class to retrieve json response - Synapse/Django
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/47104824
answer count: 1
has body: What would be the best way to insert a character conditionally in a PANDAS string field with the following criteria: Insert a "." after the first 3 numeric characters from the left (ignore letters) Do not add a "." if there are no additional characters trailing 96501 E0000 V909 965 Becomes 965.01 E000.0 V909 965
type: Question
has answer: http://stackoverflow.com/a/47104868
has title: Python PANDAS: Conditionally Insert Character in String Field
tagged with: python
tagged with: regex
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47104868
score: 0
tagged with: pandas

http://stackoverflow.com/comment/81181918
type: QuestionComment
comment on: http://stackoverflow.com/q/47115996
type: Comment
has text: Because you are reassigning?
score: 2

http://stackoverflow.com/q/47087907
accepted answer: http://stackoverflow.com/a/47087955
tagged with: null
has answer: http://stackoverflow.com/a/47087955
has body: I need to fill the nan value in a dataframe by using the previous available value in a row, as the data are timeseries. Here there is an example: 1 2 3 4 b b nan c c nan d nan d nan nan c What I need is: 1 2 3 4 b b b c c c d d d d d c I know the method fillna from panda, but the methods are only based on columns. I think about doing a transposition and after the use of the fillna method, but I would like to know if there are more efficient way to do that.
tagged with: dataframe
tagged with: python
has title: How to fill nan value with the previous available in the row?
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/59344730
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/59344730
downvote count: 0
upvote count: 1
tagged with: nan
favorite count: 0
type: Question

http://stackoverflow.com/comment/85952280
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48837789
has text: Hey, sorry for the delayed response. I clicked that link Hardbyte, didn't have premission to access it. I'm currently looking into ESP32 and Beagel Bone Black as it's more compact for what I want to do.

http://stackoverflow.com/comment/81205020
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47125723
has text: hmm I was trying to avoid that, but I'll try it. Thanks for the suggestion :)

graph-tool
tag name: graph-tool
type: Tag
tags question: http://stackoverflow.com/q/47081663
tags question: http://stackoverflow.com/q/47183762

http://stackoverflow.com/a/67660589
upvote count: 1
has body: You can use for loop: #!/usr/bin/python3 for _ in range(3): usr = input("Enter username: ") psw = input("Enter password: ") if usr == "bank_admin" and psw == "Hytu76E": print("Access Granted!") break else: print("Access Denied!") print("Try Again!") else: print("No more attemps!")
type: Answer
score: 1
answers question: http://stackoverflow.com/q/47202331
downvote count: 0

http://stackoverflow.com/comment/82185344
score: 1
has text: Just confirming that you mean the former, otherwise your code above is not correct.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47146755

http://stackoverflow.com/a/47163795
has body: You can use Pandas. Read the csv with the function read_csv (where you can explicitly use the ',' separator or any other), and write the csv with the to_csv funtion. Here's an example: import pandas as pd def function_to_generate_new_column_values(row): return [12,13,14] df = pd.read_csv('file1.csv', sep=',') df['new_column'] = df.apply(lambda x: ' '.join(map(str, function_to_generate_new_column_values(x))), axis=1) df.to_csv('file2.csv', sep = ',', header = True, mode = 'w', index=False) You can add the list to each row by editing the function "function_to_generate_new_column_values" on the code above.
score: 0
has comment: http://stackoverflow.com/comment/81400136
answers question: http://stackoverflow.com/q/47163127
has comment: http://stackoverflow.com/comment/81437127
type: Answer

http://stackoverflow.com/q/47145858
has answer: http://stackoverflow.com/a/47145894
has body: I did some research but cant find the answer for my case I have 2 csv files a.csv id, fname, lname, address 1, aaa, bbb, ccc 2, abb, ccb, ddd 3, ddd, eee, fff 4, eee, ggg, fff 5, EEE, GGG, RRRR and 2nd file b.csv ID 1 3 5 desire result would be (the id header below is not strict but id would be fine) id, fname, lname, address 1, aaa, bbb, ccc 3, ddd, eee, fff 5, EEE, GGG, RRRR what i tried merged = a.merge(b, left_on = ['id'], right_on= ['ID'], how = 'inner') merged.to_csv(r'C:\things\output.csv', index=False) and got a cannot allocate memory for array error... edit: the code below would work fine if headers are exactly the same (both are 'id')but life is not perfect merged = a.merge(b, on = 'id')
possible better answer: http://stackoverflow.com/a/47146119
type: Question
has comment: http://stackoverflow.com/comment/81242047
accepted answer: http://stackoverflow.com/a/47145894
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/47146119
has title: Python pandas Inner join 2 csv files with different header
type: AnsweredQuestion
answer count: 2
tagged with: pandas
score: 0

http://stackoverflow.com/comment/81201699
type: Comment
comment on: http://stackoverflow.com/q/47122752
has text: Thanks!! Basically, I get each cell coordinate that contains "a" in a row. I want to grab the very last "a" instance coordinates ([-1:]?). Row 1 has dates and I need to grab the column coordinate (from "a" list of coordinates) and add a 1 to it to reference the date. Later I plan to write that date to another field
type: QuestionComment
score: 0

psycopg2
tags question: http://stackoverflow.com/q/47143090
tags question: http://stackoverflow.com/q/47207032
tags question: http://stackoverflow.com/q/47097838
tags question: http://stackoverflow.com/q/47090912
tags question: http://stackoverflow.com/q/47081807
tags question: http://stackoverflow.com/q/47192163
tags question: http://stackoverflow.com/q/47116877
tags question: http://stackoverflow.com/q/47152086
type: Tag
tags question: http://stackoverflow.com/q/47165342
tag name: psycopg2

http://stackoverflow.com/q/47177112
downvote count: 0
has answer: http://stackoverflow.com/a/47177432
possible better answer: http://stackoverflow.com/a/47177847
favorite count: 0
upvote count: 4
type: Question
accepted answer: http://stackoverflow.com/a/47177432
has title: ValueError: Length of object (3) does not match with length of fields
answer count: 2
tagged with: pyspark
tagged with: python
has body: I manually create PySpark DataFrame as follows: acdata = sc.parallelize([ [('timestamp', 1506340019), ('pk', 111), ('product_pk', 123), ('country_id', 'FR'), ('channel', 'web')] ]) # Convert to tuple acdata_converted = acdata.map(lambda x: (x[0][1], x[1][1], x[2][1])) # Define schema acschema = StructType([ StructField("timestamp", LongType(), True), StructField("pk", LongType(), True), StructField("product_pk", LongType(), True), StructField("country_id", StringType(), True), StructField("channel", StringType(), True) ]) df = sqlContext.createDataFrame(acdata_converted, acschema) But when I write df.head() and do spark-submit, I get the following error: org.apache.spark.api.python.PythonException: Traceback (most recent call last): File "/mnt/yarn/usercache/hdfs/appcache/application_1510134261242_0002/container_1510134261242_0002_01_000003/pyspark.zip/pyspark/worker.py", line 177, in main process() File "/mnt/yarn/usercache/hdfs/appcache/application_1510134261242_0002/container_1510134261242_0002_01_000003/pyspark.zip/pyspark/worker.py", line 172, in process serializer.dump_stream(func(split_index, iterator), outfile) File "/mnt/yarn/usercache/hdfs/appcache/application_1510134261242_0002/container_1510134261242_0002_01_000003/pyspark.zip/pyspark/serializers.py", line 268, in dump_stream vs = list(itertools.islice(iterator, batch)) File "/mnt/yarn/usercache/hdfs/appcache/application_1510134261242_0002/container_1510134261242_0002_01_000001/pyspark.zip/pyspark/sql/session.py", line 520, in prepare File "/mnt/yarn/usercache/hdfs/appcache/application_1510134261242_0002/container_1510134261242_0002_01_000003/pyspark.zip/pyspark/sql/types.py", line 1358, in _verify_type "length of fields (%d)" % (len(obj), len(dataType.fields))) ValueError: Length of object (3) does not match with length of fields (12) at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193) at org.apache.spark.api.python.PythonRunner$$anon$1.&lt;init&gt;(PythonRDD.scala:234) at org.…
has answer: http://stackoverflow.com/a/47177847
score: 4
tagged with: apache-spark
type: AnsweredQuestion

http://stackoverflow.com/q/47098270
has body: I've got a CSV that contains multiple rows, one field is named "Market". What I'm trying to do is match each line with it's Market point of contact that I have in a list, but I can't quite seem to get it working. So far I've tried the following: PoC1 = ["Georgia", "Florida", "Alabama", "Mississippi"] PoC2 = ["New York", "New Jersey", "Connecticut", "Pennsylvania"] PoC3 = ["California", "Arizona", "Nevada", "Oregon"] import pandas as pd df = pd.read_csv("Markets.csv") PoC1Markets = df[df['Market'] == PoC1] PoC2Markets = df[df['Market'] == PoC2] PoC3Markets = df[df['Market'] == PoC3] But that didn't return anything. For reference, each line contains a latitude/longitude coordinate and an alphanumeric code that I'd expect to be returned. I'm trying to return each line that's pertinent to the market points of contact and send them each an email individually with their respective lines within the CSV. Any help would be appreciated!
has comment: http://stackoverflow.com/comment/81146309
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47098430
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81146673
has title: search for multiple values in csv and return line in a list
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47098505
tagged with: python
has comment: http://stackoverflow.com/comment/81146458
possible better answer: http://stackoverflow.com/a/47098430
accepted answer: http://stackoverflow.com/a/47098505

http://stackoverflow.com/q/47137187
tagged with: python
score: 2
type: AnsweredQuestion
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/81224056
downvote count: 0
has answer: http://stackoverflow.com/a/47139384
has body: I have this DataFrame: df = pd.DataFrame(columns=["App","Feature1", "Feature2","Feature3", "Feature4","Feature5", "Feature6","Feature7","Feature8"], data=[["SHA",0,0,1,1,1,0,1,0], ["LHA",1,0,1,1,0,1,1,0], ["DRA",0,0,0,0,0,0,1,0], ["FRA",1,0,1,1,1,0,1,1], ["BRU",0,0,1,0,1,0,0,0], ["PAR",0,1,1,1,1,0,1,0], ["AER",0,0,1,1,0,1,1,0], ["SHE",0,0,0,1,0,0,1,0]]) UPDATE: (sorry I incorrectly formulated the expected result) I want to count the number of time that the value 1 appears for each feature: Features Count Feature1 6 Feature2 7 ... I tried this: df.groupBy("App").count() But I do not get an expected output.
possible better answer: http://stackoverflow.com/a/47139384
favorite count: 0
type: Question
has title: How to group by and count values in my DataFrame?
has comment: http://stackoverflow.com/comment/81223591
upvote count: 2
has answer: http://stackoverflow.com/a/47137233
accepted answer: http://stackoverflow.com/a/47137233

http://stackoverflow.com/a/47125329
has comment: http://stackoverflow.com/comment/81200819
has comment: http://stackoverflow.com/comment/81200760
type: Answer
has comment: http://stackoverflow.com/comment/81200850
answers question: http://stackoverflow.com/q/47124972
has body: You can use defaultdict module to accomplish the task. Here is an example: from collections import defaultdict my_list = ['A', 'The', 'the', 'LAZY', 'Low'] def split_words(a): b = defaultdict(list) for k in a: b[k[0].lower()].append(k.lower()) return b &gt;&gt;&gt; split_words(my_list) defaultdict(list, {'a': ['a'], 'l': ['lazy', 'low'], 't': ['the', 'the']}) &gt;&gt;&gt; dict(split_words(my_list)) {'a': ['a'], 'l': ['lazy', 'low'], 't': ['the', 'the']}
has comment: http://stackoverflow.com/comment/81200785
has comment: http://stackoverflow.com/comment/81200861
score: 0

http://stackoverflow.com/comment/81212201
has text: Sorry, what's your expected output?
score: 0
comment on: http://stackoverflow.com/q/47131193
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81246736
type: QuestionComment
comment on: http://stackoverflow.com/q/47148262
score: 0
has text: By this you mean throughout the solution I devise put in timing checkpoints as that will instruct me on where the slowest portions are? Or are you saying try writing this function a different way and see which is faster?
type: Comment

http://stackoverflow.com/a/47097175
downvote count: 0
has comment: http://stackoverflow.com/comment/81235031
type: Answer
accepted answer of: http://stackoverflow.com/q/47096633
has comment: http://stackoverflow.com/comment/81156946
has body: Hashed keys are more evenly distributed comparing to compound keys, especially the ones with low cardinality. Balancer started to migrate chunks at some point, so you had same documents on both shards during the migration. https://docs.mongodb.com/manual/sharding/#sharding-strategy and related docs have a good explanation on what's going on behind the scene.
answers question: http://stackoverflow.com/q/47096633
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/81371929
score: 2
has text: Where would you expect those imported symbols to go? Not into your C module's namespace, obviously, because C symbols must all be defined at compile time.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47211132

http://stackoverflow.com/comment/81374329
comment on: http://stackoverflow.com/q/47212409
has text: You can play around with e.g. https://regex101.com to understand what a regex does.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47118677
upvote count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/47118890
favorite count: 0
type: Question
tagged with: numpy
tagged with: arrays
accepted answer: http://stackoverflow.com/a/47118850
tagged with: python
has answer: http://stackoverflow.com/a/47118850
has title: Does Numpy fancy indexing copy values directly to another array?
has answer: http://stackoverflow.com/a/47118890
type: AnsweredQuestion
score: 2
has body: According to the documentation that I could find, when using fancy indexing a copy rather than a view is returned. However, I couldn't figure out what its behavior is during assignment to another array, for instance: A = np.arange(0,10) B = np.arange(-10,0) fancy_slice = np.array([0,3,5]) A[fancy_slice] = B[fancy_slice] I understand that A will just receive a call to __setitem__ while B will get a call to __getitem__. What I am concerned about is whether an intermediate array is created before copying the values over to A.
answer count: 2

pandas-groupby
tags question: http://stackoverflow.com/q/47100481
tags question: http://stackoverflow.com/q/47123154
type: Tag
tags question: http://stackoverflow.com/q/47129013
tags question: http://stackoverflow.com/q/47184409
tags question: http://stackoverflow.com/q/47201227
tags question: http://stackoverflow.com/q/47159554
tags question: http://stackoverflow.com/q/47089785
tags question: http://stackoverflow.com/q/47173571
tags question: http://stackoverflow.com/q/47213579
tags question: http://stackoverflow.com/q/47189212
tags question: http://stackoverflow.com/q/47131431
tags question: http://stackoverflow.com/q/47197949
tags question: http://stackoverflow.com/q/47169856
tags question: http://stackoverflow.com/q/47145201
tags question: http://stackoverflow.com/q/47185894
tags question: http://stackoverflow.com/q/47067519
tags question: http://stackoverflow.com/q/47121675
tags question: http://stackoverflow.com/q/47100160
tags question: http://stackoverflow.com/q/47068935
tags question: http://stackoverflow.com/q/47096081
tags question: http://stackoverflow.com/q/47101917
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/47192568
tags question: http://stackoverflow.com/q/47142864
tags question: http://stackoverflow.com/q/47079717

list-comprehension
tags question: http://stackoverflow.com/q/47191226
type: Tag
tags question: http://stackoverflow.com/q/47101461
tags question: http://stackoverflow.com/q/47188843
tags question: http://stackoverflow.com/q/47163008
tags question: http://stackoverflow.com/q/47208007
tags question: http://stackoverflow.com/q/47170051
tags question: http://stackoverflow.com/q/47105671
tags question: http://stackoverflow.com/q/47080379
tags question: http://stackoverflow.com/q/47168821
tag name: list-comprehension
tags question: http://stackoverflow.com/q/47176955
tags question: http://stackoverflow.com/q/47175707
tags question: http://stackoverflow.com/q/47066584

http://stackoverflow.com/comment/81118964
has text: @fiticida, `aux` here is just a file's content without undesirable chars. It can be easily edited based on what kind of output you want.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47084590
type: AnswerComment

http://stackoverflow.com/a/47197127
has comment: http://stackoverflow.com/comment/81343286
accepted answer of: http://stackoverflow.com/q/47197083
has comment: http://stackoverflow.com/comment/81343324
has comment: http://stackoverflow.com/comment/81343252
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: try to install (or reinstall) pyOpenSSL : pip uninstall pyOpenSSL pip install pyOpenSSL try : sudo apt-get purge python-openssl sudo apt-get install libffi-dev sudo pip install pyopenssl
upvote count: 7
score: 7
answers question: http://stackoverflow.com/q/47197083

http://stackoverflow.com/q/47134324
has answer: http://stackoverflow.com/a/47134681
has body: I have been trying to create a program that will take in multiple scores for pizza. I then need to remove the highest and lowest value in the list to remove outliers. However when I try to remove the highest and lowest score, it removes the highest and lowest score from the oldScores list pizzaScores = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]] oldPizzaScores = pizzaScores for i in range(len(pizzaScores)): pizzaScores[i].remove(max(pizzaScores[i])) pizzaScores[i].remove(min(pizzaScores[i])) print(oldPizzaScores) print(pizzaScores)
tagged with: python
accepted answer: http://stackoverflow.com/a/47134355
linked to: http://stackoverflow.com/q/44891076
answer count: 4
has answer: http://stackoverflow.com/a/47134355
tagged with: python-3.x
score: 0
has answer: http://stackoverflow.com/a/47134367
has comment: http://stackoverflow.com/comment/81218320
has answer: http://stackoverflow.com/a/47134370
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47134367
has title: Lists reassigning each other without specifying to change them

http://stackoverflow.com/comment/81084791
type: Comment
type: AnswerComment
score: 0
has text: Thank you! This is very helpful and elegant. I would also like to use groupby across both 'Session' and 'Subject', so 'CumScore' begins again when there is a new subject, not just a new session. How could I add that dimension?
comment on: http://stackoverflow.com/a/47068219

http://stackoverflow.com/a/52309010
has body: Find length by getting shape for index, row in tqdm(df.iterrows(), total=df.shape[0]): print("index",index) print("row",row)
type: Answer
score: 251
upvote count: 251
has comment: http://stackoverflow.com/comment/93444460
has comment: http://stackoverflow.com/comment/109316594
has comment: http://stackoverflow.com/comment/103424315
answers question: http://stackoverflow.com/q/47087741
has comment: http://stackoverflow.com/comment/112714389
downvote count: 0
has comment: http://stackoverflow.com/comment/110157698
has comment: http://stackoverflow.com/comment/129892413
has comment: http://stackoverflow.com/comment/98393088

http://stackoverflow.com/q/47148672
has title: python multiprocessing with multiple cpus?
type: UnansweredQuestion
answer count: 1
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/81292132
has answer: http://stackoverflow.com/a/47148814
tagged with: multiprocessing
type: Question
has body: I have two Xeon processors (each has 8 cores, so total 32 threads) on my MOBO, and I ran a simple code using multiprocessing.Pool(processors=30). When I monitor using htop, I find that only 12 threads are utilized. Does anyone know why that might be happening?
has comment: http://stackoverflow.com/comment/81247477

http://stackoverflow.com/comment/81318297
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47184076
has text: this error is returned to me 'QuerySet' object has no attribute 'f1'

http://stackoverflow.com/comment/81198965
type: QuestionComment
has text: You can't just expect random names to get interpolated into your string. Try something like `'[{}]'.format(symbols)`.
comment on: http://stackoverflow.com/q/47124359
score: 0
type: Comment

http://stackoverflow.com/comment/81126847
type: Comment
comment on: http://stackoverflow.com/a/47088524
score: 0
type: AnswerComment
has text: It gave me this: driver.find_elements_by_xpath("//*[@id='textarea']").click() And when I used it I got an error: AttributeError: 'list' object has no attribute 'click'

http://stackoverflow.com/comment/81330132
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47190372
has text: Have you tried something? What problems did you encounter?
type: Comment

http://stackoverflow.com/comment/81367611
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47209214
has text: Wouldn't it use the apt binary from the host? I mean, how can then a go binary run inside `scratch`?

http://stackoverflow.com/a/51711251
has body: You get this error when your Python client receives an empty response (header /body). BTW newer Python version will throw a different Exception, It can happen when the server disconnects the connections, or a network issue. In my case, we spent some weeks trying to reproduce it until we found the main cause, We have a Python application sending requests to a service behind Nginx loadbalancer, We found that Nginx disconnects the connection when the client exceeded the default Nginx configurations client_header_timeout / client_body_timeout (60 sec), it's the time that Nginx will wait for additional data packet from the client. You can follow this reference http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_timeout When our application is loaded with CPU processing, connections are established but header and request body have a long delay until transmitted, over 82 seconds. So Nginx closes the connection and returns reset packet (recorded tcpdump with empty body and headers), officially it should return status code 408, which is not happening. We solved it by increasing the client_header_timeout / client_body_timeout to 180s for both params: server { .. client_body_timeout 180s; client_header_timeout 180s; }
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47196100
type: Answer

http://stackoverflow.com/comment/81158971
comment on: http://stackoverflow.com/a/47104095
type: AnswerComment
has text: wow, that last part you added is so simple and does it all! I am very new to coding as you can see...
score: 0
type: Comment

http://stackoverflow.com/q/47222351
has answer: http://stackoverflow.com/a/47224858
has answer: http://stackoverflow.com/a/47222775
accepted answer: http://stackoverflow.com/a/47224858
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/81394438
has comment: http://stackoverflow.com/comment/81398938
favorite count: 0
has comment: http://stackoverflow.com/comment/81398564
possible better answer: http://stackoverflow.com/a/47222487
linked to: http://stackoverflow.com/q/35446015
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81397558
has title: How to reassign the values of a dictionary by exisiting values?
score: 1
has comment: http://stackoverflow.com/comment/81394368
has answer: http://stackoverflow.com/a/47222487
has comment: http://stackoverflow.com/comment/81395048
answer count: 4
has comment: http://stackoverflow.com/comment/81397541
has answer: http://stackoverflow.com/a/47224062
downvote count: 0
has body: I have a counter objects like Counter({'the': 10, 'to': 10, 'of': 5, 'independence': 5, 'puigdemont': 5, 'mr': 5, 'a': 4, 'spain': 4, 'for': 4}) I want to reassign each element's value in increasing order by existing value, like Counter({'the': 0, 'to': 1, 'of': 2, 'independence': 3, 'puigdemont': 4, 'mr': 5, 'a': 6, 'spain': 7, 'for': 8}) Is there any possible method? Thanks in advance. Update: (My English is not very good, so you may skip my explanation and roll down to see the example below.) Sorry, it seems that I didn't make my question clear. Actually the whole Counter object is much longer. The object is obtained from a paragraph, and the value of each word is the occurrence in that paragraph. I want to build a dictionary to replace the words in my paragraph with the corresponding values in the dictionary. The values in the dictionary are ordered by the frequencies of the words in my paragraph, and if two words have the same occurrence, then in alphabetical order. Example: string=“where there is smoke there is fire" Occurrences for each word in string: where=1, there=2, is=2, smoke=1, fire=1. So I need a dictionary like: {“is”: 0, “there”: 1, ”fire”:2 , “smoke”: 3, “where”:4} The most frequent words are "is" and "there", but in alphabetical order, "i" is in front of "t", so "is" is 0 and "there" is 1. Is there any good method to accomplish this? Very thankful!!
upvote count: 1
has comment: http://stackoverflow.com/comment/81397630

http://stackoverflow.com/a/47160176
has body: Do refer to this thread below: scikit-learn cross validation, negative values with mean squared error In summary, this is supposed to happen. The actual MSE is simply the positive version of the number you're getting. Hope this helps!
answers question: http://stackoverflow.com/q/47157555
type: Answer
accepted answer of: http://stackoverflow.com/q/47157555
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/90826642
type: Comment
comment on: http://stackoverflow.com/a/47941032
score: 0
type: AnswerComment
has text: How is definite defaultdict(dict)

http://stackoverflow.com/comment/81139200
has text: I don´t understand your question, why don´t u save the links you selected in an array and progress them by an similar mehtod and search for what u want ?
type: QuestionComment
comment on: http://stackoverflow.com/q/47094900
score: 0
type: Comment

http://stackoverflow.com/a/47105585
accepted answer of: http://stackoverflow.com/q/47105560
type: Answer
has body: Your JSON file has an invalid format. You can only have one top level element in valid JSON Try Placing the top level objects into an array. [ { "created_at": "Thu Nov 02 01:09:12 +0000 2017", "text": "RT @coindesk: SEC: Celebrity ICO Endorsements Could Be Illegal gHoWduXOBp t.co/iyWla0Ryuk", "tweet_id": 925892516087558145, "user_id": 153962533, "user_name": "Christine Duhaime" }, { "created_at": "Thu Nov 02 01:09:44 +0000 2017", "text": "Cornell Professor C t.co/RuNu6UQyr9", "tweet_id": 925892650884108289, "user_id": 1255045351, "user_name": "Local SEO Somerset" } ]
answers question: http://stackoverflow.com/q/47105560
has comment: http://stackoverflow.com/comment/81162806
has comment: http://stackoverflow.com/comment/81162885
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/47070220
downvote count: 1
has body: Say I have an N-dimensional prism, bounded by two points: the minimum, and the maximum. In three dimensions, this would be the lower-left and upper-right points on the prism. The bounds of a prism is technically all one needs to define the prism, and yet I am having difficulty extrapolating certain pieces of information. I can get a list of all the points using a cartesian product. But is there an elegant way to calculate a list of surfaces from this starting point? For example, a three dimensional cube bounded by (0, 0, 0) and (1, 1, 1) would have these surfaces: [(0, 0, 0), (0, 1, 0), (0, 1, 1), (0, 0, 1)] [(0, 0, 0), (1, 0, 0), (1, 0, 1), (0, 0, 1)] [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)] [(1, 1, 1), (1, 0, 1), (1, 0, 0), (1, 1, 0)] [(1, 1, 1), (0, 1, 1), (0, 1, 0), (1, 1, 0)] [(1, 1, 1), (0, 1, 1), (0, 0, 1), (1, 0, 1)] It bears mentioning that I ultimately intend to display these surfaces graphically. Hence, part of the issue I am dealing with is that the points for each surface should be in an order that actually defines a closed surface. So, the surface: [(0, 0, 0), (0, 1, 0), (0, 1, 1), (0, 0, 1)] is valid, but [(0, 0, 0), (0, 1, 0), (0, 0, 1), (0, 1, 1)] is not in the right order, since the edges cross over each other (and I cannot think of a very good approach to putting the points in their proper order). I have tried and failed to think of a way to calculate the list of surfaces for a prism that isn't horribly messy. Any advice on the correct way to tackle this would be much appreciated. I realize this is an oddly specific question. However, I believe there should be a good approach to solve this, and I can't seem to find it. How does one go about solving a problem like this?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47145094
tagged with: python
has comment: http://stackoverflow.com/comment/81284880
tagged with: spatial
tagged with: surface
upvote count: 2
type: UnansweredQuestion
tagged with: arrays
answer count: 1
score: 1
has title: Is there an elegant way to generate the surfaces of an N-dimensional prism from only min and max points?

http://stackoverflow.com/q/47159723
linked to: http://stackoverflow.com/q/21556512
tagged with: types
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47169891
accepted answer: http://stackoverflow.com/a/47234185
has answer: http://stackoverflow.com/a/47169891
has answer: http://stackoverflow.com/a/47234185
score: 1
has title: Sympy function derivatives and sets of equations
tagged with: python
type: AnsweredQuestion
has body: I'm working with nonlinear systems of equations. These systems are generally a nonlinear vector differential equation. I now want to use functions and derive them with respect to time and to their time-derivatives, and find equilibrium points by solving the nonlinear equations 0=rhs(eqs). Similar things are needed to calculate the Euler-Lagrange equations, where you need the derivative of L wrt. diff(x,t). Now my question is, how do I implement this in Sympy? My main 2 problems are, that deriving a Symbol f wrt. t diff(f,t), I get 0. I can see, that with x = Symbol('x',real=True); diff(x.subs(x,x(t)),t) # because diff(x,t) =&gt; 0 and diff(x**2, x) does kind of work. However, with x = Fuction('x')(t); diff(x,t); I get this to work, but I cannot differentiate wrt. the funtion x itself, like diff(x**2,x) -DOES NOT WORK. Since I need these things, especially not only for scalars, but for vectors (using jacobian) all the time, I really want this to be a clean and functional workflow. Which kind of type should I initiate my mathematical functions in Sympy in order to avoid strange substitutions? It only gets worse for matricies, where I cannot get eqns = Matrix([f1-5, f2+1]); variabs = Matrix([f1,f2]); nonlinsolve(eqns,variabs); to work as expected, since it only allows symbols as input. Is there an easy conversion here? Like eqns.tolist() - which doesn't work either? EDIT: I just found this question, which was answered towards using expressions and matricies. I want to be able to solve sets of nonlinear equations, build the jacobian of a vector wrt. another vector and derive wrt. functions as stated above. Can anyone point me into a direction to start a concise workflow for this purpose? I guess the most complex task is calculating the Lie-derivative wrt. a vector or list of functions, the rest should be straight forward. Edit 2: def substi(expr,variables): return expr.subs( {w:w(t)} ) would automate the subsitution, such that substi(vector_expr,varlist_vector).diff(t) …
answer count: 2
tagged with: sympy

http://stackoverflow.com/a/79435030
answers question: http://stackoverflow.com/q/47077829
type: Answer
downvote count: 0
has body: For the lazy devs like me, urllib is included natively, doesn't require layers or zips or anything like that. import json import urllib.requests def send_slack_message(prefix): slack_message = json.dumps({ "text": f"New file uploaded to: `{prefix}`" }).encode('utf-8') req = urllib.request.Request( SLACK_WEBHOOK_URL, data=slack_message, headers={"Content-Type": "application/json"} ) with urllib.request.urlopen(req) as response: if response.status != 200: print(f"Failed to send Slack message: {response.read().decode('utf-8')}") return
upvote count: 1
score: 1

http://stackoverflow.com/comment/81167661
has text: BTW, it's not a good idea to use `input` as a variable name because that shadows the built-in `input` function.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47107663
type: QuestionComment

http://stackoverflow.com/a/47113259
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Use find_all function. Here is the documentation. for td in soup.find_all('td'): td['class'] = "list"
accepted answer of: http://stackoverflow.com/q/47105557
answers question: http://stackoverflow.com/q/47105557
type: Answer
score: 1

http://stackoverflow.com/q/47147012
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: daemon
type: Question
tagged with: systemd
has title: Handling start/stop/restart systemd events in a Python service without a daemon
has body: I want to create a system service from a Python program. The standard way up until recently seems to have been to make a daemon; however, I've read here that systemd can make many daemons obsolete: the idea is that you can use the main process to run the system service and let systemd do the rest. So, assuming the "cool" thing to do these days is to use the main process, then what I can't get my head around is how to handle stopping and restarting of the service gracefully (i.e. via sysctl myscript restart, etc.) I know systemd has an ExecStop parameter which can run a command on exit, and I guess I could write a script which sets a flag in a file somewhere, and my Python program could then periodically poll this file and act accordingly. However, I imagine there is a more graceful way to do this. So, is it possible to handle stop/restart events without a daemon when using systemd?
linked to: http://stackoverflow.com/q/43711966
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/13069634
has comment: http://stackoverflow.com/comment/81245796
tagged with: python
has comment: http://stackoverflow.com/comment/81244539
linked to: http://stackoverflow.com/q/18499497
duplicate of: http://stackoverflow.com/q/43711966
has comment: http://stackoverflow.com/comment/81244416
answer count: 0
has comment: http://stackoverflow.com/comment/81244569
score: 1
has comment: http://stackoverflow.com/comment/81244395

http://stackoverflow.com/q/47084168
answer count: 1
tagged with: less-unix
type: Question
has title: Python Fabric prompts: weird behaviour with 'less' and raw_input
has body: I have a fabric task that looks like this: @task def test(): with settings(prompts={'This is a test.': 'q', 'question?':'answer'}): run("python test.py") my test.py script looks like this: import subprocess, os subprocess.call(['less', '-e', os.path.abspath('test.txt')]) response = raw_input("A question?") print("response is [{0}]".format(response)) And test.txt contains: This is a test. If I run this, and I add a few prints in fabric to see what's happening, indeed when reading the file fabric finds the text, enters q. It then stops on raw_input, sends the response. But raw_input gets "" as an answer instead of response!! If I remove 'question?':'answer' from my prompts dict, and enter the answer manually, again, it is somehow swallowed... However if I remove 'This is a test.': 'q' and exit the less command manually, both manual or automatic response for the raw_input work again. How can I exit less without my subsequent answers being swallowed? Of course, I simplified a real life scenario where I can't change these files...
tagged with: fabric
tagged with: python
has comment: http://stackoverflow.com/comment/81117648
has answer: http://stackoverflow.com/a/47085461
tagged with: raw-input
type: UnansweredQuestion
score: 0

http://stackoverflow.com/a/47206961
accepted answer of: http://stackoverflow.com/q/47150566
upvote count: 1
score: 1
type: Answer
has body: Following MRocklin's advice above, I ran through my class element by element, and here are the issues that were causing the exception stated above. 1. Class With Inner Functions Credit to Emlyn O'Regan for this blogpost that made me realise that I had code which did the following and cannot be pickled: class A: def __init__(self, parent): self.parent = parent def do_something(): # access self.parent class B: def my_func(): a = A(self) a.do_something() Fixed by rewriting the code to pass the attributes as parameters to the appropriate method. 2. Class Referenced Global Variables This was just hastily written code where I'd placed some constant variables (parameters set once at start up) outside of the class definition, then referenced from within a class that needed to be pickled. Fixed by moving the variables into the class definition. 3. Class Defined In Main Module I had inherited from a base class in the main module to create a new class with overridden behaviour. The new class lies in the main name space, so could not be pickled. The solution was simply to move the definition of the inherited class into a separate file so it resided in a namespace other than main. i.e. instead of: my_script.py class A: # define stuff if __name__ == "__main__": # do stuff which will instantiate A create two files: class_a.py class A: #define stuff main.py from class_a import A if __name__ == "__main__": # do stuff which at some point will instantiate A Ian
answers question: http://stackoverflow.com/q/47150566
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81371408
has text: @JacobKrall isn't it verifiable and complete? You could simply run this script.
score: 1
comment on: http://stackoverflow.com/q/47210965
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47084223
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/118400585
has body: I'm new to python programming. This is probably a dumb question but when I evaluate a file in the PyDev console and type in __name__, it returns builtins rather than __main__, which makes if(__name__ == "__main__") doesn't work. How to fix this?? Thanks in advance.
tagged with: python
has title: Why PyDev console says my __name__ is "builtins"?
has comment: http://stackoverflow.com/comment/81119523
has comment: http://stackoverflow.com/comment/81121071
upvote count: 3
score: 3
downvote count: 0
linked to: http://stackoverflow.com/q/49030636
has comment: http://stackoverflow.com/comment/81117891
tagged with: eclipse
favorite count: 0
has comment: http://stackoverflow.com/comment/81117850
type: Question
answer count: 0
tagged with: pydev

http://stackoverflow.com/q/47153575
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/47175260
has title: create csv from different files using python
type: Question
accepted answer: http://stackoverflow.com/a/47174472
tagged with: python
has body: I have 2 csv files that I am generating via python. The records are below (a.csv and b.csv). b.csv has 2 rows and the values in second row can be duplicates. I want to have a result like final.csv. How can I do that? I tried below code but that's not right. I am not doing the right comparison. Any help would be great. a.csv "all","1","1Gi","4","8Gi" "als","0","0","100m","128Mi" "awx","6","9Gi","20","32Gi" "cho-1","9","9728Mi","15","20Gi" "cho-2","12250m","15395Mi","20","24Gi" b.csv "all","ABC" "als","ABC" "awx","DPL" "cho-1","ABC" "cho-2","ABC" "cho-3","ABC" I want to create one file out of both like below final.csv "all","1","1Gi","4","8Gi","ABC" "als","0","0","100m","128Mi","ABC" "awx","6","9Gi","20","32Gi","DPL" "cho-1","9","9728Mi","15","20Gi","ABC" "cho-2","12250m","15395Mi","20","24Gi","ABC" my code: csv1 = csv.reader(open("reports/a.csv", "r")) csv2 = csv.reader(open("reports/b.csv", "r")) s=[] while True: try: line1 = csv1.next() line2 = csv2.next() if (line1[0] == line2[0]): s.append([line1[1], line2[0], line2[1], line2[2], line2[3], line2[4]]) else: s.append(["NA", line2[0], line2[1], line2[2], line2[3], line2[4]]) except StopIteration: break
has answer: http://stackoverflow.com/a/47174472
possible better answer: http://stackoverflow.com/a/47154665
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/47154665

http://stackoverflow.com/a/47089838
type: Answer
has body: Need value_counts for one column or groupby + size (or count if need omit NaNs): a = df['Label'].value_counts() print (a) Cee 4 Bar 4 Foo 3 Name: Label, dtype: int64 #alternative #a = df.groupby('Label').size() print (a.mean()) 3.6666666666666665 print (a.median()) 4.0 a = df.groupby(['Label','Letter']).size() print (a) Label Letter Bar A 1 G 1 N 1 P 1 Cee B 2 C 1 D 1 Foo A 1 B 1 C 1 dtype: int64 print (a.mean()) 1.1 print (a.median()) 1.0
score: 2
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47089785
has comment: http://stackoverflow.com/comment/97003356
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81129065
answers question: http://stackoverflow.com/q/47089785
has comment: http://stackoverflow.com/comment/81128930

http://stackoverflow.com/a/47100845
has comment: http://stackoverflow.com/comment/81161033
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47100670
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81152175
has body: def calculate(): name = (textboxName.get()) age = (textboxAge.get()) try: newAge = int(age)+5 except ValueError: tkinter.messagebox.showinfo("Error", "The Intended Reading Age is invalid") textboxAge.delete("0","end") return print("Hello",name) print("In 5 years time you will be ",newAge) # ... If an error occurs somewhere in the try-section, python will not crash, but rather jump to the except part. The critical step is converting age into integer. This throws a ValueError if it is a string. In this case, the message box is shown and the text in your textbox is deleted. return then will stop the function, so the rest of it won't be processed. If nothing happens in the try-section, then except will be skipped.
type: Answer
accepted answer of: http://stackoverflow.com/q/47100670

http://stackoverflow.com/comment/81107484
comment on: http://stackoverflow.com/q/47077683
has text: This is just a copy of some of your code from above. What I'm asking is what the problem is. You wrote "this is not working". How is it not working? Why do you think setting the `Referer` header has anything to do with it?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82240491
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47633825
has text: It turns out I actually wanted case 1, so thanks for providing that. However, I sometimes get KeyErrors when using your code. The nodes in my set A are integers, and the nodes in my set B are two letter strings, such as 'dk', to keep the sets differentiated. When I run your code for case 1, I sometimes get errors like the following:
type: Comment

http://stackoverflow.com/a/65824735
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47207237
has body: For dataframe df, duplicate rows can be dropped using this code. df = pd.read_csv('./data/data-set.csv') print(df['text']) def clean_data(dataframe): # Drop duplicate rows dataframe.drop_duplicates(subset='text', inplace=True) clean_data(df) print(df['text'])
score: 1
downvote count: 0

http://stackoverflow.com/a/47248021
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47193139
downvote count: 0
has body: I figured out how to fix it train_set=jobs+jobs2 train_set=[tmp.lower() for tmp in train_set] That's pretty much it. I just needed to add lower to the strings inside my list.

http://stackoverflow.com/a/47091435
has comment: http://stackoverflow.com/comment/81132343
answers question: http://stackoverflow.com/q/47091183
type: Answer
has body: Not sure if I got the question right, but here's an example that searches for symbols in [Python]: globals(): import sys x = [1, 2, 33] def dummy(): pass def symbol(obj): globals_dict = globals() for name in globals_dict: if obj is globals_dict[name]: return name def main(): for obj in [sys, x, dummy, symbol, main]: obj_name = symbol(obj) print(obj_name, type(obj_name)) if __name__ == "__main__": main() Output: E:\Work\Dev\StackOverflow\q47091183&gt;"E:\WinOBT\1.0.0.0\OPSWpython\2.7.10__00\x86\python.exe" a.py ('sys', &lt;type 'str'&gt;) ('x', &lt;type 'str'&gt;) ('dummy', &lt;type 'str'&gt;) ('symbol', &lt;type 'str'&gt;) ('main', &lt;type 'str'&gt;)
score: 0
has comment: http://stackoverflow.com/comment/81132384
has comment: http://stackoverflow.com/comment/81132196

http://stackoverflow.com/comment/88411591
type: QuestionComment
has text: Did you solve it? If yes, how?
comment on: http://stackoverflow.com/q/47170773
score: 1
type: Comment

http://stackoverflow.com/comment/81357596
type: Comment
has text: But I don't know the slow cases until *after* the slow stuff has occurred (something with thread blocking that shouldn't block)
type: QuestionComment
comment on: http://stackoverflow.com/q/47191304
score: 0

http://stackoverflow.com/comment/105391384
score: 0
type: AnswerComment
has text: @geckos Could you please elaborate on those exceptions? Can you add a link for the import hooks? [The official python docs](https://docs.python.org/3/tutorial/modules.html) state "The __init__.py files are required to make Python treat directories containing the file as packages.". Are the docs outdated?
comment on: http://stackoverflow.com/a/47193123
type: Comment

http://stackoverflow.com/comment/81212760
has text: That's perfect. I kept getting caught up in running a counter but it was stuck in the while loop and throwing wild data. Thanks
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47131654

http://stackoverflow.com/q/47087741
has answer: http://stackoverflow.com/a/52309010
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/51908622
has answer: http://stackoverflow.com/a/74851871
upvote count: 115
has body: Is it possible to use TQDM progress bar when importing and indexing large datasets using Pandas? Here is an example of of some 5-minute data I am importing, indexing, and using to_datetime. It takes a while and it would be nice to see a progress bar. #Import csv files into a Pandas dataframes and convert to Pandas datetime and set to index eurusd_ask = pd.read_csv('EURUSD_Candlestick_5_m_ASK_01.01.2012-05.08.2017.csv') eurusd_ask.index = pd.to_datetime(eurusd_ask.pop('Gmt time'))
has answer: http://stackoverflow.com/a/47210797
favorite count: 0
type: Question
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48350868
has title: Use TQDM Progress Bar with Pandas
score: 115
tagged with: python
has comment: http://stackoverflow.com/comment/81125617
tagged with: tqdm

http://stackoverflow.com/comment/81171230
type: AnswerComment
comment on: http://stackoverflow.com/a/47110082
has text: Okay, now I see what you are doing, I didnt realize a dictionary could hold dataframes... So, I implemented your recommended version via: d_df={} for col in model_data.drop(['usrec'],axis=1).columns: for i in range(12,0,-1): d_df['t'+str(i)]=model_data[col].shift(i).add_suffix('_t'+str(i)).to_frame() However, it will only preserve the last column of the 2300 or so columns in the original dataframe, I know of the append function, however unsure if this would work here, any ideas?
score: 0
type: Comment

http://stackoverflow.com/a/47084159
type: Answer
accepted answer of: http://stackoverflow.com/q/47083402
has comment: http://stackoverflow.com/comment/81195368
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81161183
downvote count: 0
has comment: http://stackoverflow.com/comment/81195550
upvote count: 1
has comment: http://stackoverflow.com/comment/81191662
has comment: http://stackoverflow.com/comment/81168459
has body: I haven't found a way of doing this by recognizing the android device's orientation. However, the following program changes it's contents by comparing the window's height and width. The program's Label changes dynamically, so when the width is greater (landscape mode) it's Label has a different text then when the height is greater (portrait mode). Currently it works on Windows, but unfortunately I don't have a Linux system to build an android version. Theoretically it should work, but i'm not 100% sure. from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.label import Label from kivy.graphics import Rectangle, Color class MainScreen(FloatLayout, Label): """MAIN WINDOW CLASS""" def __init__(self, **kwargs): super(MainScreen, self).__init__(**kwargs) with self.canvas.before: Color(0.988, 0.725, 0.074, 1, mode='rgba') self.rect = Rectangle(pos=self.pos, size=self.size) self.bind(size=self.update_rect) self.titlos = Label(text="", bold=True, text_size=(None,None), font_size="20sp", pos_hint={'center_x': 0.5, 'center_y': .85}, size_hint_y=None, size = self.size, height=self.texture_size[1], halign="center", valign = "middle", color=(0.055, 0.235, 0.541, 1)) self.add_widget(self.titlos) self.bind(size=self.update_orientation) def update_rect(self, *args): """FUNCTION TO UPDATE THE RECATANGLE OF CANVAS TO FIT THE WHOLE SCREEN OF MAINSCREEN ALWAYS""" self.rect.pos = self.pos self.rect.size = self.size def update_orientation(self, *args): """FUNCTION TO UPDATE THE SCREEN CONTENTS WHEN THE WINDOW SIZE CHANGES""" if self.parent.size[1] &gt; self.parent.size[0]: self.titlos.text = "This is\nPortrait\nOrientation" else: self.titlos.text = "This is Landscape Orientation" # This is just for checking. Not essential to the program. print("Width:", self.parent.size[0], ", Height:", self.parent.size[1]) class main(App): """BUILDING THE APP""" def build(self): return MainScreen() if __name__ == "__main__": main().run() You can use the update_orientation f…
answers question: http://stackoverflow.com/q/47083402
score: 1

http://stackoverflow.com/comment/81342841
has text: After using pytz.utc.localize the data appears like this dataToSFDC = [{'Birthdate': datetime.datetime(2017, 8, 19, 0, 0, tzinfo=<UTC>)] and Error thrown is: Object of type 'datetime' is not JSON serializable
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47196444

http://stackoverflow.com/q/47148170
linked to: http://stackoverflow.com/q/39114382
tagged with: dataframe
tagged with: python
has body: So far, I have this code that adds a row of zeros every other row (from this question): import pandas as pd import numpy as np def Add_Zeros(df): zeros = np.where(np.empty_like(df.values), 0, 0) data = np.hstack([df.values, zeros]).reshape(-1, df.shape[1]) df_ordered = pd.DataFrame(data, columns=df.columns) return df_ordered Which results in the following data frame: A B 0 a a 1 0 0 2 b b 3 0 0 4 c c 5 0 0 6 d d But I need it to add the row of zeros every 2nd row instead, like this: A B 0 a a 1 b b 2 0 0 3 c c 4 d d 5 0 0 I've tried altering the code, but each time, I get an error that says that zeros and df don't match in size. I should also point out that I have a lot more rows and columns than I wrote here. How can I do this?
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47148278
accepted answer: http://stackoverflow.com/a/47148278
tagged with: pandas
score: 1
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
has title: Pandas: Inserting an empty row after every 2nd row in a data frame

http://stackoverflow.com/comment/81136040
type: AnswerComment
score: 0
has text: i can only call the function to process after 4 minutes, your condition will call my function before the data has pass over 4 minutes. after 4 minutes it will call my functions and call again every other 4 minutes.
comment on: http://stackoverflow.com/a/47092060
type: Comment

http://stackoverflow.com/q/47156443
has body: I need to read from a socket several times. Since I need to respond back within 2 seconds, the reading should be efficient, also when I need to read a line with more than 12,000 integers (the computation done with those integers does not take long, i.e. 0.015s) I have the following approach: import socket host = "SOMEHOST" port = SOMEPORT client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((host, port)) def read_from_socket(client): response = '' char = '' while not '\n' in char: char = client.recv(1) response += char return response for SOMEWHILE: line = read_from_socket(client) # do some stuff with line client.send(SOMEANSWER) Can this be done more efficiently, such that it does not take longer than those 2 seconds to respond? EDIT: The input looks the like the following: Case #SOME_NUMBER: T N N numbers I have modified the code according to the comments like this: def read_from_socket(client, size=1): if size &gt; 1: return client.recv(size*4) else: response = '' char = '' while not '\n' in char: char = client.recv(size) response += char return response for i in SOME_RANGE: case = read_from_socket(client) print case T, N = read_from_socket(client).split(' ') numbers = read_from_socket(client, int(N)).split(' ') numbers = filter(None, numbers) numbers = [int(number) for number in numbers] answer = # DO SOME STUFF WITH numbers print "{}".format(answer) Hereby I get the following output: Case #1: 4 Case #2: 1 Case #3: 3 Case #4: 6 Case #5: 5 Case #6: 6 17 14 5 13 6 1 18 15 3 7 3 4 2 15 3 11 13 13 19 17 15 11 4 6 13 16 20 1 9 13 12 5 19 8 10 16 1 7 2 3 14 5 7 7 19 1 10 4 13 20 12 20 10 15 5 14 11 17 14 11 1 17 15 11 5 16 7 5 3 8 19 8 4 5 6 3 18 15 18 10 6 9 9 16 4 6 9 6 14 15 16 6 11 2 17 7 18 3 3 12 2 2 11 6 18 16 20 15 3 17 17 8 5 5 15 20 2 16 17 7 10 4 13 12 6 9 19 15 3 1 18 16 14 8 1 12 15 12 18 9 8 14 9 5 11 3 4 12 18 13 11 19 16 3 11 13 3 1 19 17 13 16 12 7 15 5 10 2 16 19 10 16 13 18 20 3 13 15 6 10 7 8 1 3 10 3 7 4 3 6 20 15 1 12 13 8 8 …
type: UnansweredQuestion
tagged with: sockets
linked to: http://stackoverflow.com/q/10742639
tagged with: python
has comment: http://stackoverflow.com/comment/81262235
has comment: http://stackoverflow.com/comment/81262324
has title: How to read EFFICIENTLY from a socket
has comment: http://stackoverflow.com/comment/81262362
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/81262419
tagged with: processing-efficiency
has comment: http://stackoverflow.com/comment/81262413
type: Question

http://stackoverflow.com/a/47081228
has comment: http://stackoverflow.com/comment/81125841
has comment: http://stackoverflow.com/comment/81131303
has comment: http://stackoverflow.com/comment/81127171
type: Answer
has comment: http://stackoverflow.com/comment/81128206
has comment: http://stackoverflow.com/comment/81125909
has comment: http://stackoverflow.com/comment/81125722
accepted answer of: http://stackoverflow.com/q/47076009
has body: If you want to return form errors in your AJAX response, Override form_invalid like this: def form_invalid(self, form): error_dict= {'status':'form-invalid','form-errors':form.errors} return HttpResponse(json.dumps(error_dict),content_type="application/json") form.errors: gets the form validation errors if password1 != password2. In your ajax success response("form valid and invalid will always return a response, error function will work only if the code breaks in form valid") In your AJAX: if (data.status=="form-invalid") { Whatever you want to do e.g. $('.class-name').html(data.form-errors) } data.status checks if the json-dict returned in response has status="form-errors", then append those errors in a div or anywhere you want. Note: Ajax error function only works if there is no response to a request. Form valid and invalid will always return a response and will come in ajax success function unless a break/error in code(will return no response).
upvote count: 3
score: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47076009
downvote count: 0

http://stackoverflow.com/comment/81205264
type: Comment
type: QuestionComment
score: 0
has text: hmm.. it seems to work fine for me, try installing it with pip: `pip install mpmath`
comment on: http://stackoverflow.com/q/47099370

http://stackoverflow.com/comment/81153812
type: QuestionComment
type: Comment
has text: Since `3` is only the third number in `a`, the first two iterations of the while loop do get to the printing of time.
score: 0
comment on: http://stackoverflow.com/q/47101693

neo4j-python-driver
type: Tag
tags question: http://stackoverflow.com/q/47133423
tag name: neo4j-python-driver

http://stackoverflow.com/q/47110254
tagged with: curve-fitting
tagged with: python
has body: I am trying to fit two Gaussians on a bimodal distribution data, but most of the optimisers give me wrong results always based on starting guess as below I also tried GMM from scikit-learn, which didn't help much. I am wondering what I may be doing wrong and what is better approach so that we can test and fit the bimodal data. One of the example code using curve_fit and data is as follows import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit def gauss(x,mu,sigma,A): return A*np.exp(-(x-mu)**2/2/sigma**2) def bimodal(x,mu1,sigma1,A1,mu2,sigma2,A2): return gauss(x,mu1,sigma1,A1)+gauss(x,mu2,sigma2,A2) def rmse(p0): mu1,sigma1,A1,mu2,sigma2,A2 =p0 y_sim = bimodal(x,mu1,sigma1,A1,mu2,sigma2,A2) rms = np.sqrt((y-y_sim)**2/len(y)) data = pd.read_csv('data.csv') x, y = data.index, data['24hr'].values expected=(400,720,500,700,774,150) params,cov=curve_fit(bimodal,x,y,expected, maxfev=100000) sigma=np.sqrt(np.diag(cov)) plt.plot(x,bimodal(x,*params),color='red',lw=3,label='model') plt.plot(x,y,label='data') plt.legend() print(params,'\n',sigma)
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47133018
has comment: http://stackoverflow.com/comment/81181179
upvote count: 2
has comment: http://stackoverflow.com/comment/81181422
has title: Fitting two Gaussians on less expressed bimodal data
answer count: 1
score: 1
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/47133018
downvote count: 1
has comment: http://stackoverflow.com/comment/81180914
tagged with: scipy
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81181069
has comment: http://stackoverflow.com/comment/81191732

http://stackoverflow.com/comment/81086156
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47068017
has text: @hpaulj I'm reading the answer you kindly provided and trying to understand it. one other idea that came to my mind was slicing ds2 array into multiple parts and retrieving indexes in parallel. I'm not a professional so sorry if I talk very basics.
score: 0

http://stackoverflow.com/a/47216885
has comment: http://stackoverflow.com/comment/81392761
has comment: http://stackoverflow.com/comment/81394068
has comment: http://stackoverflow.com/comment/81395183
has comment: http://stackoverflow.com/comment/81391580
score: 1
answers question: http://stackoverflow.com/q/47216716
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81394962
upvote count: 1
has comment: http://stackoverflow.com/comment/81394188
has comment: http://stackoverflow.com/comment/81392813
has body: Setup df1 # yod_user id password username 0 2 YkxJNWNDT pk@gmail.in 1 4 VjNUYWh test@gmail.com 2 6 dddd zz113@gmail.com 3 8 ssss faulmike@aol.com 4 10 errfs newr10@gmail.com df2 # yod_bank acc_number bank_name bankid userid 0 4590 xyz 99 2 1 4520 abc 100 4 2 4980 xyz 56 6 3 4570 ypr 99 8 4 4530 abc 17 2 First, take df2 and convert it to a list of dictionaries grouped by userid: df3 = df2.set_index('userid', drop=False)\ .rename_axis('id')\ .apply(dict, 1)\ .groupby(level=0)\ .apply(lambda x: x.tolist())\ # x.values.T.tolist() .to_frame('account') df3.index = df3.index.astype(int) df3 account id 2 [{'bankid': '99', 'userid': '2', 'bank_name': ... 4 [{'bankid': '100', 'userid': '4', 'bank_name':... 6 [{'bankid': '56', 'userid': '6', 'bank_name': ... 8 [{'bankid': '99', 'userid': '8', 'bank_name': ... Note here that I converted the df3.index to an integer type, since df1.id is of integer type as well. This will help with the next step. Now, perform a merge: df = df1.merge(df3, left_on='id', right_index=True) df id password username \ 0 2 YkxJNWNDT pk@gmail.in 1 4 VjNUYWh test@gmail.com 2 6 dddd zz113@gmail.com 3 8 ssss faulmike@aol.com account 0 [{'bankid': '99', 'userid': '2', 'bank_name': ... 1 [{'bankid': '100', 'userid': '4', 'bank_name':... 2 [{'bankid': '56', 'userid': '6', 'bank_name': ... 3 [{'bankid': '99', 'userid': '8', 'bank_name': ... (Optional) convert to records: import pprint pprint.pprint(df.to_dict('r')) [{'id': 2, 'password': 'YkxJNWNDT', 'userid': [{'acc_number': '4590', 'bank_name': 'xyz', 'bankid': '99', 'userid': '2'}, {'acc_number': '4530', 'bank_name': 'abc', 'bankid': '17', 'userid': '2'}], 'username': 'pk@gmail.in'}, {'id': 4, 'password': 'VjNUYWh', 'userid': [{'acc_number': '4520', 'bank_name': 'abc', 'bankid': '100', 'userid': '4'}], 'username': 'test@gmail.com'}, {'id': 6, 'password': 'dddd', 'userid': [{'acc_number': '4980', 'bank_name': 'xyz', 'bankid': '56', 'userid': '6'}], 'username': 'zz113@gmail.com'}, {'id': 8, 'password': 'ssss', …
has comment: http://stackoverflow.com/comment/81394886
has comment: http://stackoverflow.com/comment/81394054
has comment: http://stackoverflow.com/comment/81392706
has comment: http://stackoverflow.com/comment/81394122
type: Answer
has comment: http://stackoverflow.com/comment/81392843
has comment: http://stackoverflow.com/comment/81394743
has comment: http://stackoverflow.com/comment/81393941
has comment: http://stackoverflow.com/comment/81391538
has comment: http://stackoverflow.com/comment/81394773
accepted answer of: http://stackoverflow.com/q/47216716
has comment: http://stackoverflow.com/comment/81392993
has comment: http://stackoverflow.com/comment/81393882

http://stackoverflow.com/comment/85035992
comment on: http://stackoverflow.com/a/47144250
has text: I've edited the question to clarify that I am writing a functional test.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47147146
type: Question
has comment: http://stackoverflow.com/comment/81244732
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/81244798
tagged with: spectrogram
tagged with: python
tagged with: savefig
has answer: http://stackoverflow.com/a/52575818
tagged with: plot
possible better answer: http://stackoverflow.com/a/52575818
linked to: http://stackoverflow.com/q/9295026
has comment: http://stackoverflow.com/comment/81244762
linked to: http://stackoverflow.com/q/11837979
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/81244830
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81244668
linked to: http://stackoverflow.com/q/8218608
downvote count: 0
has answer: http://stackoverflow.com/a/47147362
has title: Save an image (only content, without axes or anything else) to a file using Matloptlib
accepted answer: http://stackoverflow.com/a/47147362
has body: I'd like to obtain a spectrogram out of a wav file and then save it to a png, but I need just the content of the image (not axes or anything else). I came across these questions Matplotlib plots: removing axis, legends and white spaces scipy: savefig without frames, axes, only content I've also read the Matplotlib documentation but it seems useless and so either answers to questions above are outdated or I'm doing something wrong because simple plt.savefig('out.png', bbox_inches='tight', pad_inches=0) does not do what I want to achieve. Initially I tried to follow this guide but the code crashes. Then I tried this approach, but since it's outdated I modified it a little: import matplotlib.pyplot as plt from scipy.io import wavfile import numpy as np def graph_spectrogram(wav_file): rate, data = wavfile.read(wav_file) pxx, freqs, bins, im = plt.specgram(x=data, Fs=rate, noverlap=384, NFFT=512) plt.axis('off') plt.savefig('sp_xyz.png', bbox_inches='tight', dpi=300, frameon='false') if __name__ == '__main__': # Main function graph_spectrogram('...') This is what I got: Maybe it's not visible, but there's a white border around the content (from the biggest to the smallest): left, bottom, top, right. I want the same image but just the content without anything else. How can I achieve that? I use python 3.6 and Matplotlib 2.0.2.
favorite count: 0

http://stackoverflow.com/comment/81103330
type: QuestionComment
comment on: http://stackoverflow.com/q/47076323
score: 0
has text: @VasilisG. This is what I did before and worked fine with the newline encoding. But I had problems with it when working with Turkish unfortunately. This is why I try to find a good solution to it with opening the files in binary mode. Then Turkish is fine but newlines act up :/
type: Comment

http://stackoverflow.com/comment/81322180
has text: @IgnacioVazquez-Abrams It's not my own API, if that's what you're thinking
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47169602

http://stackoverflow.com/q/47153975
tagged with: ordereddictionary
has body: I'm having second thoughts on my approach to this problem. I'm new to python. So still have gots lots to cover. https://www.testdome.com/for-developers/solve-question/11195 I'm currently stuck at this problem. I have somewhat of a temporary solution. I want to know if there is a more optimised approach to this. from collections import Counter from collections import OrderedDict class LeagueTable: def __init__(self, players): self.standings = OrderedDict([(player, Counter()) for player in players]) def record_result(self, player, score): self.standings[player]['games_played'] += 1 self.standings[player]['score'] += int(score)# print(self.standings)# print("") def player_rank(self, rank): #res = OrderedDict() x=self.standings d=self.standings def swap_list(xl,co): xl[co],xl[co+3]=xl[co+3],xl[co] xl[co+1],xl[co+4]=xl[co+4],xl[co+1] xl[co+2],xl[co+5]=xl[co+5],xl[co+2] return(xl,co) player_list=[] lc=len(x) lc1=lc lc=lc*3 for p,c in x.items(): player_list.append(p) player_list.append(c["score"]) player_list.append(c["games_played"]) for j in range(lc1): for i in range(0,lc-3,3): # print(i+4) if (player_list[i+1] &lt; player_list[i+4]): swap_list(player_list,i) elif (player_list[i+1]==player_list[i+4]): if(player_list[i+2]&gt;player_list[i+5]): swap_list(player_list,i) elif(player_list[i+2]==player_list[i+5]): pass return(player_list[(rank-1)*3]) table = LeagueTable(['Mike', 'Chris', 'Arnold']) table.record_result('Mike', 2) table.record_result('Mike', 3) table.record_result('Arnold', 5) table.record_result('Chris', 5) rk=int(input("enter rank \n")) print(table.player_rank(rk)) Any help would be appreciated
answer count: 0
has title: A better way to sort contents of OrderedDict
has comment: http://stackoverflow.com/comment/81257759
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81258952
has comment: http://stackoverflow.com/comment/81257695
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81257970
score: 0

http://stackoverflow.com/comment/81328589
comment on: http://stackoverflow.com/a/47185640
type: Comment
score: 0
type: AnswerComment
has text: @MALKAVIAN: do you know cython?

flask-sqlalchemy
tags question: http://stackoverflow.com/q/47191039
tags question: http://stackoverflow.com/q/47194222
tags question: http://stackoverflow.com/q/47066212
tags question: http://stackoverflow.com/q/47081385
tags question: http://stackoverflow.com/q/47150390
tags question: http://stackoverflow.com/q/47088637
type: Tag
tags question: http://stackoverflow.com/q/47100781
tag name: flask-sqlalchemy
tags question: http://stackoverflow.com/q/47177863
tags question: http://stackoverflow.com/q/47197139
tags question: http://stackoverflow.com/q/47123860
tags question: http://stackoverflow.com/q/47069114
tags question: http://stackoverflow.com/q/47206201
tags question: http://stackoverflow.com/q/47153242
tags question: http://stackoverflow.com/q/47180202

http://stackoverflow.com/q/47199817
has comment: http://stackoverflow.com/comment/81348175
accepted answer: http://stackoverflow.com/a/47199909
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/47199909
has body: I've installed existing Django project very 1st time and I've the problem with starting servers python manage.py runserver Here it's what I've done 1.Clone the repo, 2.Make a virtual environment 3.Pip install requirements.txt 4.Generate access token and secret key and put in secrets.sh. I've the same SECRET_KEY in settings.py and secrets.sh and I've added secrets.sh to .gitignore 5.Change settings.py as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'USER': 'name', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', } } And I cannot run python manage.py migrate results below: (tag_gen) local_user@local_user:~/Repo/tag_gen/generator$ python manage.py runserver Performing system checks... Unhandled exception in thread started by &lt;function wrapper at 0x7febe4712488&gt; Traceback (most recent call last): File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/home/local_user/Repo/tag_gen/tag_gen/local/lib/python2.7/site-packages/dja…
downvote count: 0
tagged with: django
possible better answer: http://stackoverflow.com/a/61256229
tagged with: git
favorite count: 0
linked to: http://stackoverflow.com/q/23842713
type: Question
tagged with: python
has title: Syntax error in existing Django project
has answer: http://stackoverflow.com/a/61256229

http://stackoverflow.com/a/47222201
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47217438
has body: Django Rest Framework has metadata classes. But you can augment it with another library called drf-schema-adapter. pip install drf-schema-adapter which should be 0.9.43 go to settings.py and add this 'DEFAULT_METADATA_CLASS': 'drf_auto_endpoint.metadata.AutoMetadata', to your REST_FRAMEWORK settings add in this brand new setting DRF_AUTO_METADATA_ADAPTER = 'drf_auto_endpoint.adapters.ReactJsonSchemaAdapter' in the same file It should look like this: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_METADATA_CLASS': 'drf_auto_endpoint.metadata.AutoMetadata', 'TEST_REQUEST_DEFAULT_FORMAT': 'json', 'PAGE_SIZE': 20, 'SEARCH_PARAM': 'q' } DRF_AUTO_METADATA_ADAPTER = 'drf_auto_endpoint.adapters.ReactJsonSchemaAdapter' Choosing ReactJsonSchemaAdapter is a purely personal preference. You can also stick with the SimpleMetadata from DRF itself. use something like postman to test on the same url but using OPTIONS as the method You should get back something like this: { "data": { "name": "Shape Detail", "description": "Retrieve a shape by its id.", "renders": [ "application/json" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "PUT": { "id": { "type": "integer", "required": false, "read_only": true, "label": "ID" }, "name": { "type": "string", "required": true, "read_only": false, "label": "Shape Name", "max_length": 100 }, "name_en": { "type": "string", "required": false, "read_only": false, "label": "Shape Name [en]", "max_length": 100 }, "name_zh_hans": { "type": "string", "required": false, "read_only": false, "label": "Shape Name [zh-hans]", "max_length": 100 }, "serial_number": { "type": "string", "required": false, "read_only": false, …
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47217438
score: 5
upvote count: 5

google-cloud-storage
tags question: http://stackoverflow.com/q/47126157
tags question: http://stackoverflow.com/q/47211584
tags question: http://stackoverflow.com/q/47088830
type: Tag
tags question: http://stackoverflow.com/q/47141291
tags question: http://stackoverflow.com/q/47102579
tag name: google-cloud-storage
tags question: http://stackoverflow.com/q/47180349

http://stackoverflow.com/q/47218970
has answer: http://stackoverflow.com/a/47219730
has comment: http://stackoverflow.com/comment/81387973
has answer: http://stackoverflow.com/a/47219146
has title: Error in attribute creation and reference Python classes multilevel inheritance
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/81387883
has answer: http://stackoverflow.com/a/47219490
has comment: http://stackoverflow.com/comment/81387912
type: Question
has comment: http://stackoverflow.com/comment/81388021
upvote count: 0
accepted answer: http://stackoverflow.com/a/47219146
tagged with: python
has body: I have the following program that seeks to demonstrate multilevel inheritance. Unfortunately on calling m2 and the eligible_for_reward method, I am getting the following: m2=Marks() m2.eligible_for_reward() Error: Marks has no attribute totalmarks The code is below: # Define a class as 'student' class Student: # Method def getStudent(self): self.name = input("Name: ") self.age = input("Age: ") self.gender = input("Gender: ") #The Test Class inherits from the Student Class. class Test(Student): # Method def getMarks(self): self.stuClass = input("YearGroup/Class: ") print("Enter the marks of the respective subjects") self.literature = int(input("Literature: ")) self.math = int(input("Math: ")) self.biology = int(input("Biology: ")) self.physics = int(input("Physics: ")) # Note that the Marks Class inherits from the Test Class and in doing so inherits from the Student Class class Marks(Test): # Method def display(self): print("\n\nName: ",self.name) print("Age: ",self.age) print("Gender: ",self.gender) print("Class Year Group: ",self.stuClass) self.totalmarks=self.literature+self.math+self.biology+self.physics print("Total Marks: ", self.literature + self.math + self.biology + self.physics) def eligible_for_reward(self): if self.totalmarks&gt;=90 and self.age&gt;13: print("You are eligible for the fabulous school sponsored trip to London") else: print("Sorry, you are not eligible and so are going nowhere....!") UPDATE: I also tried the following, that is definig self.totalmarks in the relevant method, but that also came up with an error:name 'totalmarks' is not defined def eligible_for_reward(self): self.totalmarks=totalmarks if self.totalmarks&gt;=90 and self.age&gt;13: print("You are eligible for the fabulous school sponsored trip to London") else: print("Sorry, you are not eligible and so are going nowhere....!") Furthmore, I also tried m2=Marks() m2.display() m2.eligible_for_reward() and the error: AttributeError: 'Marks' object has no attribute 'name'
has comment: http://stackoverflow.com/comment/81388181
tagged with: inheritance
has comment: http://stackoverflow.com/comment/81388061
downvote count: 1
tagged with: class
has comment: http://stackoverflow.com/comment/81387574
possible better answer: http://stackoverflow.com/a/47219490
has comment: http://stackoverflow.com/comment/81387835
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81387932
answer count: 3

http://stackoverflow.com/a/47077480
answers question: http://stackoverflow.com/q/47065548
score: 0
has body: Python has got many added functionalities which makes this task very simple. max gives the maximum value and index gives the index value of the maximum which can be used to find the corresponding element in backk1. backk1[ptotal.index(max(ptotal))]
type: Answer

http://stackoverflow.com/a/47126857
upvote count: 2
has comment: http://stackoverflow.com/comment/81204081
has body: Just a few things you have wrong, the rest are pretty good, explain are in the comments: All the variables in [x, y , even , odd] are useless at all, so that's why I erased them. def calc(time): i = 1 while i &lt;= time: num = int(input("Enter your number")) i+=1 # important thing here, to update the value the symbol is +=, not just + if (int(num) % 2 == 0): print("even") else: # there is no need of elif, if the number is not even, by definition, it is odd print("odd") times = int(input("How many numbers will you be putting in this calc?")) calc(times) you can try it here, and see how do correctly the job :) -> https://repl.it/Nm70/0
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47126805
type: Answer

http://stackoverflow.com/q/47165342
score: 2
tagged with: postgresql
has comment: http://stackoverflow.com/comment/81284380
upvote count: 2
answer count: 1
downvote count: 0
has body: I'm doing insert or update around 3 to 4 millions of data in postgresql using python script. Please see the code below. The requirement is insert if its new key or update the key with new value if key is already exist. But below code is making too much round trip connection to DB and its taking around 35 - 45 minutes to insert the 3 million records in DB which is very slow. How to avoid round trip connection and insert or update in a faster way? Any help would be really appreciated. Thanks for your help in advance. InputFile.txt - This file has around 3 to 4 million line itesm productKey1 printer1,printerModel1,printerPrice1,printerDesc1| productKey2 sacnner2,scannerModel2,scannerPrice2,scannerDesc2| productKey3 mobile3,mobileModel3,mobilePrice3,mobileDesc3| productKey4 tv4,tvModel4,tvPrice4,tvDescription4| productKey2 sacnner22,scannerModel22,scannerPrice22,scannerDesc22| insert.py def insertProduct(filename, conn): seen = set() cursor = conn.cursor() qi = "INSERT INTO productTable (key, value) VALUES (%s, %s);" qu = "UPDATE productTable SET value = CONCAT(value, %s) WHERE key = %s;" with open(filename) as f: for line in f: if line.strip(): key, value = line.split(' ', 1) if key not in seen: seen.add(key) cursor.execute(qi, (key, value)) else: cursor.execute(qu, (value, key)) conn.commit() conn = psycopg2.connect("dbname='productDB' user='myuser' host='localhost'") insertProduct('InputFile.txt', conn)
has comment: http://stackoverflow.com/comment/81280670
has title: How to optimize python postgresql query for 3 millions records
linked to: http://stackoverflow.com/q/8134602
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81280614
type: UnansweredQuestion
tagged with: postgresql-performance
has comment: http://stackoverflow.com/comment/81280751
has comment: http://stackoverflow.com/comment/81281579
tagged with: python
tagged with: psycopg2
has answer: http://stackoverflow.com/a/47181537

http://stackoverflow.com/q/47206201
tagged with: alembic
downvote count: 0
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
linked to: http://stackoverflow.com/q/37848815
favorite count: 0
score: 39
has answer: http://stackoverflow.com/a/65173731
type: Question
has body: Here's my Post model: class Post(Base): __tablename__ = 'posts' title = db.Column(db.String(120), nullable=False) description = db.Column(db.String(2048), nullable=False) I'd like to add Enum status to it. So, I've created a new Enum: import enum class PostStatus(enum.Enum): DRAFT='draft' APPROVE='approve' PUBLISHED='published' And added a new field to model: class Post(Base): ... status = db.Column(db.Enum(PostStatus), nullable=False, default=PostStatus.DRAFT.value, server_default=PostStatus.DRAFT.value) After doing FLASK_APP=server.py flask db migrate, a such migration was generated: def upgrade(): op.add_column('posts', sa.Column('status', sa.Enum('DRAFT', 'APPROVE', 'PUBLISHED', name='poststatus'), server_default='draft', nullable=False)) After trying to upgrade DB, I'm getting: sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) type "poststatus" does not exist LINE 1: ALTER TABLE posts ADD COLUMN status poststatus DEFAULT 'draf... ^ [SQL: "ALTER TABLE posts ADD COLUMN status poststatus DEFAULT 'draft' NOT NULL"] Why type poststatus was not created on DB-level automatically? In the similar migration it was. How to specify server_default option properly? I need both ORM-level defaults and DB-level ones, because I'm altering existing rows, so ORM defaults are not applied. Why real values in DB are 'DRAFT', 'APPROVE', 'PUBLISHED', but not draft, etc? I supposed there should be ENUM values, not names. Thank you in advance.
has answer: http://stackoverflow.com/a/53556214
has title: How to use Enum with SQLAlchemy and Alembic?
accepted answer: http://stackoverflow.com/a/55160320
tagged with: python
has answer: http://stackoverflow.com/a/55160320
possible better answer: http://stackoverflow.com/a/65173731
answer count: 4
duplicate of: http://stackoverflow.com/q/14845203
has answer: http://stackoverflow.com/a/73861502
type: AnsweredQuestion
upvote count: 39

http://stackoverflow.com/comment/81379838
type: QuestionComment
comment on: http://stackoverflow.com/q/47214992
has text: will you provide your error list?
score: 0
type: Comment

http://stackoverflow.com/comment/81360929
type: Comment
has text: By "overlap" you mean you want the blue bar be hidden behind the yellow? (Seems to not make too much sense.) In any case please provide a [mcve] (not your actual data) and clearly state how the plot should look like, what you have tried and in how far it was unsuccessful.
score: 0
comment on: http://stackoverflow.com/q/47205918
type: QuestionComment

http://stackoverflow.com/comment/81132384
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47091435
has text: I understand. The answer is to be found in the source code: ```symbol(y) => 'y'```. The content of the object is not relevant.
type: Comment

http://stackoverflow.com/q/47115600
has body: I'm trying to color code a simple categorical heatmap using python's Bokeh library. For example, given the following table, I would want to replace each 'A' with a red square and each 'B' with a blue square: AAAABAAAAB BBBAAAABBB To start, I thought the following would produce 2 rows of 10 squares of the same color. but I just get a blank plot. I must be missing a core concept of how to create categorical heatmaps in bokeh. To start, I was trying to mimic an example on the bokeh site: https://docs.bokeh.org/en/latest/docs/gallery/categorical.html Does anyone see what I'm missing? (This is a simple example. I have many rows with hundreds of columns that I need to color by category.) from bokeh.plotting import figure, show, output_file hm = figure() colors = ['#2765a3' for x in range(20)] x_input = [x for x in range(10)] y_input = ['a', 'b'] hm.rect(x_input, y_input, width = 1, height = 1, color = colors) output_file('test.html) show(hm)
answer count: 1
tagged with: rect
has title: Python 3 Bokeh Heatmap Rect simple example not showing anything in plot
has comment: http://stackoverflow.com/comment/81185221
type: AnsweredQuestion
tagged with: python
tagged with: bokeh
has answer: http://stackoverflow.com/a/50750769
favorite count: 0
tagged with: heatmap
type: Question
upvote count: 2
score: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/50750769

http://stackoverflow.com/q/47146942
tagged with: python-2.7
tagged with: python-jira
has answer: http://stackoverflow.com/a/55746347
upvote count: 5
tagged with: jira
type: Question
score: 5
type: UnansweredQuestion
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/81244252
tagged with: python
has comment: http://stackoverflow.com/comment/81253708
favorite count: 0
has title: Python JIRA client returning 401 error
has body: I tried using Python JIRA client with following code: #!/usr/bin/env python # -*- coding: utf-8 -*- from jira.client import JIRA jira = JIRA(options={'server': 'http://server.atlassian.net'}, basic_auth=('email@example.com', 'pass')) projects = jira.projects() for v in projects: print v And I got following error: Got recoverable error from GET https://server.atlassian.net/rest/api/2/serverInfo, will retry [1/3] in 17.5832343958s. Err: 401 Unauthorized Using python 2.7 (virtualenv), installed using pip install jira. I tried using my username and email and am certain that my login credentials are correct (I can login using my browser with same credentials without a problem). Any tips what am I doing wrong?

http://stackoverflow.com/comment/81444971
type: QuestionComment
comment on: http://stackoverflow.com/q/47219769
score: 0
has text: Thanks. Solved conventionally by manual installation/update of "comtypes" modules.
type: Comment

image-processing
tags question: http://stackoverflow.com/q/47180020
type: Tag
tags question: http://stackoverflow.com/q/47172219
tags question: http://stackoverflow.com/q/47172770
tags question: http://stackoverflow.com/q/47176979
tags question: http://stackoverflow.com/q/47084179
tags question: http://stackoverflow.com/q/47113465
tags question: http://stackoverflow.com/q/47117179
tags question: http://stackoverflow.com/q/47155631
tags question: http://stackoverflow.com/q/47208640
tag name: image-processing
tags question: http://stackoverflow.com/q/47087953
tags question: http://stackoverflow.com/q/47186313
tags question: http://stackoverflow.com/q/47190372
tags question: http://stackoverflow.com/q/47206699
tags question: http://stackoverflow.com/q/47069058

http://stackoverflow.com/q/47201417
has title: How to configure Python in a GPU cluster?
has answer: http://stackoverflow.com/a/47222728
score: 0
answer count: 2
tagged with: pip
has body: I have a GPU cluster with one storage-node and several computing nodes each has 8 GPU. I am configuring the cluster. One of the task is to configure the python, what we need is several versions of Python and some python packages, and for some packages we may require several versions of it, such as different version of tensorflow. So the question is how to configure the python and the packages so that it' convenient to use different version of the package I want to use. I have installed both python2.7 and python3.6 in each computing node and in the storage node. But I think it is a good way if one has a huge amount of computing node to configure. One of the solution is to install python in the share directory of the cluster instead of the default /usr/local path. Anyone has a better way to do this? What I use now is OpenPBS(Torque) and I am new to HPC. Thanks a lot.
has answer: http://stackoverflow.com/a/47715420
tagged with: tensorflow
type: Question
type: UnansweredQuestion
tagged with: hpc
tagged with: python

http://stackoverflow.com/comment/81391634
comment on: http://stackoverflow.com/q/47220993
has text: @cᴏʟᴅsᴘᴇᴇᴅ From what I understand, OP wants to loop through the sorted index array, access the value array's matching values and print them.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81191868
type: Comment
type: QuestionComment
has text: You can use Using `np.where` and a simple indexing. You'll find a lot of similar question in SO if you search thoroughly. (`np.where(a==-1)` and `a[a != -1]`)
comment on: http://stackoverflow.com/q/47121045
score: 1

themes
type: Tag
tag name: themes
tags question: http://stackoverflow.com/q/47169539

http://stackoverflow.com/a/47094610
answers question: http://stackoverflow.com/q/47094551
has body: Use drop_duplicates with specify columns names, parameter keep='last' is for last duplicated row: df2 = df2.drop_duplicates(["Invoice","Value"]) #same as #df2 = df2.drop_duplicates(["Invoice","Value"], keep='first') df3=pd.merge(df1,df2, on=["Invoice","Value"]) print (df3) Invoice Value TestData 0 2 25 A 1 5 15 C df2 = df2.drop_duplicates(["Invoice","Value"], keep='last') df3=pd.merge(df1,df2, on=["Invoice","Value"]) print (df3) Invoice Value TestData 0 2 25 D 1 5 15 C EDIT: If need groupby by all rows, is necessary add new column for uniqueness: df1['g'] = df1.groupby(['Invoice','Value']).cumcount() df2['g'] = df2.groupby(['Invoice','Value']).cumcount() print (df1) Invoice Value g 0 1 10 0 1 2 25 0 2 3 40 0 3 4 10 0 4 5 15 0 print (df2) Invoice TestData Value g 0 2 A 25 0 1 3 B 11 0 2 5 C 15 0 3 2 D 25 1 df3=pd.merge(df1,df2, on=["Invoice","Value", "g"]).drop('g', axis=1) print (df3) Invoice Value TestData 0 2 25 A 1 5 15 C
has comment: http://stackoverflow.com/comment/81139672
has comment: http://stackoverflow.com/comment/81140783
score: 10
has comment: http://stackoverflow.com/comment/134615338
upvote count: 10
has comment: http://stackoverflow.com/comment/81140894
type: Answer
accepted answer of: http://stackoverflow.com/q/47094551
downvote count: 0
has comment: http://stackoverflow.com/comment/81139496
type: AcceptedAnswer

http://stackoverflow.com/comment/81132829
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47076218
has text: If you find it hard to test that might be a signal that something is wrong in the design. But without more details is not possible to go beyond that.
score: 0

http://stackoverflow.com/a/47205176
has body: In python, functions are first class objects by themselves, that can be passed as arguments. You can define the base function outside. def my_f(x): return x**2+3 def my_functor(f, x, iterations): for i in xrange(iterations): x = f(x) return x print my_functor(my_f, -1, 20) Perhaps you can find useful a more implicit way of defining the same functor by using decorators. def iterated(fn): """ A decorator to make a function iterate over its outputs. """ def iterated_func(*args, **kwargs): x = args[0] iterations = args[1] for i in xrange(iterations): x = fn(x) return x return iterated_func @iterated def my_g(x): return x**2+3 In this case, my_g(3,1)==my_f(3) will evaluate to True. That is, by adding the decorator @iterated over a function you defined, you can change its behavior to get the number of iterations as an argument too.
accepted answer of: http://stackoverflow.com/q/47204928
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47204928
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81366711

http://stackoverflow.com/comment/81342115
has text: You should simplify this: you are trying to create a *metaclass* using `type`. This complicates things, and I'll admit, has my head scratching a bit.
type: Comment
comment on: http://stackoverflow.com/q/47196329
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81305367
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47177986
type: AnswerComment
has text: BFS does, in a maze with uniform edge weights as I assume is the case in this problem, find the shortest path.

http://stackoverflow.com/comment/81192893
comment on: http://stackoverflow.com/q/47121586
score: 0
type: QuestionComment
has text: Please, improve the readability of your post. First of all, if you have an error with a specific instruction, is not necessary to post the whole code. Secondly, if you have an error message, it is very relevant to include it in the post as well. Lastly, do not post your code and hope for someone to come and solve your problem. Instead, introduce your problematic and explain what you tried so far, and maybe which hypothesis you have
type: Comment

http://stackoverflow.com/comment/81338366
has text: You are getting that error because you are using the `download_file("bin_files/scaler.pkl", data)` API. It expects the 2nd parameter to be a string. see the [doc link](http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.download_file) .Instead use the `download_fileobj("bin_files/scaler.pkl", data)` API.
type: Comment
comment on: http://stackoverflow.com/a/47177196
score: 0
type: AnswerComment

flask-restful
tags question: http://stackoverflow.com/q/47066328
tags question: http://stackoverflow.com/q/47150546
type: Tag
tag name: flask-restful
tags question: http://stackoverflow.com/q/47099682

http://stackoverflow.com/comment/81423744
has text: It worked thanks, and windows worked without a specific shebang
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47223516
type: Comment

http://stackoverflow.com/q/47142467
answer count: 2
has title: ''.join(random.choice(chars) for _ in range(size))
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/81235703
favorite count: 0
has comment: http://stackoverflow.com/comment/81234987
type: AnsweredQuestion
has body: I have the following generator: import random import string def random_string_generator(size = 10, chars = string.ascii_lowercase + string.digits): return "".join(random.choice(chars) for _ in range(size)) When I use interactive mode to inspect the generator, I get the following: In [30]: random_string_generator() Out[30]: '6v0vhljxac' However, I do not understand how it works. From what I've found so far: _ has no special meaning in the grammar of Python _ isn't in the chars list The generator works like (expression(x) for x in iterator) I have tried to further decompose the code in interactive mode and this is what I've found: In [38]: chars=string.ascii_lowercase + string.digits In [39]: size=10 In [40]: (random.choice(chars) for _ in range(size)) Out[40]: &lt;generator object &lt;genexpr&gt; at 0x10bc6b258&gt; In [41]: list( (random.choice(chars) for _ in range(size)) ...: ) Out[41]: ['6', 'v', '3', 'd', 'm', 'c', 'h', '1', 'v', 'n'] So my question is how does the random.choice(chars) portion of the generator communicate with the iterative part for _ in range(size) when they have no apparent connection to each other?
has answer: http://stackoverflow.com/a/47142605
accepted answer: http://stackoverflow.com/a/47142605
linked to: http://stackoverflow.com/q/2257441
tagged with: python
possible better answer: http://stackoverflow.com/a/47142624
has comment: http://stackoverflow.com/comment/81234956
tagged with: generator
type: Question
has answer: http://stackoverflow.com/a/47142624

http://stackoverflow.com/q/47186264
has comment: http://stackoverflow.com/comment/81321999
has title: Do functions that convert data into lists use more memory?
has comment: http://stackoverflow.com/comment/81321967
tagged with: data-structures
has body: *I'm aware datetime would serve as an effective way to resolve this problem, but I'm still a beginner and would like to understand why this code isn't displaying the desired output The following code produced an error message stating that the program used 13 CPU seconds so it was ended. I don't understand why this code would take up so much memory, originally the functions below didn't convert their inputs into a list, but I did that so we could alter each parameter until the condition in IsBefore returned False, which would end the while loop and return an updated "number_of_days" for the total iterations of the nextDay function on start_date. Edit: I converted the items into lists because I wasn't sure if year1, month1, day1 = nextDay(year1,month1,day1) Would properly update those values def nextDay(year, month, day): """Simple version: assume every month has 30 days""" date=[year,month,day] if date[2] &lt; 30: return [year, month, day + 1] else: if date[1] == 12: return [year + 1, 1, 1] else: return [year, month + 1, 1] def IsBefore(year1, month1, day1, year2, month2, day2): Before=[year1,month1,day1] Current=[year2,month2,day2] if (Before[0]&gt;Current[0]) or (Before[0]==Current[0] and Before[1]&gt;Current[1]) or (Before[0]==Current[0] and Before[1]==Current[1] and Before[2]&gt;Current[2]): return False else: return True def daysBetweenDates(year1, month1, day1, year2, month2, day2): number_of_days=0 start_date=[year1,month1,day1] while IsBefore(year1, month1, day1, year2, month2, day2)==True: start_date=nextDay(year1,month1,day1) number_of_days+=1 return number_of_days def test(): test_cases = [((2012,9,30,2012,10,30),30), ((2012,1,1,2013,1,1),360), ((2012,9,1,2012,9,4),3)] for (args, answer) in test_cases: result = daysBetweenDates(*args) if result != answer: print "Test with data:", args, "failed" else: print "Test case passed!" test()
accepted answer: http://stackoverflow.com/a/47186937
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47186937
has comment: http://stackoverflow.com/comment/81322707
answer count: 1
tagged with: python
tagged with: loops
tagged with: memory
has comment: http://stackoverflow.com/comment/81322228
type: Question

http://stackoverflow.com/q/47104440
has answer: http://stackoverflow.com/a/47104584
accepted answer: http://stackoverflow.com/a/47104584
tagged with: python
linked to: http://stackoverflow.com/q/744373
has title: Python 3: How do i change variables in different scripts?
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has body: So, kind of new to python, as I kinda started learning it a few months ago. I'm currently trying to make my own game (not expecting it to be super good, but I want it to work decently) The game is basically going around a dungeon, fighting monsters, leveling up, doing puzzles, and then fighting the final boss. Basically, your average RPG game. I am making it all text though. Currently stuck on a bit of code for my levelup script and my stats script. I have a variable in stats called "constitution", and whenever i level up (if exp >= expmax) i add 3 to the value of constitution. (starts out at 10) import LevelUP constitution = 10 that one is my code in the Stats script, and the one is the code in the LevelUP script. import Stats level = 1 expMax = 100 exp = 100 if exp &gt;= expMax: level=level+1 exp = 0 expMax = expMax+expMax*0.5 Stats.constitution = Stats.constitution+3 Stats.strength = Stats.strength+4 Stats.dexterity = Stats.dexterity+4 Stats.intelligence = Stats.intelligence+3 Stats.wisdom = Stats.wisdom+3 Stats.charisma = Stats.charisma+2 Stats.luck = Stats.luck+2 This is the error that comes up Traceback (most recent call last): File "main.py", line 3, in &lt;module&gt; import Stats File "/home/runner/Stats.py", line 1, in &lt;module&gt; import LevelUP File "/home/runner/LevelUP.py", line 9, in &lt;module&gt; Stats.constitution = Stats.constitution+3 AttributeError: module 'Stats' has no attribute 'constitution' exited with non-zero status Kind of new to the site, but I have looked around for something like this and all i could find was using print() in different scripts.
favorite count: 0
type: Question

http://stackoverflow.com/a/47102413
has body: The problem is that, in the for loop, you have already reached the EOF (end of file). That means that, once you start the lambda function, there is nothing left to read in the file. You could find a way to read the data in within that for loop, or if you want to do it (somewhat) inefficiently, you can do this: from itertools import dropwhile attributes = [] with open('stuff.txt', 'r') as f: for l in f.readlines(): ##1 items = l.split(' ') ##2 if items[0] == '@attribute': ##3 attributes.append(items[1]) f.seek(0) ##4 data = dropwhile(lambda _line: "@data" not in _line, f) ##5 next(data,"") ##6 for line in data: ##7 print(line.strip()) ##8 print(attributes)
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47102193
score: 1
type: Answer

http://stackoverflow.com/comment/81327903
type: Comment
type: QuestionComment
has text: How the data will pop up? Entered manually or automatically based on logs?
score: 0
comment on: http://stackoverflow.com/q/47188197

http://stackoverflow.com/comment/81326464
has text: `len(string) return INT`, cannot be concatenated with `string`
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47188590

http://stackoverflow.com/a/47140880
has body: I got the answer from someone on micropython forum: You cannot. It is an TODO item. If you want to put it into flash memory, you can embed it as frozen source code in some ports. Just put these files in a subdirectory called scripts, like esp8266/scripts or stm32/scripts. But it will still be compiled at import time and consume RAM. Typically, that should not hurt, when this variant of coding is used only for small, time-critical sections of the code.
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/47127671
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47127671
type: Answer
downvote count: 0

http://stackoverflow.com/comment/81190079
type: Comment
has text: What do you mean fails? Time is too big?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47120159

http://stackoverflow.com/q/47169075
has comment: http://stackoverflow.com/comment/81288416
downvote count: 1
possible better answer: http://stackoverflow.com/a/47169094
favorite count: 0
has comment: http://stackoverflow.com/comment/81288085
accepted answer: http://stackoverflow.com/a/47169176
type: AnsweredQuestion
has body: So basically I'm trying to loop through my sub-directories and files (images), such that each sub-directory contains two images, one that starts with the word first, and one that starts with the word second. What I would like to do is that in each sub-directory I would like to assign the image that starts with first to the variable img1, and that which starts with second to img2. Here's what I got: path = '/my_path/' for root, dirs, files in os.walk(path): for file in files: if file.startswith('first'): img1 = numpy.asarray(Image.open(root + '/' + file)) if file.startswith('second'): img2 = numpy.asarray(Image.open(root + '/' + file)) print 'Image 1 is:' print img1 print 'Image 2 is:' print img2 When I run the above code however, I get the following: Image 1 is: Traceback (most recent call last): File "test.py", line 17, in &lt;module&gt; print img1 NameError: name 'img1' is not defined What am I doing wrong? Thanks.
has title: Variable name is not defined
has answer: http://stackoverflow.com/a/47169176
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/81288349
tagged with: python
score: -1
tagged with: image
type: Question
has comment: http://stackoverflow.com/comment/81289211
tagged with: numpy
has comment: http://stackoverflow.com/comment/81288431
has answer: http://stackoverflow.com/a/47169094
answer count: 2
upvote count: 0

http://stackoverflow.com/a/47199095
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81347064
type: Answer
answers question: http://stackoverflow.com/q/47198876
has comment: http://stackoverflow.com/comment/81346930
has comment: http://stackoverflow.com/comment/81347122
has body: Why don't you build a simple parser for that construct? I guess you're planning to process some kind of input from external data sources anyway as otherwise your question wouldn't make much sense: It's more easy to resolve a few specifications like that manually instead of writing special code to handle it. This approach would follow these steps: prepare an empty list for output split the input string at "," for each item check if a "-" is present if no => convert the item to an int and put it into the output list if yes => split the string at "-" add a range of int values to the output list return the output list I guess this is the easiest way. Should be very simple to code that yourself using the split method provided at strings to split strings and the int(...) function to convert strings to int. Building such a simple parser will have a big advantage anyway: You can at the same time verify that the input you receive is perfectly valid. You even can check if the values provided are in increasing order. That seems to be a basic condition if I look at the example(s) you provided.
has comment: http://stackoverflow.com/comment/81347090
score: 1

http://stackoverflow.com/a/47100785
type: Answer
has body: Your program is crashing on the line From: stephen.marquard@uct.ac.za that appears later (line 38), not on the first line in the file. Check to make sure sline has enough elements before you try to grab the day field from it.
score: 2
answers question: http://stackoverflow.com/q/47100524
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/65624165
upvote count: 22
answers question: http://stackoverflow.com/q/47093561
type: Answer
score: 22
has body: A few things to expand on other answers: If you use os.walk(topdown=False), it goes in reverse order, so you encounter the child directories before the parents. Then if you track which directories you've deleted, you can delete parent directories recursively. import os def delete_empty_folders(root): deleted = set() for current_dir, subdirs, files in os.walk(root, topdown=False): still_has_subdirs = False for subdir in subdirs: if os.path.join(current_dir, subdir) not in deleted: still_has_subdirs = True break if not any(files) and not still_has_subdirs: os.rmdir(current_dir) deleted.add(current_dir) return deleted
downvote count: 0
has comment: http://stackoverflow.com/comment/131352535

http://stackoverflow.com/a/47079417
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47072224
score: 1
has body: Make the database do the work. You don't need annotations either as you want the objects, not the values or manipulated values. To get a set of all scores for a candidate (not split by model_used) you would do: queryset = candidate.property_set.filter(candidate=candidate).order_by('-score)[:2] jobs_serializer = MatchingJobsSerializer(queryset, many=True) jobs = jobs_serializer.data What you're proposing isn't particularly well suited in the Django ORM, annoyingly - I think you may need to make separate queries for each model_used. A nicer solution (untested for this example) is to hook Q queries together, as per this answer. Example is there is tags, but I think holds - #lets get a distinct list of the models_used - all_models_used = PredictedScore.objects.values('models_used').distinct() q_objects = Q() # Create an empty Q object to start with for m in all_models_used: q_objects |= Q(model_used=m)[:3] # 'or' the Q objects together queryset = PredictedScore.objects.filter(q_objects)
type: Answer
has comment: http://stackoverflow.com/comment/81300037
answers question: http://stackoverflow.com/q/47072224
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47179547
score: 0
has body: From the (Java) documentation Find all elements within the current context using the given mechanism. When using xpath be aware that webdriver follows standard conventions: a search prefixed with "//" will search the entire document, not just the children of this current node. Use ".//" to limit your search to the children of this WebElement. This method is affected by the 'implicit wait' times in force at the time of execution. When implicitly waiting, this method will return as soon as there are more than 0 items in the found collection, or will return an empty list if the timeout is reached. Specified by: findElements in interface SearchContext Parameters: by - The locating mechanism to use Returns: A list of all WebElements, or an empty list if nothing matches. So, it is correct that you have a list of webelements. For example if your html is something like this: Month Savings January $100 February $80 $100 And you want to iterate on all the td for each tr: trList= driver.find_elements(By.TAG_NAME, "tr") print("len trList: " + str(len(trList))) i=0 for tr in trList: tdList= tr.find_elements(By.TAG_NAME, "td") print("len tdList: " + str(len(tdList))) print ("value: " + tr.text) print ("-----------------"+str(i)+"------------") i=i+1 The output will be: len trList: 3 ----------------- len tdList: 0 value: Month Savings -----------------0------------ len tdList: 2 value: January $100 -----------------1------------ len tdList: 3 value: February $80 $100 -----------------2------------
type: Answer
answers question: http://stackoverflow.com/q/47178684

while-loop
tags question: http://stackoverflow.com/q/47189414
tags question: http://stackoverflow.com/q/47144580
tags question: http://stackoverflow.com/q/47066690
tags question: http://stackoverflow.com/q/47202331
type: Tag
tags question: http://stackoverflow.com/q/47086954
tags question: http://stackoverflow.com/q/47205195
tags question: http://stackoverflow.com/q/47163008
tags question: http://stackoverflow.com/q/47158741
tags question: http://stackoverflow.com/q/47148262
tags question: http://stackoverflow.com/q/47110352
tags question: http://stackoverflow.com/q/47172555
tags question: http://stackoverflow.com/q/47084759
tags question: http://stackoverflow.com/q/47203951
tags question: http://stackoverflow.com/q/47139930
tags question: http://stackoverflow.com/q/47181628
tags question: http://stackoverflow.com/q/47126805
tags question: http://stackoverflow.com/q/47215004
tags question: http://stackoverflow.com/q/47104898
tags question: http://stackoverflow.com/q/47163992
tags question: http://stackoverflow.com/q/47144456
tag name: while-loop
tags question: http://stackoverflow.com/q/47191296
tags question: http://stackoverflow.com/q/47164494

http://stackoverflow.com/comment/81122633
comment on: http://stackoverflow.com/q/47086508
score: 1
has text: That code is wrong. The `\b`s mean something entirely different from what the author wanted them to mean, because the author forgot to use the `r` prefix for a raw string literal.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81355355
comment on: http://stackoverflow.com/q/47203240
type: QuestionComment
has text: Instructions unclear... Neither `aa` nor `sequence` are defined.
type: Comment
score: 1

python-requests
tags question: http://stackoverflow.com/q/47086772
tags question: http://stackoverflow.com/q/47081045
tags question: http://stackoverflow.com/q/47092167
tags question: http://stackoverflow.com/q/47125932
tags question: http://stackoverflow.com/q/47102496
tags question: http://stackoverflow.com/q/47147512
tags question: http://stackoverflow.com/q/47202790
type: Tag
tags question: http://stackoverflow.com/q/47144665
tags question: http://stackoverflow.com/q/47093405
tags question: http://stackoverflow.com/q/47129399
tags question: http://stackoverflow.com/q/47215144
tags question: http://stackoverflow.com/q/47195778
tags question: http://stackoverflow.com/q/47188244
tags question: http://stackoverflow.com/q/47066666
tags question: http://stackoverflow.com/q/47142848
tags question: http://stackoverflow.com/q/47215367
tags question: http://stackoverflow.com/q/47142290
tags question: http://stackoverflow.com/q/47074691
tags question: http://stackoverflow.com/q/47076402
tags question: http://stackoverflow.com/q/47074993
tags question: http://stackoverflow.com/q/47108295
tags question: http://stackoverflow.com/q/47166597
tags question: http://stackoverflow.com/q/47193745
tags question: http://stackoverflow.com/q/47086615
tag name: python-requests
tags question: http://stackoverflow.com/q/47112122
tags question: http://stackoverflow.com/q/47178618
tags question: http://stackoverflow.com/q/47103183
tags question: http://stackoverflow.com/q/47116246
tags question: http://stackoverflow.com/q/47171154
tags question: http://stackoverflow.com/q/47073922
tags question: http://stackoverflow.com/q/47075723
tags question: http://stackoverflow.com/q/47065193
tags question: http://stackoverflow.com/q/47215161
tags question: http://stackoverflow.com/q/47215704
tags question: http://stackoverflow.com/q/47215168
tags question: http://stackoverflow.com/q/47146212
tags question: http://stackoverflow.com/q/47107106
tags question: http://stackoverflow.com/q/47071771
tags question: http://stackoverflow.com/q/47127918
tags question: http://stackoverflow.com/q/47196100
tags question: http://stackoverflow.com/q/47142340
tags question: http://stackoverflow.com/q/47163065
tags question: http://stackoverflow.com/q/47204301
tags question: http://stackoverflow.com/q/47113376
tags question: http://stackoverflow.com/q/47121572
tags question: http://stackoverflow.com/q/47162039
tags question: http://stackoverflow.com/q/47145629
tags question: http://stackoverflow.com/q/47144606
tags question: http://stackoverflow.com/q/47219360
tags question: http://stackoverflow.com/q/47096859

http://stackoverflow.com/q/47163599
type: Question
has comment: http://stackoverflow.com/comment/81285743
has comment: http://stackoverflow.com/comment/81276860
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/23667086
tagged with: javascript
tagged with: python
has title: CSV average from javascript
has comment: http://stackoverflow.com/comment/81276990
score: 0
answer count: 0
has body: I have a python script that is meant to read and write a csv locally. It also counts an average value of the number of lines. Now I need to translate it in JS native. But I don not even succeed to display it in an array. The array stays empty and I don't have any clue why. The CSV I use look like: outbound;API1;Restitution;1.0 outbound;API1;Restitution;1.0 outbound;API1;Operations;1.0 outbound;API2;Operations;2.0 outbound;API2;Operations;2.0 outbound;API3;Service;1.0 And when I translate it with my python script I obtain something like : API1,0.50 API2,0.33333 API3,0.16666 The python script I want to translate: import csv from glob import glob myDict = {} filename = glob('*.csv')[0] #take any .csv file row_number = 0 with open(filename, 'rU') as f: #arg 'r' for reading and 'U' for Universal, can read .csv without quotes. reader = csv.reader(f, delimiter=';') for row in reader: row_number +=1 if row[1] in myDict: myDict[row[1]] += 1 else: myDict[row[1]] = 1 data = open("output.csv", "w") w = csv.writer(data) for word in myDict: data = word, float(myDict[word])/row_number*100 w.writerow(data) my JS function : var a_api = new Array(); $.get('/data/dataTest2.csv', function(data) { let rows = data.split("\n"); rows.forEach( function getvalues(thisRow) { let columns = thisRow.split(";"); for (var i=0;i&lt;a_api.length;i++){ if(columns[1]==a_api[i]){ a_api[i][1] +=1; } else { a_api[i][0]=columns[1]; a_api[i][1]=1; } } }) }); console.log(a_api);
tagged with: http://stackoverflow.com/tag/csv

aws-cloudformation
tag name: aws-cloudformation
type: Tag
tags question: http://stackoverflow.com/q/47208770
tags question: http://stackoverflow.com/q/47077446

http://stackoverflow.com/comment/81222456
type: Comment
type: QuestionComment
has text: You should always provide a [mcve] of the issue. Looking at the code you should indeed get as many lines as you have rows in `df_year`, but since we do not have a [mcve], we cannot help you.
score: 0
comment on: http://stackoverflow.com/q/47136578

http://stackoverflow.com/q/47149662
tagged with: class
score: 0
tagged with: pycharm
answer count: 0
linked to: http://stackoverflow.com/q/136097
tagged with: methods
has comment: http://stackoverflow.com/comment/81249158
has comment: http://stackoverflow.com/comment/81249192
type: Question
tagged with: static
linked to: http://stackoverflow.com/q/735975
has comment: http://stackoverflow.com/comment/81249184
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81249170
has title: what does it means that method should be static?
tagged with: python
has body: I am a new beginner in computer programming and English is not my first language. When I use Class in python on IDE Pycharm, and it says that method which may safely made static. I don't understand this. Could you tell me what does that mean and how to make the method static? Thank you very much This is my code: class Ga: def __init__(self, ha): self.ha = ha def ar(self): return ade.ha The Python inspection occurs in the 5th line under the 'ar', which is: def ar(self): (I only have 9 reputation so that I can't post any pictures.)
duplicate of: http://stackoverflow.com/q/735975

http://stackoverflow.com/comment/81304821
type: Comment
type: QuestionComment
has text: @Siva /usr/local/bin/python
score: 0
comment on: http://stackoverflow.com/q/47177256

http://stackoverflow.com/comment/81330338
comment on: http://stackoverflow.com/a/47189850
type: Comment
score: 0
type: AnswerComment
has text: I fixed it in my answer now, so please copy / paste the code again.

http://stackoverflow.com/comment/81339780
has text: I also felt that something was off with this library but it's really easy. Do you think this works in a pure python environment or do I need to install any php dependencies ? I would like to why being 'PHP port' is an issue here. I'm in the early stage of project, so your views on it will really help.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47195075

http://stackoverflow.com/a/47100594
has body: The error happens in casting the non-number input to int p = int(input("Rock: 0; Paper: 1; scissor: 2:")) which can be handled with try-catch. I also feel strange to use recursion in choosing() function. I would do the function as def choosing(): while True: try: p = int(input("Rock: 0; Paper: 1; scissor: 2:")) if p &lt; 0 or p &gt; 2: print("\nPlease enter valid value") else: return p except ValueError: print("\nPlease enter valid value")
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47100024

http://stackoverflow.com/comment/81161484
has text: @RNar not sure whether directly editing something in `lib` is a good idea. I am personally using an environment, so it might work, but for those using system-wide python this might be an issue. Moreover, these changes are still hard to sync between multiple environments.
score: 0
comment on: http://stackoverflow.com/q/47105276
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81151252
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47100524
has text: It looks like you have a line consisting solely of `From: stephen.marquard@uct.ac.za`. When split, the resulting list contains two elements, so the valid indices are 0 and 1. You can't use index 2 on a list with only two elements.
type: Comment

http://stackoverflow.com/comment/81384949
comment on: http://stackoverflow.com/q/47216928
score: 0
has text: @Blurp Yes, I do like this, I means, I want to the serializers order as same as the models order in .py files.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47105311
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81161575
upvote count: 0
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47112014
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47112014
type: AnsweredQuestion
has title: I need to be able to parse an output from the pyowm library
has body: I have tried to use the pyowm library to get the current temperature (https://github.com/csparpa/pyowm). However, when i call for the temperature in celsius it gives me an output like this : {'temp_max': 10.5, 'temp': 9.7, 'temp_min': 9.0} I need the temp data field but cannot figure out how to get it Thanks to everyone who helps
score: -1

http://stackoverflow.com/comment/81497342
has text: Anyway, looks like the author forgot about his question)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47141356
score: 0

http://stackoverflow.com/comment/91468805
type: AnswerComment
comment on: http://stackoverflow.com/a/51282062
type: Comment
has text: @oens Yes, I create a new model dir every time I test it. I don't know if it's somehow relevant, but I create my estimator from a Keras model like this: `estimator = tf.keras.estimator.model_to_estimator(keras_model=my_model, model_dir='{0}/{1}/model_{2}'.format(def_modelpath, modeldir, my_model.name))`
score: 0

http://stackoverflow.com/comment/81235747
type: QuestionComment
score: 2
has text: NumPy plus mmap seems like it would be the fastest.
comment on: http://stackoverflow.com/q/47142665
type: Comment

http://stackoverflow.com/comment/81242720
has text: You could, but it might just keep the imports more organized if you're only interacting with the `flask_login` package in the codebase. I'm not sure what the convention is in this case, but from what I gather you're relying on `flask_login`, which relies on `flask-security`. If `flask_login` changed the implementation and defined their own version of `current_user`, you'd have to update your code. Of course, if you're already directly working with `flask-security`, you should import it from `flask-security`.
comment on: http://stackoverflow.com/a/47145126
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/81327829
comment on: http://stackoverflow.com/q/47189101
score: 0
type: Comment
has text: See about [using the connection as a context manager](https://docs.python.org/2/library/sqlite3.html#using-the-connection-as-a-context-manager)
type: QuestionComment

http://stackoverflow.com/a/47075265
answers question: http://stackoverflow.com/q/47074972
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: I don't get the exception you mention, but are you sure your exit condition is correct? Wouldn't "while not (L[a]==L[b]=='P'):" be more correct if you want to quit when you have two 'P' after each other? Or perhaps even "while not (L[a]=='P' and L[b]=='P'):" to make it more readable since two "==" in the same statement can easily be misunderstood. Here's a shorter implementation by the way, there's really no need to keep track of indices: def experience(): L = [rd.choice(['P', 'F'])] while True: L.append(rd.choice(['P', 'F'])) if L[-1] == L[-2] == 'P': return L
type: Answer
accepted answer of: http://stackoverflow.com/q/47074972

http://stackoverflow.com/a/47136703
score: 1
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47136626
has body: Everything in Python is a reference. List indices are just references, just like names (variables). So a_list[2] is a reference to a list object, just like a_list[0] is a reference to an integer object. You created a shallow copy of a_list, meaning that all 3 references were copied to a new list object. Ergo, b_list[2] references the same object as a_list[2], another list object. modifying that list object via a_list[2] or b_list[2] will make the change visible via either. If you need to have referenced objects copied too, create a deep copy. You could use copy.deepcopy() to recursively copy everything, or use a list comprehension to create shallow copies of directly nested lists only.

http://stackoverflow.com/a/47074217
type: Answer
has body: This is one way to get your required output: import functools def gcd(a,b): def factArr(x): list = [] i=2 while i &lt;= x: if (x % i) == 0: list.append(i) x = x/i i = 2 else: i = i+1 return list aArr = factArr(a); bArr = factArr(b); print("aArr",aArr,"bArr",bArr) cArr = [] for v in aArr: if v in bArr: cArr.append(v) bArr.remove(v) print("cArr",cArr) return functools.reduce(lambda x, y: x*y, cArr) gcd(60,24)`
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47073426

http://stackoverflow.com/q/47153250
tagged with: pyqt
answer count: 10
has answer: http://stackoverflow.com/a/47172781
tagged with: pyqt5
has answer: http://stackoverflow.com/a/51227002
favorite count: 0
has answer: http://stackoverflow.com/a/69767961
type: Question
has answer: http://stackoverflow.com/a/64618975
has answer: http://stackoverflow.com/a/70503976
tagged with: pyuic
upvote count: 5
has answer: http://stackoverflow.com/a/72745616
score: 5
has answer: http://stackoverflow.com/a/77389508
possible better answer: http://stackoverflow.com/a/62862703
has body: I am trying to convert ui file created by QTDesigner to py file. but i get the error: pyuic5 is not recognized as an internal or external command. I use anaconda 3, and tried all suggestions here: C:/Program is not recognized ...related to pyuic5. and i have seen here: 'Pyuic4' is not recognized as an internal external command.
linked to: http://stackoverflow.com/q/40446572
tagged with: pyqt4
has answer: http://stackoverflow.com/a/62862703
accepted answer: http://stackoverflow.com/a/47172781
tagged with: python
linked to: http://stackoverflow.com/q/25883365
has answer: http://stackoverflow.com/a/71944142
has title: 'pyuic5' is not recognized as an internal or external command
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/76068541

http://stackoverflow.com/q/47110354
has body: I got two files 1) paragaph.txt and list.txt. I want a program to run through list.txt line by line and match it against phrases in paragraph.txt, if matches capitalize found matches in paragraph.txt. Paragraph.txt On the Insert tab, the galleries include items that are designed to coordinate with the overall look of your document. You can use these galleries to insert tables, headers, footers, lists, cover pages, and other document building blocks. When you create pictures, charts, or diagrams, they also coordinate with your current document look. . list.txt - List content is listed below:(but there are no bullet point in list.txt file, just phrases one below the another) Pictures, Charts, or Diagrams Building Blocks Expected output On the Insert tab, the galleries include items that are designed to coordinate with the overall look of your document. You can use these galleries to insert tables, headers, footers, lists, cover pages, and other document Building Blocks. When you create Pictures, Charts, or Diagrams, they also coordinate with your current document look. My understanding of the problem: If both contains data as listed items than the code below yields a result that could be title cased and returned to the paragraph. Can this approach be extended to paragraph? Should i have to use nltk n-gram model to coin two words phrases and 3 words phrase? with open("paragraph.txt") as f, open("list.txt") as g: l=f.readlines() l1=g.readlines() print list(set(l)&amp;set(l1)) Some improvement: Now able to identify phrase and match it against paragraph and return matches as capitalized. capitalized_phrases = open("list.txt").readlines() words = open("paragraph.txt").read() for phrase in capitalized_phrases: all_words_found = False capitalized_phrases = phrase.lower().split(" ") for word in capitalized_phrases: if word in words: all_words_found = True break if all_words_found: print phrase.title() So, now the key is to replace the found matches (titlecased) in place of or…
tagged with: python
has title: Capitalization of phrase from list
has comment: http://stackoverflow.com/comment/81171046
answer count: 0
type: UnansweredQuestion
tagged with: capitalization
type: Question
score: 0
has comment: http://stackoverflow.com/comment/81170786

http://stackoverflow.com/comment/81323395
comment on: http://stackoverflow.com/a/47183742
type: AnswerComment
has text: Oh! I thought variables declared within the class worked like private C++ class variables. Today I learn. You saved me, thank you very much!
score: 0
type: Comment

http://stackoverflow.com/q/47181660
has answer: http://stackoverflow.com/a/47181860
score: 3
upvote count: 3
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81314538
has comment: http://stackoverflow.com/comment/81314391
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/81778703
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/81827625
has body: The below code works. However, the line calculating rez is likely not written in the way intended by numpy developers. How can I rewrite it in an efficient way, without converting to and from lists? Also, if you happen to know a good guide on how to write mathematical functions in python, which would work equally with numbers and np.arrays, please share :) import numpy as np from matplotlib import pyplot as plt def L2normSquared(X, Y, x, y): return sum((X-x)**2 + (Y-y)**2) X = np.random.normal(0, 1, 10) Y = np.random.normal(0, 1, 10) PX = np.arange(-1, 1, 0.1) PY = np.arange(-1, 1, 0.1) PXm, PYm = np.meshgrid(PX, PY) rez = np.array([[L2normSquared(X, Y, x, y) for y in PY] for x in PX]) print(rez.shape) plt.imshow(rez, cmap='jet', interpolation='nearest', origin='lower', extent=[-1, 1, -1, 1]) plt.show() Edit: Let me explain what I am trying to do I generate 10 random points in 2D. Then I define a loss function for any arbitrary point (x,y) in 2D. Result of that function is the sum of euclidian distances of all 10 fixed points to this arbitrary point. Finally, I want to plot this loss function using 2d imshow method Edit 2: According to Nils Werner's answer, one can use 3D arrays and broadcasting, producing the following code import numpy as np from matplotlib import pyplot as plt def L2normSquared(X, Y, x, y): return np.sum((X-x)**2 + (Y-y)**2, axis=0) X = np.random.normal(0, 1, 10) Y = np.random.normal(0, 1, 10) PX = np.arange(-1, 1, 0.1) PY = np.arange(-1, 1, 0.1) PXm, PYm = np.meshgrid(PX, PY) rez = L2normSquared(X[:, None, None], Y[:, None, None], PXm, PYm) print(rez.shape) plt.imshow(rez, cmap='jet', interpolation='nearest', origin='lower', extent=[-1, 1, -1, 1]) plt.show() However, this code is actually slower than list comprehension (for 10000 random coordinates, step 0.01, it is roughly 2-3 times slower). For even larger inputs, there is a memory crash, which leads me to believe that this method internally results in 3D array dynamic programming, which does …
has comment: http://stackoverflow.com/comment/82583626
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81312779
has answer: http://stackoverflow.com/a/47182475
tagged with: python
has answer: http://stackoverflow.com/a/47183387
has comment: http://stackoverflow.com/comment/81312620
has title: Correctly write a function of numpy meshgrid

http://stackoverflow.com/q/47157230
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47157737
upvote count: 1
tagged with: python
tagged with: class
has title: python transfer args from __new__ to __init__
score: 1
answer count: 1
downvote count: 0
favorite count: 0
has body: i am trying to change the args before i run the init but it doesn't change and stays as the first args that given in the main, how do i change the args from the new? class A(object): def __init__(self,ip,st): print 'A arrived to init '+st self.ip=ip def __new__(cls,ip,st): print "A arrived to new" if ip&gt;10: return object.__new__(cls,ip,"A") while True: s=input("input?") a=A(s,"a") print type(a) output: input?88 A arrived to new A arrived to init a &lt;class '__main__.A'&gt; input?44 A arrived to new A arrived to init a &lt;class '__main__.A'&gt; input?22 A arrived to new A arrived to init a &lt;class '__main__.A'&gt; input?12 A arrived to new A arrived to init a &lt;class '__main__.A'&gt;
type: Question

http://stackoverflow.com/comment/81125301
comment on: http://stackoverflow.com/q/47087807
score: 0
has text: You can use `"".join(c for c in s if c.isdigit())`, where `s` is your string.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81345556
has text: No problem. [This](https://matplotlib.org/users/dflt_style_changes.html#colormap) shows the changes that were made to matplotlib 2 colormap default style
type: AnswerComment
comment on: http://stackoverflow.com/a/47198052
type: Comment
score: 0

http://stackoverflow.com/comment/81338047
has text: Hello ken wei, thanks for your answer. I tried this code yet unfortunately this code returns only one word when a string contains multiple keywords. for example for the text "Tom likes banana and orange " it returns only banana but both "banana, orange". Is it possible to get multiple keywords returned at the same time?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47193240
score: 0

http://stackoverflow.com/comment/81367715
comment on: http://stackoverflow.com/a/47209007
type: Comment
type: AnswerComment
has text: My hard earned reputation has been brought down by some people. I don't know why I am getting so many down votes for this question. I really think this is a valid question. Though I would like to accept your answer, i don't have the privilege to do that.
score: 0

http://stackoverflow.com/a/47183117
type: Answer
answers question: http://stackoverflow.com/q/47169556
has body: In python when using it always returns a string. That is when using input() to store variables ,the variables will be always of type string, thus to convert age variable into integer write as shown below : age = input('Please enter your age:') ten = 10 agePlusTen= int(age) + ten print('You will be', agePlusTen, 'in 10 years'), i think this should work.
score: 0

http://stackoverflow.com/comment/81110964
type: Comment
comment on: http://stackoverflow.com/q/47080315
type: QuestionComment
score: 0
has text: What are you trying to do to the column? That would help determine what the correct approach is. Something like df.loc[df.IDnumber.str.startswith('2'), 'column_you_want_to_modify'] = modification

http://stackoverflow.com/a/47157972
answers question: http://stackoverflow.com/q/47157802
has body: You can create dict of list with 'a','b','c' as keys as follows d = {} d['a'] = [1,2,3,4] d['b'] = [5,6,7,8] d['c'] = [9,10,11,12] names = ['a', 'b', 'c'] for i in names: print(d[i])
score: 0
type: Answer

http://stackoverflow.com/comment/81170918
comment on: http://stackoverflow.com/q/47110304
type: Comment
has text: Animation with matplotlib are slightly more complex than this you will need the `animation` module. [Here is one of the few existing tutorial on the topic](https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/).
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81389280
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47219531
has text: @Miraj50 That's correct. The times are in seconds. I'm doing 3 trials with each trial consisting of 10000 loops. The `timeit` docs recommend taking the minimum value of 3 (or more) trials, see those docs for the reason why.

http://stackoverflow.com/comment/81141592
score: 0
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/158163/discussion-between-pankaj-mishra-and-bryan-oakley).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47091374

http://stackoverflow.com/q/47118723
tagged with: cntk
linked to: http://stackoverflow.com/q/42504669
answer count: 1
downvote count: 0
has body: I am using Keras and CNTK(backend) my code is like this: def run_han(embeddings_index, fname, opt) ... sentence_input = Input(shape=(MAX_SENT_LENGTH,), dtype='int32') embedded_sequences = embedding_layer(sentence_input) l_lstm = Bidirectional(GRU(GRU_UNITS, return_sequences=True, kernel_regularizer=l2_reg, implementation=GPU_IMPL))(embedded_sequences) l_att = AttLayer(regularizer=l2_reg)(l_lstm) sentEncoder = Model(sentence_input, l_att) review_input = Input(shape=(MAX_SENTS, MAX_SENT_LENGTH), dtype='int32') review_encoder = TimeDistributed(sentEncoder)(review_input) l_lstm_sent = Bidirectional(GRU(GRU_UNITS, return_sequences=True, kernel_regularizer=l2_reg, implementation=GPU_IMPL))(review_encoder) l_att_sent = AttLayer(regularizer=l2_reg)(l_lstm_sent) preds = Dense(n_classes, activation='softmax', kernel_regularizer=l2_reg)(l_att_sent) model = Model(review_input, preds) model.compile(loss='categorical_crossentropy', optimizer=opt, #SGD(lr=0.1, nesterov=True), metrics=['acc']) ... model.fit(x_train[ind,:,:], y_train[ind,:], epochs=NUM_EPOCHS, batch_size=BATCH_SIZE, shuffle=False, callbacks=[cr_result, history, csv_logger], verbose=2,validation_data=(x_test, y_test), class_weight = class_weight) ... %xdel model gc.collect() I call the above model several times as I change optimizer. like this: opt = optimizers.RMSprop(lr=0.0001, rho=0.9, epsilon=1e-08, decay=0.0, clipvalue=0.5) run_han(embeddings_index, 'w2v_100_all_rms_cw', opt, class_weight) opt = optimizers.Adadelta(lr=1.0, rho=0.95, epsilon=1e-08, decay=0.0, clipvalue=0.5) run_han(embeddings_index, 'w2v_100_all_adadelta_cw', opt, class_weight) opt = optimizers.Adagrad(lr=0.01, epsilon=1e-08, decay=0.0, clipvalue=0.5) run_han(embeddings_index, 'w2v_100_all_adagrad_cw', opt, class_weight) When the model.fit() is called second time, out of memory error is showing RuntimeError: CUDA failure 2: out of memory ; GPU=0 ; hostname=USER-PC ; expr=cudaMalloc((void**) &amp;deviceBufferPtr, sizeof(AllocatedElemType) * AsMult…
favorite count: 0
type: Question
score: 5
upvote count: 5
tagged with: python
accepted answer: http://stackoverflow.com/a/47126744
tagged with: keras
has comment: http://stackoverflow.com/comment/81768378
has answer: http://stackoverflow.com/a/47126744
has title: CNTK out of memory error when model.fit() is called second time
type: AnsweredQuestion

http://stackoverflow.com/comment/81577847
type: AnswerComment
has text: sorry - I ran it against your second file but not the first, personally I'd turn it into a function or even a class and run it over each file in turn and then merge the answers rather than the whole files. the output is fairly inelegant but gets the answers you want: `Host failure for: server1.test.com:1717 Time OK: 99.000% (100.000%) Host failure for: server2.test.com:1717 Time OK: 99.000% (100.000%) Host failure for: Average Time OK: 0.000% (0.000%)`
type: Comment
comment on: http://stackoverflow.com/a/47313035
score: 0

http://stackoverflow.com/comment/81157152
type: Comment
has text: guys, thankyou so much for helping me. actually i have a mistake with my program. I append 2 list into book_list and it solved now.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47102738

http://stackoverflow.com/q/47128207
score: 1
upvote count: 1
tagged with: tcp
has body: I'm trying to connect with Teltonika device (FMB1xx) with this code: import socket port = 12050 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', port)) s.listen(1) conn, addr = s.accept() print('Connected by ', addr) imei = conn.recv(1024) conn.send('\x01') while True: try: data = conn.recv(1024) if not data: break print (data) except socket.error: print ("Error Occured.") break So far I've figured out that conn.send('\x01') doesn't work as it should, and device don't send the rest of data. There were a few questions like this, but none has a good answer. Here you can find documentation of this device.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/65517980
possible better answer: http://stackoverflow.com/a/65517980
answer count: 2
tagged with: sockets
downvote count: 0
tagged with: python
has title: Connecting Teltonika device with Python over TCP
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48320447
accepted answer: http://stackoverflow.com/a/48320447

http://stackoverflow.com/comment/81369058
type: Comment
has text: But the answers will shuffle all the time so ans will not always be B
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47209940

http://stackoverflow.com/comment/81101196
score: 0
has text: i confirmed it with my server log files. I think i've added that in my question.
comment on: http://stackoverflow.com/q/47076402
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47088458
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81177569
has comment: http://stackoverflow.com/comment/81178220
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81176571
favorite count: 0
type: Question
has title: New Relic on AWS lambda not reading its config file
has body: I'm using zappa to deploy a python/django wsgi app to AWS API Gateway and Lambda. I have all of these in my environment: NEW_RELIC_CONFIG_FILE: /var/task/newrelic.ini NEW_RELIC_LICENSE_KEY: redacted NEW_RELIC_ENVIRONMENT: dev-zappa NEW_RELIC_STARTUP_DEBUG: "on" NEW_RELIC_ENABLED: "on" I'm doing "manual agent start" in my wsgi.py as documented: import newrelic.agent # Will collect NEW_RELIC_CONFIG_FILE and NEW_RELIC_ENVIRONMENT from the environment # Dear god why??!?! # NB: Looks like this IS what makes it go newrelic.agent.global_settings().enabled = True newrelic.agent.initialize('/var/task/newrelic.ini', 'dev-zappa', log_file='stderr', log_level=logging.DEBBUG) I'm not using @newrelic.agent.wsgi_application since django should be auto-magically detected I've added a middleware to shutdown the agent before the lambda gets frozen, but the logging suggests that only the first request is being sent to New Relic. Without the shutdown, I get no logging from the New Relic agent, and there are no events in APM. class NewRelicShutdownMiddleware(MiddlewareMixin): """Simple middleware that shutsdown the NR agent at the end of a request""" def process_request(self, request): pass # really wait for the agent to register with collector # Enabling this causes more log messages about starting data samplers, but only on the first request # newrelic.agent.register_application(timeout=10) def process_response(self, request, response): newrelic.agent.shutdown_agent(timeout=2.5) return response def process_exception(self, request, exception): pass newrelic.agent.shutdown_agent(timeout=2.5) In my newrelic.ini I have the following, but when I log newrelic.agent.global_settings() it contains the default App name (which did get created in APM) and enabled = False, which led to some of the hacks above (environment var, and just editing newrelic.agent.global_settings() before initialize : [newrelic:dev-zappa] app_name = DEV APP zappa monitor_mode = true TL;DR - Two questions: How to get New…
has comment: http://stackoverflow.com/comment/81145411
accepted answer: http://stackoverflow.com/a/47524511
has comment: http://stackoverflow.com/comment/81164148
downvote count: 0
has answer: http://stackoverflow.com/a/47524511
upvote count: 1
tagged with: django
tagged with: python
tagged with: newrelic
tagged with: aws-lambda

http://stackoverflow.com/comment/81290361
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47170263
has text: @0TTT0. [LeetCode](https://github.com/kamyu104/LeetCode/blob/master/Python/fizz-buzz.py).

http://stackoverflow.com/comment/81360453
type: QuestionComment
comment on: http://stackoverflow.com/q/47205870
has text: Please show your effort. What's the code you've come up with so far?
score: 3
type: Comment

http://stackoverflow.com/a/47081811
type: Answer
has comment: http://stackoverflow.com/comment/81114391
has body: Seems like you want to keep all other columns Top15.assign(sizeofg=Top15.groupby('Continent')['PopEst'].transform('size')).\ drop_duplicates('Continent') EDIT: You need agg Top15.groupby('Continent')['PopEst'].agg(['sum','mean','count'])
has comment: http://stackoverflow.com/comment/81114397
has comment: http://stackoverflow.com/comment/81114260
score: 1
accepted answer of: http://stackoverflow.com/q/47081624
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81114498
upvote count: 1
answers question: http://stackoverflow.com/q/47081624
has comment: http://stackoverflow.com/comment/81114139
has comment: http://stackoverflow.com/comment/81113865
has comment: http://stackoverflow.com/comment/81113796
has comment: http://stackoverflow.com/comment/81113076

http://stackoverflow.com/a/47210167
has comment: http://stackoverflow.com/comment/81371898
has body: You can compare the slice of the first 10 string elements with .str.slice(None, 10): dividas_dep["CNPJ_Devedor"].str.slice(None, 10) == funrural["CNPJ_Raiz"] Example: &gt;&gt;&gt; dividas_dep = pd.DataFrame({"CNPJ_Devedor": ['17.080.201/0001-49', '76.205.723/0001-99', '04.885.828/0001-25']}) &gt;&gt;&gt; funrural = pd.DataFrame({"CNPJ_Raiz": ['17.080.201', '04.244.173', '05.006.407']}) &gt;&gt;&gt; dividas_dep["CNPJ_Devedor"].str.slice(None, 10) == funrural["CNPJ_Raiz"] 0 True 1 False 2 False dtype: bool You can use the result to create a new dataframe: res = dividas_dep["CNPJ_Devedor"].str.slice(None, 10) == funrural["CNPJ_Raiz"] funrural[res]
accepted answer of: http://stackoverflow.com/q/47209927
score: 0
has comment: http://stackoverflow.com/comment/81371735
answers question: http://stackoverflow.com/q/47209927
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81371815
type: Answer

http://stackoverflow.com/a/47544901
has comment: http://stackoverflow.com/comment/100651031
has body: Took me a while debugging, but here's a working example: from kivy.uix.behaviors.compoundselection import CompoundSelectionBehavior from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.uix.behaviors import FocusBehavior from kivy.app import App class SelectableBoxLayout(FocusBehavior, CompoundSelectionBehavior, BoxLayout): def keyboard_on_key_down(self, window, keycode, text, modifiers): """Based on FocusBehavior that provides automatic keyboard access, key presses will be used to select children. """ print(keycode, text, modifiers) print(self.orientation) if super(SelectableBoxLayout, self).keyboard_on_key_down( window, keycode, text, modifiers): return True if self.orientation == 'horizontal' and keycode[1] in ['up', 'down']: self.clear_selection() return self.parent.keyboard_on_key_down(window, keycode, text, modifiers) if self.orientation == 'vertical' and keycode[1] in ['up', 'down']: direction = 'focus_next' if keycode[1] == 'down' else 'focus_previous' if self.selected_nodes: next_row = self.selected_nodes[0]._get_focus_next(direction) else: next_row = self.children[-1] self.clear_selection() self.select_node(next_row) if next_row: next_row.focus = True next = next_row.children[-1] if next and not isinstance(next, SelectableBoxLayout): print("moving to {0}".format(next)) next.focus = True next_row.clear_selection() next_row.select_node(next) return True if self.select_with_key_down(window, keycode, text, modifiers): return True return False def keyboard_on_key_up(self, window, keycode): """Based on FocusBehavior that provides automatic keyboard access, key release will be used to select children. """ if super(SelectableBoxLayout, self).keyboard_on_key_up(window, keycode): return True if self.orientation == 'horizontal' and keycode[1] in ['up', 'down']: return self.parent.keyboard_on_key_up(window, keycode) if self.select_with_key_up(window, keycode): return True return False def add_widget(self, widget, index=0): """ Override …
score: 0
answers question: http://stackoverflow.com/q/47212144
type: Answer

http://stackoverflow.com/q/47123465
answer count: 3
has answer: http://stackoverflow.com/a/47124017
has comment: http://stackoverflow.com/comment/81197078
has comment: http://stackoverflow.com/comment/81199426
tagged with: python
score: -1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47123610
has body: How can I create a new dictionary out of 2 dictionaries that I already have created? It should look like this: d1 = {'a': 2, 'b': 3} d2 = {'s': 4, 'k': 5} The keys from d1 and the values from d2 have to be in d3. d3= {'a': 4, 'b': 5} Is there an operation that combines the keys from one dict and the values from another dict to create a new dictionary.
upvote count: 0
type: UnansweredQuestion
tagged with: python-3.5
has comment: http://stackoverflow.com/comment/81196907
has answer: http://stackoverflow.com/a/47123912
downvote count: 1
has title: How to create a dict out of 2 dict's that already exist in Python 3
has comment: http://stackoverflow.com/comment/81198256

http://stackoverflow.com/comment/81189807
has text: `.sendmail` expects a list of recipient addresses. Does your `receiver` variable have this format?
comment on: http://stackoverflow.com/q/47119868
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81350720
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47200492
has text: Unfortunately, I am working on web application which handle only python 2.4.
score: 0

http://stackoverflow.com/comment/81122018
has text: @learnjquery: Well, in the update, lines 1 and 3 have the same key, different values. So how do you handle that? Keep first, keep last, keep collection of all values?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47086002
score: 0

http://stackoverflow.com/q/47206788
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
upvote count: 1
answer count: 1
tagged with: mysql
has answer: http://stackoverflow.com/a/53177378
has body: I am trying to retrive a image from a SQl database and save in local storage. The image uploaded into database is a tif file(using a medium blob field). How can i retrieve the image as a tif file in to the local storage. I have tried to do perform this query using This tutorial. Here is my code import pymysql from arcpy import env from mysql.connector import MySQLConnection, Error env.workspace = "D:/year 4 semester 1/Python/Data/TestData" def write_file(data, filename): with open(filename, 'wb') as f: f.write(data) def read_blob(author_id, filename): # select photo column of a specific author query = "SELECT picture FROM sourcedata WHERE Number = %s" try: # query blob data form the authors table conn = pymysql.connect(host='localhost', user='root', password='', db='research') cursor = conn.cursor() cursor.execute(query, (author_id,)) photo = cursor.fetchone()[0] # write blob data into a file write_file(photo, filename) except Error as e: print(e) finally: cursor.close() conn.close() def main(): read_blob(1, "D:\\year 4 semester 1\\Python\\Data\\TestData\\abc.tif") if __name__ == '__main__': main() Instead of following code in tutorial from python_mysql_dbconfig import read_db_config db_config = read_db_config() try: conn = MySQLConnection(**db_config) I have tried following code to connect to database conn = pymysql.connect(host='localhost', user='root', password='', db='research') Python script runs without generating any error. But the image is not downloaded into file location.
favorite count: 0
type: Question
has title: Retrieve a blob file from SQL database and save on local storage in python environment
tagged with: imagedownload

http://stackoverflow.com/comment/81356486
type: QuestionComment
has text: What should your search return? `Name1` or `Name1:2`? Also: don't you find the answer in [this](https://stackoverflow.com/questions/9553638/python-find-the-index-of-an-item-in-a-list-of-lists) or [this](https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) SO thread?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47203685

http://stackoverflow.com/comment/81153409
comment on: http://stackoverflow.com/q/47101607
has text: AFAIK, you can't create a variable out of a string. Your best bet would probably be creating a dict with lists as values. `{ 'this': ['this', 'is', 'my', 'list'], 'and': ['and', 'thats', 'what', 'it', 'is'] }` etc.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81250872
type: Comment
type: AnswerComment
has text: in the example the chat_id is passed only. How can I pass several items into it?
comment on: http://stackoverflow.com/a/47150604
score: 0

http://stackoverflow.com/comment/81288524
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47169097
has text: Can you give an example what your processed JSON looks like, and maybe a short description of your workflow, e.g. what are your routes used for? Maybe it is just me, but I'm having a hard time understanding what your issue is.
type: Comment

http://stackoverflow.com/comment/81201846
type: QuestionComment
comment on: http://stackoverflow.com/q/47124387
type: Comment
has text: filepath should be `desktop/img/bitcoin.jpg`
score: 1

http://stackoverflow.com/comment/81127833
comment on: http://stackoverflow.com/q/47089049
has text: @solarissmoke then how do i map it to the url part
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/92632287
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50889569
has text: whenever there is an update to the Shelf, I followed with a Shelf.sync() , and I succeed to get rid of the issue

http://stackoverflow.com/a/47117993
has body: This is one possible solution, also mentioned by @OTTO del_list = ['file1.csv', 'file2.csv', 'file3.csv']; for fd in del_list: try: os.remove(os.path.join(my_dir, fd)) except OSError: pass You first need to create a list of file names that you want to delete in any directory my_dir you will be cleaning. The loop goes through the list and uses error handling that prevents the program from exiting if a file is not present in that particular directory. You can turn this program into a function and call it for each directory you want to delete files from or add another, outer loop that goes through a list of your target directories.
upvote count: 4
has comment: http://stackoverflow.com/comment/81186299
has comment: http://stackoverflow.com/comment/81186214
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/47117780
has comment: http://stackoverflow.com/comment/81186098
has comment: http://stackoverflow.com/comment/81186109
has comment: http://stackoverflow.com/comment/81186014
answers question: http://stackoverflow.com/q/47117780
has comment: http://stackoverflow.com/comment/81186545
has comment: http://stackoverflow.com/comment/81185990
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/81186572

http://stackoverflow.com/a/75503485
answers question: http://stackoverflow.com/q/47181684
score: 0
has body: Works with TKinter and export to Excel: def utf_2_iso(text: str) -&gt; str: try: result: str = text.encode('ISO-8859-1', errors='ignore').decode('utf-8', errors='ignore') except UnicodeError: result = text return result
type: Answer
has comment: http://stackoverflow.com/comment/133291479

http://stackoverflow.com/comment/81265863
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47152987
has text: Also I dont see with the above code that it doesn't overwrite anything when I run the file second time.
type: Comment

firefox
type: Tag
tags question: http://stackoverflow.com/q/47067506
tag name: firefox
tags question: http://stackoverflow.com/q/47095720
tags question: http://stackoverflow.com/q/47088907

http://stackoverflow.com/a/47212018
score: 0
answers question: http://stackoverflow.com/q/47195512
has body: In python, you cannot have positional arguments after keyword arguments. You have to use Q as the first argument to filter. queryset = User.objects.filter(~Q(status = 4), is_staff=True, is_admin=True)
type: Answer

http://stackoverflow.com/comment/81252021
comment on: http://stackoverflow.com/q/47151148
score: 1
type: Comment
type: QuestionComment
has text: your question has ambiguity like what will happen when i reached to end of array in first or second part of skipping.

http://stackoverflow.com/comment/81560599
comment on: http://stackoverflow.com/q/47086718
has text: @AmodGokhale I updated the post with the error. Thank you
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47168330
accepted answer of: http://stackoverflow.com/q/47168056
answers question: http://stackoverflow.com/q/47168056
type: Answer
score: 15
upvote count: 15
has body: Arrays have a fixed size. You can't append to them. If you know the upper bounds of the array, you can preallocate the array with np.empty((10, 10, 10)) For a 10x10x10 matrix. You can then keep 3 indices x,y,z to track the actual size you have. Eg, add a new element with: matrix[x,y,z] = newElement x += 1 Then when you're done, you can extract the submatrix with finalMatrix = matrix[:x,:y,:z]
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81177749
comment on: http://stackoverflow.com/q/47113543
type: QuestionComment
type: Comment
has text: martineau: I added the if i > stop_value: break but couldn't define stop_value. It has to be second i value but how can ı define before find the i values with loop? sorry for the question, probably it is too easy but ı can't understand.
score: 0

http://stackoverflow.com/comment/81149596
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47096938
type: AnswerComment
has text: Why there is `In [187]:` type of thing in most of the pandas related answers ?

http://stackoverflow.com/comment/85422074
type: Comment
type: QuestionComment
has text: *"Are if statements considered functions?"* No, `if` statements and function definitions are two different kinds of [compound statement](https://docs.python.org/3/reference/compound_stmts.html).
comment on: http://stackoverflow.com/q/47105228
score: 0

http://stackoverflow.com/comment/81242620
type: AnswerComment
has text: Hm, I'll check that tomorrow. If you don't have `threaded=True`, will multiple users then be able to use the site at the same time (even if there are long-running queries)?
type: Comment
comment on: http://stackoverflow.com/a/47144339
score: 0

http://stackoverflow.com/q/47188370
tagged with: dask
type: Question
has body: I have custom Dask's graphs for processing large amounts of pictures. Some of those pictures appear to be unusable at runtime, after a number of operations. Right now, I propagate None to abort the subgraph, as for example : # coding: utf-8 from dask import delayed @delayed def load(filename): print("Load " +filename) return filename @delayed def clean(data): if data == 'c.data': return None # &lt;========== Aborting print("clean " + data) return data @delayed def analyze(sequence): for s in sequence: if not s: continue print("Analyzing " + s) inputs = ['a.data','b.data', 'c.data'] loads = [load(i) for i in inputs] cleaned = [clean(x) for x in loads] analysis = analyze(cleaned) analysis.visualize() analysis.compute() is there a way to tell Dask to abort a part of the graph and have it execute like this at runtime ?
answer count: 0
tagged with: python
type: UnansweredQuestion
tagged with: directed-acyclic-graphs
has comment: http://stackoverflow.com/comment/81326462
has comment: http://stackoverflow.com/comment/81326952
has title: Terminate subgraphs in Dask at runtime
score: 0
tagged with: multithreading
tagged with: multiprocessing

http://stackoverflow.com/comment/81186355
type: AnswerComment
has text: @Eyshika Thats even easier. `[lis for i in range(3)]` or `[lis]*3`(not `lis*3` Try both and see the difference :) ), where `lis = [1,2,3,4,5]`. Btw I think you should really read about `list comprehension`. Very helpful.
type: Comment
comment on: http://stackoverflow.com/a/47107900
score: 0

http://stackoverflow.com/a/47168866
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47168397
has body: Ok, I figured out how to get this done after a while of trying everything I could find, needed to use parse instead of tostring: trees_to_save = [{'tree': lxml.etree.tostring(tree,encoding='utf-8',method='html')} for tree in trees] t2sdf = pd.DataFrame(trees_to_save) t2sdf.to_csv('location_trees.csv') trees_from_file = pd.read_csv('location_trees.csv') EncodeForamt = lxml.etree.HTMLParser(encoding='utf-8') trees_from_file['tree'] = trees_from_file['tree'].apply(lambda x: lxml.etree.parse(x,parser=EncodeForamt))
type: Answer
accepted answer of: http://stackoverflow.com/q/47168397
score: 2

http://stackoverflow.com/comment/81131992
type: AnswerComment
has text: About the class solution (instantiating an object only for the side effects of the instantiating): I was not thinking about performance. I was thinking about the pattern's acceptance in the community. I have definitely got some negative feedback from experienced people on StackOverflow on a similar question (later deleted) in the recent past ("This is a hack"). But @jsbueno and some more thinking convinced me that this is a good pattern.
comment on: http://stackoverflow.com/a/47065027
type: Comment
score: 0

http://stackoverflow.com/q/47141482
answer count: 1
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has title: Tensorflow : Improve a Tensorflow model on false predictions loaded from checkpoint
has body: After training a network and out-putting a model, is it possible to feed single false predictions into the network after loading the first model from a checkpoint to help improve performance. The current solutions I have tried so far have involved: with tf.Session() as sess: #Try new method... saver = tf.train.import_meta_graph('./model2.ckpt.meta') saver.restore(sess, './model2.ckpt') graph = tf.get_default_graph() x_1 = graph.get_tensor_by_name("x:0") y_1 = graph.get_tensor_by_name("y_:0") train_step = graph.get_tensor_by_name("train_step:0") trX = image trY = np.eye(10)[digit] sess.run(train_step, feed_dict={x: trX, y_: [trY], keep_prob:0.5}) new_saver = tf.train.Saver() new_saver.save(sess, "./model2.ckpt") sess.close() trX = image trY = np.eye(10)[digit] sess.run(train_step, feed_dict={x: trX, y_: [trY], keep_prob:0.5}) Or this solution: with tf.Session() as sess: saver = tf.train.Saver() saver.restore(sess, "./model2.ckpt") trX = image trY = np.eye(10)[digit] sess.run(train_step, feed_dict={x: trX, y_: [trY], keep_prob:0.5}) Both have resulted in the network loosing the ability to correctly predict a previously image, that was being predicted correctly.
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47303749
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/47303749

http://stackoverflow.com/comment/81193532
type: Comment
comment on: http://stackoverflow.com/q/47121960
type: QuestionComment
score: 0
has text: Probably is. If you're familiar with pywin32 and or pygtk/pyqt that can do these type of things. Your question is regarding a opinion, if it's hard or not. So I'm voting to close this.

http://stackoverflow.com/q/47185451
upvote count: 3
answer count: 1
downvote count: 0
tagged with: global-variables
favorite count: 0
type: Question
tagged with: python-3.x
score: 3
type: UnansweredQuestion
has title: Sharing a list between Python modules
tagged with: python
has answer: http://stackoverflow.com/a/47185708
has body: SO feedback motivated me to create a package with often used routines, so I don't have to copy/paste functions into new modules any more. This works well, but now I encountered a problem. My module 2 function f2 is supposed to be called from module 1 with a number n1. If list1 exists in module 1, f2 uses it to analyse n1, otherwise it has to create list2 from scratch for this analysis. My approach so far is to use optional arguments. module1.py from standardpackage.module2 import f2 list1 = [1, 2, 3] n = 1 a = f2(n, list1) #works with existing list1 b = f2(n) #works without list1 module2.py def f2(n, *arg): if arg: list2 = arg[0] #uses list1 else: list2 = [3, 2, 1] #uses its own list res = dosth(n, list2) #code executed within module2 return res This approach does, what it is supposed to do, but imho it doesn't look clever. I know from experience, that list1 can be very long and f2() might be called millions of times. To create a copy of list1 every time, you call f2(), seems to waste time and memory space. My question is: Can module 2 somehow use list1 from module 1? I read on SO and tutorial websites about global variable sharing and understand now, why my global list1 approach didn't work. I've seen suggestions to bind module 1 to module 2, but I want to use module 2 in future projects, so I don't know the name of those modules. I've seen suggestions with threading and multiprocessing, but as a Python newbie, I didn't understand the relevance to my question. Any suggestions welcome. Thank you.
has comment: http://stackoverflow.com/comment/81320156

http://stackoverflow.com/a/47185548
answers question: http://stackoverflow.com/q/47185315
score: 2
has comment: http://stackoverflow.com/comment/81320414
upvote count: 2
has body: Or you can just do within basic calculation. df['New']=(df.index%5).values df.New=df.New.add(1)
downvote count: 0
has comment: http://stackoverflow.com/comment/81320524
type: Answer
has comment: http://stackoverflow.com/comment/81320464

http://stackoverflow.com/comment/81196493
comment on: http://stackoverflow.com/a/47115520
type: Comment
score: 2
has text: This is blazing fast. I really need to learn how to use numpy for data manipulation. Thanks!
type: AnswerComment

http://stackoverflow.com/comment/82144859
has text: @galaxy_twirl in my opinion, it is not worth. But I'd avoid the `raise` and go directly with the `if not buff printf` (why do you have to raise an exception?), unless you strictly require an exception.
comment on: http://stackoverflow.com/a/47158770
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81189949
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47120110
has text: Thanks for sharing. It's working now. Probably it was the "time.sleep(2)". I dont know, but really thanks!
score: 0

http://stackoverflow.com/a/77274564
answers question: http://stackoverflow.com/q/47194211
score: 0
type: Answer
has body: I found a quick solution. when you import the file, you must add another '/'. Example: pd.read_csv('c:/drive/py.csv'), then you put this pd.read_csv('c://drive//py.csv').

http://stackoverflow.com/comment/81906337
has text: I am trying out the following: https://apple.stackexchange.com/a/198282/55242 `sudo launchctl config user path <my path setting>`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47475621
type: Comment

http://stackoverflow.com/comment/81126523
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47088492
has text: What you have is correct. It is also possible to use `self` for all 3.
score: 0

http://stackoverflow.com/comment/81201477
type: Comment
type: QuestionComment
has text: Note that `MIDDLEWARE_CLASSES` is the old setting for Django <= 1.9. You shouldn't set it as well as `MIDDLEWARE`.
score: 0
comment on: http://stackoverflow.com/q/47122838

http://stackoverflow.com/comment/81086473
type: AnswerComment
comment on: http://stackoverflow.com/a/47069338
score: 0
type: Comment
has text: if not sorry haha i try my best peace and love

http://stackoverflow.com/comment/81143513
comment on: http://stackoverflow.com/a/47096499
has text: @Bharath I don't agree. You have to define a **source** and **target** group to check for consistency from source to target. In your solution, you check both ways and use the minimum. But the OP's desired output does not match your result because *G2* is the source group and *G1* is the target group.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81145360
comment on: http://stackoverflow.com/q/47097293
type: Comment
type: QuestionComment
score: 0
has text: Also, this is my case at the moment, but in general I'm looking for an easy way of doing this. I looked documentation several times but can't find an easy way of handling migrations As I said, the only easy way out of it I found was `--merge` but is this enough ?

http://stackoverflow.com/q/47152095
score: 0
has body: I am looking at using google cloud python SDKs to manage my resources. I am not able to find compute module in the python SDK. Python Doc here: https://googlecloudplatform.github.io/google-cloud-python/latest/ However compute module is available in Node.js SDK. Node.js Doc here: https://googlecloudplatform.github.io/google-cloud-node/#/docs/google-cloud/0.56.0/compute Can I get information if this module(compute) is available in python? If not is this being planned and when can I expect it.
type: Question
tagged with: google-python-api
has answer: http://stackoverflow.com/a/47216932
type: UnansweredQuestion
answer count: 1
has title: Using Compute module in "Google Cloud Client Library for Python"
tagged with: google-compute-engine
tagged with: python

http://stackoverflow.com/q/47166191
downvote count: 0
accepted answer: http://stackoverflow.com/a/49256710
has body: (Apologies for the long post) All, I want to use the bottleneck features from a pretrained Inceptionv3 model to predict classification for my input images. Before training a model and predicting classification, I tried 3 different approaches for extracting the bottleneck features. My 3 approaches yielded different bottleneck features (not just in values but even the size was different). Size of my bottleneck features from Approach 1 and 2: (number of input images) x 3 x 3 x 2048 Size of my bottleneck features from Approach 3: (number of input images) x 2048 Why are the sizes different between the Keras based Inceptionv3 model and the native Tensorflow model? My guess is that when I say include_top=False in Keras, I'm not extracting the 'pool_3/_reshape:0' layer. Is this correct? If yes, how do I extract the 'pool_3/_reshape:0' layer in Keras? If my guess is incorrect, what 'am I missing? I compared the bottleneck feature values from Approach 1 and 2 and they were significantly different. I think I'm feeding it the same input images because I resize and rescale my images before I even read it as input for my script. I have no options for my ImageDataGenerator in Approach 1 and according to the documentation for that function all the default values do not change my input image. I have set shuffle to false so I assumed that predict_generator and predict are reading images in the same order. What 'am I missing? Please note: My inputs images are in RGB format (so number of channels = 3) and I resized all of them to 150x150. I used the preprocess_input function in inceptionv3.py to preprocess all my images. def preprocess_input(image): image /= 255. image -= 0.5 image *= 2. return image Approach 1: Used Keras with tensorflow as backend, an ImageDataGenerator to read my data and model.predict_generator to compute bottleneck features I followed the example (Section Using the bottleneck features of a pre-trained network: 90% accuracy in a minute) from Keras' blog. Instead of…
tagged with: keras
has answer: http://stackoverflow.com/a/49256710
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 8
has comment: http://stackoverflow.com/comment/85510654
tagged with: python
possible better answer: http://stackoverflow.com/a/49249062
has answer: http://stackoverflow.com/a/49249062
score: 8
has title: extracting Bottleneck features using pretrained Inceptionv3 - differences between Keras' implementation and Native Tensorflow implementation
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/a/47173116
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47173086
has body: This should do it - center_list.append(miniBatchKMeans_cluster_centers) This is the standard way of adding elements in the list.

http://stackoverflow.com/comment/81263953
score: 0
type: AnswerComment
has text: @arizamoona Again depends on the setup. Why not try it at your end? The timing should be proportional to the dataset size.
comment on: http://stackoverflow.com/a/47156173
type: Comment

http://stackoverflow.com/comment/81302527
type: Comment
score: 0
type: AnswerComment
has text: An entire column was removed. This is very strange indeed.
comment on: http://stackoverflow.com/a/47175265

pca
tag name: pca
tags question: http://stackoverflow.com/q/47077349
type: Tag

http://stackoverflow.com/q/47185432
type: Question
has answer: http://stackoverflow.com/a/47185806
linked to: http://stackoverflow.com/q/15891038
accepted answer: http://stackoverflow.com/a/47186026
tagged with: python
has answer: http://stackoverflow.com/a/47185557
has answer: http://stackoverflow.com/a/47186026
has comment: http://stackoverflow.com/comment/81320172
type: AnsweredQuestion
answer count: 3
tagged with: pandas
has title: Convert data frame to numeric and dropna
possible better answer: http://stackoverflow.com/a/47185557
downvote count: 0
has comment: http://stackoverflow.com/comment/81319927
upvote count: 1
score: 1
has body: I been using: df = df.convert_objects(convert_numeric=True).dropna() but since it's being deprecated I need to replace it with to_numeric I've tried df = pd.to_numeric df = df.dropna() Sample data: Name Race Fav Age Weight Height Style Cut John D K 23 120 23.5 DD RET Rose Z U 33 110 47.9 KZ DEZ James Z U FF UK NOT Z R Would like to convert to drop the rows that are non numeric Output: Name Race Fav Age Weight Height Style Cut John D K 23 120 23.5 DD RET Rose Z U 33 110 47.9 KZ DEZ
favorite count: 0

http://stackoverflow.com/a/47117170
type: Answer
accepted answer of: http://stackoverflow.com/q/47115996
type: AcceptedAnswer
has body: It's the slicing that's changing the shape not the division: In [11]: a = np.random.rand(9, 9, 9) In [12]: a[0:2, :, :].shape Out[12]: (2, 9, 9) In [13]: a[:, 0:2, :].shape Out[13]: (9, 2, 9) In [14]: a[:, :, 0:2].shape Out[14]: (9, 9, 2) In [15]: (a[:, :, 0:2] / 255).shape Out[15]: (9, 9, 2) See the numpy indexing docs.
answers question: http://stackoverflow.com/q/47115996
score: 0

http://stackoverflow.com/a/47193896
has body: Original Question The stability of the FTCS scheme hinges on the size of the constant r. If r&lt;1/2, then rounding errors introduced at each step will exponentially decay. If r&gt;1/2, then those rounding errors will exponentially increase. (As you've alluded to in your edit). Small-ish Errors dx = L/nx and dt = tmax/nt. (If this is confusing to you, imagine the case of nx = 2 and L = 1... then dx = 0.5). L and tmax should be floats. (ie - L = 1.0). You are not updating the temperature u at the second to last position on the rod. Make sure the for loop over position extends to nx-1 and NOT nx-2. Things to consider You might consider using real values/units for time, length, thermal conductivity and initial temperature. When you apply the boundary conditions (under the comment #BC), only the time t=0 has values of u which are non-zero, so you do not need to iterate through all the time steps. While it is necessary for you to iterate through time (hence the time for loop), you can actually vectorize the spatial derivative. You could replace your for loop with the following: for t in range(0, nt-1): u[t+1, 1:nx-1] = r*(u[t,0:nx-2] + u[t,2:]) + r2*(u[t,1:nx-1])
answers question: http://stackoverflow.com/q/47129097
score: 1
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/81297874
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47172348
has text: It'll be slower because of matplotlib plt. I dont think reducing the delay will improve it much.

http://stackoverflow.com/comment/81181684
comment on: http://stackoverflow.com/q/47115684
type: Comment
type: QuestionComment
score: 0
has text: Yes, resize the canvas so the canvas fills the entire window when the window is resized by the user employing a 'click and drag' on the window edge.

http://stackoverflow.com/comment/81357837
score: 1
comment on: http://stackoverflow.com/q/47203287
type: Comment
type: QuestionComment
has text: Unfortunately, notices are not included in DB-API 2.0 as it's a feature specific for Postgres.

http://stackoverflow.com/comment/81198935
type: Comment
comment on: http://stackoverflow.com/a/47123747
has text: I guess there is more dates like `20/10/2016 15:22:51:700`, then `dayfirst=True` is not necessary
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81681829
score: 0
has text: Thanks for the thorough response! This definitely beats trying to figure out the doc.
type: Comment
comment on: http://stackoverflow.com/a/47228403
type: AnswerComment

http://stackoverflow.com/comment/81124479
type: AnswerComment
has text: Sweet, I do understand now. Thanks a lot man. I wish I could accept both answers, because both are brilliant, I don't know which one should I accept :(
score: 0
comment on: http://stackoverflow.com/a/47082551
type: Comment

http://stackoverflow.com/comment/81217559
has text: I am on mobile and it shows me more of your first comment only later. If you failed to install brew you should get that solved first. There are Q&A regarding brew install on this site to follow.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47125440

http://stackoverflow.com/a/48837789
has comment: http://stackoverflow.com/comment/86648051
upvote count: 1
has comment: http://stackoverflow.com/comment/86049815
has body: I'm sure you've already run into the python-can library? If not we have a native python version of socketcan that correctly parse data out of CAN messages. Some of the source might help you out - or you might want to use it directly. CAN_RAW is probably what you want, if you plan on leaving virtual can for real hardware you might also want to get the timestamp from the hardware. Not all constants have been exposed in Python's socket module so there is also a ctypes version which made in easier to experiment with things like the socketcan broadcast manager. Docs for both are here.
has comment: http://stackoverflow.com/comment/85952280
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86049792
score: 1
answers question: http://stackoverflow.com/q/47083099

http://stackoverflow.com/comment/81231455
comment on: http://stackoverflow.com/q/47140801
has text: In Python 2, if you calculate `n/m` for two ints where `0<n<m`, then you get zero, because `/` does int division on ints.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47143722
accepted answer: http://stackoverflow.com/a/47143776
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47143776
type: AnsweredQuestion
score: 2
has body: Please, given the two dataframes: DF1: A B a1 b1 a2 b2 a3 b3 DF2: C1 C2 C3 0 0 1 I would like to do the following DF1+DF2 producing the following: A B C1 C2 C3 a1 b1 0 0 1 a2 b2 0 0 1 a3 b3 0 0 1 it is not clear to me how I should use one of Merge, Join or concatenate. Please, any help would be very appreciated.c.
possible better answer: http://stackoverflow.com/a/47143772
answer count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/38188420
has title: Joining two Pandas Dataframe
has answer: http://stackoverflow.com/a/47144249
has comment: http://stackoverflow.com/comment/81237518
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81237477
upvote count: 2
has answer: http://stackoverflow.com/a/47143772
downvote count: 0

http://stackoverflow.com/comment/81102308
comment on: http://stackoverflow.com/q/47076883
has text: And if you want to say you've searched things, show what isn't working so we won't close your question as possible duplicates of any of them
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47193586
type: Answer
upvote count: 1
score: 1
downvote count: 0
has body: Since attribute value is in json format for responseBodyContent try this authkey_text = json.loads(auth_key.get_attribute) print str(authkey_text)
answers question: http://stackoverflow.com/q/47191535

http://stackoverflow.com/comment/81352705
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47201262
has text: Not sure if understand, can you add data sample, 5-6 rows? What is `sort these location names with that column values` ?

http://stackoverflow.com/comment/81117222
type: QuestionComment
has text: @schwobaseggl that's a great question - I assumed that as long as the hashes where the same, python would treat them as equal. However yes, the __eq__ function considered them equal, as well as having equal hashes.
comment on: http://stackoverflow.com/q/47083667
score: 0
type: Comment

http://stackoverflow.com/comment/81339038
type: Comment
comment on: http://stackoverflow.com/q/47194806
score: 2
type: QuestionComment
has text: I'm using pandas 0.20.3 on Python 3, and can initialize `df2` if I use an empty list for the data. I'm guessing the variables defined as `od3` and `od4` are meant to be `od1` and `od2` respectively, but after making this change, the code runs fine.

http://stackoverflow.com/comment/81244989
score: 1
type: QuestionComment
has text: Well no, one iterator will be consumed fully before the other (since I will call the processing functions one after the other). So the tee solution doesn't cut it as it will just load it all in memory!
type: Comment
comment on: http://stackoverflow.com/q/47146905

http://stackoverflow.com/q/47087099
accepted answer: http://stackoverflow.com/a/47087393
has answer: http://stackoverflow.com/a/47087412
tagged with: python
has title: Find groups of increasing numbers (with varying deltas) within list
favorite count: 0
type: Question
tagged with: numpy
upvote count: 2
downvote count: 0
has body: I have a list containing 'groups' of increasing numbers with varying deltas. Here's an example: l = [0, 1, 5, 8, 10, 20, 30, 40, 45, 48, 77, 100, 200, 300, 400] I would like to get back: [[0], [1], [5], [8], [10, 20, 30, 40], [45], [48], [77], [100, 200, 300, 400]] Explanation: The 0, 1, 5, 8 don't follow a fixed delta (+1, +4, +3), while [10, 20, 30, 40] all have a fixed +10 delta. I see how this could be done using for loops and curr_group, curr_delta, etc. variables, but I would like to avoid this. Using pandas, I was able get this: import pandas as pd df = pd.DataFrame({'col': [0, 1, 5, 8, 10, 20, 30, 40, 45, 48, 77, 100, 200, 300, 400]}) df['shift_diff'] = (df.diff() != df.diff().shift(-1)).astype('int') df['group'] = df.shift_diff.cumsum() print list(df.groupby('group').col.apply(list)) which outputs [[0], [1], [5], [8], [10, 20, 30], [40], [45], [48], [77], [100, 200, 300], [400]] Pretty close, but all groups with length > 1 (the [10, 20, 30] and [100, 200, 300]) are missing their last element. A short and elegant solution would be appreciated! Thank you
has answer: http://stackoverflow.com/a/47087393
has answer: http://stackoverflow.com/a/47087541
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47087412
answer count: 3
tagged with: pandas

http://stackoverflow.com/q/47163658
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/81277042
type: Question
score: 1
has comment: http://stackoverflow.com/comment/81277626
tagged with: python
has comment: http://stackoverflow.com/comment/81291883
has title: tensorflow.python.framework.errors_impl.InvalidArgumentError: Shape mismatch in tuple component 0
has body: When I use tensorflow to build my own neural network and run it, I meet a very strange error. The error is that tensorflow.python.framework.errors_impl.InvalidArgumentError: Shape mismatch in tuple component 0. Expected [400], got [3200]. I have no idea about how [3200] comes, could anyone can help to fix this problem? The input of the neural network is a 400-dimension vector. Here is one part of my code Here is one part of my code Here is one part of my code Here is one part of my code Here is the output output 1 output2 output3
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81281924
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/103669491
score: 0
type: Comment
type: AnswerComment
has text: Woo, magic! that works for me, with Python 2.7.16 and resulted in downgrade to *backports.functools_lru_cache==1.2.1*
comment on: http://stackoverflow.com/a/52006664

http://stackoverflow.com/comment/81313011
comment on: http://stackoverflow.com/q/47181719
type: Comment
type: QuestionComment
has text: There is a startswith built-in function. Or splice the start of the string yourself. Or split the line on colon, and compare to the first string.
score: 0

http://stackoverflow.com/q/47103712
possible better answer: http://stackoverflow.com/a/47103805
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47103805
duplicate of: http://stackoverflow.com/q/33239308
upvote count: 54
accepted answer: http://stackoverflow.com/a/47103744
tagged with: python
score: 53
type: AnsweredQuestion
tagged with: try-except
has body: Is it possible to do a try-except catch all that still shows the error without catching every possible exception? I have a case where exceptions will happen once a day every few days in a script running 24/7. I can't let the script die but they also don't matter since it retries regardless as long as I try except everything. So while I track down any last rare exceptions I want to log those to a file for future debugging. example: try: print(555) except: print("type error: "+ str(the_error)) Any way to replace the_error with a stack trace or something similar?
has title: python 3 try-except all with error
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47103744
linked to: http://stackoverflow.com/q/33239308
tagged with: python-3.x

ipv6
tag name: ipv6
tags question: http://stackoverflow.com/q/47088992
tags question: http://stackoverflow.com/q/47077323
type: Tag

http://stackoverflow.com/q/47096172
tagged with: cgi
has comment: http://stackoverflow.com/comment/81147457
tagged with: shebang
type: Question
has comment: http://stackoverflow.com/comment/81144254
has comment: http://stackoverflow.com/comment/81147528
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81146520
tagged with: apache
has comment: http://stackoverflow.com/comment/81146401
tagged with: python
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/81147571
has body: I am trying to make python work on Apache on Ubuntu. When I tried to run a cgi-script, with custom installed libraries, it would not work, so I looked for a solution and I discovered, that it runs wrong version of python. Even when I put #!/usr/bin/python3 as the first line of the script and try to display version of python it uses by print(sys.version), it still uses python 2.7.6. It even worked, when I completely deleted the shebang line. I checked that the path /usr/bin/python3 is the correct one and it even has 777 permission. It seems it just ignores the shebang line. Or is there any settings in Apache that "hardcodes" the version of the python it uses?
score: 0
has comment: http://stackoverflow.com/comment/81147260
answer count: 0
has title: CGI script ignores shebang line

http://stackoverflow.com/q/47131795
tagged with: tkinter
tagged with: for-loop
has answer: http://stackoverflow.com/a/47139482
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/81213068
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/81224065
answer count: 1
upvote count: 1
has body: k = [1,3] listBasket = [[1,2,3],[4,5,6],[6,7,8],[9,10,11]] def cont(self, listBasket, k, userID): for t in range(len(k)): upInfo = Entry(self) upInfo.pack() updateButton = ttk.Button(self, text="Update", command=lambda: updateListBasket(self, userID, listBasket, t, upInfo.get(), k)) updateButton.pack() def updateListBasket(self, userID, listBasket, t, upInfo, k): listBasket[t][2] = (upInfo) cont(self, listBasket, k, userID) For some reason my code just goes through the for loop without caring if the value is entered in my upInfo or not. So my updateListBasket recieves the 2nd position of k(value 3); this leads to the updatelist only able to update the element at the 3rd position of the list and not the 2nd
favorite count: 0
type: Question
has title: Python: tkinter for loop, looping through without caring if my entry field is filled?

http://stackoverflow.com/q/47112874
upvote count: 1
tagged with: loops
has answer: http://stackoverflow.com/a/47113233
accepted answer: http://stackoverflow.com/a/47113233
favorite count: 0
type: Question
tagged with: python-3.x
has body: I have the following program: random_pool=[[[0, 2, 3, 1, 3, 2, 0, 1], [0, 1], [1], [0]], [[0, 3, 2, 1, 2, 3, 0, 1], [0, 3], [3], [1]], [[1, 2, 3, 0, 3, 2, 1, 0], [2, 2], [4], [2]], [[2, 1, 3, 0, 3, 1, 2, 0], [2, 1], [3], [3]]] binary_list=[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0]] def GeneratePopulation(random_pool, binary_list): individual = [] population = [] for gene in range(0, len(binary_list)): gene=binary_list[gene] for game in range (0, len(random_pool)): fitness=random_pool[game][2] counter=random_pool[game][3] individual=[gene,fitness,counter] population.append(individual) return(population) With the output: [[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [1], [0]], [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [3], [1]], [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [4], [2]], [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [3], [3]], [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [1], [0]], [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]], [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [4], [2]], [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [3]], [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [1], [0]], [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [3], [1]], [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]], [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [3], [3]], [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1], [0]], [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [3], [1]], [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [4], [2]], [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [3], [3]]] My objective is to combine the elements gene (binary vector), from the binary_list with the last two elements of each item in the random_pool list, so the correct outcome would be: [[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, …
has title: Combining selected items from different lists into a new one
tagged with: python
tagged with: genetic-programming
has answer: http://stackoverflow.com/a/47113950
possible better answer: http://stackoverflow.com/a/47113950
type: AnsweredQuestion
tagged with: list
answer count: 2
score: 1
downvote count: 0

http://stackoverflow.com/comment/81097471
has text: You're getting downvoted because you haven't shown us what you've tried. Per the guidance on [how to write a good question](https://stackoverflow.com/help/how-to-ask), what you've given isn't a problem, it's just asking others to do the work for you. If you present a problem that you can't make work, that meets the MVCE requirements mentioned there, then we'll be able to help.
score: 0
comment on: http://stackoverflow.com/q/47072224
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47202469
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47202331
has comment: http://stackoverflow.com/comment/81353257
has body: I think this is what you're looking for: Accept username and password and verify it against a particular one mentioned in the code, with a max try limit of 3 print('Enter correct username and password combo to continue') count=1 while count&lt;4: username=input('Enter username: ') password=input('Enter password: ') if password=='Hytu76E' and username=='bank_admin': print('Access granted') count=5 else: print('Access denied. Try again.') count+=1

http://stackoverflow.com/q/47126370
has comment: http://stackoverflow.com/comment/81203278
tagged with: python
linked to: http://stackoverflow.com/q/10965417
tagged with: opencv
has body: I am doing some image operations on a numpy array via OpenCV. These images are then being baked out to jpeg, then ingested into FFMPEG to make a video. However, baking it out to a file is not very efficient. I would like to stream this directly into FFMPEG. In theory, it would look something like this: p = Popen(['/usr/local/bin/ffmpeg', '-s', '1920x1080', '-pix_fmt', 'yuvj420p', '-y', '-f', 'image2pipe', '-vcodec', 'mjpeg', '-r', self.fps, '-i', '-', '-r', self.fps, '-f', 'mp4', '-vcodec', 'libx264', '-preset', 'fast', # '-crf', '26', 'output/{}.mp4'.format(self.animation_name)], stdin=PIPE) image_resize = cv.resize(self.original_image, (0, 0), fx=zoom, fy=zoom) M = np.float32([[1, 0, x_total], [0, 1, y_total]]) image_offset = cv.warpAffine(image_resize, M, (self.original_image_width, self.original_image_width)) image = image_offset[0:self.output_raster_height, 0:self.output_raster_width].copy() cv.imwrite(p.stdin, image) # this doesn't actually work, but that's the idea... I've been able to achieve this with Pillow using this setup: p = Popen(['/usr/local/bin/ffmpeg', '-s', '1920x1080', '-pix_fmt', 'yuvj420p', '-y', '-f', 'image2pipe', '-vcodec', 'mjpeg', '-r', self.fps, '-i', '-', '-r', self.fps, '-f', 'mp4', '-vcodec', 'libx264', '-preset', 'fast', # '-crf', '26', 'output/{}.mp4'.format(self.animation_name)], stdin=PIPE) image_resize = self.original_image.resize((resize_width, resize_height), resample=PIL.Image.BICUBIC) image_offset = ImageChops.offset(image_resize, xoffset=int(x_total), yoffset=int(y_total)) image = image_offset.crop((0, 0, self.output_raster_width, self.output_raster_height)) image.save(p.stdin, 'JPEG') So, my question is: How would I write an OpenCV Jpeg buffer into the p.stdin object like it's being done in the Pillow version?
has comment: http://stackoverflow.com/comment/81202868
answer count: 0
has comment: http://stackoverflow.com/comment/81203900
score: 1
has comment: http://stackoverflow.com/comment/81202940
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has title: OpenCV write jpeg buffer into Popen object
has comment: http://stackoverflow.com/comment/81203444
upvote count: 2
tagged with: ffmpeg
type: UnansweredQuestion

http://stackoverflow.com/comment/81380330
comment on: http://stackoverflow.com/q/47214594
has text: This is a really good question by the way ! good job! should have generated more traffic in my opinion, hope I could help.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47171562
tagged with: python-2.7
answer count: 2
tagged with: tkinter
upvote count: 0
accepted answer: http://stackoverflow.com/a/47171579
downvote count: 3
has answer: http://stackoverflow.com/a/47171579
favorite count: 0
type: Question
has title: How to fix: NameError: name 'on_key_release' is not defined? (Python)
possible better answer: http://stackoverflow.com/a/47171638
tagged with: python
has body: I was typing in some code (as most of us do) from a book, but when I ran it, I got this error: NameError: name 'on_key_release' is not defined. I typed it in perfectly, but it still won't work, and I know that I have defined it. It may be because the book is for python3 and I have python2. The full error is: Traceback (most recent call last): File "C:\Users\caleb.sim\Downloads\Sim Inc\Sim Inc\Applications\Games\Ball and Bat\BallAndBat.py", line 97, in &lt;module&gt; window.bind("&lt;KeyRelease&gt;", on_key_release) NameError: name 'on_key_release' is not defined' Here is the code: import tkinter import time canvasWidth = 750 canvasHeight = 500 window = tkinter.Tk() canvas = tkinter.Canvas(window, width = canvasWidth, height = canvasHeight) canvas.pack() bat = canvas.create_rectangle(0, 0, 40, 10, fill="dark turquoise") ball = canvas.create_oval(20,0,30,10, fill="deep pink") windowOpen = True score = 0 bounceCount = 0 def main_loop(): while windowOpen == True: move_bat() move_ball() window.update() time.sleep(0.02) if windowOpen == True: check_game_over() leftPressed = 0 rightPressed = 0 def on_key_press(event): global leftPressed, rightPressed if event.keysym == "Left": leftPressed = 1 elif event.keysym == "Right": rightPressed = 1 def on_key_press(event): global leftPressed, rightPressed if event.keysym == "Left": leftPressed = 0 elif event.keysym == "Right": rightPressed = 0 batSpeed = 6 def move_bat(): batMove = batSpeed * rightPressed - batSpeed * leftPressed (batLeft, batTop, batRight, batBottom) = canvas.coords(bat) if (batLeft &gt; 0 or batMove &gt; 0) and (batRight &lt; canvasWidth or batMove &lt; 0): canvas.move(bat, batMove, 0) ballMoveX = 4 ballMoveY = -4 setBatTop = canvasHeight - 40 setBatBottom = canvasHeight - 30 def move_ball(): global ballMoveX, ballMoveY, score, bounceCount, batSpeed (ballLeft, ballTop, ballRight, ballBottom) = canvas.coords(ball) if ballMoveX &gt; 0 and ballRight &gt; canvasWidth: ballMoveX = -ballMoveX if ballMoveX &gt; 0 and bal…
score: -3
has comment: http://stackoverflow.com/comment/81308143
has answer: http://stackoverflow.com/a/47171638
type: AnsweredQuestion

parsing
tags question: http://stackoverflow.com/q/47187792
tags question: http://stackoverflow.com/q/47154471
tags question: http://stackoverflow.com/q/47144474
tags question: http://stackoverflow.com/q/47079615
tags question: http://stackoverflow.com/q/47184677
tags question: http://stackoverflow.com/q/47178150
tags question: http://stackoverflow.com/q/47162916
tags question: http://stackoverflow.com/q/47086372
tags question: http://stackoverflow.com/q/47075370
tags question: http://stackoverflow.com/q/47216630
tags question: http://stackoverflow.com/q/47090508
tag name: parsing
tags question: http://stackoverflow.com/q/47136376
tags question: http://stackoverflow.com/q/47126695
tags question: http://stackoverflow.com/q/47108253
tags question: http://stackoverflow.com/q/47140746
tags question: http://stackoverflow.com/q/47158559
tags question: http://stackoverflow.com/q/47157568
tags question: http://stackoverflow.com/q/47188835
tags question: http://stackoverflow.com/q/47218337
tags question: http://stackoverflow.com/q/47132966
tags question: http://stackoverflow.com/q/47117781
type: Tag

http://stackoverflow.com/comment/81123106
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47085527
has text: The output is b'U1A6RlJEQ1...

http://stackoverflow.com/a/47090421
has body: try m.group(1) m.group(0) matches the entire string. searchstring = "([A-Z0-9]*)_" basename = "AK4RAE00005_ALL_MEASUREMENT.a2l" m = re.search(searchstring, basename) if m: print m.group(1)
has comment: http://stackoverflow.com/comment/81129958
answers question: http://stackoverflow.com/q/47090396
score: 1
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47090396
type: AcceptedAnswer
type: Answer
upvote count: 1

http://stackoverflow.com/comment/81329507
comment on: http://stackoverflow.com/q/47190008
score: 0
has text: Where is your code?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81265402
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47156173
has text: @arizamoona No worries. Thanks for upvoting! On timing, try something like this - https://stackoverflow.com/a/2866456/?
type: Comment

http://stackoverflow.com/comment/81196365
has text: Thanks for the reply. I get an error "decoder = Decoder(config) File "C:\Python27\lib\site-packages\pocketsphinx\pocketsphinx.py", line 277, in __init__ this = _pocketsphinx.new_Decoder(*args) RuntimeError: new_Decoder returned -1" Is there another package I need to import?
comment on: http://stackoverflow.com/a/47122732
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81292335
comment on: http://stackoverflow.com/a/47171038
has text: Thanks. See the very end of orig question for an actual table entry for 1 camera. I have 10 of these. So not sure how to handle the `'d5': Camera(...list of properties...),` format...? Putting everything in one line for 1 camera? 10 lines for 10 cameras?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/110973080
has text: While this is good, does this guarantee transaction? Assume there is a data frame write statement after the connection, will the table still be truncated if there is some error while writing the data frame to DB? @thenaturalist
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50984173

http://stackoverflow.com/q/47147512
tagged with: switch-statement
accepted answer: http://stackoverflow.com/a/47148604
tagged with: proxies
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47148604
score: 0
upvote count: 1
has title: Switching proxies in python: Psuedo code
tagged with: python-requests
answer count: 1
downvote count: 1
favorite count: 0
has body: Lets say I have a website that I want to scrape. Ex. cheapoair.com I want to use a normal requests in python to scrape the data on the first, hypothetical page. If I end up being blocked by the server, I want to switch to a proxy. I have a list of proxy servers and a method, and I also have a list of user agent strings. However, I think I need help thinking through the problem. For reference uagen() will return a user agent string proxit() will return a proxy Here is what I have so far: import requests from proxy_def import * from http import cookiejar import time from socket import error as SocketError import sys start_time = time.time() class BlockAll(cookiejar.CookiePolicy): return_ok = set_ok = domain_return_ok = path_return_ok = lambda self, *args, **kwargs: False netscape = True rfc2965 = hide_cookie2 = False headers = {'User-Agent': uagen()} print(headers) s = requests.Session() s.cookies.set_policy(BlockAll) cookies = {'SetCurrency': 'USD'} sp = proxit() for i in range(100000000000): while True: try: print('trying on ', sp) print('with user agent headers', headers) s.proxies = {"http": sp} r = s.get("http://www.cheapoair.com", headers=headers, timeout=15, cookies=cookies) print(i, sp, 'success') print("--- %s seconds ---" % (time.time() - start_time)) except SocketError as e: print('passing ', sp) sp = proxit() headers = {'User-Agent': uagen()} print('this is the new proxy ', sp) print('this is the new headers ', headers) continue except requests.ConnectionError as e: print('passing ', sp) sp = proxit() headers = {'User-Agent': uagen()} print('this is the new proxy ', sp) print('this is the new headers ', headers) continue except requests.Timeout as e: print('passing ', sp) sp = proxit() headers = {'User-Agent': uagen()} print('this is the new proxy ', sp) print('this is the new headers ', headers) continue except KeyboardInterrupt: print("The program has been terminated") sys.exit(1) break #print(r.text) print('all done', '\n') What I am looking for is an i…
type: Question
tagged with: python

http://stackoverflow.com/a/47085913
has body: That is not a valid version number. You have to use a final version of python (as stated in Klaus D.'s comment).
type: Answer
answers question: http://stackoverflow.com/q/47085598
score: 0

http://stackoverflow.com/q/47093277
has title: Inconsistent python rounding to two decimal places
has comment: http://stackoverflow.com/comment/81136738
downvote count: 0
linked to: http://stackoverflow.com/q/10825926
upvote count: 1
has comment: http://stackoverflow.com/comment/81136489
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81136655
duplicate of: http://stackoverflow.com/q/10825926
tagged with: rounding
type: UnansweredQuestion
tagged with: python
has body: What am I doing wrong? &gt;&gt;&gt; round(2.5), round(0.25, 1), round(0.025, 2) (3.0, 0.3, 0.03) &gt;&gt;&gt; round(4.5), round(0.45, 1), round(0.045, 2) (5.0, 0.5, 0.04) Why is 0.025 rounded to 0.03 (up), but 0.045 to 0.04 (down)? Using Python2.7 on OSX: Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
has comment: http://stackoverflow.com/comment/81136545
answer count: 0
score: 1

http://stackoverflow.com/comment/81243041
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47146248
has text: @Wiktor Stribiżew I am not asking to convert that code. It's a question if Python has an equivalent for that functionality. I can convert to Python myself once I know if it's possible to achieve this in Python.
score: 0

http://stackoverflow.com/comment/81345408
comment on: http://stackoverflow.com/q/47198365
has text: groups in groups ??? change to something group in groups
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47068468
has comment: http://stackoverflow.com/comment/81084855
possible better answer: http://stackoverflow.com/a/47068708
type: Question
has answer: http://stackoverflow.com/a/62204900
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47068650
has answer: http://stackoverflow.com/a/47068708
tagged with: python
upvote count: 6
tagged with: sklearn-pandas
has body: I label encoded my categorical data into numerical data using label encoder data['Resi'] = LabelEncoder().fit_transform(data['Resi']) But I when I try to find how they are mapped internally using list(LabelEncoder.inverse_transform(data['Resi'])) I am getting below error TypeError Traceback (most recent call last) &lt;ipython-input-67-419ab6db89e2&gt; in &lt;module&gt;() ----&gt; 1 list(LabelEncoder.inverse_transform(data['Resi'])) TypeError: inverse_transform() missing 1 required positional argument: 'y' How to fix this Sample data Resi IP IP IP IP IP IE IP IP IP IP IP IPD IE IE IP IE IP IP IP
has comment: http://stackoverflow.com/comment/81084936
tagged with: numpy
type: AnsweredQuestion
has title: Reverse Label Encoding giving error
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/47068650
tagged with: scikit-learn
score: 6
favorite count: 0

http://stackoverflow.com/q/47076650
tagged with: python
has comment: http://stackoverflow.com/comment/81108758
tagged with: boto
has comment: http://stackoverflow.com/comment/81102144
score: 0
has comment: http://stackoverflow.com/comment/81102718
has answer: http://stackoverflow.com/a/70662449
has comment: http://stackoverflow.com/comment/81101657
answer count: 1
type: Question
tagged with: amazon-sqs
has body: I am using python and boto sqs for sending and receiving the message , Now I wanted to send the message to aws FIFO queue , but I don't find any resource of how to set the MessageGRoupID using the boto,there are plenty of resource available for sending message using boto3 , but I wanted to set the message group Id using the boto , can anyone help , my Current code is : def _send_msg_to_Fifo_queue(queue_name,message_body,message_groupID,message_DeduplicationId): q = conn.get_queue(queue_name) if not q: # TODO idk, this should never happen, but log or something? pass m=Message() m.set_body(message_body) m.MessageGroupID=message_groupID q.write(m)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81103775
has title: Trying to Send the message from to Amazon SQS

http://stackoverflow.com/a/47126917
downvote count: 0
upvote count: 1
has body: For Selenium, one good way to test is build a plain HTML page that only contains what you want (For example, a h3) and mimic the scenario. I don't really know your problem but one changes that you can try is presence_of_element_located will return true if it is in the DOM, that means it is not necessary visible, this might be the reason for it to quit immediately. Try changing to visibility_of_element_located Hope it helps!
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47126559
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47126559

http://stackoverflow.com/q/47148894
score: 2
downvote count: 0
has title: Django Rest Framework ModelSerializer create if not exists
favorite count: 0
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I'm using Django Rest Framework 3.6.3. I'm trying to write nested create serializers for one optional argument and one required argument inside a child. I know that I need to override create in the base serializer to tell DRF how to create the nested children - http://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers. However, I can't figure out how to get it to parse the object information without telling it what the nested child serializer is defined as. Doing that then causes DRF to use it to parse the children objects, which then returns a validation error that I have no control over because the child serializer doesn't call its create method. Base Specification(many=True) OptionalField RequiredField The information I pass in is a JSON object: { base_id: 1, base_info: 'blah' specifications: [ { specification_id: 1, optional_info: { optional_id: 1, optional_stuff: 'blah' }, required_info: { required_id: 1, required_stuff: 'required', } } ] } The BaseCreationSerializer calls it's create method. I know that I need to pull out the rest of the information and create it manually. However, I can't figure out how to get the BaseCreationSerializer to parse the data into validated_data without defining specification = SpecificationCreationSerializer(), which then tries to parse that and throws an error. Printing self shows the entire JSON object in data, but then validated_data only contains the subset of things that the serializer knows about. How do I parse the appropriate things from data so that I can create the objects on my own?
tagged with: django-rest-framework

http://stackoverflow.com/comment/81350981
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47201202
has text: Maybe try putting your big values for `t0` and `t_end` directly into your test to see if it's the values that pose a problem or something else? (like you do in your second example)

http://stackoverflow.com/a/47109530
type: Answer
has body: You will have to call configure_logging with install_root_handler=False as described in https://doc.scrapy.org/en/latest/topics/logging.html#module-scrapy.utils.log. import logging from logging.handlers import RotatingFileHandler from scrapy.utils.log import configure_logging # Disable default Scrapy log settings. configure_logging(install_root_handler=False) # Define your logging settings. log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' log_level = logging.INFO # Or better yet get `LOG_LEVEL` from settings. log_file = 'log.log' # Or better yet get `LOG_FILE` from settings. logging.basicConfig( format=log_format, level=log_level ) rotating_file_log = RotatingFileHandler(log_file, maxBytes=1024, backupCount=1) rotating_file_log.setFormatter(logging.Formatter(log_format)) root_logger = logging.getLogger() root_logger.addHandler(rotating_file_log) This way you will log to console (as per the basicConfig default settings; though, this handler can be removed) and to rotating file(s).
answers question: http://stackoverflow.com/q/47105544
score: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47105544
upvote count: 5

http://stackoverflow.com/a/47102802
answers question: http://stackoverflow.com/q/47102727
type: Answer
score: 0
has body: You don't need to include the temperatureList parameter to your constructor - you're going to assign the return value of loadTemperatureData() to it regardless of the value of that parameter, so you can discard it entirely. On an unrelated note, I think you want to assign the return value of self.loadTemperatureData(filename) to temperatureList so it'd look something like def __init__(self, filename): self.__filename = filename self.temperatureList = self.loadTemperatureData(self.__filename) Also, your loadTemperatureData is defined inside another function - so this code won't work if your class actually looks like the one you've included in the question.

http://stackoverflow.com/comment/98426161
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/54686096
score: 0
has text: use this open source github code for any tye of steaming... https://github.com/umbrashia/power-streaming-project

http://stackoverflow.com/comment/81193719
type: Comment
score: 0
has text: Yep, like i said, obvious mistake. Thank you
type: QuestionComment
comment on: http://stackoverflow.com/q/47122028

http://stackoverflow.com/a/47147586
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47146886
accepted answer of: http://stackoverflow.com/q/47146886
score: 1
has body: I don't see what the problem is. The statement you want to execute last is currently present in the function 'path_finder' which is why it is running every time. To make this run only once and after the for loop is finished, put the statement after it. for table in input: path_finder( table, mysql_user, user, dir, ) subprocess.call(["cp", Linux_path, New_path]) This should do it.

http://stackoverflow.com/q/47064885
has comment: http://stackoverflow.com/comment/81078067
tagged with: python
has answer: http://stackoverflow.com/a/47065088
has comment: http://stackoverflow.com/comment/81078108
has comment: http://stackoverflow.com/comment/81078135
type: Question
possible better answer: http://stackoverflow.com/a/58730468
has body: I am trying to list all the factors of a number called count. Whenever I run it, it returns 1. For example: if 6 = count, then what should be returned when calling findFactor(6) is 1 2 3 6. What is returned is 1 divisors = "" def findFactor(count): divisors = "" valueD = 0 for i in range(1, count+1): valueD = count/i if isinstance(valueD,int) == True: divisors = str(valueD)+" " print divisors
has comment: http://stackoverflow.com/comment/81078225
has comment: http://stackoverflow.com/comment/81078202
downvote count: 0
has answer: http://stackoverflow.com/a/62961757
has answer: http://stackoverflow.com/a/58730468
upvote count: 1
has answer: http://stackoverflow.com/a/47087033
has title: List all factors of number
has comment: http://stackoverflow.com/comment/81078100
favorite count: 0
has comment: http://stackoverflow.com/comment/81078077
tagged with: factors
has comment: http://stackoverflow.com/comment/81078132
has answer: http://stackoverflow.com/a/47065107
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47065107
has comment: http://stackoverflow.com/comment/81078168
has comment: http://stackoverflow.com/comment/81078057
has comment: http://stackoverflow.com/comment/81078005
answer count: 5
has comment: http://stackoverflow.com/comment/81078146
has comment: http://stackoverflow.com/comment/81078230
score: 1

http://stackoverflow.com/comment/81078135
score: 0
comment on: http://stackoverflow.com/q/47064885
type: Comment
has text: @juanpa.arrivillaga how would I fix it? is there a way to tell if it is a double or an int
type: QuestionComment

http://stackoverflow.com/comment/81147621
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47098470
has text: I tried `fig = plt.figure(figsize=(6, 12)); fig.add_axes(fig.add_axes(test_df.plot.box()))`, but I get `ValueError: The Axes must have been created in the present figure`.
score: 0

http://stackoverflow.com/comment/81095901
type: Comment
score: 0
type: AnswerComment
has text: @MaartenFabré I want it to iterate until first valid occurrence. By using a generator I can achieve that. `next(columnType(columna),'undetermined')` gives me the first valid occurrence of `columnType(columna)` and if it can't be found it gives me the fallback `'undetermined'`.
comment on: http://stackoverflow.com/a/47073633

http://stackoverflow.com/q/47116572
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47116956
type: Question
upvote count: 2
score: 2
downvote count: 0
tagged with: python
answer count: 1
tagged with: jinja2
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: template-engine
has body: I want to design my own HTML template with tags like JSP or Jade and then pass data from python to it and let it generate full html page. I don't want to construct document at python side like with DOM. Only data goes to page and page tempalte decides, how data lays out. I don't want to serve resulting pages with HTTP, only generate HTML files. Is it possible? UPDATE I found Jinja2, but I has strange boilerplate requirements. For example, they want me to create environment with env = Environment( loader=PackageLoader('yourapplication', 'templates'), autoescape=select_autoescape(['html', 'xml']) ) while saying that package yourapplication not found. If I remove loader parameter, it complains on line template = env.get_template('mytemplate.html') saying no loader for this environment specified Can I just read template from disk and populate it with variables, without extra things?
has title: Generate HTML from HTML template in python?
favorite count: 0
accepted answer: http://stackoverflow.com/a/47116956

http://stackoverflow.com/q/47141503
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/47141663
downvote count: 0
has comment: http://stackoverflow.com/comment/81232833
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81233068
has body: I am using flask, here giving example, what I want to do. I copied code from flask portal. from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' Running the app (py35) root@localhost:tmp root$ flask run * Serving Flask app "hello" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Send request root@localhost:~ root$ curl http://localhost:5000/ Hello, World! I modify my function and change it to raise error. @app.route('/') def hello_world(): print(xyz) return 'Hello, World!' When i try to send request, it failed [2017-11-06 10:22:13,625] ERROR in app: Exception on / [GET] Traceback (most recent call last): File "/py35/lib/python3.5/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/py35/lib/python3.5/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/py35/lib/python3.5/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/Users/nile2691/sbdev/StorageCenterUI/.tox/py35/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise raise value File "/py35/lib/python3.5/site-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "py35/lib/python3.5/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/private/tmp/hello.py", line 6, in hello_world print(xyz) NameError: name 'xyz' is not defined I have can add try...except in my code, but in real code, its in many place, and I dont want to handle this general exception everywhere. Is there any way like try: process_flask_request() except Exception as ex: # Log detail exception logger.exception(ex) return "Custome error message for all general exception" With this changes, instead of getting general error like below curl http://localhost:5000/ 500 Internal Server Error Internal Server Error The serve…
tagged with: flask
has title: How to handle general exception in flask at single place?
favorite count: 0
accepted answer: http://stackoverflow.com/a/47141663
type: AnsweredQuestion
tagged with: exception
score: 1

http://stackoverflow.com/comment/81207972
comment on: http://stackoverflow.com/q/47128812
score: 0
type: Comment
has text: You see, that’s what i thought. And then it matched in the loop. If constructed regex doesn’t match anything, why does it work there?
type: QuestionComment

http://stackoverflow.com/q/47183635
score: 0
answer count: 1
tagged with: django
type: AnsweredQuestion
has title: get_user_model() returns all my users
has answer: http://stackoverflow.com/a/47183783
tagged with: python
has comment: http://stackoverflow.com/comment/81316350
has comment: http://stackoverflow.com/comment/81316446
accepted answer: http://stackoverflow.com/a/47183783
type: Question
has body: I am trying to link only one user at a time to my model. But I am using many to many because I want to enable the option to link multiple users at a time in the future. When I run this code it assigns all my users to the Company model, I need it to assign only one. Any help will be appreciated. Model: class Company(models.Model): user = models.ManyToManyField(get_user_model()) name = models.CharField(max_length=265) def __str__(self): return self.name def get_absolute_url(self): return reverse('nodisoapp:home') View class CreateCompany(LoginRequiredMixin, generic.CreateView): login_url = '/scrty/login/' form_class = forms.Companyform template_name = 'nodiso/create_company.html' Form class Companyform(forms.ModelForm): class Meta: model = models.Company fields = ['name']

http://stackoverflow.com/a/47196606
downvote count: 0
has comment: http://stackoverflow.com/comment/81344100
upvote count: 1
has comment: http://stackoverflow.com/comment/81343047
answers question: http://stackoverflow.com/q/47196391
has comment: http://stackoverflow.com/comment/81343308
has comment: http://stackoverflow.com/comment/81342717
has comment: http://stackoverflow.com/comment/81342527
type: Answer
has comment: http://stackoverflow.com/comment/81343858
has comment: http://stackoverflow.com/comment/81344424
has body: I think it can be done like this: sqlQuery = "SELECT a.xval, a.yval,b.pid,pxval,b.pyval from table1 as a, (select t1.id as pid,pxval,pyval from &lt;tbl1&gt; t1 left join ( select * from &lt;tbl2&gt; where clubid="+clubid+") t2 on t1.id=t2.projectid where t1.cityid in ( SELECT cityid FROM &lt;tbl3&gt; WHERE cbdid ="+cbdid+" group by cityid) and t1.pxval&gt;0 and t2.distance is null order by projectid) as b WHERE a.DOMID="+dom_id[i]+" cursor.execute(sqlQuery) This will give required data from both the table. NOTE: If both tables has different row count then tell will be NULL values you can check for that using some condition in your code. If you want to add this on a single execute, try this: cursor.execute("SELECT a.xval, a.yval,b.pid,b.pxval,b.pyval from table1 as a, (select t1.id as pid,pxval,pyval from table2 t1 left join (select * from table3 where clubid=?) t2 on t1.id=t2.pid where t1.cityid in (SELECT cityid FROM table1 WHERE domid = ? group by cityid) and t1.pxval&gt;0 and t2.distance is null order by pid) as b WHERE a.DOMID=?",dom_id[i],dom_id[i],dom_id[i]) Hope this helps.
has comment: http://stackoverflow.com/comment/81343964
has comment: http://stackoverflow.com/comment/81344236
accepted answer of: http://stackoverflow.com/q/47196391
has comment: http://stackoverflow.com/comment/81344762
score: 1
has comment: http://stackoverflow.com/comment/81342816
type: AcceptedAnswer

http://stackoverflow.com/q/47209287
has comment: http://stackoverflow.com/comment/81368101
tagged with: python
has comment: http://stackoverflow.com/comment/81367974
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81367698
accepted answer: http://stackoverflow.com/a/47209603
has title: How to replace super().__str___?
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/47209603
linked to: http://stackoverflow.com/q/47201846
has body: Day! I was answering the post and try to create Class where __str__ is replaced with my __str__ like that: from decimal import * class Zar(Decimal): def __init__(self, z): self.__z = Decimal(z) def __str__(self): return 'R{!r}'.format(self.__z) def __repr__(self): return 'R{!r}'.format(self.__z) z1 = Zar(3.62) z2 = Zar(4.12) z = Zar(z1 + z2) print('{:.3f}'.format(z)) print(z) I expected output like R7.740 but it does not work. Please - say - how to reload str method for standard class?? It so boring to do all +-/* ... methods Now I have output: 7.740 RDecimal('7.740000000000000213162820728')
upvote count: 1
has comment: http://stackoverflow.com/comment/81368297
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81367778
has comment: http://stackoverflow.com/comment/81367708
score: -2

http://stackoverflow.com/a/47173093
type: Answer
score: 4
has body: Edit: It seems I misread your question. This solution is meant to remove any element that has 'id' in it, not just the first. Option 1 I believe the most straightforward solution is using apply: df col 0 [a_id, b, c, d] 1 [d_ID, e, f] 2 [h, i, j, k, l] 3 [id_m, n, o, p] 4 [ID_q, r, s] df.col = df.col.apply(lambda y: (y[1:] if 'id' in y[0].lower() else y)) df col 0 [b, c, d] 1 [e, f] 2 [h, i, j, k, l] 3 [n, o, p] 4 [r, s] Option 2 Alternatively, use a list comprehension: df.col = [(y[1:] if 'id' in y[0].lower() else y) for y in df.col] df col 0 [b, c, d] 1 [e, f] 2 [h, i, j, k, l] 3 [n, o, p] 4 [r, s] Timings df = pd.concat([df] * 100000) %%timeit m = df['col'].str[0].str.contains('ID', case=False) df['col'].mask(m, df['col'].str[1:]) 1 loop, best of 3: 917 ms per loop %timeit [(y[1:] if 'id' in y[0].lower() else y) for y in df.col] 1 loop, best of 3: 272 ms per loop %timeit df.col.apply(lambda y: (y[1:] if 'id' in y[0].lower() else y)) 1 loop, best of 3: 309 ms per loop
has comment: http://stackoverflow.com/comment/81296349
has comment: http://stackoverflow.com/comment/81295520
answers question: http://stackoverflow.com/q/47173057
has comment: http://stackoverflow.com/comment/81295817
downvote count: 0
upvote count: 4
has comment: http://stackoverflow.com/comment/81295735

http://stackoverflow.com/q/47189194
has title: break function does not work when the correct password and username are entered from the file
has comment: http://stackoverflow.com/comment/81327968
answer count: 2
has comment: http://stackoverflow.com/comment/81328842
has comment: http://stackoverflow.com/comment/81327844
downvote count: 0
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/47189350
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81327771
possible better answer: http://stackoverflow.com/a/47189326
has body: Break function does not work when I enter the correct username and password from the file. The words 'access to something special' print infinitely. How do I fix this? I want the program to start again if the user enters the password/username wrong. content2=input('Username:') content=input('Password:') while True: file=open('username1.txt','r') data1 =file.read() file.close() file1=open('password1.txt','r') data2 =file1.read() file1.close() data1 = data1.split("\n") data2 = data2.split("\n") for i in range(len(data1)): if data1[i] == content2 and data2[i] == content: print('You have access to something special.') break else: print('Access denied.')
has answer: http://stackoverflow.com/a/47189326
tagged with: python
has comment: http://stackoverflow.com/comment/81327789
has comment: http://stackoverflow.com/comment/81328459
has answer: http://stackoverflow.com/a/47189350
type: AnsweredQuestion

http://stackoverflow.com/q/47082466
has answer: http://stackoverflow.com/a/47086132
score: 3
upvote count: 3
tagged with: matplotlib
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/81116808
has body: In the following example when I hover the cursor over the image, as well as the text I want displaying in the bottom left corner, there is also the gray scale value of the corresponding pixel. Is there a way to suppress this information (or format it)? import numpy as np import matplotlib.pyplot as plt class test(): def __init__(self): fig=plt.figure() ax=fig.add_subplot(111) ax.imshow(np.random.rand(20,20)) def format_coord(x,y): return "text_string_made_from(x,y)" ax.format_coord=format_coord fig.canvas.draw()
type: Question
has title: matplotlib imshow formatting from cursor position
tagged with: python
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/81160401
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47104894
has text: your `for` loops are not nested, they're sequential
type: Comment

http://stackoverflow.com/a/47084256
has comment: http://stackoverflow.com/comment/81123433
has comment: http://stackoverflow.com/comment/81119456
has comment: http://stackoverflow.com/comment/81118897
has comment: http://stackoverflow.com/comment/81122481
has comment: http://stackoverflow.com/comment/81119640
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/81119636
has comment: http://stackoverflow.com/comment/81123494
has comment: http://stackoverflow.com/comment/81123381
has comment: http://stackoverflow.com/comment/81119781
has body: You can try this: s = ['hello','hullo','zeros'] final_data = [{d:''.join(i).count(d) for d in ''.join(i)} for i in zip(*s)] Output: [{'h': 2, 'z': 1}, {'u': 1, 'e': 2}, {'r': 1, 'l': 2}, {'l': 2, 'o': 1}, {'s': 1, 'o': 2}] Edit: functional method: def get_count(the_index, the_list): listing = [i[the_index] for i in the_list] return {a:listing.count(a) for a in listing}
has comment: http://stackoverflow.com/comment/81118911
answers question: http://stackoverflow.com/q/47084190
score: 1
type: Answer

http://stackoverflow.com/q/47078250
has body: in my application, i need to perform multiplication of a very large data frame with a large full_allocation_multiidx_pd.shape (32892090, 10) weights_and_time_series.shape (30839760,) by doing full_allocation_multiidx_pd.multiply(weights_and_time_series,axis=0) I realize pandas multiplication only used 1 core of my 16 cores. I think if it becomes a MPI process it would be much faster. Are there any pandas way to enable multiprocess? Or do I have to hard code something myself? Thank you.
type: Question
has comment: http://stackoverflow.com/comment/81105214
tagged with: python
has comment: http://stackoverflow.com/comment/81105292
score: 0
has title: enabling multiprocess for pandas data frame multiplication
answer count: 0
tagged with: pandas
type: UnansweredQuestion

http://stackoverflow.com/comment/82704666
score: 4
has text: please, add an answer if you have found a way to do it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47120376

http://stackoverflow.com/a/47163348
answers question: http://stackoverflow.com/q/47162455
type: Answer
has body: manager_name = raw_input("please enter managers Name: ") email_address = raw_input("please enter your Email Address: ") phone_number = raw_input("please enter your Phone number: ") print("-----------------------------------------------------") print ("Our Stuido can Accommodate up to max 8 musicians") print("-----------------------------------------------------") amount_of_band_members = int(raw_input("please enter the amount of band members")) if amount_of_band_members &gt;8: print ("Sorry we can only Accommodate maxuim 8 Musicians") else : print raw_input("please enter musicians and insterments") while amount_of_band_members &lt;8: print raw_input("please enter next name") amount_of_band_members +=1
score: 0

tcpsocket
tags question: http://stackoverflow.com/q/47107754
type: Tag
tag name: tcpsocket

http://stackoverflow.com/comment/81342757
has text: did you install pyOpenSSL?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47197083
type: Comment

http://stackoverflow.com/q/47145070
has title: TypeError when using mergesort on large amounts of data (python)
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81240407
answer count: 1
tagged with: mergesort
accepted answer: http://stackoverflow.com/a/47145188
has answer: http://stackoverflow.com/a/47145188
type: Question
has body: So, I want to make a benchmark and compare different algorithm's processing speed on different size arrays. I have the following script which is supposed to use mergeSort on size 10, 100, 1000, 10000, 100000, 1000000 input arrays: import sys import time import random def merge(arr, l, m, r): n1 = m - l + 1 n2 = r- m # create temp arrays L = [0] * (n1) R = [0] * (n2) # Copy data to temp arrays L[] and R[] for i in range(0 , n1): L[i] = arr[l + i] for j in range(0 , n2): R[j] = arr[m + 1 + j] # Merge the temp arrays back into arr[l..r] i = 0 # Initial index of first subarray j = 0 # Initial index of second subarray k = l # Initial index of merged subarray while i &lt; n1 and j &lt; n2 : if L[i] &lt;= R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Copy the remaining elements of L[], if there # are any while i &lt; n1: arr[k] = L[i] i += 1 k += 1 # Copy the remaining elements of R[], if there # are any while j &lt; n2: arr[k] = R[j] j += 1 k += 1 # l is for left index and r is right index of the # sub-array of arr to be sorted def mergeSort(arr,l,r): if l &lt; r: # Same as (l+r)/2, but avoids overflow for # large l and h m = (l+(r-1))/2 # Sort first and second halves mergeSort(arr, l, m) mergeSort(arr, m+1, r) merge(arr, l, m, r) data = [] L10 = [] L100 = [] L1000 = [] L10000 = [] L100000 = [] L1000000 = [] inf = open("10.txt", "r") inputData = inf.readlines() for line in inputData: L10.append(int(line.rstrip())) data.append(L10) inf = open("100.txt", "r") inputData = inf.readlines() for line in inputData: L100.append(int(line.rstrip())) data.append(L100) inf = open("1000.txt", "r") inputData = inf.readlines() for line in inputData: L1000.append(int(line.rstrip())) data.append(L1000) inf = open("10000.txt", "r") inputData = inf.readlines() for line in inputData: L10000.append(int(line.rstrip())) data.append(L10000) inf = open("100000.txt", "r") inputData = inf.readlines() for line in inputData: L100000.append(int(line.rstrip())) data.append(L100000) inf …

http://stackoverflow.com/q/47076707
type: UnansweredQuestion
tagged with: loss-function
tagged with: python
score: -1
has body: I am trying to modify a bit the loss function of my convent and I have some questions from the implementation side. I already know how to create a custom loss function in Keras, and how to call it. But I still do not have clear where to include the derivative of the function. Let's say that my new loss function is: Loss = cross-entropy + f(x) where f(x) = x**2. Where should I include f'(x)=2x so that it is used in the back-prop step? Does Keras automatically do that? Or should I define this explicitly in some part? Thanks for any hint on this, since I do not know how to do it. Chuan.
tagged with: objective-function
tagged with: deep-learning
upvote count: 0
has answer: http://stackoverflow.com/a/47077135
answer count: 1
has title: Keras: custom objective function, where to put the derivative
tagged with: keras
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/47147748
score: 1
tagged with: matplotlib
tagged with: python
has body: I'm pretty new with matplotlib and I tried to write a class to open and close image through matplotlib, here is the code: import matplotlib matplotlib.use("TkAgg") import matplotlib.pyplot as plt class ptlShow(): def __init__(self, file, pos): plt.rcParams['toolbar'] = 'None' fig, ax = plt.subplots(figsize=(1, 1.4)) fig.subplots_adjust(0, 0, 1, 1) ax.axis("off") im = plt.imread(file) ax.imshow(im) fig.canvas.manager.window.overrideredirect(1) plt.get_current_fig_manager().window.wm_geometry(pos)# plt.show() def close(self): plt.close a = ptlShow('1.jpg', '+700+100') b = ptlShow('2.jpg', '+500+100') a.close() b.close() but finally I have only one instance of image and close doesn't work, what I'm doing wrong ! Thanks!
tagged with: image
type: Question
has title: python matplotlib how to open an image with class
accepted answer: http://stackoverflow.com/a/47147865
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47147865
upvote count: 1
favorite count: 0
tagged with: class
type: AnsweredQuestion

http://stackoverflow.com/comment/83032498
score: 0
type: Comment
type: QuestionComment
has text: I had the same problem two days ago. When I came out of virtual environment, the binary/exe was running successfully!! I'm suspicious that `from distutils.version import LooseVersion` is the culprit. I've seen with multiple libraries. I still don't know what is the solution with virtual env. If you found a solution please do share :)
comment on: http://stackoverflow.com/q/47146196

http://stackoverflow.com/comment/81150664
has text: This would probably work as well. I have no problem using numpy for this and it solved the problem. Signed and unsigned is not relevant here as it is in practice just a binary number used in AES encryption. It does not need a numerical representation. Java shows it as signed but it does not matter.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47100309
score: 0

http://stackoverflow.com/comment/81118200
has text: So in your second loop, just loop over the iterable, no need for a while and a sentinel, right?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47084046
score: 0

http://stackoverflow.com/comment/81127297
type: QuestionComment
comment on: http://stackoverflow.com/q/47088969
score: 0
has text: can you fix Indentation first?
type: Comment

http://stackoverflow.com/comment/81186829
score: 2
type: Comment
type: QuestionComment
has text: There are at least a couple of simple ways of doing this. but if you are having trouble working with square brackets, what you really need is an introductory Python tutorial.
comment on: http://stackoverflow.com/q/47118470

http://stackoverflow.com/comment/81163818
comment on: http://stackoverflow.com/a/47105000
score: 0
type: AnswerComment
has text: I see...Thank you!!
type: Comment

http://stackoverflow.com/a/47147884
has body: Your "list" is not a list and will yield an error. You also have to keep track of which listbox the selection number is from. A simple modification to show the concept. from tkinter import * from functools import partial class MyApp: def __init__(self, parent): self.myParent = parent #the root self.listbox_instances=[] #select setup list_of_choices = [["Setup 1","Blue Setup","Setup 12","Broken Setup", "Noise Generator"], ["test 2a", "test 2b", "test 2c"], ["test 3a", "test 3b", "test 3c"],] msg = "Select Setup" ##self.SVAL = 0; for ctr in range(3): self.Sframe = Frame(parent) self.Sframe.grid(row=0, column=ctr) self.Slabel = Label(self.Sframe,text=msg) self.Slabel.pack() self.Sbox = Listbox(self.Sframe) for item in list_of_choices[ctr]: self.Sbox.insert(END,item) self.Sbox.pack() self.listbox_instances.append(self.Sbox) ## send the listbox number with the command call self.Sbut = Button(self.Sframe,text="select", command=partial(self.Sselect, ctr)) self.Sbut.pack() self.Smess = Message(self.Sframe,text="Go") self.Smess.pack() def Sselect(self, this_num): print("box_num=%d &amp; item num=%s" % (this_num, self.listbox_instances[this_num].curselection())) ## self.SVAL = self.Sbox.curselection() ## self.Smess.configure(text=self.Sbox.get(self.SVAL[0])) root = Tk() myapp = MyApp(root) root.mainloop()
answers question: http://stackoverflow.com/q/47146805
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47146805
type: Answer

http://stackoverflow.com/q/47112826
tagged with: python
has answer: http://stackoverflow.com/a/47112875
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47112869
tagged with: distance-matrix
answer count: 2
has answer: http://stackoverflow.com/a/47112869
tagged with: matrix
score: 0
possible better answer: http://stackoverflow.com/a/47112875
type: Question
has body: I am trying to store the distances between all given documents into a matrix of distances. This is my code: dists = [] #a matrix of distances i=0 for row in self.matrix: current_row = row document_distances = [] # build list with possibilities for every document in labels for label in self.labels: document_distances.append((1 - self.row_distance(current_row, label), label)) dists[i] = document_distances #[(0.22529600444665132, 'Doc1'), (0.22952074233187614, 'Doc2'), (0.289625872768411, 'Doc3'), ...] i += 1 print(dists) But after running the code I get the following error: IndexError: list assignment index out of range Can anyone please tell me what should I change so that my code would work?
has title: How to store distance values with labels into a matrix of distances?

http://stackoverflow.com/comment/81323061
comment on: http://stackoverflow.com/q/47160098
score: 0
type: Comment
has text: Again. What do you want `print("Test String")` to do that it doesn't? no matter if buffered or not, the output will be the same.
type: QuestionComment

beautifulsoup
tags question: http://stackoverflow.com/q/47186825
tags question: http://stackoverflow.com/q/47115771
tags question: http://stackoverflow.com/q/47141049
tags question: http://stackoverflow.com/q/47181567
tags question: http://stackoverflow.com/q/47209301
tags question: http://stackoverflow.com/q/47105557
type: Tag
tags question: http://stackoverflow.com/q/47083094
tags question: http://stackoverflow.com/q/47066666
tags question: http://stackoverflow.com/q/47199211
tags question: http://stackoverflow.com/q/47161156
tags question: http://stackoverflow.com/q/47110263
tags question: http://stackoverflow.com/q/47089570
tags question: http://stackoverflow.com/q/47157423
tags question: http://stackoverflow.com/q/47168489
tags question: http://stackoverflow.com/q/47126505
tags question: http://stackoverflow.com/q/47116178
tags question: http://stackoverflow.com/q/47149056
tags question: http://stackoverflow.com/q/47216768
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/47071120
tags question: http://stackoverflow.com/q/47093283
tags question: http://stackoverflow.com/q/47163072
tags question: http://stackoverflow.com/q/47099741
tags question: http://stackoverflow.com/q/47138501
tags question: http://stackoverflow.com/q/47197187
tags question: http://stackoverflow.com/q/47100398
tags question: http://stackoverflow.com/q/47129592
tags question: http://stackoverflow.com/q/47221859
tags question: http://stackoverflow.com/q/47092107
tags question: http://stackoverflow.com/q/47150234
tags question: http://stackoverflow.com/q/47112401
tags question: http://stackoverflow.com/q/47135922
tags question: http://stackoverflow.com/q/47138884
tags question: http://stackoverflow.com/q/47087508
tags question: http://stackoverflow.com/q/47137551
tags question: http://stackoverflow.com/q/47158548
tags question: http://stackoverflow.com/q/47172262
tags question: http://stackoverflow.com/q/47218100
tags question: http://stackoverflow.com/q/47133737
tags question: http://stackoverflow.com/q/47094900
tags question: http://stackoverflow.com/q/47120642
tags question: http://stackoverflow.com/q/47108295
tags question: http://stackoverflow.com/q/47182055
tags question: http://stackoverflow.com/q/47194378
tags question: http://stackoverflow.com/q/47192452
tags question: http://stackoverflow.com/q/47192202
tags question: http://stackoverflow.com/q/47076883
tags question: http://stackoverflow.com/q/47182733
tags question: http://stackoverflow.com/q/47115574
tags question: http://stackoverflow.com/q/47106878
tags question: http://stackoverflow.com/q/47108253
tags question: http://stackoverflow.com/q/47168022
tags question: http://stackoverflow.com/q/47216684
tags question: http://stackoverflow.com/q/47086605
tags question: http://stackoverflow.com/q/47104192
tags question: http://stackoverflow.com/q/47200845
tags question: http://stackoverflow.com/q/47203650
tags question: http://stackoverflow.com/q/47174004
tags question: http://stackoverflow.com/q/47212113
tags question: http://stackoverflow.com/q/47192182

http://stackoverflow.com/comment/81183175
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47116552
score: 0
has text: Using `repr(payload)` gives a more helpful string including type information

http://stackoverflow.com/a/47149126
answers question: http://stackoverflow.com/q/47144329
type: Answer
has body: First of all, I'm not sure if your code does what you describe in your question. Secondly, it takes (much) less than second to process 12,000 random numbers. Regardless, it can be sped up by not calling min() and max() on the numlist every time a new element is appended to it. Instead you can just update the current minimum and maximum variables with a couple of if statements. Here code showing that being done, along with a simple framework I wrote for timing performance: def getLength(T, N, numbers): max_length = 1 for i in range(N-1): start = numbers[i] numlist = [start] min_numlist = max_numlist = start # Added variables. for j in range(i+1, N): end = numbers[j] numlist.append(end) # Inefficient - replaced. # if (max(numlist) - min(numlist)) &gt; T: # break # Update extremities. if end &gt; max_numlist: max_numlist = end if end &lt; min_numlist: min_numlist = end if max_numlist-min_numlist &gt; T: break if j-i+1 &gt; max_length: max_length = j-i+1 return max_length if __name__ == '__main__': import random import time random.seed(42) # Use hardcoded seed to get same numbers each time run. T = 100 N = 12000 numbers = [random.randrange(1000) for _ in range(N)] starttime = time.time() max_length = getLength(T, N, numbers) stoptime = time.time() print('max length: {}'.format(max_length)) print('processing {:,d} elements took {:.5f} secs'.format(N, stoptime-starttime))
score: 0

http://stackoverflow.com/comment/86648051
type: AnswerComment
comment on: http://stackoverflow.com/a/48837789
has text: Thanks I came across that, will be playing around with it, I may actually pick up one of those TI CAN simulators to just learn more, really fun stuff! Thanks again for all your input, much appreciated kind sir!
type: Comment
score: 0

http://stackoverflow.com/comment/81118079
comment on: http://stackoverflow.com/q/47084342
type: Comment
type: QuestionComment
has text: You programmed a recursion inside the child class and `rMontant` is not modified , so the maximum recursion depth is reached.
score: 0

http://stackoverflow.com/q/47115164
has body: What I'm trying to do: Translate input -> pig latin onclick and display output. See code below: class translator: def pigLatin(sentence): translation = " " for word in sentence.split(): if word[0] in "aeiou": translation += word + "yay " if word[0] and word[1] not in "aeiou": translation += word[2:] + word[0:2] + "ay" print("hai") else: translation += word[1:] + word[0] + "ay " return translation sentence = input("Enter word/sentence you want translated to pig latin below: ") print(pigLatin(sentence)) What's happening: As soon as I run my local server, the above input prompt ^ appears in console, as seen below: translator running in console Problem being, I want this to appear in my browser onclick. Instead, when I click my "translate" button, it just repeats my translate div in the output section. (see below image for clarity.) translator in browser Other relevant code/file structure: Views.py from django.shortcuts import render from django.http import HttpResponse from pigLatinApp import pigLatinTranslator def index(request): return render(request, 'pigLatinApp/home.html') def output(request): if request.is_ajax(): py_obj = pigLatinTranslator.translator return render(request, 'pigLatinApp/home.html', {'output': py_obj}) Templates header.html Pig Latin Translator {% load staticfiles %} {% block content %} {% endblock %} home.html {% extends "pigLatinApp/header.html" %} {% block content %} Pig Latin Translator Enter below what you want translated! Translate {% endblock %}
has title: Django project printing to console instead of browser
score: 0
answer count: 1
tagged with: jquery
has answer: http://stackoverflow.com/a/47116534
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: javascript
tagged with: python

http://stackoverflow.com/q/47088883
has title: how to store and parse real-time streaming data in mqtt paho for every Nth minutes (python)
tagged with: time
type: UnansweredQuestion
tagged with: mqtt
tagged with: python
has body: Im working on a real-time data streaming project to parse and store the data every Nth minute. My objective is to throw away the very first minute of data(as buffer) and store every 4 minutes long of data from the server. The data will then be parsed to other functions to be clustered and calculation(functions not included here). I have initialized the condition at 'on_message' function and data parse it inside that fuction. I dont think my structuring and calling is the correct way to achieve my objective. Please let me know if you require any additional details. on_message def on_message(r_c_client, userdata, message): if (message.topic == "scanning"): c = datetime.now().time() current = (c.hour * 60 + c.minute) * 60 + c.second time.sleep(60) #initial delay data = json.loads(message.payload.decode("utf-8")) x = data['host'] y = data['data'] hostList = store(x, y) while (current&gt;=total_Time ): #time.sleep(60) #initial delay nodeList = listToDf(hostList) nodeDf= df_reformat(nodeList) print clustering_results_reformat(process_startTime, nodeDf) store function def store(host, data): if host in hostList: hostList[host].append(data) else: hostList[host] = [data] return hostList main global process_startTime t = datetime.now().time() process_startTime = (t.hour * 60 + t.minute) * 60 + t.second total_Time = process_startTime + 300 #4 minutes + 1 minute print t , process_startTime broker_address = '10.10.0.100' c_client = mqtt.Client("trilateration") c_client.on_connect = on_connect c_client.on_message = on_message c_client.on_subscribe = on_subscribe c_client.connect(broker_address, 1883) c_client.loop_forever()
has answer: http://stackoverflow.com/a/47092060
score: 0
answer count: 1
tagged with: paho
type: Question

http://stackoverflow.com/comment/81078057
comment on: http://stackoverflow.com/q/47064885
score: 1
has text: try concatenating the results within the loop, something like `divisors += str(valueD)+" "`
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47220993
has comment: http://stackoverflow.com/comment/81391518
tagged with: python
tagged with: numpy
type: AnsweredQuestion
has body: If I have an index array with all unique sequential values, such as: index_array = array([0, 4, 2, 5, 6, 1, 3, 7, 8]) with a corresponding value array: value_array = array([0, 400, 200, 500 600, 100, 300, 700, 800]) is it possible to loop through the index array in sequential order, such that I get array([0, 100, 200, 300, 400, 500, 600, 700, 800]) I need to loop through the index array in order (i.e. 0, 1, 2, 3, 4...) with the corresponding values (i.e. 0, 100, 200, 300, 400). The reason these values aren't in order is because I'm subdividing edges, which means the new edges are added at the end of the index array (using vstack), rather than inserted into the index array at the appropriate point. The pseudocode (if I was printing out the values), would be something like this: for point in sorted(index_array): print sorted(point(value_array)) producing: 0 100 200 300 How memory sensitive is this (I'm guessing I would need to use numpy.where) Is it just better practice to reorder before looping, or is there a performance cost to looping out of order?
has title: Efficient looping using index array
tagged with: for-loop
has comment: http://stackoverflow.com/comment/81391864
upvote count: 2
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/81391563
downvote count: 1
has comment: http://stackoverflow.com/comment/81391634
favorite count: 0
type: Question
tagged with: indexing
has comment: http://stackoverflow.com/comment/81391718
has comment: http://stackoverflow.com/comment/81391692
has answer: http://stackoverflow.com/a/47221183
linked to: http://stackoverflow.com/q/19821425
accepted answer: http://stackoverflow.com/a/47221183

http://stackoverflow.com/a/70817689
has comment: http://stackoverflow.com/comment/137091252
score: 10
upvote count: 10
type: Answer
has comment: http://stackoverflow.com/comment/137189462
has comment: http://stackoverflow.com/comment/131127663
answers question: http://stackoverflow.com/q/47113813
downvote count: 0
has body: Demo of appending a Pandas dataframe to an existing .parquet file. Note: Other answers cannot append to existing .parquet files. This can; see discussion at end. Tested on Python v3.9 on Windows and Linux. Install PyArrow using pip: pip install pyarrow==6.0.1 Or Anaconda / Miniconda: conda install -c conda-forge pyarrow=6.0.1 -y Demo code: # Q. Demo? # A. Demo of appending to an existing .parquet file by memory mapping the original file, appending the new dataframe, then writing the new file out. import os import numpy as np import pandas as pd import pyarrow as pa import pyarrow.parquet as pq filepath = "parquet_append.parquet" Method 1 of 2 Simple way: Using pandas, read the orignal .parquet file in, append, write entire file back out. # Create parquet file. df = pd.DataFrame({"x": [1.,2.,np.nan], "y": ["a","b","c"]}) # Create dataframe ... df.to_parquet(filepath) # ... write to file. # Append to original parquet file. df = pd.read_parquet(filepath) # Read original ... df2 = pd.DataFrame({"x": [3.,4.,np.nan], "y": ["d","e","f"]}) # ... create new dataframe to append ... df3 = pd.concat([df, df2]) # ... concatenate together ... df3.to_parquet(filepath) # ... overwrite original file. # Demo that new data frame has been appended to old. df_copy = pd.read_parquet(filepath) print(df_copy) # x y # 0 1.0 a # 1 2.0 b # 2 NaN c # 0 3.0 d # 1 4.0 e # 2 NaN f Method 2 of 2 More complex but faster: using native PyArrow calls, memory map the original file, append the new dataframe, write new file out. # Write initial file using PyArrow. df = pd.DataFrame({"x": [1.,2.,np.nan], "y": ["a","b","c"]}) # Create dataframe ... table = pa.Table.from_pandas(df) pq.write_table(table, where=filepath) def parquet_append(filepath:Path or str, df: pd.DataFrame) -> None: """ Append to dataframe to existing .parquet file. Reads original .parquet file in, appends new dataframe, writes new .parquet file out. :param filepath: Filepath for parquet file. :param df: Pandas dataframe to append. Must …

http://stackoverflow.com/comment/81198622
type: AnswerComment
comment on: http://stackoverflow.com/a/47123747
has text: Or `df['new'] = df['Latitude'].astype(str) + '_' + ,df['Longitude'].astype(str)`
score: 0
type: Comment

http://stackoverflow.com/a/47107735
accepted answer of: http://stackoverflow.com/q/47104617
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47104617
upvote count: 1
score: 1
type: Answer
has body: What's happening is that the line [data.pop(col_del) for position in data] is deleting half your rows, and then you're displaying the first 20 rows of what's left. (It would delete all the rows, but the call to pop is advancing the loop iterator.) If you don't want certain columns you should pass your delete list to the columns_to_ignore parameter when you call load_csv. See the function description at load_csv. If you need to remove columns from a dataset in memory I think it would be worth your time to learn the basics of the Pandas library; it will make your life much simpler. You would need n_classes if your target labels were categorical, in order to tell load_csv how many categories there are. Since you have categorical_labels=False, you shouldn't need it.

http://stackoverflow.com/comment/81225796
score: 0
has text: Also `new_array = test_array[:, np.newaxis]` (or, equivalently, `new_array = test_array[:, None]` as you were already told by Coldspeed) — do yourself a favor and google for "numpy broadcasting" to discover one of the strengths of Numpy...
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47135961

http://stackoverflow.com/q/47090519
has answer: http://stackoverflow.com/a/47092330
has comment: http://stackoverflow.com/comment/81141451
has answer: http://stackoverflow.com/a/47093302
possible better answer: http://stackoverflow.com/a/47093302
has comment: http://stackoverflow.com/comment/81165847
has comment: http://stackoverflow.com/comment/81131302
tagged with: arrays
has comment: http://stackoverflow.com/comment/81130383
tagged with: python
has comment: http://stackoverflow.com/comment/81135388
has comment: http://stackoverflow.com/comment/81131330
has comment: http://stackoverflow.com/comment/81131529
has title: How to map closest integers from two lists in least time?
has comment: http://stackoverflow.com/comment/81131485
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81131121
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/47093328
has comment: http://stackoverflow.com/comment/81131409
accepted answer: http://stackoverflow.com/a/47093328
score: 1
has body: I have two very long lists and am trying to map every integer in first list to closet integer in other list within a maximum threshold difference. I can do it looping over entire lists but is there a faster way to do it? Output can be like x (of list A ) = y (of list B) . If a number is equidistant from two integers, any one can be chosen. I tried using - from itertools import product sorted(product(arr1, arr2), key=lambda t: abs(t[0]-t[1])) which is very slow and also not one to one mapping. Example: Input A = [1, 3, 8, 77, 66, 25, 40] B= [2, 5, 12, 120, 30, 21, 40] Threshold = 40 Output 1=2 ; 3=5 ; 8=12 ; 77- dropped out as nothing best under threshold; 66=30 (as 40 is closer but has better match in other list ); 25=21; 40=40
downvote count: 1
has comment: http://stackoverflow.com/comment/81135410
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/comment/81161634
comment on: http://stackoverflow.com/a/47105465
has text: it further clarifies your answer. i didn't want to be rude and edit your answer.
type: Comment
score: 0
type: AnswerComment

data-structures
tags question: http://stackoverflow.com/q/47164748
tag name: data-structures
tags question: http://stackoverflow.com/q/47186264
type: Tag

http://stackoverflow.com/comment/81300098
score: 0
type: AnswerComment
has text: Why not `for i in range(1, 4)`?
comment on: http://stackoverflow.com/a/47175318
type: Comment

http://stackoverflow.com/q/47118379
has answer: http://stackoverflow.com/a/47118652
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/81186731
favorite count: 0
tagged with: recursion
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47118652
tagged with: algorithm
has title: Python Check if its possible to reach right most end of the array by hop left or right
type: Question
accepted answer: http://stackoverflow.com/a/47119085
answer count: 2
has body: I am writing a program that finds if a game is solvable or not solvable. The rules of the game are: You start from the leftmost position You can hop left or right by the value of the array at the position and you cannot go beyond the endpoints. Ex: a={4,4,1,5,2,6,3,4,2,0} you start from left most position so you can jump 4 places right to 2(left is not possible) I have to check if we can reach other end which is always equal to 0. If we can reach the rightmost (i.e 0) then it is solvable else not solvable I have tried using recursion in Python, but have no idea how to proceed def KAuhop(b,c,d,current_position): position_move=b[current_position] if b[current_position+position_move]==0: print("found") else: KAuhop(b,current_position+position_move,d,current_position) print("Not found") a=[4,4,1,5,2,6,3,4,2,0] print(KAuhop(a,0,len(a)-1,0))
upvote count: 2
has answer: http://stackoverflow.com/a/47119085

http://stackoverflow.com/comment/81226459
type: Comment
has text: So, it would be the same as calling `sh -c 'ffmpeg -i "$1" 2>&1 | grep Duration' _ path_to_file.mp4` ?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47138440

http://stackoverflow.com/q/47145798
score: 0
tagged with: oop
answer count: 3
has answer: http://stackoverflow.com/a/47145884
type: Question
has title: How to choose the method that overrides a method of superclass in constructor?
has body: I like to override one of the methods of a superclass and have different options for the target method. For example, the function in superclass is called __func__ and I have two implementations __func1 and __func2 that implement __func__. I would like to choose one of these two functions in the constructor based on user's input. I have tried a few things I could think of, but none of them worked. Is this at all possible? If yes, what is the right way of doing it? EDIT: my class uses __slots__ to define the member variables, so I cannot use something like self.__func__ = self.__func1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47145844
has answer: http://stackoverflow.com/a/47145920
tagged with: python
has comment: http://stackoverflow.com/comment/81241882

http://stackoverflow.com/comment/81164386
has text: Thanks for your reply, unfortunately print(tec_list[1]) will only return "Date de sortie (approx.)", which is the following "product-tech-section-row" class
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47106878

http://stackoverflow.com/a/47069023
score: 0
has body: Try This: maxrows = sheet.nrows print maxrows
type: Answer
answers question: http://stackoverflow.com/q/47068734

http://stackoverflow.com/q/47215035
has comment: http://stackoverflow.com/comment/81380017
accepted answer: http://stackoverflow.com/a/47215376
tagged with: python
has title: Sort items of globals() by created time
has comment: http://stackoverflow.com/comment/81379585
has comment: http://stackoverflow.com/comment/81379547
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81379509
has comment: http://stackoverflow.com/comment/81379583
has comment: http://stackoverflow.com/comment/81379559
downvote count: 0
has comment: http://stackoverflow.com/comment/81379546
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/47215376
has comment: http://stackoverflow.com/comment/81379643
has comment: http://stackoverflow.com/comment/81379535
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81379727
has comment: http://stackoverflow.com/comment/81380037
has body: Working in IPython, I input 3 assignments: In [1]: foo = 1 In [2]: bar = 2 In [3]: zoo = 3 I intend to fetch a dict of them. In [4]: globals() Out[4]: {... 'bar': 2, 'exit': &lt;IPython.core.autocall.ExitAutocall at 0x10e61b048&gt;, 'foo': 1, 'get_ipython': &lt;bound method InteractiveShell.get_ipython of &lt;IPython.terminal.interactiveshell.TerminalInteractiveShell object at 0x10e617208&gt;&gt;, 'quit': &lt;IPython.core.autocall.ExitAutocall at 0x10e61b048&gt;, 'zoo': 3} globals prints a dict in an alphabetical order, so I cannot select them all with one opearation. How to get an dict from globals() in assignnent_created order?
has comment: http://stackoverflow.com/comment/81379896

http://stackoverflow.com/a/47226787
answers question: http://stackoverflow.com/q/47181268
score: 1
type: Answer
has body: I don't think there's any way to do this with the Model API, but there is a way to do it if you are willing to depend on an implementation detail of peewee Models. Also it probably won't be very fast at scale. There is a dict representing the Model's data in m.__dict__['_data'] that you can use. First, get a dict of old_models by id: old_models_by_id = {m.get_id(): m for m in old_models} Then, write a simple function comparing two Model's data def compare_models(m1, m2): """Return True if two models have exactly the same data""" return m1.__dict__['_data'] == m2.__dict__['_data'] Finally, get updated models: updated_models = [m for m in updated_models if m.get_id() in old_models_by_id and not compare_models(m, old_models_by_id.get(m.get_id()))]
accepted answer of: http://stackoverflow.com/q/47181268
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/81390476
type: AnswerComment
comment on: http://stackoverflow.com/a/47218367
type: Comment
score: 0
has text: Cheers! I raised [this issue](https://bugs.python.org/issue32001) based on your answer.

http://stackoverflow.com/comment/81387139
has text: I was considering listing all 128 ascii characters but it would take a lot of time
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47218801

http://stackoverflow.com/comment/81249469
has text: Info on starting the Java server: https://stanfordnlp.github.io/CoreNLP/corenlp-server.html
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47149845

http://stackoverflow.com/comment/81372035
comment on: http://stackoverflow.com/q/47210957
score: 0
type: Comment
type: QuestionComment
has text: From the error, it looks like you are passing a nested list. `[ [ inst1, inst2, ...]` ] instead of `[ inst1, inst2, ...]`

http://stackoverflow.com/comment/81350923
has text: I have added some pictures, please check it again, thanks very much
type: Comment
comment on: http://stackoverflow.com/q/47200617
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81265365
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47158071
score: 1
has text: @CoryKramer it doesn't explain the difference between python versions.

http://stackoverflow.com/a/75019189
has body: If list comprehension is not necessarily required, below is the function which can be used to return a list of numbers whose all digits are even. def only_even_digits_num(my_list): my_list_cp = my_list.copy() for num in my_list_cp: remove_flag = 0 for i in str(num): if int(i)%2==0 and remove_flag==0: pass else: remove_flag = 1 if num in my_list: my_list.remove(num) return my_list test_list = [0,1,2,3,102,201,202,88,636] print(only_even_digits_num(test_list)) returns [0, 2, 202, 88] I tried to do it using List Comprehension but I didn't succeeded. If someone can do it then I will further update my answer with credit and reference.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47145872

http://stackoverflow.com/comment/81123070
type: AnswerComment
comment on: http://stackoverflow.com/a/47086418
has text: Thank you for the link, it was helpful. following the code that is on there for String literal's still, wouldn't work. it keeps giving me the same error, it looks like it just doesn't want that data. However, replacing the %s with 'whatever I want to add to the table' will add that data to my column value in the table. this is weird
score: 0
type: Comment

http://stackoverflow.com/q/47104354
has title: efficient, pythonic way to zig-zag through meshgrid data
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81159421
accepted answer: http://stackoverflow.com/a/47104770
downvote count: 0
has answer: http://stackoverflow.com/a/47104770
has comment: http://stackoverflow.com/comment/81159462
favorite count: 0
type: Question
has body: I want to make a trajectory of (x, y) points that zig-zag through an even grid. I want to be able to specify which axis to start on. Is there an efficient way to do this with numpy? For instance: xv, yv = np.meshgrid([1,2,3], [4,5]) produces xv: [[1 2 3] [1 2 3]] yv: [[4 4 4] [5 5 5]] I want my trajectory to be: (1,4), (2,4), (3,4), (3,5), (2,5), (1,5) or (1,4), (1,5), (2,5), (2,4), (3,4), (3,5)
tagged with: performance
has comment: http://stackoverflow.com/comment/81159304
possible better answer: http://stackoverflow.com/a/47104567
tagged with: python
has comment: http://stackoverflow.com/comment/81159268
has answer: http://stackoverflow.com/a/47104567
score: 2
tagged with: numpy
type: AnsweredQuestion

http://stackoverflow.com/comment/81279381
type: QuestionComment
type: Comment
has text: You are probably using an IDE and stdout is redirected or replaced. Run it in a Windows console and you should see the output.
score: 1
comment on: http://stackoverflow.com/q/47160328

http://stackoverflow.com/q/47093347
has title: Exception Handling by validating simple inputs
accepted answer: http://stackoverflow.com/a/47093547
type: Question
tagged with: exception
has answer: http://stackoverflow.com/a/47093547
answer count: 2
has answer: http://stackoverflow.com/a/47093450
tagged with: python
has body: I am new to Python, after I managed to learn Java at an advanced level. In Java input validation with exception handling was never a problem to me but somehow in python i get a little confused: Here an example of a simple FizzBuzz programm which can only read numbers in between 0 and 99, if otherwise, an exception has to be thrown: if __name__ == '__main__': def fizzbuzz(n): try: if(0&lt;= n &lt;= 99): for i in range(n): if i==0: print("0") elif (i%3==0 and i%7==0) : print("fizzbuzz") elif i%3==0: print("fizz") elif i%7==0: print("buzz") else: print(i) except Exception: print("/// ATTENTION:The number you entered was not in between 0 and 99///") try: enteredNumber = int(input("Please enter a number in between 0 and 99: ")) fizzbuzz(enteredNumber) except Exception: print("/// ATTENTION: Something went wrong here. Next time, try to enter a valid Integer ////") If i run that and enter e.g. 123 the code just terminates and nothing happens.
possible better answer: http://stackoverflow.com/a/47093450
type: AnsweredQuestion
score: 0
tagged with: validation
has comment: http://stackoverflow.com/comment/81136392

source-code-protection
type: Tag
tag name: source-code-protection
tags question: http://stackoverflow.com/q/47096120

http://stackoverflow.com/comment/81236105
score: 1
type: Comment
type: QuestionComment
has text: A note about terminology: "odds" conventionally means a ratio of probabilities. Odds of A against B = p(A)/p(B). Odds can be any nonnegative number while probabilities are between 0 and 1 inclusive. Obviously if you have odds you can calculate probabilities and vice versa. Looks like you have probabilities and not odds in this case, maybe you want to adjust the title and text.
comment on: http://stackoverflow.com/q/47143004

shellcode
tag name: shellcode
type: Tag
tags question: http://stackoverflow.com/q/47193282

http://stackoverflow.com/q/47133630
type: Question
accepted answer: http://stackoverflow.com/a/48803633
has comment: http://stackoverflow.com/comment/81217374
score: 0
tagged with: python-asyncio
has title: Stopping asyncio in thread
tagged with: python
has comment: http://stackoverflow.com/comment/81217954
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/81217501
has answer: http://stackoverflow.com/a/48803633
has comment: http://stackoverflow.com/comment/81217325
answer count: 1
has body: I have a thread that start (and eventually stops) a asyncio loop like so: class Ook(Thread): […] def run(self): try: self._logger.debug("Asyncio loop runs forever.") self.loop.run_forever() except Exception as ex: # We do want to see ALL unhandled exceptions here. self._logger.error("Exception raised: %s", ex) self._logger.exception(ex) finally: # Stop the loop! self._logger.warn('Closing asyncio event loop.') self.loop.run_until_complete(self.loop.shutdown_asyncgens()) self.loop.close() def stop(self): self._logger.info("Thread has been asked to stop!") if self.loop.is_running(): self._logger.debug("Asked running asyncio loop to stop.") for task in asyncio.Task.all_tasks(): self.loop.call_soon_threadsafe(task.cancel) self.loop.call_soon_threadsafe(self.loop.stop) A silly (?) unit test to check that works is @pytest.mark.asyncio async def test_start_and_stop_thread(): sut = Ook() sut.start() if sut.isAlive(): sut.stop() sut.join() assert not sut.isAlive() assert not sut.loop.is_running() This does not work because of raised asyncio.CancelledError… Catching those anywhere in the stop method does not seem to help. If I run the test code not marked with @pytest.mark.asyncio, I get a message saying Task was destroyed but it is pending!. What am I doing wrong?

http://stackoverflow.com/q/47110707
answer count: 1
tagged with: python
tagged with: regex
has title: Regex pattern with 3 groups in Python
has answer: http://stackoverflow.com/a/47110825
score: 0
has comment: http://stackoverflow.com/comment/81172799
has body: I am trying to understand regex in Python. I'm trying to trying this pattern: string = re.sub(r'(\".+?\")(: )', '\"here!\": ', string) for this kind of string: { some text "data": { "first": "xyz" some text} I expected this to replace "first": "xyz" but to my surprise the string which is replaced is: "data": { "first": "xyz". Why is that? I have no idea why is it working in such way.
type: Question
has comment: http://stackoverflow.com/comment/81172372
type: UnansweredQuestion

django-views
tags question: http://stackoverflow.com/q/47094872
tags question: http://stackoverflow.com/q/47111801
tags question: http://stackoverflow.com/q/47145002
tags question: http://stackoverflow.com/q/47219336
tags question: http://stackoverflow.com/q/47116706
tags question: http://stackoverflow.com/q/47154094
tags question: http://stackoverflow.com/q/47069425
tags question: http://stackoverflow.com/q/47106082
tags question: http://stackoverflow.com/q/47167331
tag name: django-views
tags question: http://stackoverflow.com/q/47096820
tags question: http://stackoverflow.com/q/47183153
type: Tag
tags question: http://stackoverflow.com/q/47172689
tags question: http://stackoverflow.com/q/47184231
tags question: http://stackoverflow.com/q/47146497

http://stackoverflow.com/comment/81198535
comment on: http://stackoverflow.com/q/47080031
has text: please see edit2
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81391395
type: Comment
score: 0
has text: What is the type of file that you want to open ? and maybe you can try to decode it with 'latin-1' sometimes it works. keep me in touch
type: AnswerComment
comment on: http://stackoverflow.com/a/47204081

http://stackoverflow.com/comment/81130865
comment on: http://stackoverflow.com/a/47090475
type: Comment
score: 0
type: AnswerComment
has text: `open(page2, 'r') as f: for m in expr.finditer(f.read()):` worked. Thanks @Shpionus

http://stackoverflow.com/q/47182733
tagged with: python
has title: Beautifulsoup only returning first item
has body: although I am seemingly not the first person who has had this problem, I was not able to find the answer to my problem. I am scraping an HTML table and although I am trying to loop through it, I am only getting the first row from the table. import requests from bs4 import BeautifulSoup # Webpage connection html = "https://www.wegochem.com/chemicals/organic-intermediates/supplier-distributor" r=requests.get(html) c=r.content soup=BeautifulSoup(c,"html.parser") # Grab title-artist classes and store in recordList wegoList = soup.find_all("tbody") try: for items in wegoList: material = items.find("td", {"class": "click_whole_cell",}).get_text().strip() cas = items.find("td", {"class": "text-center",}).get_text().strip() category = items.find("div", {"class": "text-content short-text",}).get_text().strip() print(material,cas,category) except: pass the result for the first row is coming out correctly: (1,2-Dimethylimidazole 1739-84-0 Organic Intermediates, Plastic, Resin &amp; Rubber, Coatings); however the for loop is not looping through the table. Thank you for any help
has answer: http://stackoverflow.com/a/47183150
type: AnsweredQuestion
answer count: 2
score: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47183150
favorite count: 0
tagged with: beautifulsoup
type: Question
possible better answer: http://stackoverflow.com/a/47183380
has answer: http://stackoverflow.com/a/47183380

http://stackoverflow.com/q/47065831
tagged with: scripting
tagged with: python
has comment: http://stackoverflow.com/comment/81079990
has title: Find a string in a file and replace the whole line
has answer: http://stackoverflow.com/a/47065986
score: 0
duplicate of: http://stackoverflow.com/q/125703
has body: I am Recently quite new to python and am trying to write a script. What would be the easiest way to search for a string in a file and replace the whole line. I have found that re.sub can achieve this, but nothing is specific enough that I can do it. For example: #configuration file Stuff that configures a file to #configuration file Port 22 by searching for configures Also does this command have different functions such as searching for a string in the middle of a line and replacing everything after it.
answer count: 1
has comment: http://stackoverflow.com/comment/81079965
type: Question
tagged with: linux
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/125703

http://stackoverflow.com/comment/81276925
type: Comment
has text: Note: if you're defining `__eq__`, you should also define `__ne__` (on Python 2 -- and here the question had a python-2.7 tag).
comment on: http://stackoverflow.com/a/47116468
type: AnswerComment
score: 0

http://stackoverflow.com/q/47127856
tagged with: powershell
tagged with: python
accepted answer: http://stackoverflow.com/a/47127882
has comment: http://stackoverflow.com/comment/81206000
has answer: http://stackoverflow.com/a/47127882
possible better answer: http://stackoverflow.com/a/47150462
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81206046
tagged with: environment-variables
tagged with: windows
has title: How do I access the current account environment variables from powershell?
has answer: http://stackoverflow.com/a/47150462
upvote count: 1
score: 1
favorite count: 0
has body: I am trying to track changes in my system as I install various programs. For example I have installed a few versions of python and kept checking my path variable which did not change. However my current account path did change. Without having admin rights a user can set environment variables for their account. How can I see these with powershell? I'm looking for the User Variable Path highlighted in blue below, not the System variable named Path.
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/83031918
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47966210
score: 0
has text: @MaxLunar I have just registered on Telegram if you need to reach me there. My username there is `@anara32`. Feel free to message me any questions you have!

http://stackoverflow.com/comment/81354321
type: QuestionComment
comment on: http://stackoverflow.com/q/47194201
has text: Ohhhh, I finally looked it up and yeah, ok, I got rid of the parentheses and my code runs without an error now, but I don't get an answer that shows up, do I need to use a "return" function?
score: 0
type: Comment

http://stackoverflow.com/comment/81357863
score: 0
has text: Why just don't check it in `init` function?
type: QuestionComment
comment on: http://stackoverflow.com/q/47204471
type: Comment

http://stackoverflow.com/q/47175297
has body: I am currently testing out aiohttp and I am having a problem with the following code: async def index(request: web.Request) -&gt; web.StreamResponse: response = web.StreamResponse(headers={'content-type': 'text/plain'}) await response.prepare(request) for i in range(1000000): try: response.write(b'test response') await response.drain() except concurrent.futures.CancelledError: print('Remote connection closed... Cleaning up...') # Do cleanup process here? raise return response Now I try this out with the following curl request: curl -v http://127.0.0.1:8080 And then I hit Ctrl-C to cause curl to disconnect and stop downloading the response. On the console log from the aiohttp web server I get a lot of the following: 2017-11-08 14:42:31,295|WARNING|asyncio|socket.send() raised exception. 2017-11-08 14:42:31,295|WARNING|asyncio|socket.send() raised exception. 2017-11-08 14:42:31,295|WARNING|asyncio|socket.send() raised exception. 2017-11-08 14:42:31,295|WARNING|asyncio|socket.send() raised exception. 2017-11-08 14:42:31,295|WARNING|asyncio|socket.send() raised exception. Which keeps looping and I cannot kill the server with Ctrl-C. I have to kill it with kill -KILL in order to fully terminate it. It seems that the client socket disconnection is silently handled. I would like to silence the above warnings which are thrown by asyncio.selector_events._SelectorSocketTransport.write(). I could silence that by setting the appropriate logger level, but that's not what I want. Plus there's a lot of cleanup procedures that I would like to do when a client connection terminates. I have looked through the aiohttp code and there doesn't seem to be any handlers or signals that I can hook into to handle it. Ideally I would like to be able to do some cleanup when a client connection is closed. In Django I am able to do it by creating a custom SelfCleaningStream class with the StreamingHttpResponse class. The custom SelfCleaningStream class handles the cleanup in the close() method wh…
type: AnsweredQuestion
tagged with: aiohttp
tagged with: python-asyncio
score: 1
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47215803
has comment: http://stackoverflow.com/comment/81357669
favorite count: 0
has answer: http://stackoverflow.com/a/47215803
type: Question
has comment: http://stackoverflow.com/comment/81418062
has title: Handling premature client disconnection in aiohttp
upvote count: 1
tagged with: python

django-polymorphic
type: Tag
tags question: http://stackoverflow.com/q/47074632
tag name: django-polymorphic

http://stackoverflow.com/comment/81200086
score: 3
has text: Sorry, can you add an example with a valid output ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47124845

http://stackoverflow.com/q/47126567
tagged with: pandas
tagged with: dataframe
has comment: http://stackoverflow.com/comment/81203263
duplicate of: http://stackoverflow.com/q/21137150
type: Question
score: 0
has title: Expanding Int64 data type in dataframe
has comment: http://stackoverflow.com/comment/81203261
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I have read a csv file using pandas and have a feature that is in scientific notation: 3.450 e +04 How can I change the data type here to show the entire number? I tried changing to a float a few others with no luck I am using Python 2.7 on Jupyter
linked to: http://stackoverflow.com/q/25099626
linked to: http://stackoverflow.com/q/21137150
tagged with: python-2.7

http://stackoverflow.com/q/47169345
tagged with: django
tagged with: python
tagged with: django-autocomplete-light
tagged with: css
score: 3
upvote count: 3
has body: I have a model form that is made up largely of django-autocomplete-light ModelSelect2 boxes: class AlertForm(ModelForm): class Meta: model = Alert fields = '__all__' widgets = { 'entity': ModelSelect2(url='eda', attrs={'data-minimum-input-length': 2}), 'logic': ModelSelect2(url='logic', attrs{'class':'hello'}) } The CSS class hello which I am attempting to add to the logic select box does not appear when the page is rendered. How do I add a CSS class to a dal select box? Edit: Even if this did add a class to the select box, the class actually needs to be added to the select container. How would this be accomplished?
answer count: 1
downvote count: 0
tagged with: django-forms
has answer: http://stackoverflow.com/a/70527138
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Add CSS Class to Django-Autocomplete-Light ModelSelect2 Container/Selection

http://stackoverflow.com/q/47100138
has answer: http://stackoverflow.com/a/47100215
answer count: 3
downvote count: 2
accepted answer: http://stackoverflow.com/a/47100220
has comment: http://stackoverflow.com/comment/81150275
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47100258
tagged with: python
score: -1
has title: Need some hints for analyzer.py! I really do not know what is wrong with my code, error TypeError: expected string or bytes-like object
has body: Here's part of my code in def analyze(self,text): (Removed in light of academic honesty.) Had a TypeError which is induced by the lack of () at the end of a build-in function, lower. Conclusion: for all functions, do take note of what to include in the parentheses, else, remember to end off with (), eg. lower().
has answer: http://stackoverflow.com/a/47100220
has comment: http://stackoverflow.com/comment/81150327
possible better answer: http://stackoverflow.com/a/47100215
type: AnsweredQuestion

http://stackoverflow.com/a/47148231
downvote count: 0
type: Answer
upvote count: 1
has body: TerryA's answer is really good, and when you want to keep applying the result of a function to the same function again (as in this example) recurssion is normally a very good idea. Just for the sake of completeness though, the solution can be implemented with a simple while loop, not too dissimilar to what you have attempted: def persistance(num): counter=0 while num&gt;9: counter+=1 num_str=str(num) total=1 for i in num_str: total=total* int(i) num=total print (counter) The counter keeps track of how many times the loop runs, which gives you your final answer.
score: 1
answers question: http://stackoverflow.com/q/47147136

http://stackoverflow.com/comment/81181018
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47093283
has text: You could at least paste above the relevant html elements. Your defined class names are different in two expressions. Anyways, BeautifulSoup doesn't support xpah but it does support css selectors which is more robust and concise.
type: Comment

http://stackoverflow.com/a/47125312
downvote count: 0
upvote count: 1
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/81209944
has body: To check status code of get() or any requests you need to check status_code of response so you need to replace if user_info['meta']['code'] == 200: with if user_info.status_code == 200:.
answers question: http://stackoverflow.com/q/47125028

http://stackoverflow.com/comment/81238441
has text: duplicate of the ca 1000 questions related to lists of identical objects: your `child` contains the *same* list ten times. Not ten different lists.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/47144215

http://stackoverflow.com/comment/81244621
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47147107
type: Comment
has text: Last time I looked into this kind of thing, the best rewrite-the-consumers option seemed to be [inverting the control flow with `send`](https://stackoverflow.com/questions/21945732/consuming-two-iterators-in-parallel). That was back before `async`.

http://stackoverflow.com/comment/81252701
type: Comment
type: QuestionComment
has text: I am executing this in admin prompt import os os.system('netsh interface tcp set global nonsackrttresiliency=enabled') getting error as "Set global command failed on IPv4 The parameter is incorrect."
score: 0
comment on: http://stackoverflow.com/q/47151452

http://stackoverflow.com/comment/81317113
has text: this solution solves the problem stated in the question, but you're right, the OP was not clear, and finally, the solution of @Ajax1234 is the good one.
comment on: http://stackoverflow.com/a/47183178
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/81364358
comment on: http://stackoverflow.com/q/47202189
has text: sorry because I am not good in English , but I want to mention that this code take screen shoots efficiency and store them in my local computer too , but when I open my account in byethost.com (FTP) to get uploading images ,I find only one image and while refreshing the website,I find my image is replaced with anothor uploaded image
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47115809
has comment: http://stackoverflow.com/comment/81182102
has answer: http://stackoverflow.com/a/47116008
tagged with: containers
tagged with: python
has comment: http://stackoverflow.com/comment/81182283
tagged with: backend
score: 4
tagged with: read-eval-print-loop
has title: Web REPL architecture
has comment: http://stackoverflow.com/comment/81182248
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81181936
has body: I want to make web REPL for my custom interpreter. Let me explane my idea. When user write code in browser and then click "evaluate" button, code goes through linter and validator written in JS (validator and linter will be as separate modules), if OK code sends to server via ajax. Then on server separate environment created for that code evaluation. After evaluation that code, results goes back to broswer. So that thing that I dont know is how and with what tools create that separate environment for client code evaluation. If that is right, my question is: what should I do on server to run client's code safely? separate from main OS I guess. May be docker can help?
accepted answer: http://stackoverflow.com/a/47116008
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/100799299
tagged with: web
has comment: http://stackoverflow.com/comment/81182120
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81182422
has comment: http://stackoverflow.com/comment/101184147

http://stackoverflow.com/q/47086016
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has body: SO IMAGE 1 works just fine, it's really image 2 that doesn't come on screen. Also when the first image moves around and hits the second I want the if conditional below to execute. This involves pygame and two images of small size. Please get those. import pygame #Messing with PyGame import sys, pygame Smaller Subheader pygame.init() #needed to start pygame size = width, height = 900, 600 #size is a variable that contains two integers #and represents the width and height of the game window speed = [2, 2] #this array represents the speed you move at vel = [0, 0] #this array represents your current velocity black = 0, 0, 0 screen = pygame.display.set_mode(size) #sets up the window ball = pygame.image.load("macbook.jpg") ball2 = pygame.image.load("home.jpg") #load the image ballrect = ball.get_rect() #get the image rectangle object ballrect2 = ball2.get_rect() print("Get the Macbook home!") Smaller Subheader ballrect = ballrect.move(100,100) #move the image 100 pixels right and 100 pixels down #note: the top left corner of the window is 0,0, and DOWN is POSITIVE Y ballrect2 = ballrect2.move(900,300) exiter = True; #variable for exiting game loop Smaller Subheader #main game loop while exiter: #pygame broadcasts events, which should be processed in this loop #events are things like keyboard presses and mouse clicks #pygame.event.get() returns an array of events and then the python for event in pygame.event.get(): if event.type == pygame.QUIT: exiter = False; #We use KEYDOWN and KEYUP events because we want to know when #keys are pressed and released elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: vel[1] = -speed[1] if event.key == pygame.K_DOWN: vel[1] = speed[1] if event.key == pygame.K_LEFT: vel[0] = -speed[0] if event.key == pygame.K_RIGHT: vel[0] = speed[0] elif event.type == pygame.KEYUP: if event.key == pygame.K_UP or event.key == pygame.K_DOWN: vel[1] = 0 if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: vel[0] = 0 Smaller Subheader #ed…
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/47086397
has title: How to display two images in Pygame
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/a/47324336
score: 8
upvote count: 8
answers question: http://stackoverflow.com/q/47088484
type: Answer
accepted answer of: http://stackoverflow.com/q/47088484
type: AcceptedAnswer
downvote count: 0
has body: You can use __repr__ or __str__ method of the view (those methods are by default inherited by every python class). There are 2 options: Get the representation (__repr__ do you get it yet? :D) every time a REST method gets called: class MyView(View): def get(self, request): # &lt;view logic&gt; print(self.__repr__()) return HttpResponse(result) or return it in the HttpResponse: class MyView(View): def get(self, request): # &lt;view logic&gt; result['self_repr'] = self.__repr__() return HttpResponse(result) Get the representation of the class each time it gets instantiated: class MyView(View): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) print(self.__repr__()) The end result though will be something like this: &lt;my_app.views.MyView object at 0x7f63b5e05668&gt; which is not very helpful. You can override the __str__() method to return something more specific but that is up to you!

http://stackoverflow.com/q/47144096
has answer: http://stackoverflow.com/a/47144196
score: 2
upvote count: 2
downvote count: 0
has body: Let's say we have a numpy array like this: array([{'k': 1}, {'k': 2}, {'k': 3}]) Is is possible to filter filter out only the elements that fulfill a certain condition? For example return only the dictionaries whose keys are > 1. Something like filter() function with lambda. I was looking into numpy.where() but I can't figure out the proper syntax.
tagged with: python
type: AnsweredQuestion
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47144196
tagged with: numpy
has title: Searching numpy array of objects by condition

http://stackoverflow.com/comment/81283621
type: Comment
type: AnswerComment
has text: I made the changes suggested and got: j = 0 while j < len(sDate - 1): date_delta = timedelta(microseconds=(sDate[j] - index_reference_date).delta) j += 1 Error: incompatible type for a datetime/timedelta operation [__sub__]
score: 0
comment on: http://stackoverflow.com/a/47149905

http://stackoverflow.com/q/47108320
downvote count: 0
has answer: http://stackoverflow.com/a/47108374
has body: In my models.py, I have a couple classes, and a couple manager classes. I have some methods that are general methods used by the model, but not necessarily a part of it. For example: def profile_photo_upload_loc(instance, filename): return "profile_photo/%s/%s" % (instance.user, filename) class Profile(models.Model): profile_photo = models.ImageField( upload_to=profile_photo_upload_loc, null=True, blank=True, width_field='width_field', height_field='height_field', verbose_name='Profile Image', ) Is it okay to have standalone functions outside of classes in the models file? When is it appropriate and when should the functions be inside the class?
possible better answer: http://stackoverflow.com/a/47108375
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/47108375
accepted answer: http://stackoverflow.com/a/47108374
tagged with: django
tagged with: django-models
tagged with: python
tagged with: class
score: 2
type: AnsweredQuestion
has title: Should a function in a models.py ever reside outside of a class?
answer count: 2

http://stackoverflow.com/comment/81363191
comment on: http://stackoverflow.com/a/47207107
type: Comment
has text: It says the compiler is 3.4, but my compiler is python 3.5 I believe. Would that make a difference?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/81249147
has text: From what I understand you want the x axis to vary for example: 1,2,3, ... 50, and an instant after 2,3,4, ... 51 and another time 3,4,5, .. ., 52. I am right?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47149397
type: Comment

http://stackoverflow.com/q/47112109
has comment: http://stackoverflow.com/comment/81174382
downvote count: 2
answer count: 3
possible better answer: http://stackoverflow.com/a/47113937
has comment: http://stackoverflow.com/comment/81174567
has answer: http://stackoverflow.com/a/47113937
has answer: http://stackoverflow.com/a/47112474
has body: Let's say I have a list such as the following, which indicates four groups (A, B, C and D). Imagine that each element in the list indicates a person. So person 1 is in Group A, person 2 is in Group B, person 3 is in Group D, and so on. ["A", "B", "D", "C", "B", "C", "A", "B", "A", "C", "A", "D", "A", "D", "A"] The number of occurrences of each alphabet is always in multiples of 3. Notice that B and C occur thrice each, while A occurs six times. I want to divide each of these four groups into four random subgroups. An example of the desired output: ["A1", "B2", "D2", "C1", "B1", "C3", "A2", "B3", "A3", "C2", "A2", "D3", "A3", "D1", "A1"] Here, A1 is one subgroup, which is distinct from A2 and A3. A2 is also distinct from A3. Likewise for the rest. Notice that all subgroups starting with the same alphabet must be of the same size. Hence A1, A2, and A3 have the same number of elements, but B1 can have a different number of elements as compared to A1. Another example of the desired output (since allocation to subgroups is random): ["A2", "B3", "D2", "C1", "B2", "C3", "A3", "B1", "A1", "C2", "A2", "D1", "A1", "D3", "A3"] How can I do this?
has comment: http://stackoverflow.com/comment/81174130
favorite count: 0
has answer: http://stackoverflow.com/a/47112560
has comment: http://stackoverflow.com/comment/81174648
accepted answer: http://stackoverflow.com/a/47112560
has comment: http://stackoverflow.com/comment/81174462
type: AnsweredQuestion
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/81174185
has comment: http://stackoverflow.com/comment/81174107
tagged with: python
has title: Making subgroups in Python
has comment: http://stackoverflow.com/comment/81174232
has comment: http://stackoverflow.com/comment/81174124
type: Question
upvote count: 2

http://stackoverflow.com/comment/81203249
score: 0
has text: To make it even more weird: I added those lines in my code, which I start twice (one with gpu, one with cpu parameter from CLI). So even my cpu-process has executed those lines...
type: Comment
comment on: http://stackoverflow.com/a/47126459
type: AnswerComment

http://stackoverflow.com/comment/81150929
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47100479
has text: z = float(x / y) TypeError: unsupported operand type(s) for /: 'str' and 'str'

http://stackoverflow.com/q/47105056
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47105219
tagged with: python
tagged with: dictionary
score: 0
has title: Filter/group dictionary by nested value
answer count: 2
has answer: http://stackoverflow.com/a/47106588
has body: Here‘s a simplified example of some data I have: {"id": "1234565", "fields": {"name": "john", "email":"john@example.com", "country": "uk"}} The wholeo nested dictionary is a bigger list of address data. The goal is to create pairs of people from the list with randomized partners where partners from the same country should be preferd. So my first real issue is to find a good way to group them by that country value. I‘m sure there‘s a smarter way to do this than iterating through the dict and writing all records out to some new list/dict?
has comment: http://stackoverflow.com/comment/81160802
type: Question

http://stackoverflow.com/comment/81330320
type: QuestionComment
comment on: http://stackoverflow.com/q/47187607
score: 0
has text: If `n` is a number, you will get and error since integers are not iterable. You are safe using `for i in range(1,n+1):` as @CoryKramer suggested.
type: Comment

http://stackoverflow.com/comment/81343511
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47197428
type: AnswerComment
has text: @Mahdi https://stackoverflow.com/questions/25183197/getting-oauth-access-token-for-linkedin-using-python-linkedin-library. Also have a look at this link.

http://stackoverflow.com/comment/81382899
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47216716
type: Comment
has text: Fix your data, please, you cannot declare key value pairs inside lists.

http://stackoverflow.com/comment/81159907
type: QuestionComment
comment on: http://stackoverflow.com/q/47104668
score: 2
type: Comment
has text: Two hints to help us help you: Post the code you currently have, and also be more specific about the problem you're having (For example, if you've made it as far as having an error, post the error)

http://stackoverflow.com/q/47094083
has title: How to paste to a specific column with python excel
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/81137556
downvote count: 1
has comment: http://stackoverflow.com/comment/81138648
favorite count: 0
tagged with: excel
type: Question
has answer: http://stackoverflow.com/a/47096010
has answer: http://stackoverflow.com/a/47095264
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/81138685
tagged with: python
has comment: http://stackoverflow.com/comment/81139529
has answer: http://stackoverflow.com/a/47094882
possible better answer: http://stackoverflow.com/a/47094882
accepted answer: http://stackoverflow.com/a/47096010
type: AnsweredQuestion
answer count: 3
upvote count: 2
has body: I am wanting to copy and paste data from a csv to an excel so I can later filter that table. I have done all these steps in VBA but I've noticed that VBA can be buggy so am wanting to migrate to Python. I have converted the csv to an excel and I have successfully copied the converted xlsx file to the excel document. My question is, how do I copy and paste to a specific starting column. As I have other data I need to copy at cell AN1. I have tried the below.. I am able to write to one specific cell but I am wanting to post the data... for row in ws1: for cell in row: ws2['K1'].value #ws2[cell.coordinate].value = cell.value wb2.save(path2) Entirety... ## csv to xlsx from openpyxl import Workbook import csv wb = Workbook() ws = wb.active with open('C:/B.csv', 'r') as f: for row in csv.reader(f): ws.append(row) wb.save('C:/B.xlsx') ###### COPY FROM B to existing E workbook import openpyxl as xl path1 = 'C:/B.xlsx' path2 = 'C:/E.xlsx' wb1 = xl.load_workbook(filename=path1) ws1 = wb1.worksheets[0] wb2 = xl.load_workbook(filename=path2) ws2 = wb2.worksheets[0] #ws2 = wb2.create_sheet(ws1.title) #cell.value = ['A2'] for row in ws1: for cell in row: ws2.cell(row=1, column=1).value = cell.value wb2.save(path2)
score: 1

http://stackoverflow.com/comment/81381870
type: QuestionComment
comment on: http://stackoverflow.com/q/47215977
type: Comment
has text: @JackHoman Sure, that would work, but in practice it's rare where you couldn't do the same thing with a simple `while` loop rather than recursion. Another option is to simply let the exceptions bubble up to the calling code, where you have a chain of (un-nested) `except` clauses, assuming that the calling code is able to handle those exceptions.
score: 0

http://stackoverflow.com/q/47180690
type: UnansweredQuestion
has body: I am currently developing a version of game of life using the graphics.py module. I am new to programming so do bear with me! Currently the nested for-loop I am using can generate smaller grids fairly fast, but it gets noticeably slower around 50x50 and upwards: for i in range(self.scale, Interface.worldsize_max+2, self.scale): for u in range(self.scale, Interface.worldsize_max+2,self.scale): self.point1 = graphics.Point(i,u) self.point2 = graphics.Point(i-self.scale, u-self.scale) self.square = graphics.Rectangle(self.point1, self.point2) self.square.draw(self.window) self.square.setFill('black') self.grid[round(i/(Interface.worldsize_max/self.worldsize))-1][round(u/(Interface.worldsize_max/self.worldsize))-1]=self.square worldsize_max is the maximum pixels of width/height of the window the program is running in. scale is worldsize_max divided by amount of columns/rows. So far I can't think of a way to make this any faster other than a) pre-generating these arrays in seperate modules and importing them(I will only have preset size options anyway Small, Medium etc) or b) using multiprocessing somehow to brute-force it. It isn't absolutely necessary to have arrays this large but it's more out of curiosity if its a limitation of my code or if it's perhaps a limitation of the graphics.py module? Edit: I have also noticed that as it iterates through the loop, it slows down the further it gets! How come this happens?
tagged with: python
has answer: http://stackoverflow.com/a/47180723
score: 0
answer count: 1
tagged with: loops
tagged with: multiprocessing
type: Question
tagged with: graphics
tagged with: for-loop
has title: Faster way of setting instantiating objects and assigning them to an array

http://stackoverflow.com/q/47104266
answer count: 1
downvote count: 1
tagged with: python
favorite count: 0
type: Question
has title: Passing url to spider in scrapy
type: UnansweredQuestion
has body: I am trying to passing the url to my spider but after looking through what others have done in stack overflow I am always getting the following error: raise TypeError('Request url must be str or unicode, got %s:' % type(url).__name__) Could someone explain what I am doing wrong? Just trying to learn how to se this api. import scrapy from drinkRecipe.items import DrinkrecipeItem class RecipeSpider(scrapy.Spider): name = "recipe" allowed_domains = ["www.1001cocktails.com"] def __init__(self,*args, **kwargs): self.start_urls = [kwargs.get('searchUrl')] super(RecipeSpider, self).__init__(*args, **kwargs) self.start_urls = [kwargs.get('searchUrl')] print self.start_urls def parse(self, response): for selector in response.xpath('//a[contains(@title,"Cocktail")]'): href = selector.xpath('@href').extract()[0] if href is not None: href = response.urljoin(href) yield scrapy.Request(url=href, callback=self.parse_Recipe) def parse_Recipe (self,response): item = DrinkrecipeItem() item['name'] = response.xpath('//h1/text()').extract()[0][:-17] measurements = response.xpath('//td[@class="normal2"]/text()').re(r'.*oz.*') ingredients = [] recipe = "" for selector in response.xpath('//a[contains(@alt,"Recipes with")]'): ingredient = selector.xpath('u/text()').extract()[0] try: ingredients.append(str(ingredient)) except: continue for i in range(len(measurements)): measurement = str(measurements[i]).replace(" ","") recipe += measurement+ingredients[i]+":" item['recipe'] = recipe yield item Main script that runs spider from scrapy import signals from scrapy.crawler import CrawlerProcess, Crawler from scrapy.utils.project import get_project_settings from drinkRecipe import DrinkrecipeItem,RecipeSpider items = [] def scrapedItems(item, response, spider): items.append(item) def main(): settings = get_project_settings() crawler = Crawler(RecipeSpider(searchUrl='http://www.1001cocktails.com/recipes/cocktails/cocktails_list_vu.php3?&amp;start=0')) crawler.signals.connect(scrapedItems,signal=s…
tagged with: scrapy
has answer: http://stackoverflow.com/a/47105038
score: 0
upvote count: 1

odoo-8
tags question: http://stackoverflow.com/q/47088652
tags question: http://stackoverflow.com/q/47143233
tags question: http://stackoverflow.com/q/47221794
tags question: http://stackoverflow.com/q/47067073
tags question: http://stackoverflow.com/q/47159112
tags question: http://stackoverflow.com/q/47172810
tags question: http://stackoverflow.com/q/47199332
tags question: http://stackoverflow.com/q/47130865
type: Tag
tag name: odoo-8
tags question: http://stackoverflow.com/q/47107219
tags question: http://stackoverflow.com/q/47221357
tags question: http://stackoverflow.com/q/47121531
tags question: http://stackoverflow.com/q/47106218

http://stackoverflow.com/comment/81281963
comment on: http://stackoverflow.com/a/47166080
type: Comment
has text: @displayname You make a good point, but if they are having a problem with a self-created log, the practice of creating one from scratch will help with managing files through a class, as well as keeping tracking of it. It's also likely that an existing logging package is more bells and whistles than is necessary (although, using a package may be more ideal simply because of the likelihood of errors is reduced)
type: AnswerComment
score: 0

http://stackoverflow.com/comment/81117960
comment on: http://stackoverflow.com/a/47084292
has text: Thanks for the suggestion! After looking at the code, I realized some error checking should be done and changed the first loop by raising an exception instead of breaking. Would you mind adapting your already well-written answer for the exceptional case?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47088695
has comment: http://stackoverflow.com/comment/81173540
answers question: http://stackoverflow.com/q/47086380
has comment: http://stackoverflow.com/comment/81132773
score: 3
has comment: http://stackoverflow.com/comment/81173502
has body: This is too long for a single comment. So I am putting it here. Note that I am not an expert on any of these tools, other than ImageMagick, but have dabbled a little with each. I welcome comments or opinions from others more expertise than I with these tools I have not used Wand or PIL much. I don't like PIL since it is not as compatible with numpy without reformatting in my limited experience. So I do not use it. Wand looks good if you like ImageMagick convert. I have used both Skimage and OpenCV for different things. And have mixed them in some Python numpy scripts. Wand is probably the easiest to use if you know ImageMagick. I do not know much about its speed. See https://docs.wand-py.org/en/0.6.12/wand/image.html. One Wand limitation that I believe exists is that it is missing the ability to deal with profile. See https://pillow.readthedocs.io/en/stable/reference/Image.html for PIL, which is likely the next easiest to use. But its image format may require format changing to work with numpy. I do not think it is quite as full-functioned as Wand. Also see http://scikit-image.org/docs/dev/api/skimage.transform.html for rotate, resize and affine transform. It is the next easiest to use but may be faster than the other two. Also See https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_geometric_transformations/py_geometric_transformations.html, though you have to do all that with matrices. It is also very fast and has GPU capabilities. I have no experience with timing other than I find Skimage and OpenCV faster than Imagemagick. But they are less directly functional for simple things that Imagemagick can do, apart from my comments above. I think you have to decide what compromise you want with respect to speed and efficiency of coding. If any one knows of a set of coding and speed tests comparing these tools on simple operations such as resize, rotate, crop, affine, perspective, etc, then that would be useful and I would welcome knowing more about the comp…
type: Answer
has comment: http://stackoverflow.com/comment/81175770
has comment: http://stackoverflow.com/comment/81177184
has comment: http://stackoverflow.com/comment/81151487
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/81175588
has comment: http://stackoverflow.com/comment/81893483

http://stackoverflow.com/comment/81148431
type: AnswerComment
has text: @CordKaldemeyer is `n` a numpy array, how are you getting n1, n2, n3, ... n1000 ?!
score: 1
comment on: http://stackoverflow.com/a/47099111
type: Comment

http://stackoverflow.com/comment/81241638
comment on: http://stackoverflow.com/q/47144132
has text: @ivan_pozdeev: note that the question isn't how to write the assignment; OP wants to know what is wrong with *this* implementation. Your link should be a great help, but I don't know that it qualifies as a duplicate.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47090609
downvote count: 0
has body: Tensorflow imports the python module into its init.py file from tensorflow.python import *
has comment: http://stackoverflow.com/comment/81133118
score: 3
answers question: http://stackoverflow.com/q/47090463
has comment: http://stackoverflow.com/comment/81131910
type: Answer
has comment: http://stackoverflow.com/comment/81131093
has comment: http://stackoverflow.com/comment/81132091
accepted answer of: http://stackoverflow.com/q/47090463
has comment: http://stackoverflow.com/comment/81133173
has comment: http://stackoverflow.com/comment/81132658
has comment: http://stackoverflow.com/comment/81131339
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/47160594
tagged with: python
possible better answer: http://stackoverflow.com/a/47161236
has answer: http://stackoverflow.com/a/47161236
type: AnsweredQuestion
tagged with: mocking
answer count: 3
accepted answer: http://stackoverflow.com/a/47161570
downvote count: 0
has answer: http://stackoverflow.com/a/47161570
has comment: http://stackoverflow.com/comment/81271176
upvote count: 1
tagged with: unit-testing
favorite count: 0
type: Question
has body: If you have seen my other question you will know I am having a very hard time at the moment with unit tests in Python. Two days of trying and I've made no progress. In my method which is part of a Class there is several calls to a DAL. car_registration = self.dal.cars.get_by_registration('121D121') This DAL is configured in the base class. I want to completely overrid/mock these calls when running my unit tests and instead return predefined responses so I can continue with the method and ensure everything works as expected. The method starts of with: def change_registration(self): body = json.loads(self.request.body) registration = body['registration'] car = self.dal.cars.get_by_registration(registration) My Python test file at the moment is: class CarTestCase(unittest.TestCase): def setUp(self): self.car_controller = CarController() def test_change_registrations(self): self.car_controller.dal.cars.get_by_registration = MagicMock(return_value=3) response = self.car_controller.change_registration() I am expecting to get the response 3. However, an error is being thrown. AttributeError: 'CarController' object has no attribute '_py_object' It appears the mocking isn't working and it still trying to use the main DAL which isn't fully set up when using the unit tests. How do I prevent it for looking for the actual DAL but instead mocks?
has answer: http://stackoverflow.com/a/47161993
has title: Python Unit Test Mocking
has comment: http://stackoverflow.com/comment/81271738
score: 1

http://stackoverflow.com/comment/81238244
comment on: http://stackoverflow.com/q/47144092
score: 0
type: Comment
type: QuestionComment
has text: try `fields = ['is_empty']` instead

http://stackoverflow.com/comment/81241147
comment on: http://stackoverflow.com/q/47145404
score: 1
type: Comment
type: QuestionComment
has text: You are missing a `)` (or open one `(` to much) in the lines beginning with `new_code = chr((((`

http://stackoverflow.com/comment/81379352
comment on: http://stackoverflow.com/q/47210115
score: 0
has text: Take a look at https://stackoverflow.com/questions/10463898/creating-a-custom-categorized-corpus-in-nltk-and-python
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81363655
comment on: http://stackoverflow.com/q/47207328
score: 0
type: QuestionComment
type: Comment
has text: what are you expecting it to output? it is in the list

http://stackoverflow.com/comment/92475288
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47179427
score: 0
has text: Why? Use 2 different loggers. Or use a logging system (Syslog) so you can filter them easily by level.

http://stackoverflow.com/a/47116949
score: 0
upvote count: 1
downvote count: 1
has body: That's because you sets new value for input_list which is local variable of mutation function. The simplest solution is changing value of first element of list passed as argument: def mutation(input_list): input_list[0] = 10 Otherwise you can write function which changes value of global variable called sample_list def mutation(): global sample_list list_copy = sample_list[:] list_copy[0] = 10 sample_list = list_copy
answers question: http://stackoverflow.com/q/47116919
type: Answer

http://stackoverflow.com/comment/81110233
score: 0
type: AnswerComment
has text: I am getting the following error whille running the above {'command': 'C:/Python35/pypx-0.01/bin/px-echo --timeout 5 -aec ORTHANC -aet CHIPS 127.0.0.1 4242', 'status': 'error', 'data': 'The system cannot find the path specified.\r\n'} The path here I have mentioned is that of px-echo file located inside bin.
type: Comment
comment on: http://stackoverflow.com/a/47079083

http://stackoverflow.com/comment/81222614
type: AnswerComment
comment on: http://stackoverflow.com/a/47136606
has text: It does indeed look like a duplicate. I find the title misleading on the other question, also because it didn't turn up in my google search for the problem. Maybe there is value of keeping the question here with your link.
type: Comment
score: 0

http://stackoverflow.com/a/52697316
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47172758
type: Answer
score: 0
has body: One solution that worked for me was to convert all matrix entries to 'char' format (in MATLAB), and load the new .mat file using the 'scipy.io.loadmat'.

http://stackoverflow.com/comment/81147242
type: QuestionComment
has text: After reading the comments on the question you provided more closely, I believe it's an error with deploying to IIS which requires creation of a DJANGO_SETTINGS_MODULE environment variable that has a value of myapp.settings. unsure of how to reconcile the two though.
comment on: http://stackoverflow.com/q/47098181
score: 0
type: Comment

http://stackoverflow.com/comment/81206323
type: Comment
comment on: http://stackoverflow.com/q/47128135
type: QuestionComment
has text: Why do you want to restrict the access to your abstract class?
score: 0

http://stackoverflow.com/a/47221215
upvote count: 2
score: 2
has body: from tkinter import * from tkinter import messagebox class MainWindow(Frame): def __init__(self, master = None): Frame.__init__(self, master) self.master = master self.master.title("Tournament Software") self.menu() self.popup = None def open_up(self): if self.popup is None or not self.popup.top.winfo_exists(): self.popup = addparticipant_window() else: self.popup.top.lift(self.master) def menu(self): menu = Menu(self.master) self.master.config(menu=menu) participant = Menu(menu, tearoff=False) participant.add_command(label="Add participant", accelerator="Ctrl+S", command=self.open_up) menu.add_cascade(label="Participants", menu=participant) self.bind_all('&lt;Control-s&gt;', lambda e: menu.after(100,self.open_up)) class addparticipant_window: def __init__(self): self.top = Toplevel() self.top.geometry("400x350") self.top.resizable(False, False) top_frame = Frame(self.top, bg='cyan', width=450, height=50, pady=3) top_frame.grid(row=0, sticky="ew") root = Tk() root.geometry("500x400") root.resizable(False, False) app = MainWindow(root) root.mainloop()
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/81394509
answers question: http://stackoverflow.com/q/47220783
accepted answer of: http://stackoverflow.com/q/47220783
type: Answer

http://stackoverflow.com/comment/81369246
has text: @Ben: no, even without parenthesis Python will do that. For instance if you write `return 55,000` this will return a tuple as well.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47209598
type: Comment

http://stackoverflow.com/comment/81370432
type: QuestionComment
score: 0
has text: @juanpa.arrivillaga No, dude, loading any structure of size `N` to memory is at least `O(N)`.
comment on: http://stackoverflow.com/q/47210225
type: Comment

http://stackoverflow.com/comment/81347606
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47199246
has text: Do you know what a regex is? What you have here is a list of elements to search, not a regular expression that matches your search
score: 0

http://stackoverflow.com/comment/81257493
has text: Please provide the whole traceback.
comment on: http://stackoverflow.com/q/47153957
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47130822
tagged with: wxpython
upvote count: 1
has title: wxPython remove window border
linked to: http://stackoverflow.com/q/2504143
has answer: http://stackoverflow.com/a/47983634
score: 1
has body: I used the code from original source - How to resize and draw an image using wxpython? The question is how to display window without border, with param-wx.NO_BORDER or wx.BORDER_NONE? frame = wx.Frame(None, -1, 'Scaled Image', style= wx.BORDER_NONE) When I use it the image shows cut in left upper corner, any suggestions? Like this : def scale_bitmap(bitmap, width, height): image = wx.ImageFromBitmap(bitmap) image = image.Scale(width, height, wx.IMAGE_QUALITY_HIGH) result = wx.BitmapFromImage(image) return result class Panel(wx.Panel): def __init__(self, parent, path): super(Panel, self).__init__(parent, -1) bitmap = wx.Bitmap(path) bitmap = scale_bitmap(bitmap, 100, 100) control = wx.StaticBitmap(self, -1, bitmap) # control.SetPosition((10, 10)) if __name__ == '__main__': app = wx.PySimpleApp() frame = wx.Frame(None, -1, 'Scaled Image', style= wx.BORDER_NONE) panel = Panel(frame, 'onewayr.jpg') frame.SetPosition((100, 100)) frame.Show() app.MainLoop()
has comment: http://stackoverflow.com/comment/81494659
tagged with: python
tagged with: image
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81494989
tagged with: border
type: UnansweredQuestion
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/81350915
comment on: http://stackoverflow.com/q/47198506
type: Comment
score: 0
type: QuestionComment
has text: @JugrajSingh after a little search, I found answers that mentioned there could be a problem with the speculated schema. Can you add the output of `df.printSchema()` and check whether the datatypes are correct? If not, change the schema accordingly. I would also try changing the limit to different values in order to understand more or less where the problem exists within the data.

http://stackoverflow.com/comment/120473874
type: AnswerComment
score: 0
has text: Man you saved me! Thanks!
comment on: http://stackoverflow.com/a/53098510
type: Comment

http://stackoverflow.com/comment/81109116
comment on: http://stackoverflow.com/q/47079191
type: Comment
has text: Now the answer is simple. Hope my answer helps
score: 0
type: QuestionComment

http://stackoverflow.com/comment/81314330
type: Comment
has text: @Hayat sorry I don't understand your question, what are you after? Can you edit your question
comment on: http://stackoverflow.com/a/47182145
type: AnswerComment
score: 0

http://stackoverflow.com/a/47147602
type: Answer
has comment: http://stackoverflow.com/comment/95894972
upvote count: 6
has body: Approach 1 Use pd.DataFrame.query c = [('field1', 3), ('field2', 2), ('field3', 4)] f = '{0[0]} &lt; {0[1]}'.format df.query(' &amp; '.join(f(t) for t in c)) Approach 2 c = [('field1', 3), ('field2', 2), ('field3', 4)] df[df[[t[0] for t in c]].lt([t[1] for t in c]).all(1)] Approach 3 Create a pd.Series out of c and then compare c = [('field1', 3), ('field2', 2), ('field3', 4)] s = pd.Series(dict(c)) df[df[s.index].lt(s).all(1)]
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/81246053
has comment: http://stackoverflow.com/comment/81245573
answers question: http://stackoverflow.com/q/47147414

http://stackoverflow.com/a/47172893
downvote count: 0
has body: I am not sure you want a flattened output or a nested output, but see if this makes sense - print([ a*b for xi_rppi_instance,pi_instance in zip(xi_rppi,pi) for a,b in zip(xi_rppi_instance,pi_instance)]) It is a dual for loop problem, where I have used two for loops in list comprehension. Sample output would have helped!
has comment: http://stackoverflow.com/comment/81295086
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/81295043
answers question: http://stackoverflow.com/q/47172769
upvote count: 2

http://stackoverflow.com/comment/81262775
type: QuestionComment
score: 0
has text: Sorry the example wasn't specific enough, question edited! @WiktorStribiżew
type: Comment
comment on: http://stackoverflow.com/q/47156680

http://stackoverflow.com/comment/81319183
comment on: http://stackoverflow.com/a/47182714
score: 0
has text: I tried adding the annotate and prefetch lines you gave into the view and replaced the line in index.html, but now the order counts don't appear at all. The view uses the ListView and `company_list` is presumably defined in it as `model = Company`, in case that affects anything.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81245880
has text: That's a lot of look-ups if your doing it for a billion rows.
type: AnswerComment
comment on: http://stackoverflow.com/a/47147768
score: 0
type: Comment

http://stackoverflow.com/a/54799481
has body: I had the same exact error, and I figured out that I was running python 3.6 on pycharm and pip was using 3.7 I typed pip3.6 install pyaudio and problem solved Actually because I'm totally new to CS, this kind of problem happened more than several times. Always remember to check the versions.
score: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47136471
upvote count: 1

http://stackoverflow.com/comment/81374384
type: QuestionComment
has text: This looks like homework assignment - if you want to get assistance, you need to try something and explain where you have difficulties. We wont provide a solution, but might put you on the right track to find it yourself.
score: 0
comment on: http://stackoverflow.com/q/47212344
type: Comment

http://stackoverflow.com/a/49763566
has body: My experience with the -32700 error showed up when trying to use python 3, wordpress REST API and wordpress_xmlrpc python package. When using the REST API the read functions all worked with pycurl. However, the authentication was a problem. I moved to using wordpress_xmlrpc to solve the logon/handshake method. This worked well with my development/test wordpress instance but failed miserably when I moved to the QA site (fully copy of production). In QA I kept receiving a -32700 xmlrpc python wordpress parse error. Very specific message with no real insight into what caused the problem. Searching "-32700 xmlrpc wordpress rest api python" gave many results, but few that actually helped. After trying numerous things here is the what actually helped. Turn on Debugging in WordPress. In wp-config.php there was a line: define('WP_DEBUG', false); To turn on debugging you need to change this to: define('WP_DEBUG', true); and then add the line: define('WP_DEBUG_LOG', true); Once this is in place you run your program it will produce an error that shows up in wp-content/debug.log. My error showed: [10-Apr-2018 16:53:30 UTC] PHP Notice: PHP's XML extension is not available. Please contact your hosting provider to enable PHP's XML extension. in /home/cqinfo/www-wordpress/wp-includes/IXR/class-IXR-message.php on line 48 From here it was rather simple to solve. I had my admin install the PHP XML extension. AND RESTART apache. Hope this helps others solve the mystery of the -32700 error for others. We use this to populate a weekly news clipping that has our own thoughts on what is going on in the world of AI and Machine learning at CloudQuant.
answers question: http://stackoverflow.com/q/47135771
accepted answer of: http://stackoverflow.com/q/47135771
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/81266165
type: AnswerComment
score: 0
has text: How would I stop it failing in this way? Would I put an if else telling it to continue if the condition is not met or something? It is definitely only happening when no image links or present, or if the description tag is empty.
type: Comment
comment on: http://stackoverflow.com/a/47099385

http://stackoverflow.com/q/47135360
score: -3
type: AnsweredQuestion
tagged with: sqlite
downvote count: 3
accepted answer: http://stackoverflow.com/a/47136272
has answer: http://stackoverflow.com/a/47136272
answer count: 1
favorite count: 0
type: Question
upvote count: 0
has title: how to delete entire row from my database table , based on a variable using python
has body: I want to delete entire row from my database table , when my variable 'row_id' is 0,1,2,3,etc.... ex: when row_id is 1, then my script should delete row with the values:"1" "2017-11-06" "D" "D" "Good", when is 2 delete row with the values:"2" "2017-11-06" "SS" "SS" "Sent to repair" My database table "cards" looks like this: ID, date, card, serial_card, statuscard "1" "2017-11-06" "D" "D" "Good" "2" "2017-11-06" "SS" "SS" "Sent to repair" I Tried: def delete(self): # Delete from Listbox selection = lb.curselection() lb.delete(selection[0]) row_id=int(selection[0]) print(row_id) c.execute("DELETE FROM cards WHERE ID = ?",(row_id,)) My whole source code: from tkinter import * import sqlite3 import time import datetime conn = sqlite3.connect('cards.db') c = conn.cursor() class MainWindow(): def __init__(self,master): self.master=master self.master.geometry("220x120") self.master.title('Cards!') self.button2=Button(self.master,text="Status ASRU Cards",fg='blue',command=self.gotoasru) self.button2.place(x=50, y=20) self.button4=Button(self.master,text="Exit",fg='red',command=self.exit) self.button4.place(x=90, y=60) def exit(self): self.master.destroy() def gotoasru(self): root2=Toplevel(self.master) myGUI2=status_asru(root2) class status_asru(): def __init__(self,master): self.master=master self.master.geometry("760x310") self.master.title('ASRU cards') self.connection = sqlite3.connect('cards.db') self.cur = self.connection.cursor() self.insert() self.button5=Button(self.master,text="Exit",fg='red',command= self.exit) self.button5.place(x=340,y=270) def exit(self): self.master.destroy() def insert(self): self.cur.execute('CREATE TABLE IF NOT EXISTS cards(ID INT AUTO_INCREMENT, date TEXT,card TEXT,serial_card TEXT,statuscard TEXT)') global insert_data global exit1 global lb global readfromdatabase tipcard=StringVar() serial_card=StringVar() statuscard=StringVar() label1=Label(self.master,text='Insert card type:',fg='black') label1.place(x=5,y=120) label2=Label(self.maste…
tagged with: python

http://stackoverflow.com/q/47119569
has answer: http://stackoverflow.com/a/47119754
has title: Get data from 2 Model in Django python
type: Question
tagged with: django
tagged with: python
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/47119754
type: AnsweredQuestion
score: 0
tagged with: models
has comment: http://stackoverflow.com/comment/81188877
has body: class Product(models.Model): name = models.CharField(max_length=200) price = models.FloatField() avgrating = models.FloatField() def __str__(self): return self.name class Rating(models.Model): Product_id = models.ForeignKey('Product', related_name='Product_id') User_id = models.ForeignKey('User', related_name='User_id') rate = models.IntegerField() I want like - name of the product - price of the product - avgrating (AVG rating) - depend on User_id and Product_id and SQL query like: select p.name,p.price,p.avgrating,r.rate from Product p, Rating r where User_id=1; out Like: in json formate { "name":"Iphone 8", "Price":80000, "avgrating":3.5, "rate":5 }
answer count: 1
tagged with: orm

http://stackoverflow.com/q/47222304
tagged with: scikit-learn
tagged with: python
has body: I want to deploy a Sklearn knn model onto Azure ML Web Service according the following tutorial. from azureml import services from sklearn.neighbors import KNeighborsClassifier knn_model = KNeighborsClassifier(n_neighbors=5, n_jobs=-1, algorithm="auto") knn_model.fit(X_train, Y_train) @services.publish(workspace_id, authorization_token) @services.types(input_1=int, input_2=int, input_3=int, input_4=int) @services.returns(int) def my_knn_predictor(input_1, input_2, input_3, input_4): return knn_model.predict([input_1, input_2, input_3, input_4]) This works indeed, but in the meantime I have to deploy a model where both the input and output dimensionality is very high (magnitude of thousands) so I do not want to type in the input_1, input_2, input_3, input_4 ... variable sequences by hand. Is there a way to extract these as a list from the X_train and Y_train and feed this list into the my_knn_predictor input/output definition? (Simple copy of the data frame headers is not enough because I have to add =int to the column names and remove the quotation marks.)
score: 0
has title: Deploying Machine Learning model to AzureML Web Service - how to deal with extreme high dimensionality?
tagged with: azure-machine-learning-service
has comment: http://stackoverflow.com/comment/81398818
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81398697

http://stackoverflow.com/q/47089223
tagged with: python
has comment: http://stackoverflow.com/comment/81131026
score: 0
has title: Permission Error for python on windows
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/81131216
type: Question
tagged with: python-3.x
has body: I'm trying to download some files at regular intervals, remove the old ones and replace them with new files. First time it runs well, but the second time it throws an error. def check_update(): print ('looking for update') shutil.rmtree(config.destination) shutil.os.mkdir(config.destination) threading.Timer(60.0,check_update).start() def get_videos(): response = requests.get(config.api) data = response.json() files = list() l = len(data) for i in range(l): files.append(data[i]['filename']) return files def get_newfiles(myfiles): for i in range(len(myfiles)): url = config.videos+myfiles[i] filename = wget.download(url) def move_files(myfiles): for i in range(len(myfiles)): file = myfiles[i] shutil.move(config.source_files+file,config.destination) def videos(): files = set(get_videos()) myfiles = list(files) get_newfiles(myfiles) move_files(myfiles) videos() print ("files are updated") res = requests.get(config.api) data = res.json() return data data = check_update() Here is the error. File "C:\Program Files (x86)\Python36-32\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files (x86)\Python36-32\lib\threading.py", line 1182, in run self.function(*self.args, **self.kwargs) File "tornado.py", line 8, in check_update shutil.rmtree(config.destination) File "C:\Program Files (x86)\Python36-32\lib\shutil.py", line 494, in rmtree return _rmtree_unsafe(path, onerror) File "C:\Program Files (x86)\Python36-32\lib\shutil.py", line 389, in _rmtree_unsafe onerror(os.unlink, fullname, sys.exc_info()) File "C:\Program Files (x86)\Python36-32\lib\shutil.py", line 387, in _rmtree_unsafe os.unlink(fullname) permissionError: [WinError 32] The process cannot access the file because it is being used by another process: How can I overcome this?
has answer: http://stackoverflow.com/a/47091027

http://stackoverflow.com/comment/81327371
score: 0
comment on: http://stackoverflow.com/q/47188972
type: Comment
has text: Consider adding the appropriate language tag.
type: QuestionComment

http://stackoverflow.com/comment/81197090
type: Comment
comment on: http://stackoverflow.com/a/47112458
type: AnswerComment
score: 0
has text: @Hayat I added comments to the code, hopefully this will help you understand. Reading this will help you better understand https://docs.python.org/3/tutorial/inputoutput.html

http://stackoverflow.com/q/47085952
type: Question
has body: So I'm trying to develop a way to way to store 4 different categories (lets call them A, B, C, D) inside a dictionary so that I can access the keys/values inside each dictionary and check them against a file name. So far, I've been able to store 3 of these categories inside the dictionary but not the 4th. The categories were from an excel file and then copied over to a regular .txt file (I've included the .txt file). Is there a way to add a 4th component to my dictionary? Link .txt file: https://drive.google.com/file/d/0B2s43FKt5BZgQldULXVOR0RBeTg/view?usp=sharing Here's my script: from collections import defaultdict source_file = &lt;file path&gt;-&lt;file name&gt;.txt data_set = defaultdict(list) #sets up a defaultdict because there may be multiple overlapping keys s = [b for b in [i.strip('\n').split('\t') for i in open(source_file)] if b] # removes new line &amp; tab spaces in .txt file for a, b, c, d in s: # a is donor, b is barcode, c is batch, d is donor if a == 'Component1': # We don't want to save the column headings pass else: data_set[a].append({b: c}) # creates the default dictionary the output is like this as of the moment: {'1':[{'ab':'tg'},{'dd':'dd'}],'2':{'dc':'yh'},3:{'we':'hh'}}
has title: Lists nested inside dictionary
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
tagged with: defaultdict
score: 0
has answer: http://stackoverflow.com/a/47086025
has comment: http://stackoverflow.com/comment/81122459
answer count: 1
has comment: http://stackoverflow.com/comment/81121583
tagged with: file

http://stackoverflow.com/q/47097191
score: 0
has comment: http://stackoverflow.com/comment/81144487
answer count: 0
has title: Python splat operator error
tagged with: splat
type: Question
has body: I have a map iterator gmm and I'm sending it to a function called fisher_vector but I receive the following error: TypeError: fisher_vector() missing 3 required positional arguments: 'means', 'covs', and 'w' I call the function in this line: return np.float32([fisher_vector(file, *gmm) for file in files]) The function is the following: def fisher_vector(samples, means, covs, w): s0, s1, s2 = likelihood_statistics(samples, means, covs, w) T = samples.shape[0] ... I should receive gmm unpacked and it should contain means, covs, w but I receive the mentioned error. gmm contains three lists: means, covs, w. means is a list of 3 elements, each element is size 128, covs is a list of 3 elements, each element is size 128 and w is a list of 3 elements, each element is size 1 Here is an example of what means contains: [ 24.13298798 20.21194077 19.60643387 20.92037392 22.41041565 20.10162354 20.14926147 21.63036919 31.96772003 27.53086281 25.40476799 27.28077888 30.47002029 25.3988018 23.52041626 25.41398811 48.02087784 28.68225288 19.95660019 19.55717659 24.30649185 25.4529705 28.90529633 39.54360199 23.47204971
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81143981

http://stackoverflow.com/q/47209598
downvote count: 2
accepted answer: http://stackoverflow.com/a/47209654
has answer: http://stackoverflow.com/a/47209654
favorite count: 0
type: Question
tagged with: python-3.x
has title: How do you work out percentages?
has comment: http://stackoverflow.com/comment/81416628
has comment: http://stackoverflow.com/comment/81369246
has comment: http://stackoverflow.com/comment/81368491
score: 1
possible better answer: http://stackoverflow.com/a/47210868
tagged with: python
has comment: http://stackoverflow.com/comment/81368288
has answer: http://stackoverflow.com/a/47210868
has comment: http://stackoverflow.com/comment/81368627
has comment: http://stackoverflow.com/comment/81369225
type: AnsweredQuestion
answer count: 2
has body: I've started to learn Python and I'm trying to build a simple salary app. What am I doing wrong? The total should be £55,000 times 24 percent, divided by 52 weeks and should equal to 216.666666667 but I am getting a total of 0.25384615384615383 my_salary = 55.000 my_taxes = 24 /100 my_weeks = 52 my_total = my_salary*my_taxes/my_weeks my_total 0.25384615384615383
upvote count: 3
has comment: http://stackoverflow.com/comment/81416651

http://stackoverflow.com/q/47128804
type: UnansweredQuestion
tagged with: sys
has body: I have two scripts that I'm working with. The first, Script1.py, imports Script2.py and uses its main() by passing arguments to it in a for loop: for ipNum in ipList: print("Checking databases for: " + ipNum) Script2.main("--ip " + ipNum) However, when Script1.py is ran, I get the erorr: vol.py: error: unrecognized arguments: --profile=WinXPSP3x86 -f B:/vmem/zeus.vmem connscan main() looks like this in Script2.py: def main(args): parser = argparse.ArgumentParser(description='Is This IP Bad?') parser.add_argument('-i', '--ip', help='IP address to check') parser.add_argument('--success', help='Also display GOOD', required=False, action="store_true") args = parser.parse_args() if args is not None and args.ip is not None and len(args.ip) &gt; 0: badip = args.ip else: my_ip = urlopen('http://icanhazip.com').read().rstrip() The unrecognized arguments are, of course, the command line arguments that were entered when launchung script1. How do I appropriately enumerate through a list of single arguments to run the script2 main() multiple times?
type: Question
score: 0
has answer: http://stackoverflow.com/a/47129046
has comment: http://stackoverflow.com/comment/81242981
has answer: http://stackoverflow.com/a/47128949
has title: Enumerating command line arguments from external script
tagged with: python
has comment: http://stackoverflow.com/comment/81207821
answer count: 2
has comment: http://stackoverflow.com/comment/81242623
has comment: http://stackoverflow.com/comment/81207718

http://stackoverflow.com/a/47078344
has comment: http://stackoverflow.com/comment/81108669
type: Answer
score: 0
has body: Each row is a Pandas Series. You're treating the whole row as a string. Do you want to write the whole row? for index, row in namedf.iterrows(): lineToWrite = row.to_string() saveFile.write(lineToWrite)
answers question: http://stackoverflow.com/q/47078053
has comment: http://stackoverflow.com/comment/81106466
has comment: http://stackoverflow.com/comment/81105818
has comment: http://stackoverflow.com/comment/81107211
has comment: http://stackoverflow.com/comment/81108480

http://stackoverflow.com/a/47067058
has body: setegid only sets the effective group id of the current process. Same with seteuid. check_output spawns a new process, which is still apparently still run as root. You might have more luck if you attempt to create your folder using python instead of shelling out to do it, but I imagine this is a simpified example so that may not be appropriate. Is it possible to run the python script as the expected user? If not you might need to do something like this; subprocess.check_output(["sudo", "-uexpected_user", "./script.sh"])
answers question: http://stackoverflow.com/q/47067013
type: Answer
accepted answer of: http://stackoverflow.com/q/47067013
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/47156739
score: 3
tagged with: pandas
upvote count: 3
has answer: http://stackoverflow.com/a/47156863
answer count: 1
downvote count: 0
has body: I have a dataframe which has one column and more that 2000 rows. How to compute the edit distance between each rows of the same column. My Dataframe looks like this: Name John Mrinmayee rituja ritz divya priyanka chetna chetan mansi mansvi mani aliya shelia Dilip Dilipa I need to calculate distance between each and every row ? How can we do this or achieve this. I have written some code but that doesnot work this .. gives and enndless list of distances I guess I am going wrong in for loop. can somebody help please import pandas as pd import numpy as np import editdistance data_dist = pd.read_csv(Data_TestDescription.csv') df = pd.DataFrame(data_dist) levdist =[] for index, row in df.iterrows(): levdist = editdistance.eval(row,row) print levdist
favorite count: 0
type: Question
tagged with: edit-distance
linked to: http://stackoverflow.com/q/47152344
accepted answer: http://stackoverflow.com/a/47156863
has title: Compute Edit distance for a dataframe which has only column and multiple rows in python
linked to: http://stackoverflow.com/q/11144513
has comment: http://stackoverflow.com/comment/81263212
tagged with: dataframe
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/47158461
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47158267
has body: Do you need really to sort the list? You could just create a new "sorted" one and use it. Something like: special_columns = ['from_date', 'to_date', 'id_1', 'id_2', 'id_3', 'id_4'] name_columns = ['a', 'id_2', 'from_date', 'to_date', 'id_4', 'c'] a = [] for el in name_columns: if el in special_columns: a.insert(0, el)#insert in the beggining of the resulting list else: a.append(el) print a ['id_4', 'to_date', 'from_date', 'id_2', 'a', 'c']
has comment: http://stackoverflow.com/comment/81266549
has comment: http://stackoverflow.com/comment/81266277
type: Answer
downvote count: 0

http://stackoverflow.com/q/47148446
tagged with: pandas
linked to: http://stackoverflow.com/q/25234941
accepted answer: http://stackoverflow.com/a/47148740
has answer: http://stackoverflow.com/a/47148740
has answer: http://stackoverflow.com/a/69896511
has comment: http://stackoverflow.com/comment/118376667
favorite count: 0
type: Question
tagged with: interpolation
upvote count: 15
answer count: 2
has title: pandas resample interpolate is producing NaNs
linked to: http://stackoverflow.com/q/66967998
downvote count: 0
possible better answer: http://stackoverflow.com/a/69896511
tagged with: python
score: 15
type: AnsweredQuestion
has body: Modified from this example: import io import pandas as pd import matplotlib.pyplot as plt data = io.StringIO('''\ Values 1992-08-27 07:46:48,1 1992-08-27 08:00:48,2 1992-08-27 08:33:48,4 1992-08-27 08:43:48,3 1992-08-27 08:48:48,1 1992-08-27 08:51:48,5 1992-08-27 08:53:48,4 1992-08-27 08:56:48,2 1992-08-27 09:03:48,1 ''') s = pd.read_csv(data, squeeze=True) s.index = pd.to_datetime(s.index) res = s.resample('4s').interpolate('linear') print(res) plt.plot(res, '.-') plt.plot(s, 'o') plt.grid(True) It works as expected: 1992-08-27 07:46:48 1.000000 1992-08-27 07:46:52 1.004762 1992-08-27 07:46:56 1.009524 1992-08-27 07:47:00 1.014286 1992-08-27 07:47:04 1.019048 1992-08-27 07:47:08 1.023810 1992-08-27 07:47:12 1.028571 .... but if I change the resample to '5s', it produces only NaNs: 1992-08-27 07:46:45 NaN 1992-08-27 07:46:50 NaN 1992-08-27 07:46:55 NaN 1992-08-27 07:47:00 NaN 1992-08-27 07:47:05 NaN 1992-08-27 07:47:10 NaN 1992-08-27 07:47:15 NaN .... Why?

http://stackoverflow.com/a/47181087
type: Answer
score: 0
has body: You can't declare reserved words as variables.
answers question: http://stackoverflow.com/q/47180910

http://stackoverflow.com/q/47212500
tagged with: python
has body: Inside of my scons script I execute another python script: fs = env.Command('fs', None, 'python updatefs.py') AlwaysBuild(fs) Depends(fs, main) In python script I am trying to access an environment variable: import os mode = os.environ['PROC_MODE'] The variable was previously set up in the shell: export PROC_MODE='some_mode' Python complain: KeyError: 'PROC_MODE' What is the proper way to propagate environment to an external script?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/81374954
accepted answer: http://stackoverflow.com/a/47214089
tagged with: scons
tagged with: environment-variables
has answer: http://stackoverflow.com/a/47214089
has title: Python script running from SCONS cannot access environment variables
has comment: http://stackoverflow.com/comment/81374972
type: Question
answer count: 1

http://stackoverflow.com/comment/82889402
type: AnswerComment
comment on: http://stackoverflow.com/a/47959838
score: 0
type: Comment
has text: I always thought about `fastText` as a classifier, would you provide some source where I could see how to use it as a dimensionality reducer?

http://stackoverflow.com/a/49625848
answers question: http://stackoverflow.com/q/47076771
has comment: http://stackoverflow.com/comment/103597833
accepted answer of: http://stackoverflow.com/q/47076771
type: Answer
has comment: http://stackoverflow.com/comment/103683844
has comment: http://stackoverflow.com/comment/110833068
upvote count: 25
has body: I made some (aehm...naive) researches, and, according to the reference, it seems that StatsModels uses the classic moving average method to detect trends and apply seasonal decomposition (you can check more here, specifically about Moving Average and Classical Decomposition). However, other advanced seasonal decomposition techniques are available, such as STL decomposition, which also has some Python implementations. (UPDATE - 11/04/2019 as pointed out in the comments by @squarespiral, such implementations appear to have been merged in the master branch of StatsModels). At the above links, you can find a complete reference on the advantages and disadvantages of each one of the proposed methods. Hope it helps!
score: 25
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/81253313
type: Comment
has text: I added te script.
comment on: http://stackoverflow.com/q/47107454
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81234733
has text: Hmm, that sucks. What about using `urllib`?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47142387
type: AnswerComment

http://stackoverflow.com/comment/81138832
type: Comment
type: QuestionComment
has text: Anyhow, I'd worry more about the humongous values that you get in both cases. Hope that you know what you're doing with your original matrix with very "wild" elements ranging from `0.006005578` to `63363.59016`. It might be that such differences can make excel or numpy lose precision/stability.
score: 0
comment on: http://stackoverflow.com/q/47094603

http://stackoverflow.com/q/47203620
tagged with: python
has title: writing the contents of a list to a csv file
has answer: http://stackoverflow.com/a/47365905
favorite count: 0
tagged with: list
downvote count: 0
tagged with: http://stackoverflow.com/tag/csv
score: 1
has comment: http://stackoverflow.com/comment/81683897
has comment: http://stackoverflow.com/comment/81510778
has body: I'm writing the contents of list to a csv file using the code below. import csv text_file = open("memberstest.txt", "r") lines = text_file.read().split(' ') print(lines) myfile = open('members.csv','w') wr = csv.writer(myfile, delimiter=" ") wr.writerows(lines) myfile.close() The problem I'm having is that each word is written to a new row rather than keeping each record on a separate row. For instance my list looks like this: ["['user1',", "'01/01/01',", "'blue',", "'green'['user2',", "'12/12/12',", "'pink',", "'orange']['user3',", "'03/03/03',", "'purple',", "'green']"] When I execute my code my csv file looks like: [ ' u s e r 1 ' ' 0 1 / 0 1 / 0 1 ' ' b l u e ' ' g r e e n ' ] [ ' u s e r 2 ' ' 1 2 / 1 2 / 1 2 ' ' p i n k ' ' o r a n g e ' ] [ ' u s e r 3 ' ' 0 3 / 0 3 / 0 3 ' ' p u r p l e ' ' g r e e n ' ] It leaves a line gap after each word and the last item and first item in each record it joins together. What I would like to see is: user 1 01/01/01 blue green user 2 12/12/12 pink orange etc. I have tried different options for the delimiter and even tried it without but I'm not having much success. Any pointers in the right direction would be much appreciated.
has comment: http://stackoverflow.com/comment/81583469
type: Question
tagged with: export-to-csv
has comment: http://stackoverflow.com/comment/81463261
upvote count: 1
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/q/47154989
tagged with: python-2.7
answer count: 0
type: UnansweredQuestion
score: 1
downvote count: 0
has title: OpenCV Inpaint not removing the watermark from the image Python2.7
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/81260879
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/81291703
has body: I have tried the following code: #!/usr/bin/env python ''' Inpainting sample. Inpainting repairs damage to images by floodfilling the damage with surrounding image areas. Usage: inpaint.py [&lt;image&gt;] Keys: SPACE - inpaint r - reset the inpainting mask ESC - exit ''' # Python 2/3 compatibility from __future__ import print_function import numpy as np import cv2 from common import Sketcher if __name__ == '__main__': import sys try: fn = sys.argv[1] except: fn = '../data/fruits.jpg' print(__doc__) img = cv2.imread(fn) if img is None: print('Failed to load image file:', fn) sys.exit(1) img_mark = img.copy() mark = np.zeros(img.shape[:2], np.uint8) sketch = Sketcher('img', [img_mark, mark], lambda : ((255, 255, 255), 255)) while True: ch = cv2.waitKey() if ch == 27: break if ch == ord(' '): res = cv2.inpaint(img_mark, mark, 3, cv2.INPAINT_TELEA) cv2.imshow('inpaint', res) if ch == ord('r'): img_mark[:] = img mark[:] = 0 sketch.show() cv2.destroyAllWindows() But the output what I got what the exact image and the watermark was available. I guess inpaint was capable of removing any watermark from the images. But it sound total failure in my case. Here is the image that I try to remove the watermark:
tagged with: python
has comment: http://stackoverflow.com/comment/81276945
has comment: http://stackoverflow.com/comment/81292523
has comment: http://stackoverflow.com/comment/81260469
has comment: http://stackoverflow.com/comment/81294387

http://stackoverflow.com/q/47140578
has answer: http://stackoverflow.com/a/47141003
type: Question
has title: Modification of a dictionary in a yaml file using tabulated data in python
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has body: I'm trying to modify/update a yaml configuration file using python. The section which a want to modify is a dictionary, here you have an example of the structure of this yaml file: DEFAULT: zoneID_dictionary_2: # Usual activity place. -1: 'Unknown zone' 1: 'Zone XX 01' 2: 'Zone XX 02' 999: 'Unknown zone' Using pandas I loaded a CSV file from where I'm going to extract the new dictionary needed. Here you have an extract of my code: def yml_manager(config_template_file_path, output_file_path, customers_catchment_area_dict_file_path=None): # Load the template of the configuration file stream = open(config_template_file_path, 'r') config = yaml.load(stream=stream) # Update directories config['DEFAULT']['dir_path_1'] = '_new_path_1_' config['DEFAULT']['dir_path_2'] = '_new_path_2_' if customers_catchment_area_dict_file_path is not None: df = pandas.read_csv(customers_catchment_area_dict_file_path, sep=';') config['DEFAULT']['zoneID_dict'] = {x: y for x, y in zip(df['zone_ID'].tolist(), df['zone_name'].tolist())} with open(output_file_path, 'w') as yml_file: yml_file.write(yaml.dump(data=config, default_flow_style=False)) yml_file.close() By using this code I have the following exception: TypeError: data type not understood/ while dumping the file. On the other side when I create the dictionary in the code, like this: d = {-1: 'Unknown zone', 1: 'catchment_zone_01', 2: 'catchment_zone_02'} config['DEFAULT']['zoneID_dict'] = d The exception is not raised anymore. Because of the context of this project i have to use YAML files and load the dictionary information from a CSV file having hundreds of lines (which I will clean using pandas), so any ideas on what I'm doing wrong? Thanks in advance folks!
tagged with: python
tagged with: dictionary
score: 0
tagged with: pandas
tagged with: yaml
answer count: 1

http://stackoverflow.com/comment/81227819
has text: This isn't so much a python problem, your OS is in charge of starting processes. Which OS are you using?
type: QuestionComment
comment on: http://stackoverflow.com/q/47139180
score: 0
type: Comment

http://stackoverflow.com/q/47101982
answer count: 2
has answer: http://stackoverflow.com/a/47102172
upvote count: 0
has comment: http://stackoverflow.com/comment/81154304
score: -4
tagged with: string
has comment: http://stackoverflow.com/comment/81154052
favorite count: 0
type: Question
has body: I am having following pandas dataframe column names. I have to simplify the names. I need to split sub-string which lies between first ' and second '.Expected output given below. Need help! for i in range(len(df.columns)): print(df.columns[i]) ('date', '') ('A Index', 'PX_LAST') ('B Index', 'PX_LAST') ('C Index', 'PX_LAST') Expected output: 'date' 'A Index' 'B Index' 'C Index' This code solved the issue: str(df.columns[i])[1:].split(',')[0] Thanks for comments.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47102083
tagged with: python
has comment: http://stackoverflow.com/comment/81154030
has title: Need to split sub-string from a string which lies between first ' and second ' - python
tagged with: split
downvote count: 4

http://stackoverflow.com/comment/81327340
type: QuestionComment
score: 0
has text: _there's an accumulation effect_, what does that mean ?
comment on: http://stackoverflow.com/q/47188899
type: Comment

http://stackoverflow.com/comment/81353249
has text: '"But, when I try to select single notice for reading, page reloads" => looks like the urls in "notice.html" are wrong - but it's hard to tell since you didn't post the template code.
comment on: http://stackoverflow.com/q/47202405
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/47144006
has body: You have to commit to comprehesions... from pprint import pprint def helper(a, b, c): return (a, b, c) fields = [1, 2, 3] values = [(1, 1), (2, 2), (3, 3)] a = a = {f: {c: {v: helper(f, v, c) for v in values} for c in ('lottery a', 'lottery b')} for f in fields[1:]} pprint(a) {2: {'lottery a': {(1, 1): (2, (1, 1), 'lottery a'), (2, 2): (2, (2, 2), 'lottery a'), (3, 3): (2, (3, 3), 'lottery a')}, 'lottery b': {(1, 1): (2, (1, 1), 'lottery b'), (2, 2): (2, (2, 2), 'lottery b'), (3, 3): (2, (3, 3), 'lottery b')}}, 3: {'lottery a': {(1, 1): (3, (1, 1), 'lottery a'), (2, 2): (3, (2, 2), 'lottery a'), (3, 3): (3, (3, 3), 'lottery a')}, 'lottery b': {(1, 1): (3, (1, 1), 'lottery b'), (2, 2): (3, (2, 2), 'lottery b'), (3, 3): (3, (3, 3), 'lottery b')}}}
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47143865
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47150604
has body: You have to pass the context when you create the job. You can read from the example here near the bottom of the page: &gt;&gt;&gt; from telegram.ext import CommandHandler &gt;&gt;&gt; def callback_alarm(bot, job): ... bot.send_message(chat_id=job.context, text='BEEP') ... &gt;&gt;&gt; def callback_timer(bot, update, job_queue): ... bot.send_message(chat_id=update.message.chat_id, ... text='Setting a timer for 1 minute!') ... ... job_queue.run_once(callback_alarm, 60, context=update.message.chat_id) ... &gt;&gt;&gt; timer_handler = CommandHandler('timer', callback_timer, pass_job_queue=True) &gt;&gt;&gt; u.dispatcher.add_handler(timer_handler) You can pass anything (including telegram objects, list/dicts, etc) into the job's context when you use the run_once, run_daily and run_repeating functions. Then in your callback function you must pass 2 parameters as you said, bot and job, then get the data you need by accessing job.context.
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47138143
has comment: http://stackoverflow.com/comment/81251274
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/81250872
accepted answer of: http://stackoverflow.com/q/47138143
downvote count: 0

http://stackoverflow.com/a/47193087
score: -1
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/47192761
has body: I think this code will solve your problem. print("Current hand:") for i in range (len(hand)): print(hand[i], end = "") or this print("Current hand:") for i in range (len(hand)): print(hand[i], end = ' ') The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed.
type: Answer

http://stackoverflow.com/comment/81171353
has text: •Calculate total tables based on the number of people. •By default, each table can fit in only 10 people. •Additional people can be added to the tables as long as it is less than 6 people •For example, if the number of people is 35 or less, a total of 3 tables are needed. If the number of people is more than 35, 4 tables is needed
comment on: http://stackoverflow.com/q/47110630
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/81104976
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47078101
has text: @mbieren running which python outside virtual environment am getting /usr/bin/python
score: 0

http://stackoverflow.com/q/47081385
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81181556
has comment: http://stackoverflow.com/comment/81123692
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/81113847
has comment: http://stackoverflow.com/comment/81112365
score: 0
has title: Python Flask-Socketio
tagged with: flask-socketio
has body: I tried to enter the post id of the user who posted something, and in the line of code: comment = Comments (comment = msg, author = current_user._get_current_object (), post_id), coment and author successfully entered into the database, but for post_id the value isnull, how how to enter id from user post according to user post id DATABASE class User(db.Model, UserMixin): __searchable__ = ["username"] id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True,unique=True) password = db.Column(db.String(64), index=True,unique=True) posts = db.relationship('Post',backref='author', lazy='dynamic') comments = db.relationship('Comments',backref='author', lazy='dynamic') def __repr__(self): return self.username class Post(db.Model): __searchable__ = ["body"] id = db.Column(db.Integer, primary_key=True) body = db.Column(db.String(140)) timestamp = db.Column(db.DateTime) user_id = db.Column(db.Integer,db.ForeignKey('user.id')) comments = db.relationship("Comments",backref='post', lazy='dynamic') def __repr__(self): return self.body class Comments(db.Model): __tablename__ = "comment" id = db.Column(db.Integer, primary_key=True) user_send_comment = db.Column(db.Integer,db.ForeignKey('user.id')) comment = db.Column(db.String(500)) post_id = db.Column(db.Integer,db.ForeignKey('post.id')) def __repr__(self): return self.comment ROUTE @app.route("/comment/&lt;int:id&gt;", methods=['GET','POST']) @login_required def comment(id): post = Post.query.get(id) form = CommentForm() if form.validate_on_submit(): return redirect(url_for('comment',id=post.id, page=1)) page = request.args.get('page', 1, type=int) if page == -1: page = (post.comments.count() - 1) / \ COMMENTS_PER_PAGE + 1 pagination = post.comments.paginate(page,per_page=COMMENTS_PER_PAGE, error_out=False) comments = pagination.items return render_template("comment.html",id=post.id, post=post, comments=comments,pagination=pagination, page=1, form=form) CLIENT &lt;script src="https://ajax.google…
tagged with: python
type: Question

http://stackoverflow.com/comment/81346313
has text: Have you isolated the numbers from each other yet? eg: Do you know how to turn it into `['1', '2', '3-6', '10']` to get started
comment on: http://stackoverflow.com/q/47198876
type: Comment
score: 4
type: QuestionComment

distribution
tags question: http://stackoverflow.com/q/47142496
tags question: http://stackoverflow.com/q/47218740
tag name: distribution
type: Tag

http://stackoverflow.com/a/47140225
answers question: http://stackoverflow.com/q/47136680
downvote count: 0
upvote count: 1
type: Answer
score: 1
has body: You may want to have a look at django.db.connections (in django/db/__init__.py) and django.db.utils.ConnectionHandler (which django.db.connections is an instance of). This should let you dynamically add new db configs without hacking settings.DATABASES (actually ConnectionHandler builds it's _databases attribute from settings.DATABASES). I can't tell for sure since I never tried but it should mostly boils down to from django import db def add_db(alias, connection_infos): databases = db.connections.databases if alias in databases: either_raise_or_log_and_ignore(your choice) db.connections.databases[alias] = connection_infos where connection_infos is a mapping similar to the ones expected in settings.DATABASES. Then it's mostly a matter of using Queryset.using(alias) for your queries, ie: alias = get_alias_for_user(request.user) posts = Post.objects.using(alias).all() cf https://docs.djangoproject.com/en/1.11/topics/db/multi-db/#manually-selecting-a-database The main problem with this IMHO (assuming you manage to make something that works out of the untested suggestion above) is that you will have to store databases users/password in clear somewhere which can be a major security issue. I don't know how much control you have on the databases admin part but it would be better if you could add a 'django' user with a same password (and appropriate permissions of course) on all those databases so you can keep the password in your settings file instead of having to keep it in your main db.

http://stackoverflow.com/q/47074966
upvote count: 2
accepted answer: http://stackoverflow.com/a/47075252
score: 1
has answer: http://stackoverflow.com/a/47075252
has comment: http://stackoverflow.com/comment/81098287
has answer: http://stackoverflow.com/a/47107327
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/69102882
tagged with: if-statement
has body: I am trying to create a simple test-scorer that grades your test and gives you a response - but a simple if/else function isn't running - Python - testScore = input("Please enter your test score") if testScore &lt;= 50: print "You didn't pass... sorry!" elif testScore &gt;=60 and &lt;=71: print "You passed, but you can do better!" The Error is - Traceback (most recent call last): File "python", line 6 elif testScore &gt;= 60 and &lt;= 71: ^ SyntaxError: invalid syntax
possible better answer: http://stackoverflow.com/a/47107327
has comment: http://stackoverflow.com/comment/81098217
tagged with: python
has title: Simple python if/else syntax not working
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81098136
answer count: 3

http://stackoverflow.com/comment/81183947
type: Comment
score: 0
has text: It worked just fine. The `sample_list` in the global namespace did not get mutates.your last line in the function effectively does nothing. `input_list = list_copy` it simply assigns to the local variable `input_list`, but that doesn't affect anything in the global scope. Please read https://nedbatchelder.com/text/names.html
type: QuestionComment
comment on: http://stackoverflow.com/q/47116919

http://stackoverflow.com/a/47092024
type: AcceptedAnswer
has body: It depends on the actual content of your mail (plain or html) but the easy way is to also encode the string you are testing against. # if you are testing HTML content self.assertTextInHTML("My email's contents", mail.outbox[0].body) # the string may need escaping the same way django escapes from django.utils.html import escape self.assertIn(escape("My email's contents"), mail.outbox[0].body)
accepted answer of: http://stackoverflow.com/q/47089450
answers question: http://stackoverflow.com/q/47089450
type: Answer
upvote count: 3
score: 3
downvote count: 0

http://stackoverflow.com/comment/81209552
type: Comment
score: 0
has text: Please check my answer [here](https://stackoverflow.com/a/47089306/5864582). I guess it's quite the same.
type: QuestionComment
comment on: http://stackoverflow.com/q/47129013

http://stackoverflow.com/comment/81157466
score: 0
type: Comment
type: QuestionComment
has text: The exception is happening in the `detect` call, not the `print`.
comment on: http://stackoverflow.com/q/47103557

http://stackoverflow.com/comment/102120004
type: AnswerComment
comment on: http://stackoverflow.com/a/47186564
score: 0
has text: Why use `order='F'`?
type: Comment

http://stackoverflow.com/a/47202917
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47202740
upvote count: 1
has body: import pprint a = [[1,2],3,4,[5,6,[7]]] b = pprint.pformat(a) print(a) this works as well, but yeah json might be better for js
type: Answer

http://stackoverflow.com/a/47154790
accepted answer of: http://stackoverflow.com/q/47154691
type: Answer
has body: Use concat: df = pd.concat([s] * len(df.columns), 1, keys=df.columns) print (df) col1 col2 0 A A 1 A A 2 B B 3 C C 4 E E Or if need faster solution use numpy.repeat + numpy.reshape: l = len(df.columns) df = pd.DataFrame(np.repeat(s,l ).reshape(-1,l), columns=df.columns, index=df.index) print (df) col1 col2 0 A A 1 A A 2 B B 3 C C 4 E E Or simplier: l = len(df.columns) df = pd.DataFrame(np.column_stack([s] * l), columns=df.columns, index=df.index) print (df) col1 col2 0 A A 1 A A 2 B B 3 C C 4 E E Timings: np.random.seed(123) L = list('abcdefghijklmno') s = pd.Series(np.random.choice(L, 100)) df = pd.DataFrame(np.random.randint(100, size=(100, 100))).add_prefix('col') print (df) In [161]: %timeit pd.concat([s] * len(df.columns), 1, keys=df.columns) 100 loops, best of 3: 2.84 ms per loop In [162]: %timeit pd.DataFrame(np.repeat(s.values,len(df.columns)).reshape(-1,len(df.columns)), columns=df.columns, index=df.index) 1000 loops, best of 3: 199 µs per loop In [163]: %timeit pd.DataFrame(np.column_stack([s] * len(df.columns)), columns=df.columns, index=df.index) 1000 loops, best of 3: 1 ms per loop In [164]: %timeit pd.DataFrame({k : s for k in df.columns}) 100 loops, best of 3: 2.33 ms per loop
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47154691

http://stackoverflow.com/q/47180020
has comment: http://stackoverflow.com/comment/81309343
type: Question
has comment: http://stackoverflow.com/comment/81311797
has comment: http://stackoverflow.com/comment/81311660
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/81309961
tagged with: opencv
score: 0
has comment: http://stackoverflow.com/comment/81310109
has title: How to get margin intersections and area of each labeled component?
has body: I have segmented a binary image using expectation maximization. After that, I used OpenCV to labeled connected components by using the below implementation: image = image.astype( 'uint8' ) nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=8) sizes = stats[:, -1]; From here, how can I get each component area and number of intersections with the image margin? Below is what I have until now.
has comment: http://stackoverflow.com/comment/81309076
has comment: http://stackoverflow.com/comment/81310794
tagged with: image-processing

http://stackoverflow.com/a/47251612
accepted answer of: http://stackoverflow.com/q/47186569
type: Answer
answers question: http://stackoverflow.com/q/47186569
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has body: Your socket.recv()-ed data are exactly matching the ZeroMQ specification, though they need not have made you happy and you doubt why you did get this, instead of nicely delivered exact copies of messages sent. So, be patient and keep reading. ZeroMQ recently added STREAM socket-archetype is rather specific Anyone having a few years experience with ZeroMQ signalling/messaging tools will tell you that the recently ( v4.x ) added STREAM archetype is not the best choice for a ZeroMQ-process to a ZeroMQ-process intercommunication needs. Why? Allmost all the gems, that the ZeroMQ tools have are and must be shortcut in STREAM, so as to allow a ZeroMQ socket access-point become able to "speak" to an opposite socket endpoint process, which knows nothing about ZeroMQ smart-sockets higher-level protocols. Native pattern The native pattern is used for communicating with TCP peers and allows asynchronous requests and replies in either direction. ZMQ_STREAM A socket of type ZMQ_STREAM is used to send and receive TCP data from a non-ØMQ peer, when using the tcp:// transport. A ZMQ_STREAM socket can act as client and/or server, sending and/or receiving TCP data asynchronously. When receiving TCP data, a ZMQ_STREAM socket shall prepend a message part containing the identity of the originating peer to the message before passing it to the application. Messages received are fair-queued from among all connected peers. When sending TCP data, a ZMQ_STREAM socket shall remove the first part of the message and use it to determine the identity of the peer the message shall be routed to, and unroutable messages shall cause an EHOSTUNREACH or EAGAIN error. To open a connection to a server, use the zmq_connect() call, and then fetch the socket identity using the ZMQ_IDENTITY zmq_getsockopt() call. To close a specific connection, send the identity frame followed by a zero-length message (see EXAMPLE section). When a connection is made, a zero-length message will be received by the application. S…
score: 3

http://stackoverflow.com/comment/81127311
has text: @AdrianC Is it something like this: `df.actions.apply(lambda x: pd.Series({a["action_type"]: a["value"] for a in x["actions"]}))` that you want?
comment on: http://stackoverflow.com/a/47088892
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48088854
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/83184579
type: Answer
answers question: http://stackoverflow.com/q/47138023
has body: Here is an alternative example: %matplotlib inline from matplotlib import animation, pyplot as plt import numpy as np plt.rc('animation', html='html5') data = np.random.random(20) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(data) # draw background anim = animation.ArtistAnimation(fig, [[ax.scatter(x, y)] for x, y in enumerate(data)]) anim The result (anim) is shown animated, but the potential side-effect is an additional display of the static frame. This side-effect vanishes if the plt.figure call occurs in a separate cell before the add_subplot method. This works because (like ImportanceOfBeingErnest said) the creation of a new figure causes the side effect of displaying a static image (depicting how the figure was left at the conclusion of the current cell evaluation in the notebook). But if nothing has been populated onto the figure yet (not even the axes), you prevent any image from being displayed (without needing jupyter magic to suppress it).
upvote count: 3

http://stackoverflow.com/comment/81359366
type: Comment
has text: Because they are placed within a `while True:`
score: 0
comment on: http://stackoverflow.com/q/47205303
type: QuestionComment

http://stackoverflow.com/comment/99948706
comment on: http://stackoverflow.com/a/47603690
score: 0
type: AnswerComment
has text: Thanks. It works well for my StackStorm Ambari client Python code. Just for POC.
type: Comment

http://stackoverflow.com/comment/115036676
has text: This has since been fixed in `mypy`, IMO it's time to close the question.
comment on: http://stackoverflow.com/q/47149154
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47102414
score: 0
answers question: http://stackoverflow.com/q/47099826
type: Answer
has body: Here a guide for Setting up Django and your web server with uWSGI and nginx

http://stackoverflow.com/a/49225446
type: Answer
answers question: http://stackoverflow.com/q/47102536
has body: When you say ignore the other fields, do you mean just drop them from the resulting dictionary after deserialisation? If so then yes that is the default behaviour. Deserialisation will automatically drop any keys which don't map to the defined schema. There if you do result = Person().deserialise(&lt;your sample dictionary&gt;) The result vairable will just be a dictionary containing the keys name and age.
score: 0

http://stackoverflow.com/q/47117354
tagged with: hough-transform
tagged with: matplotlib
downvote count: 1
favorite count: 0
has title: How to remove noise after reading a raw image file using np.fromfile() method
type: Question
tagged with: numpy
answer count: 0
upvote count: 2
type: UnansweredQuestion
has body: I got to know RAW images are interleaved and each pixel holds the value of each R,G,B component. So I have written below code to read the RGB pixel values and reshaped the image array to make it RGB image. After then I am converting the image to a binary one to process further. After conversion when I am trying to display the image it seems to contains noise. Can anyone help me in removing the noise? Python version: 3.6 CODE: from scipy import misc from scipy import ndimage import numpy as np import matplotlib.pyplot as plt import math from PIL import Image import rawpy import imageio def convert_to_binary(img): threshold = 150 img[img &lt;= 30] = 0 img[img &gt; 30] = 255 return img def sobel_test(im): dx = ndimage.sobel(im, 0) # horizontal derivative dy = ndimage.sobel(im, 1) # vertical derivative mag = np.hypot(dx, dy) # magnitude print(np.max(mag)) mag *= 255.0 / np.max(mag) # normalize (Q&amp;D) print(mag) misc.imsave('sobel.jpg', mag) return mag A = np.fromfile("ABC.raw", dtype='int8', sep="") A = np.reshape(A, (756, 1008, 3)) print("A.shape: %d", A.shape) print("A: ", A) print("A[0]: ", A[0]) img_gray = np.dot(A[..., :3], [0.30, 0.59, 0.11]) print("img_gray :", img_gray) print("img_gray shape: ", img_gray.shape) print("img_gray size: ", img_gray.size) sob_img = sobel_test(img_gray) binary_img = convert_to_binary(sob_img) plt.imshow(binary_img, cmap="gray") plt.show() INPUT RAW Image: https://drive.google.com/open?id=12LcQZyYWMg9_6T_n3gjy7kBadRGNMDdr Output Image
tagged with: python
tagged with: python-imaging-library
score: 1

http://stackoverflow.com/comment/81263709
comment on: http://stackoverflow.com/q/47155654
score: 0
type: Comment
type: QuestionComment
has text: Think about how you would tackle this problem. Simply return those 4 variables. and then inject it into the record function. Where the record function would simply write the to params as input to a csv file...

http://stackoverflow.com/a/47130068
downvote count: 0
answers question: http://stackoverflow.com/q/47129901
type: Answer
has body: By using np.where mask=df.groupby(['Name','Program']).\ apply(lambda x : np.where(len(x.Date)&gt;1,(x.FG=='Y') &amp; (x.Date&gt;= x.check),x.FG=='Y')).\ apply(pd.Series).stack().values df.sort_values(['Name','Program']).loc[mask] Out[827]: Name FG Program Date check 1 A Y Eval 2017-10-01 2017-11-30 6 C Y PO 2017-10-01 2017-11-30 9 D Y IB 2017-10-01 2017-11-30 8 D Y Info 2017-06-03 2017-08-02 7 D Y PO 2017-10-01 2017-11-30 14 G Y Info 2017-10-21 2017-12-20 17 H Y PO 2017-04-01 2017-03-02
score: 3
upvote count: 3

http://stackoverflow.com/comment/81422212
has text: Byte code '34' corresponds to ASCII digit '4' so that's why it turns b'\x34' to 4.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47208775
type: QuestionComment

http://stackoverflow.com/q/47137880
downvote count: 4
has comment: http://stackoverflow.com/comment/81225199
has comment: http://stackoverflow.com/comment/81225028
has title: Difference between inheritance and composition in a MVC architecture?
upvote count: 0
has comment: http://stackoverflow.com/comment/81225529
has answer: http://stackoverflow.com/a/47138030
has body: What is the better choice between the two? I think that they both provide the same solution, but which one is better to choose in an MVC architecture? In the code below, Parent class is part of Model and Child class is part of Controller: class Parent(): def parent_function(self): print("parent class") #passing parent as argument class Child(Parent): def child_function(self): return super().parent_function() #referencing parent on __init__ class Child(): def __init__(self): self.parent = Parent() super().__init__() def child_function(self): return self.parent.parent_function() Thank you
has answer: http://stackoverflow.com/a/47137999
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81224944
has comment: http://stackoverflow.com/comment/81225351
has comment: http://stackoverflow.com/comment/81225057
has comment: http://stackoverflow.com/comment/81225886
has answer: http://stackoverflow.com/a/47138213
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47137989
has comment: http://stackoverflow.com/comment/81225370
has comment: http://stackoverflow.com/comment/81225902
tagged with: python
score: -4
answer count: 4
has comment: http://stackoverflow.com/comment/81225149
tagged with: class
has comment: http://stackoverflow.com/comment/81225054
has comment: http://stackoverflow.com/comment/81225232

http://stackoverflow.com/q/47112012
has comment: http://stackoverflow.com/comment/81173972
has comment: http://stackoverflow.com/comment/81173991
downvote count: 7
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/128199377
has answer: http://stackoverflow.com/a/47112169
type: UnansweredQuestion
has title: What's the function of dedent() in Python?
answer count: 1
has comment: http://stackoverflow.com/comment/81173950
tagged with: python
upvote count: 23
has body: The code is below. What's the function of dedent()? When I run this code, the result is virtually the same. print(dedent(""" Like a world class boxer you dodge, weave, slip and slide right as the Gothon's blaster cranks a laser past your head. In the middle of your artful dodge your foot slips and you bang your head on the metal wall and pass out. You wake up shortly after only to die as the Gothon stomps on your head and eats you. """)) print(""" Like a world class boxer you dodge, weave, slip and slide right as the Gothon's blaster cranks a laser past your head. In the middle of your artful dodge your foot slips and you bang your head on the metal wall and pass out. You wake up shortly after only to die as the Gothon stomps on your head and eats you. """)
linked to: http://stackoverflow.com/q/11157043
duplicate of: http://stackoverflow.com/q/11157043
score: 16

rewriting
tag name: rewriting
tags question: http://stackoverflow.com/q/47208509
type: Tag

http://stackoverflow.com/q/47209035
tagged with: excel
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/47209306
upvote count: 1
has comment: http://stackoverflow.com/comment/81367593
tagged with: vba
has title: How to write a Python file using VBA?
favorite count: 0
tagged with: arcgis
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47209337
accepted answer: http://stackoverflow.com/a/47209337
has comment: http://stackoverflow.com/comment/81367438
possible better answer: http://stackoverflow.com/a/47209306
downvote count: 0
tagged with: python
has body: I want to use excel VBA to edit a script file in python then to be run in ArcGis. First I'm open to any easier way but so far I'm having trouble making a multiple line script with my VBA sub! &amp; vbCrLf &amp; doesn't work in the command Fileout.Write. When I open my script file everything is on the same line. neither is &amp; Char(34) &amp; working. Private Sub CommandButton4_Click() Dim fso As Object Set fso = CreateObject("Scripting.FileSystemObject") Dim path As String path = Application.ActiveWorkbook.path Dim Fileout As Object Set Fileout = fso.CreateTextFile(path &amp; "\" &amp; "test2.py", True, True) Fileout.Write "import arcpy &amp; vbCrLf &amp; lyr = arcpy.mapping.Layer( &amp; Char(34) &amp; limits &amp; Char(34) &amp;) &amp; vbCrLf &amp; lyr.visible = True &amp; vbCrLf &amp; arcpy.RefreshActiveView()'" Fileout.Close End Sub

http://stackoverflow.com/comment/81081153
has text: Bad phrasing, sorry. Checking for each ith element in each array if a[i] == b[i]
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47066197
score: 0

http://stackoverflow.com/comment/81142681
type: AnswerComment
has text: Next time use `pd.read_clipboard` to read the data from the OP.
score: 0
comment on: http://stackoverflow.com/a/47096499
type: Comment

http://stackoverflow.com/a/64217853
has comment: http://stackoverflow.com/comment/135045155
answers question: http://stackoverflow.com/q/47126186
type: Answer
has body: I found that if conda doesn't activate when the terminal starts up properly, you get this error. I found that by opening the terminal, typing a bunch of stuff and pressing enter a a lot to prevent conda from activating and then when I tried to run a matplotlib inclusive script it would give me this error, but when I let it start without interference, it would not give me this error (it would run fine, at least past this error). Considering this, it may be useful to keep import matplotlib at the top of the file if possible, so you don't wait a while and then find out that matplotlib won't load.
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/81407575
score: 0
has text: Well i didn't see any problem Did a simple word count program works on your spark installation?
type: Comment
comment on: http://stackoverflow.com/a/47223353
type: AnswerComment

http://stackoverflow.com/comment/81398897
type: AnswerComment
score: 0
has text: Thank you for answering me. However, it doesn't work for me... I've update my question for more detailed description.
type: Comment
comment on: http://stackoverflow.com/a/47222487

http://stackoverflow.com/q/47143506
has comment: http://stackoverflow.com/comment/81237156
score: 0
tagged with: django
has answer: http://stackoverflow.com/a/47145508
has title: Method Not Allowed (POST) using DeleteView
has body: I am new to Django and i using Class based views to add a delete option to my Restaurant List, However when i click the delete button i am getting a blank screen and getting the following error in the console "Method Not Allowed (POST):" Below is my code views.py from __future__ import unicode_literals from django.db.models import Q from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import TemplateView, ListView, DetailView, CreateView,DeleteView from django.urls import reverse_lazy class RestaurantDeleteView(DeleteView): model = RestaurantLocation success_url = reverse_lazy('restaurants:list') urls.py from django.conf.urls import url, include from .views import ( RestaurantListView, RestaurantDetailView, RestaurantCreateView, RestaurantDeleteView, ) urlpatterns = [ url(r'^create/$', RestaurantCreateView.as_view(), name= 'create'), url(r'^$',RestaurantListView.as_view(), name= 'list'), url(r'^(?P<slug>[\w-]+)/$',RestaurantDetailView.as_view(), name="detail"), url(r'^(?P<slug>[\w-]+)/delete/$', RestaurantDeleteView.as_view(), name="restaurant-delete"), ] delete.html {% csrf_token %} Are you sure you want to delete {{ obj }}?
type: Question
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47143648
has comment: http://stackoverflow.com/comment/81237452
answer count: 2

http://stackoverflow.com/comment/81342974
comment on: http://stackoverflow.com/q/47196917
type: Comment
type: QuestionComment
score: 0
has text: btw, you `return middle` instead of `return t[middle]`

http://stackoverflow.com/q/47088986
has answer: http://stackoverflow.com/a/47089646
type: Question
has comment: http://stackoverflow.com/comment/81127579
has comment: http://stackoverflow.com/comment/81127750
tagged with: python
type: UnansweredQuestion
tagged with: chrome-web-driver
has comment: http://stackoverflow.com/comment/81127488
tagged with: pycharm
score: 0
has title: pyCharm Selenium Python eol while scanning string
tagged with: selenium
has comment: http://stackoverflow.com/comment/81127387
answer count: 1
has body: I have installed selenium and I can run it on Python. When I try and run int on pyCharm I keep getting the errors below. I believe it may have to do with how and where I installed pyCharm, but I can't seem to get it to work. I am looking for help on how I should be configuring pyCharm so I can run my automation script using Python, Selenium, ChromeDriver, and set it up to be triggered every 24 hours and 5 minutes. script: from selenium import webdriver from selenium.webdriver.common.keys import Keys browser= webdriver.Chrome("D:/Projects/chromedriver.exe") browser.get("https://url.com/") formElem= browser.find_element_by_name('email') formElem.send_keys('ucsb@gmail.com') zipElem=browser.find_element_by_name('zipcode') zipElem.send_keys('93101') EnterNowElem=browser.find_element_by_xpath('//input[@value="Enter Now"]') #EnterTagElem=browser.find_element_by_class_name("") EnterNowElem.click() I get the errors below. "C:\Program Files (x86)\Python36-32\python.exe" C:/Users/rxper/Desktop/PycharmProjects/Automation/formsubmit.py Traceback (most recent call last): File "C:/Users/rxper/Desktop/PycharmProjects/Automation/formsubmit.py", line 1, in &lt;module&gt; from selenium import webdriver File "C:\Program Files (x86)\Python36-32\lib\site-packages\selenium\webdriver\__init__.py", line 18, in &lt;module&gt; from .firefox.webdriver import WebDriver as Firefox # noqa File "C:\Program Files (x86)\Python36-32\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 19, in &lt;module&gt; import http.client as http_client File "C:\Program Files (x86)\Python36-32\lib\http\client.py", line 71, in &lt;module&gt; import email.parser File "C:\Users\rxper\Desktop\PycharmProjects\Automation\email.py", line 31 'Subject: So long.\nDear Alice, so long and thanks for all the fish. Sincerely, ^ SyntaxError: EOL while scanning string literal Process finished with exit code 1
has comment: http://stackoverflow.com/comment/81127644
has comment: http://stackoverflow.com/comment/81127505
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/81127652

http://stackoverflow.com/comment/81374515
has text: This seems like a reasonable feature request (TensorProto -> org.tensorflow.Tensor). Would you mind [filing it on GitHub](https://github.com/tensorflow/tensorflow/issues/new)?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47174646

http://stackoverflow.com/a/47183898
score: 10
upvote count: 10
type: Answer
answers question: http://stackoverflow.com/q/47183828
accepted answer of: http://stackoverflow.com/q/47183828
downvote count: 0
type: AcceptedAnswer
has body: Here's one approach - np.split(a,np.flatnonzero(np.diff(a)&gt;d)+1) As a function to output list of lists - def splitme(a,d) : return list(map(list,np.split(a,np.flatnonzero(np.diff(a)&gt;d)+1))) For performance, I would suggest using zip to get the start, stop indices and then slicing, thus avoiding np.split which might prove to be the bottleneck - def splitme_zip(a,d) : m = np.concatenate(([True],a[1:] &gt; a[:-1] + d,[True])) idx = np.flatnonzero(m) l = a.tolist() return [l[i:j] for i,j in zip(idx[:-1],idx[1:])] If you need the output as a list of arrays, skip the list conversion with .tolist/map(list,). Sample runs - In [122]: a = np.array([1,2,3,5,7,10,13,16,20]) In [123]: splitme(a,1) Out[123]: [[1, 2, 3], [5], [7], [10], [13], [16], [20]] In [124]: splitme(a,2) Out[124]: [[1, 2, 3, 5, 7], [10], [13], [16], [20]] In [125]: splitme(a,3) Out[125]: [[1, 2, 3, 5, 7, 10, 13, 16], [20]] Runtime test - In [180]: a = np.sort(np.random.randint(1,10000*2,(10000))) In [181]: s = pd.Series(a) In [182]: d = 3 In [183]: %timeit pandas_way(s,d) #@cᴏʟᴅsᴘᴇᴇᴅ's soln 10 loops, best of 3: 55.1 ms per loop In [184]: %timeit np.split(a,np.flatnonzero(np.diff(a)&gt;d)+1) ...: %timeit splitme(a,d) ...: %timeit splitme_zip(a,d) 1000 loops, best of 3: 1.47 ms per loop 100 loops, best of 3: 2.87 ms per loop 1000 loops, best of 3: 516 µs per loop In [185]: a Out[185]: array([ 2, 2, 2, ..., 19992, 19996, 19999])

http://stackoverflow.com/a/56599610
type: Answer
has body: I solved this issue by upgrading to python 3.7 . I would recommend starting a new virtualenv, configured to use python 3.7 . if you do not have python3.7 on your system, you will need to install it. This site is the one I used. Works on AWS cloud9 too. installing python 3.7 virtualenv env -p python3.7 source ./env/bin/activate python --version output should be "Python 3.7.X" then continue setting up your app like normal.
score: 0
answers question: http://stackoverflow.com/q/47146586

http://stackoverflow.com/a/47175953
has body: just understand in this way: [a for b, a in matrix_a] #as [a for [a, b] in matrix_a] #or [a for (a, b) in matrix_a] #matrix_a has elements as list of length 2 each #so your list comprehenssion says, give me a output list -- having first element'a' from each element of matrix_a(whose each element represented as [a,b] type, with comma, becomes tuple (a,b)), # then from [b,a] give me a, that is 2nd element # and it will fail if you apply same on matrix_b, cause each element of matrix_b is not of type [a,b] i:e of length 2 # you will get "ValueError: too many values to unpack" Let me know if anything is not clear. Thanks.
answers question: http://stackoverflow.com/q/47175707
score: 0
type: Answer

http://stackoverflow.com/comment/81185249
type: Comment
type: QuestionComment
has text: cant help without knowing what the `quad` function does and its implementation
score: 0
comment on: http://stackoverflow.com/q/47117525

http://stackoverflow.com/a/68844651
has body: The reason you need to take the same x is easy explained if you consider x to be time for example. Now if you have two signals that are described with the time t, but you do not have the same x( or here t) array from which you constructed them; well then the times do not correspond correctly. At least the time spacing needs to be the same to work in a way that makes sense. I had a similar problem, where a laser pulse needs to be convolved with a concentration depending on time. The laser pulse is very sharp, meaning also short in time, so I take a small intervall t_laser and t_concentration is the whole time interval of my experiment: t_laser = np.linspace(-20 ,20,160) t_concentration = np.linspace(-2000,20000,88000) laser = laser_pulse(t_laser) ## Pulshape depending on time concentration = ABC_model(t_concentration, some_parameters) ## Model for concentration(t) Notice that for both time arrays I have the same spacing, leading to equal steps in time. If I had changed to t_laser = np.linspace(-20 ,20,88000) t_concentration = np.linspace(-2000,20000,88000) because I wanted a higher resolution for my laser pulse which should still go from t0=-20 to t1=20. But since I only convolve the laser with the signal, signal.convolve(concentration, laser, mode='same')/sum(laser) without taking the time arrays into account; one could interpret that the laser pulse has the same temporal extent, since it has the same length of the array. Remark: Also you need to be aware, how the signal convolve function works (scipy.signal.fftconvolve). It seems to me it places the center of the laser array on the first element of the concentration array and then calculates the sum/integral. That is basically how a convolution with arrays works (But it is different from np.convolve; that would be mode "full"). So if you choose the array for your Gaussian function not to be symmetric, the maximum of the Gaussian is not in the center of the array (regarding the index), so your result shifts in the x…
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47136595

factorial
type: Tag
tag name: factorial
tags question: http://stackoverflow.com/q/47131771
tags question: http://stackoverflow.com/q/47141359

http://stackoverflow.com/comment/81206647
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47128289
type: QuestionComment
has text: use `self.base` instead of just `base`?

http://stackoverflow.com/a/47191608
accepted answer of: http://stackoverflow.com/q/47186213
has comment: http://stackoverflow.com/comment/81353298
has comment: http://stackoverflow.com/comment/95408786
score: 0
has comment: http://stackoverflow.com/comment/81354338
has comment: http://stackoverflow.com/comment/81355599
has comment: http://stackoverflow.com/comment/81547941
type: AcceptedAnswer
has body: The for-loop in textfilemanage() waits until the thread finishes so the different thread is useless in the code. Instead: Create the empty combobox in __init__ (needed for layouting) and assign it to self.combo In textfilemanage() start the thread but don't wait for it. In read_employees() replace the final return statement by wx.CallAfter(self.combo.Append, emp_list) or wx.CallAfter(self.combo.AppendItems, emp_list) (it depends on the wxPython version which variant is accepted)
answers question: http://stackoverflow.com/q/47186213
type: Answer
has comment: http://stackoverflow.com/comment/81335811

http://stackoverflow.com/comment/81333059
score: 0
type: Comment
has text: `delete_query` is an integer, because that's what `delete()` returns.
type: AnswerComment
comment on: http://stackoverflow.com/a/47191831

http://stackoverflow.com/comment/81182157
score: 0
has text: You could try `python2.7 -m ensurepip` to install pip with that python install. But since that appears to be Apple's system python, that it uses for its scripts, you are better not to touch it. I believe you can install current 2.7.14 into `Library` (instead of `System/Library` so that it does not conflict with the system install, but not having a Mac, I do not know the details.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47105185

http://stackoverflow.com/a/47257116
type: AcceptedAnswer
has body: Found that the issue was due to AV. Stopped the anti virus for some time and it is running properly now.
type: Answer
answers question: http://stackoverflow.com/q/47194189
score: 0
accepted answer of: http://stackoverflow.com/q/47194189

http://stackoverflow.com/comment/81196786
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47123335
has text: It worked??????
type: Comment

http://stackoverflow.com/a/47105486
type: Answer
score: 0
upvote count: 1
downvote count: 1
has body: I searched online and found Why are some Python strings are printed with quotes and some are printed without quotes? I think if you print as follows, it will work as you wish: print(repr(a1)) print(repr(b1))
answers question: http://stackoverflow.com/q/47105392

http://stackoverflow.com/comment/81156116
has text: I am using Python 3.6. The order is always the same.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47102769
score: 0

http://stackoverflow.com/a/47207888
answers question: http://stackoverflow.com/q/47207815
score: 0
type: Answer
has body: In your first for loop, you return res where res = temp.intersection(sub). This causes the function to halt execution and return control to the caller - in this case lists() returns and cedes control to the main() function from which it was called. If you just wish to display content in the terminal use print (or print()) not return. return is used when you need the output of one function to be used in another function.

http://stackoverflow.com/q/47217151
tagged with: lstm
linked to: http://stackoverflow.com/q/42334335
answer count: 2
downvote count: 0
has body: I am trying the example of keras IMDB data and the data shape is like this: x_train shape: (25000, 80) I simply change the original code of keras example to code like this: model = Sequential() layer1 = Embedding(max_features, 128) layer2 = LSTM(128, dropout = 0.2, recurrent_dropout = 0.2, return_sequences = True) layer3 = Dense(1, activation = 'sigmoid') model.add(layer1) model.add(layer2) model.add(layer3) The original model set return_sequences as False and I changed it into True, and I met this error: expected dense_1 to have 3 dimensions, but got array with shape (25000, 1) But I printed the structure of the model and found the output of LSTM layer is exactly a 3D tensor: lstm_1 (LSTM): (None, None, 128)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/81442371
tagged with: word-embedding
tagged with: keras
score: 4
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/81405628
has comment: http://stackoverflow.com/comment/81441158
has answer: http://stackoverflow.com/a/47217907
has comment: http://stackoverflow.com/comment/81386299
has comment: http://stackoverflow.com/comment/81384587
tagged with: python
has answer: http://stackoverflow.com/a/47217252
upvote count: 4
has title: Keras LSTM with embedding layer before LSTM layer

http://stackoverflow.com/comment/81381859
comment on: http://stackoverflow.com/q/47215243
score: 0
has text: You act on the keydown, which means that when the key already *is* down, there is no event invoked - this prevents the *continuous* movement. What you can do for example is initialize a movement on keydown (ie. like a while loop which gets continously updated) and break it on keyup.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47088287
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47088207
has comment: http://stackoverflow.com/comment/81128503
upvote count: 1
has body: In first you decode the line then try to find a match in it line = line.decode('gbk') if re.match(u'.....', line): In Second you encode the pattern for the match. re.match((u'IPv4').encode('gbk'), line) Maybe it should be re.match((u'IPv4'), line.decode('gbk'))

http://stackoverflow.com/q/47098571
accepted answer: http://stackoverflow.com/a/47100709
answer count: 1
favorite count: 0
tagged with: numpy
has answer: http://stackoverflow.com/a/47100709
has body: I have a pandas dataframe with roughly 150,000,000 rows in the following format: df.head() Out[1]: ID TERM X 0 1 A 0 1 1 A 4 2 1 A 6 3 1 B 0 4 1 B 10 5 2 A 1 6 2 B 1 7 2 F 1 I want to aggregate it by ID &amp; TERM, and count the number of rows. Currently I do the following: df.groupby(['ID','TERM']).count() Out[2]: ID TERM X 0 1 A 3 1 1 B 2 2 2 A 1 3 2 B 1 4 2 F 1 But this takes roughly two minutes. The same operation using R data.tables takes less than 22 seconds. Is there a more efficient way to do this in python? For comparison, R data.table: system.time({ df[,.(.N), .(ID, TERM)] }) #user: 30.32 system: 2.45 elapsed: 22.88
score: 8
upvote count: 8
type: Question
has comment: http://stackoverflow.com/comment/81148936
tagged with: python
tagged with: optimization
has comment: http://stackoverflow.com/comment/81149063
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/81151418
downvote count: 0
tagged with: dataframe
has comment: http://stackoverflow.com/comment/81153117
has title: Most efficient way to groupby => aggregate for large dataframe in pandas

http://stackoverflow.com/a/58255053
answers question: http://stackoverflow.com/q/47128376
score: 1
downvote count: 0
upvote count: 1
has body: you can do it as you do in system using os import os os.environ['varible']='value'
type: Answer

http://stackoverflow.com/q/47213925
has answer: http://stackoverflow.com/a/47214119
type: Question
has body: I have a question how to select different column(create new series) based on another column value. raw data as following： DEST_ZIP5 EXP_EDD_FRC_DAY GND_EDD_FRC_DAY \ 0 00501 5 6 1 00544 5 6 2 01001 4 8 3 01001 4 8 4 01001 4 8 EXP_DAY_2 EXP_DAY_3 EXP_DAY_4 EXP_DAY_5 ... \ 0 0.0 1.00 1.00 1.0 ... 1 0.0 1.00 1.00 1.0 ... 2 0.0 0.85 1.00 1.0 ... 3 0.0 1.00 1.00 1.0 ... 4 0.0 0.85 0.85 1.0 ... GND_DAY_3 GND_DAY_4 GND_DAY_5 GND_DAY_6 GND_DAY_7 GND_DAY_8 \ 0 NaN NaN NaN NaN NaN NaN 1 NaN NaN NaN NaN NaN NaN 2 0.0 0.0 0.16 0.33 0.83 1.00 3 0.0 0.0 0.00 0.14 0.71 0.85 4 0.1 0.1 0.20 0.40 0.40 0.60 I want to have two new data serize which get the number value of for responding column. (the row 1, EXP_EDD_FRC_DAY =5, so, return df[EXP_DAY_5]. GND_EDD_FRC_DAY =6, return df[GND_DAY_6] DEST_ZIP5 EXP_percentage GND_percentage \ 0 00501 1.0 NaN 1 00544 1.0 NaN 2 01001 1.0 1.00 3 01001 1.0 0.85 4 01001 0.85 0.60 I found function lookup. Not not sure how to use that. Thank you very much -
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
tagged with: python-2.7
score: 0
tagged with: pandas
has title: select different column python pandas
answer count: 1

http://stackoverflow.com/comment/81149694
comment on: http://stackoverflow.com/a/47096657
score: 1
type: Comment
has text: A common practice is to just copy the central value and "predict" it into the future `mode='nearest'`. Or you calculate your polynomial fit according to the last known data and then extrapolating into the future. In both cases you have to deal with the fact that you are "creating" information which is not there.
type: AnswerComment

http://stackoverflow.com/q/47107179
tagged with: oauth
tagged with: api
tagged with: python
has answer: http://stackoverflow.com/a/47107438
accepted answer: http://stackoverflow.com/a/47107438
type: AnsweredQuestion
has body: I am trying to follow along with the Python-Instagram simple example on their readme: api = InstagramAPI(client_id=client_id, client_secret=client_secret) popular_media = api.media_popular(count=20) for media in popular_media: print media.images['standard_resolution'].url However, every time I try with my own client_id and client_secret I get the following error and have been unable to figure out how to solve it: Traceback (most recent call last): File "/Users/PycharmProjects/Instagram API/InstaApiTest.py", line 10, in &lt;module&gt; popular_media = api.media_popular(count=20) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/instagram/bind.py", line 197, in _call return method.execute() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/instagram/bind.py", line 189, in execute content, next = self._do_api_request(url, method, body, headers) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/instagram/bind.py", line 163, in _do_api_request raise InstagramAPIError(status_code, content_obj['meta']['error_type'], content_obj['meta']['error_message']) instagram.bind.InstagramAPIError: (400) OAuthAccessTokenException-The access_token provided is invalid. Can anyone help me solve this issue?
score: 0
tagged with: instagram
has title: OAuthAccessTokenException-The access_token provided is invalid
answer count: 1
type: Question

http://stackoverflow.com/q/47162863
favorite count: 0
type: Question
has body: I'm trying to run simulation by using gem5 on ubuntu 16.04 lts and I write code './build/X86/gem5.opt ./configs/tutorial/two_level.py'. The output on terminal was: Traceback(most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "home/park/gem5/src/python/m5/main.py", line 433, in main exec filecode in scope File "./configs/tutorial/two_level.py", line 3, in &lt;module&gt; from caches import* ImportError: No module named caches I tried everything I can, but couldn't know. What is the problem?
has answer: http://stackoverflow.com/a/48942164
type: UnansweredQuestion
tagged with: python
tagged with: ubuntu
tagged with: gem5
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has title: importerror no module named caches
has comment: http://stackoverflow.com/comment/81276145

http://stackoverflow.com/a/47219146
has comment: http://stackoverflow.com/comment/81389047
upvote count: 1
has comment: http://stackoverflow.com/comment/81387679
has comment: http://stackoverflow.com/comment/81388802
answers question: http://stackoverflow.com/q/47218970
score: 1
has comment: http://stackoverflow.com/comment/81388606
type: Answer
accepted answer of: http://stackoverflow.com/q/47218970
has comment: http://stackoverflow.com/comment/81388982
has comment: http://stackoverflow.com/comment/81388098
has body: You define attribute self.totalmarks in display() method of Marks class So when you call eligible_for_reward(), totalmarks is not defined at this moment. So you can fix this by calling display() method first: m2=Marks() m2.dispay() m2.eligible_for_reward() But this won't work because self.literature self.math self.biology self.physics are not defined at this time as well. You have to add init() method to all the classes to call super() inside and correctly instantiate the class, like this: class Student: def __init__(self): self.name = input("Name: ") self.age = input("Age: ") self.gender = input("Gender: ") class Test(Student): def __init__(self): super(Test, self).__init__() self.stuClass = input("YearGroup/Class: ") print("Enter the marks of the respective subjects") self.literature = int(input("Literature: ")) self.math = int(input("Math: ")) self.biology = int(input("Biology: ")) self.physics = int(input("Physics: ")) class Marks(Test): def __init__(self): super(Marks, self).__init__() self.total_marks = self.literature + self.math + self.biology + self.physics def display(self): print("\n\nName: ",self.name) print("Age: ",self.age) print("Gender: ",self.gender) print("Class Year Group: ",self.stuClass) print("Total Marks: ", self.literature + self.math + self.biology + self.physics) def eligible_for_reward(self): if self.total_marks&gt;=90 and self.age&gt;13: print("You are eligible for the fabulous school sponsored trip to London") else: print("Sorry, you are not eligible and so are going nowhere....!") And you can use it as follow: marks = Marks() marks.eligible_for_reward() marks.display()
has comment: http://stackoverflow.com/comment/81387755
has comment: http://stackoverflow.com/comment/81388057
has comment: http://stackoverflow.com/comment/81388890
has comment: http://stackoverflow.com/comment/81387874
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/81244238
comment on: http://stackoverflow.com/q/47146838
score: 0
has text: Also, you need to keep passing the `**kwargs` ....
type: Comment
type: QuestionComment

histogram
tags question: http://stackoverflow.com/q/47085909
tags question: http://stackoverflow.com/q/47106963
tags question: http://stackoverflow.com/q/47084879
tags question: http://stackoverflow.com/q/47186962
type: Tag
tags question: http://stackoverflow.com/q/47085662
tags question: http://stackoverflow.com/q/47087173
tags question: http://stackoverflow.com/q/47104642
tags question: http://stackoverflow.com/q/47144724
tag name: histogram

http://stackoverflow.com/a/47089850
accepted answer of: http://stackoverflow.com/q/47089673
score: 0
answers question: http://stackoverflow.com/q/47089673
type: AcceptedAnswer
has body: The problem here is that you never check if the position is already revealed. You could do it by checking for the initial 'x': # ... if wrong != 1: if [row, col] in mines: break elif board[row][col] != 'x': print('This square is already revealed!! Try again') else: board[row][col] = str(adj_mines(row,col,0)) moves = moves - 1 # ...
type: Answer

http://stackoverflow.com/comment/81210009
comment on: http://stackoverflow.com/a/47123331
has text: You could do a partial dependency plot on the classification prediction, so you'd get `f19` values vs. prediction, for a fixed set of features. "Unreasonable to ask" is really context specific, in a stakeholder setting I think you could look at some important features in a dependency plot, but wouldn't ever attempt to explain the details, or push it as proof of causation.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/47187478
type: Answer
answers question: http://stackoverflow.com/q/47186724
has body: I don't believe that you will be able to use pandas to plot a scatter plot with a categorical variable. You could assign a numeric value to each month that you are trying to plot, although you could also just use matplotlib Create a test data set: data = np.random.randn(4, 3) df = pd.DataFrame(data, columns=['Jan', 'Feb', 'Mar']) Convert this to long form: df = df.melt() When you plot you need to specify the x location of each category. I use enumerate, although you could create a new column with numeric values as well groups = df.groupby('variable') fig, ax = plt.subplots() x_ticks = [] x_ticklabels = [] for i, (name, group) in enumerate(groups): y = group.value x = [i]*len(y) ax.scatter(x, y) x_ticks.append(i) x_ticklabels.append(name) Then you can set your tick labels to be match your x-values: ax.set_xticks(x_ticks) ax.set_xticklabels(x_ticklabels); Update I like to deal with things in long form as each entry becomes a single observation, however I realize it would be more concise to loop through the columns without transforming the data: fig, ax = plt.subplots() for i, (name, value) in enumerate(df.iteritems()): ax.scatter([i]*len(value), value) ax.set_xticks(range(len(df.columns))) ax.set_xticklabels(df.columns);
has comment: http://stackoverflow.com/comment/81364352
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/81325704
has comment: http://stackoverflow.com/comment/81900075
downvote count: 0
has comment: http://stackoverflow.com/comment/81325847
has comment: http://stackoverflow.com/comment/81325811
has comment: http://stackoverflow.com/comment/81365094

http://stackoverflow.com/comment/81393188
has text: Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47221551

http://stackoverflow.com/q/47125132
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/48739485
tagged with: conda
upvote count: 4
has body: after trying to update Anaconda using conda update --all, the downloading successfully ends but when trying to install the packages, the error message: " Windows cannot find 'pythonw'. Make sure you typed the name correctly, and then try again " appears. anyone knows how to deal with it? thanks in advance P.S. I installed Anaconda somewhere other that C:\, might have something to do with that? Environment variables?
type: AnsweredQuestion
has title: Error appears when installing python packages: pythonw not found
downvote count: 0
has comment: http://stackoverflow.com/comment/81210084
has comment: http://stackoverflow.com/comment/81210359
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49718401
has answer: http://stackoverflow.com/a/65818453
has comment: http://stackoverflow.com/comment/81200488
has answer: http://stackoverflow.com/a/49718401
answer count: 3
tagged with: anaconda
tagged with: python-packaging
possible better answer: http://stackoverflow.com/a/48739485

http://stackoverflow.com/a/47120353
type: AcceptedAnswer
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/47120247
type: Answer
accepted answer of: http://stackoverflow.com/q/47120247
has body: You can use pathlib: import os import sys &gt;&gt;&gt; from pathlib import Path &gt;&gt;&gt; import os &gt;&gt;&gt; import sys &gt;&gt;&gt; p = Path(os.path.dirname(sys.executable)) &gt;&gt;&gt; p WindowsPath('C:/Python36') &gt;&gt;&gt; x = p.joinpath('Scripts/pip3.6.exe') &gt;&gt;&gt; y = p.joinpath('Scripts\\pip3.6.exe') &gt;&gt;&gt; print(x.as_posix()) C:/Python36/Scripts/pip3.6.exe &gt;&gt;&gt; print(y.as_posix()) C:/Python36/Scripts/pip3.6.exe
has comment: http://stackoverflow.com/comment/81196669
upvote count: 2

http://stackoverflow.com/q/47202607
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: anaconda
type: UnansweredQuestion
has body: when I launch this on terminal conda version I get wheel 0.30.0 even if I added conda command to system variables pointing at the .exe. Do you know how to fix this?
has title: conda version in terminal finds wheel instead of exe
tagged with: python
has comment: http://stackoverflow.com/comment/81353709
answer count: 0
score: 1

http://stackoverflow.com/comment/81322656
has text: Possible duplicate of [Python save variable to file like save() in MATLAB](https://stackoverflow.com/questions/31915120/python-save-variable-to-file-like-save-in-matlab)
score: 0
comment on: http://stackoverflow.com/q/47186746
type: QuestionComment
type: Comment

connection
tag name: connection
type: Tag
tags question: http://stackoverflow.com/q/47102036

http://stackoverflow.com/a/47214831
type: Answer
has body: Because you are comparing st[i] with st[i+1], you must iterate only until the 2nd to last item in the string: however, in the present case, your logic is also flawed. The next digit you are returning may not be the correct solution: Here is an approach: def max_even_digs(st): max_even = 0 for elt in st: if elt.isdigit() and int(elt) % 2 == 0: if int(elt) &gt; max_even: max_even = int(elt) return max_even Or, this one if you prefer conciseness: def max_even_digs(st): return max(int(elt) for elt in st if elt.isdigit() and int(elt) % 2 == 0)
score: 0
answers question: http://stackoverflow.com/q/47214786

http://stackoverflow.com/comment/81319242
has text: I can't tell what you've tried from that comment. Please edit your question. If you're using `ListView`, then you should be overriding `get_queryset`.
score: 0
comment on: http://stackoverflow.com/a/47182714
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/81324874
type: AnswerComment
comment on: http://stackoverflow.com/a/47168349
score: 0
type: Comment
has text: Regarding the 'key' attributes, if you don't store them in the players, you have to duplicate a lot of the event handling code in the event loop. The `handle_event` method can be moved to the event loop if you want, you just have to keep the `for player in self.players:` loop to avoid the duplication. I think it fits better in the `Player` class, because so many instance attributes are manipulated.

http://stackoverflow.com/a/77144783
has comment: http://stackoverflow.com/comment/135998363
has body: I've the same problem but only for one filename. I save a lot files with diferent names in the same folder. And if I change this filename save the file. I've a question, OS library have some chars reserved? When I save "PRN.csv" in any folder take this error, if I change filename to "PRN5.csv" I can save it without errors.
has comment: http://stackoverflow.com/comment/136047624
type: Answer
answers question: http://stackoverflow.com/q/47143836
score: 0

http://stackoverflow.com/comment/81327381
score: 0
comment on: http://stackoverflow.com/q/47188143
has text: Noticed the edge case fail, thanks.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/81247477
type: QuestionComment
has text: Are you sure that you are processing more than 12 items (in your `map` for example)?
comment on: http://stackoverflow.com/q/47148672
score: 0
type: Comment

http://stackoverflow.com/comment/81276966
type: QuestionComment
comment on: http://stackoverflow.com/q/47160561
has text: Hey @jacksoncyr - welcome to StackOverflow. FYI: I have edited your question to include only the essentials needed to describe the problem you're having.
score: 0
type: Comment

http://stackoverflow.com/q/47119324
accepted answer: http://stackoverflow.com/a/47123536
type: Question
linked to: http://stackoverflow.com/q/47091223
score: 0
has answer: http://stackoverflow.com/a/47123536
has body: I'm adding a color parameter to the LineBand subclass of QWidget. I've found several examples of how to add additional parameters to a subclass in Python 3 and believe I've followed the advice. Yet, when I call the new version of the class using box = LineBand(self.widget2, color), I get the error File "C:/Users/...", line 63, in showBoxes ... box = LineBand(viewport, color) ... TypeError: __init__() takes 2 positional arguments but 3 were given. But, I'm only calling LineBand with 2 arguments, right? Below is the complete code. I've commented all the sections I've changed. I've also commented out the code that changes the background color of the text in order to see the colored lines more clearly (when they actually are drawn). The background color code works fine. import sys from PySide.QtCore import * from PySide.QtGui import * db = ((5,8,'A',Qt.darkMagenta),(20,35,'B',Qt.darkYellow),(45,60,'C',Qt.darkCyan)) # added color to db class TextEditor(QTextEdit): def __init__(self, parent=None): super().__init__(parent) text="This is example text that is several lines\nlong and also\nstrangely broken up and can be\nwrapped." self.setText(text) cursor = self.textCursor() for n in range(0,len(db)): row = db[n] startChar = row[0] endChar = row[1] id = row[2] color = row[3] # assign color from db to variable cursor.setPosition(startChar) cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor, endChar-startChar) #charfmt = cursor.charFormat() #charfmt.setBackground(QColor(color)) # assign color to highlight (background) #cursor.setCharFormat(charfmt) cursor.clearSelection() self.setTextCursor(cursor) def getBoundingRect(self, start, end): cursor = self.textCursor() cursor.setPosition(end) last_rect = end_rect = self.cursorRect(cursor) cursor.setPosition(start) first_rect = start_rect = self.cursorRect(cursor) if start_rect.y() != end_rect.y(): cursor.movePosition(QTextCursor.StartOfLine) first_rect = last_rect = self.cursorRect(cursor) while True: cursor.moveP…
answer count: 1
tagged with: qpainter
tagged with: qtextedit
type: AnsweredQuestion
has title: Adding additional parameters to QWidget subclass using PySide
tagged with: pyside
tagged with: python

http://stackoverflow.com/comment/81280771
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47148306
type: AnswerComment
has text: yes, that's why I included the condition where search returns -1, and therefore 10 words are written to file. Keep testing and analysing, I'm sure you would have a solution. Could you please upvote and accept my answer if I helped. Thanks!

http://stackoverflow.com/comment/81555151
has text: what to do next to run this on docker?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47280363
type: Comment

http://stackoverflow.com/comment/81228148
type: Comment
has text: thanks. I made this change, the code still works. However, when I run the executable (from py2exe), i get an error "NameError: name '__ file __' is not defined"
type: AnswerComment
comment on: http://stackoverflow.com/a/47138950
score: 0

http://stackoverflow.com/comment/81193637
comment on: http://stackoverflow.com/q/47121960
type: Comment
has text: Hate to be the picky one, but now there's not even a question in your *question* :) You found some answers already, and you're thinking of making a script. All good, but what have you tried? what's your issue? what do you need our help with? :P
type: QuestionComment
score: 0

http://stackoverflow.com/a/56628831
has comment: http://stackoverflow.com/comment/130023921
type: Answer
score: 0
has body: I was not able to install cv2 on Anaconda-Jupyter notebook running on Ubuntu on Google Cloud Platform. But I found a way to do it as follows: Run the following command from the ssh terminal and follow the instruction: sudo apt-get install libsm6 libxrender1 libfontconfig1 Once its installed Open the Jupyter notebook and run following command: !pip install opencv-contrib-python Note: I tried to run this command: "sudo python3 -m pip install opencv-contrib-python"but it was showing an error. But above command worked for me. Now refresh the notebook page and check whether it's installed or not by running import cv2 in the notebook.
answers question: http://stackoverflow.com/q/47113029

http://stackoverflow.com/comment/114747759
score: 1
type: Comment
type: AnswerComment
has text: Really useful answer, thanks for this. This is probably the most relevant bit of documentation on object naming: https://cloud.google.com/storage/docs/naming-objects#object-considerations
comment on: http://stackoverflow.com/a/47141481

http://stackoverflow.com/comment/86648722
type: Comment
comment on: http://stackoverflow.com/a/47183890
type: AnswerComment
score: 0
has text: Here is my code snippet. `K.set_floatx('float16') for layer_idx, layer in enumerate(model.layers): old_weights = layer.get_weights() for idx, weight in enumerate(old_weights): new_weights.append(K.cast_to_floatx(weight)) model.get_layer(name=layer.name).set_weights(new_weights)` But this dosen't work

http://stackoverflow.com/q/47214856
answer count: 3
has body: I'm doing some calculation with python. But I troubling with decimal numbers. my code is like: from decimal import * x = 0.0000001582 y = 0.00000020 z = 1000 a = 0.000000100 b = (x+y)/z result = x + b print result My results comes like this 1.585582e-07 . I want simple decimal number up to 10 digits. How can I do that?
type: Question
tagged with: decimal
has title: Decimal number with 10 digits
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47214919
linked to: http://stackoverflow.com/q/19532556
tagged with: python
has comment: http://stackoverflow.com/comment/81379309
has answer: http://stackoverflow.com/a/79378242
has answer: http://stackoverflow.com/a/47214905
score: 0

http://stackoverflow.com/a/67729463
has body: After posting my answer, I realized I answered the opposite of what was being asked. I found this question while trying to figure out how to remove the space between bars. I almost deleted my answer, but in case anyone else stumbles on this question and is trying to remove the space between bars in seaborn's histplot, I'll leave it for now. Thanks to @miro for Seaborn's updated documentation, I found that element='step' worked for me. Depending on exactly what you want, element='poly' may be what you are after. My implementation with 'step': fig,axs = plt.subplots(4,2,figsize=(10,10)) i,j = 0,0 for col in cols: sns.histplot(df[col],ax=axs[i,j],bins=100,element='step') axs[i,j].set(title=&quot;&quot;,ylabel='Frequency',xlabel=labels[col]) i+=1 if i == 4: i = 0 j+=1 My implementation with 'poly': fig,axs = plt.subplots(4,2,figsize=(10,10)) i,j = 0,0 for col in cols: sns.histplot(df[col],ax=axs[i,j],bins=100,element='poly') axs[i,j].set(title=&quot;&quot;,ylabel='Frequency',xlabel=labels[col]) i+=1 if i == 4: i = 0 j+=1
type: Answer
answers question: http://stackoverflow.com/q/47144724
score: 0
has comment: http://stackoverflow.com/comment/124630894

http://stackoverflow.com/q/47156968
linked to: http://stackoverflow.com/q/38993877
has answer: http://stackoverflow.com/a/47158478
has body: I have a huge logs table stored in GoogleCloud storage. Querying it it is becoming more and more expensive, and I have to find a solution, which I think is to partition the table. I can manage by myself to upload old data from the big table to the new created partitioned one, but I am struggling to modify my existing python code which is loading data daily from the storage to the biguqery table. I want it to provide data already partitioned by different days. def bq_load(filename): bq_load_cmd = 'bq load --skip_leading_rows=1 --source_format=' + format + ' ' + schema + '.' + table + ' ' + google_bucket + '/' + filename print bq_load_cmd bq_load_cmd_out = commands.getstatusoutput(bq_load_cmd) print bq_load_cmd_out bq_status = bq_load_cmd_out[0] if bq_status == 0: print 'Bq load successfull filename : ' + filename else: print 'Error loading the file in bq : ' + filename mail_cmd = 'mail -s " bq load error hasoffer_clicks" ' + recipient + ' &lt; /dev/null' mail_cmd = commands.getstatusoutput(mail_cmd) This is part of the code I am using right now, which is in the crontab and loads csv files into the table in BigQuery on a daily basis. I searched through internet but so far I didn't manage to understand which is the proper solution to my problem. I think the bq load command might be the one to modify, but I am not sure. Any suggestion? Kind regards, Eugenio
tagged with: python
has answer: http://stackoverflow.com/a/47181404
tagged with: google-bigquery
score: 2
upvote count: 2
answer count: 2
downvote count: 0
type: UnansweredQuestion
has title: Uploading data in google cloud storage to a partitioned table through python code
favorite count: 0
type: Question

http://stackoverflow.com/a/47118533
has body: You are only missing a comma character in the RETURN clause after RETURN pd2.title as product_title: RETURN pd2.title as product_title, pd2.description as product_details
type: Answer
has comment: http://stackoverflow.com/comment/81189718
answers question: http://stackoverflow.com/q/47118349
score: 0

http://stackoverflow.com/q/47105138
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47108531
tagged with: pyspark
downvote count: 0
tagged with: python
has body: I have a df with the following schema: root |-- col1: string (nullable = true) |-- col2: array (nullable = true) | |-- element: string (containsNull = true) in which one of the columns, col2 is an array [1#b, 2#b, 3#c]. I want to convert this to the string format 1#b,2#b,3#c. I am currently doing this through the following snippet df2 = (df1.select("*", explode(col2)).drop('col2')) df2.groupBy("col1").agg(concat_ws(",", collect_list('col')).alias("col2")) While this gets the job done, it is taking time and also seems inefficient. Is there a better alternative?
answer count: 1
has title: How to convert an array to string efficiently in PySpark / Python
favorite count: 0
score: 9
type: Question
upvote count: 9