http://stackoverflow.com/a/48317854
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48255105
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/48255105
has body: Had to remove the while loop and move the after() statement to the else: now it works...this particular code I am sure doesn't work but it explains the concept. def turnOn(): global proc if proc is None: window.after(50000,file_chk) print('Starting Beacon') proc = subprocess.Popen(["python3", "/home/pi/FLBeacon/FLBeaconout.py"]) label1 = Label(window,text ="Beacon is Running") label1.configure(bg='green') label1.place(x= 350, y=10, width=150) global label2 label2 = Label(window,text = full_message) label2.configure(bg='green') label2.place(x=50, y=90, width=550) def file_chk(): filelist = ['FLBeaconRecieved.txt'] list1 = [] for file in filelist: list1.append(os.path.isfile(file)) if all(list1): #all elements are true print("file has been found") file = open("FLBeaconRecieved.txt") data = file.read() file.close() Results = Label(window, text = data) Results.place(x = 50, y = 350) turnOff() label1 = Label(window,text = "Beacon is not running") label1.configure(bg='red') label1.place(x= 350, y=10, width=150) label2.destroy() return else: print("there is no file") window.after(50000,file_chk)

http://stackoverflow.com/a/48180160
accepted answer of: http://stackoverflow.com/q/48178475
answers question: http://stackoverflow.com/q/48178475
score: 1
type: Answer
has body: If you're going to be working with data like this more in the future, I would strongly recommend that you read through the pandas documentation. This includes a 10 minute "getting started" guide which covers many of the common use-cases, including examples very similar to this one. That being said, you have most of the components that you need in the code that you gave above. The two issues that I see are as follows: If you look at the DataFrame's data types (df_raw.dtypes in your code above), you'll see that your Latlng column is actually still a string, while Pandas has helpfully already converted the Latitude and Longitude columns to floats for you. That should tell you that it may be easier to work with those two since they'll be directly usable in positioning your marker. You'll probably want to configure your map a bit - the defaults that you took from the example code create a terrain map centered somewhere in Oregon. Given that you're plotting properties in Toronto - neither of those seem like good options. I generally like to center my map at the mean point of my data. A simple example to get things working could look like: import pandas as pd import folium df = pd.read_csv("df_condo_v9_t1.csv") map_center = [df["Latitude"].mean(), df["Longitude"].mean()] map_1 = folium.Map(location=map_center, zoom_start=16) for i, row in df"Latitude", "Longitude".dropna().iterrows(): position = (row["Latitude"], row["Longitude"]) folium.Marker(position).add_to(map_1) map_1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83576204
type: Comment
type: QuestionComment
has text: @PaulPanzer I will, but I am not yet 100% satisfied with the result but will see how to fix this myself.
score: 0
comment on: http://stackoverflow.com/q/48291036

http://stackoverflow.com/q/48244991
has comment: http://stackoverflow.com/comment/83473887
has comment: http://stackoverflow.com/comment/83473367
has comment: http://stackoverflow.com/comment/83473528
has comment: http://stackoverflow.com/comment/83473378
has comment: http://stackoverflow.com/comment/83472922
has answer: http://stackoverflow.com/a/48245142
tagged with: python
has answer: http://stackoverflow.com/a/48245275
type: AnsweredQuestion
has title: Nth 1 in a sequence
has comment: http://stackoverflow.com/comment/83472719
has comment: http://stackoverflow.com/comment/83473159
score: 1
has comment: http://stackoverflow.com/comment/83472959
downvote count: 1
has comment: http://stackoverflow.com/comment/83473317
possible better answer: http://stackoverflow.com/a/48245142
answer count: 4
has body: A array of length t has all elements initialized by 1 .Now we can perform two types of queries on the array to replace the element at ith index to 0 .This query is denoted by 0 index find and print an integer denoting the index of the kth 1 in array A on a new line; if no such index exists print -1.This query is denoted by 1 k Now suppose for array of length t=4 all its elements at the beginning are [1,1,1,1] now for query 0 2 the array becomes [1,0,1,1] and for query 1 3 the output comes out to be 4 I have used a brute force approach but how to make the code more efficient? n,q=4,2 arr=[1]*4 for i in range(q): a,b=map(int,input().split()) if a==0: arr[b-1]=0 else: flag=True count=0 target=b for i,j in enumerate(arr): if j ==1: count+=1 if count==target: print(i+1) flag=False break if flag: print(-1) I have also tried to first append all the indexes of 1 in a list and then do binary search but pop 0 changes the indices due to which the code fails def binary_search(low,high,b): while(low&lt;=high): mid=((high+low)//2) #print(mid) if mid+1==b: print(stack[mid]+1) return elif mid+1&gt;b: high=mid-1 else: low=mid+1 n=int(input()) q=int(input()) stack=list(range(n)) for i in range(q): a,b=map(int,input().split()) if a==0: stack.pop(b-1) print(stack) else: if len(stack)&lt;b: print(-1) continue else: low=0 high=len(stack)-1 binary_search(low,high,b)
has comment: http://stackoverflow.com/comment/83473087
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83472985
has answer: http://stackoverflow.com/a/48245281
has answer: http://stackoverflow.com/a/48245775
accepted answer: http://stackoverflow.com/a/48245775
has comment: http://stackoverflow.com/comment/83473016
tagged with: algorithm

http://stackoverflow.com/q/48243665
has title: Compare each item in list with a value and return T/F in Python
tagged with: list
answer count: 3
has body: I have a list a = [3,5,2,3,1] and I want to check whether each item in this list is no less than 3. I tried a &gt;= 3, but it has TypeError. TypeError: '&gt;=' not supported between instances of 'list' and 'int' Desired output [True, True, False, True, False]
score: 1
has answer: http://stackoverflow.com/a/48243681
has answer: http://stackoverflow.com/a/48243774
possible better answer: http://stackoverflow.com/a/48243681
downvote count: 1
has comment: http://stackoverflow.com/comment/83469795
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48243733
has comment: http://stackoverflow.com/comment/83469835
accepted answer: http://stackoverflow.com/a/48243774
tagged with: python
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/83478571
has text: @ThomasKühn, thank you! I didn’t know the trick with the “zorder”, so I have learned something new from your comment! :)
type: AnswerComment
comment on: http://stackoverflow.com/a/48239187
score: 0
type: Comment

http://stackoverflow.com/comment/83535003
comment on: http://stackoverflow.com/q/48264736
type: QuestionComment
score: 0
has text: Each of those distributions will fit to different parameters, so if you're keeping the parameters and switching the distribution `kstest` will tell you your input distribution is nothing like the data (which is what 1 stat 0 p basically means).
type: Comment

http://stackoverflow.com/q/48264471
type: Question
has body: Is there any way to dynamically Count how many Arguments has been passed to a keyword AND is there a way to print arguments like Log ${Argument1}, ${Argument2}?. for E.g. There are some 10 check boxes to select. but in TC QA selects only few items which he/she sends as argument to a keyword. So, We want to capture all the list of arguments to create a List and iterate through them to select the right check boxes Add Arguments to List [Arguments] arg1 arg2 arg3 arg4 arg5 ${NoOf_Arguments} = #TODO: no idea how to count no of arguments @{List_To_Create}= Create List : For ${item} IN RANGE ${NoOf_Arguments} \ append to list ${List_To_Create} ${item} [Return] ${List_To_Create}
tagged with: robotframework
has comment: http://stackoverflow.com/comment/83514375
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/48265667
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83512147
downvote count: 0
score: 1
has title: Robot FrameWork:: How to Count Arguments?
tagged with: python
has comment: http://stackoverflow.com/comment/83513961
accepted answer: http://stackoverflow.com/a/48265667

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

http://stackoverflow.com/comment/83486419
score: 0
type: AnswerComment
has text: Yes, it is. I don't know, why the solutions differ. The function minimum is calculated as 368507, which is lower than your posted solution. Why? I don't kow. I would add some code to test, that all equality and inequality parameters are met indeed as expected and that the calculated function indeed gives the value you got back from scipy. I assume, you made sure, that the sample solution is correct.
comment on: http://stackoverflow.com/a/48251641
type: Comment

http://stackoverflow.com/comment/83573012
score: 0
type: QuestionComment
has text: A`continue` a the last command in the loop does not make much sense.
type: Comment
comment on: http://stackoverflow.com/q/48293382

http://stackoverflow.com/comment/86770820
comment on: http://stackoverflow.com/q/48218897
score: 0
has text: Any update/feedback on the answer I posted?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48309567
has title: How can i get a path relative from an other?
type: Question
has comment: http://stackoverflow.com/comment/83604763
answer count: 2
has comment: http://stackoverflow.com/comment/83604762
possible better answer: http://stackoverflow.com/a/48309609
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48309609
has body: I have a path1 relative from a path2 and I want to get this path1 from my script which isn't path1 or path2. I know the absolute path of path2.
tagged with: python-os
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48480098
has answer: http://stackoverflow.com/a/48480098
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/83615026
score: 0
has text: If I want to select another train('rn') from the same paragraph of route = red, will the same commands work as well?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48314603

http://stackoverflow.com/q/48182073
tagged with: dictionary
linked to: http://stackoverflow.com/q/9001509
type: Question
has title: python sort dictionary by descending order of key
has comment: http://stackoverflow.com/comment/83343808
has body: I want to sort this dictionary d based on integer keys. d = { '123': 'aaa', '124': 'bbb, '125': 'ccc', } So final dictionary would look like this. d = { '125': 'ccc', '124': 'bbb', '123': 'aaa, } I know that Dictionaries do not have any inherent order. But is it achievable?
has comment: http://stackoverflow.com/comment/83346163
duplicate of: http://stackoverflow.com/q/9001509
has comment: http://stackoverflow.com/comment/83343787
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83343812
has comment: http://stackoverflow.com/comment/83343799
score: 0
has comment: http://stackoverflow.com/comment/83343707
has comment: http://stackoverflow.com/comment/83343797
answer count: 0
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/83530580
has text: sample input and expected output.
comment on: http://stackoverflow.com/q/48273404
type: Comment
score: 2
type: QuestionComment

http://stackoverflow.com/a/49593925
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48259724
score: 1
downvote count: 0
has body: This will do definetively the job... import cv2 import os import numpy as np img = cv2.imread("image.png") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) retval, thresholded = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU) medianFiltered = cv2.medianBlur(thresholded, 3) _, contours, hierarchy = cv2.findContours(medianFiltered, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contour_list = [] for contour in contours: area = cv2.contourArea(contour) if area &gt; 80: contour_list.append(contour) numbers = cv2.drawContours(img, contour_list, -1, (0, 0, 0), 2) cv2.imshow('i', numbers) cv2.waitKey(0) sorted_ctrs = sorted(contours, key=lambda ctr: cv2.boundingRect(ctr)[0]) for i, cnts in enumerate(contours): cnt = contours[i] x, y, w, h = cv2.boundingRect(cnt) croped = numbers[y:y + h, x:x + w] h, w = croped.shape[:2] print(h, w) if h &gt; 15: cv2.imwrite("croped{}.png".format(i), croped)

http://stackoverflow.com/q/48244181
tagged with: matplotlib
tagged with: python
tagged with: ipython
tagged with: jupyter-notebook
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83481506
has body: I'm currently working on a Jupyter notebook that creates an energy level diagram using matplotlib. One parameter of the underlaying spectrum computation can be varied using an interact statement. Now I want to export this notebook to HTML while the widget functionality should stay intact. Is it possible to precompute all possible outcomes and include them into the HTML version? Users should be able to use the interact feature without having to connect to a kernel. Thanks for advice. Peter EDIT: I hope to clarify my question with the following sample code: from ipywidgets import interact import matplotlib.pyplot as plt import numpy as np def f(a): x = np.linspace(0,2,100) plt.plot(x,a*x**2) plt.ylim([0,20]) plt.show() return None interact(f, a=(1,5,1)) In the final HTML file all possible images (in this case all parabolas with a=1...5) should be included (in this sense pre-computed) and then displayed when the user selects the appropiate value with the slider.
has title: Precompute Jupyter widget results and embed in HTML
has comment: http://stackoverflow.com/comment/83479132
type: Question
has comment: http://stackoverflow.com/comment/83472513
type: UnansweredQuestion

http://stackoverflow.com/comment/83448150
comment on: http://stackoverflow.com/q/48232511
type: Comment
type: QuestionComment
has text: @Idlehands What should it return, for OP?
score: 0

http://stackoverflow.com/a/48217588
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48217471
score: 3
has body: The pythonic way of answering this question would be using a collections.Counter object: from collections import Counter def anagram(s1, s2): return Counter(s1) == Counter(s2) But since those are restricted, you can fall back to vanilla dictionaries (also known as hashmaps, a fundamental ingredient in so many efficient algorithms). A high level process is as follows. First, build a hashmap of counts for string1. Repeat the process for string2. Finally, compare the two hashmaps for equality. First, the helper function - def build_counts(string): ctr = {} for c in string: ctr[c] = ctr.setdefault(c, 0) + 1 return ctr And now, the driver - def anagram(string1, string2): c1 = build_counts(string1) c2 = build_counts(string2) return c1 == c2 Complexity Analysis - building each hashmap takes O(N) time, and performing comparison is O(N) as well, since you have to, one, test if the keys are identical, and two, compare the values of corresponding keys. All in all, a linear algorithm. Since hashmaps and hash sets are so commonplace, you should not argue that this is restricted, unless you plan on implementing your own hash map with arrays and open addressing. And no, there is no efficient algorithm that does not rely on hashmaps or something more complicated. Not unless you go with viraptor's answer, which is basically an array version of a hashmap (!), but having a unique entry for every single character in the ASCII set. For example, the count for ASCII character 65 would be accessed with arr[65], and so on. So, you'd need to have an array big enough to fit every ASCII character. Things are manageable for just the ASCII letters, but the plot thickens when you consider other, broader encodings (unicode). In the end, it's a lot more space efficient to just use a hashmap.
type: Answer
accepted answer of: http://stackoverflow.com/q/48217471
has comment: http://stackoverflow.com/comment/83418310

http://stackoverflow.com/q/48175427
favorite count: 0
type: Question
tagged with: python-3.x
has title: Propriate way to setup dispy and SSL
type: UnansweredQuestion
tagged with: sockets
tagged with: ssl
tagged with: python
tagged with: dispy
answer count: 0
score: 1
has body: I am struggling to setup dispy and SSL. Here are steps i made to setup: To create a certificate i used command: openssl req -x509 -newkey rsa:4096 -sha256 -nodes -keyout private.key -out private.crt -days 3650 Then i merged two files: cat private.crt private.key &gt; private.pem In my particular case i need to use all: scheduler (dispyscheduler), node (dispynode) and cluster (SharedJobCluster). Here is a job i submit: # canonical.py # function 'compute' is distributed and executed with arguments # supplied with 'cluster.submit' below def compute(n): import time, socket time.sleep(n) host = socket.gethostname() return (host, n) if __name__ == '__main__': # executed on client only; variables created below, including modules imported, # are not available in job computations import dispy, random # distribute 'compute' to nodes; in this case, 'compute' does not have # any dependencies to run on nodes cluster = dispy.SharedJobCluster(compute, port=0, certfile='C:\\project\\private.pem') # run 'compute' with 20 random numbers on available CPUs jobs = [] for i in range(5): job = cluster.submit(random.randint(5, 5)) job.id = i # associate an ID to identify jobs (if needed later) jobs.append(job) # cluster.wait() # waits until all jobs finish for job in jobs: host, n = job() # waits for job to finish and returns results print('%s executed job %s at %s with %s' % (host, job.id, job.start_time, n)) # other fields of 'job' that may be useful: # job.stdout, job.stderr, job.exception, job.ip_addr, job.end_time cluster.print_status() # shows which nodes executed how many jobs etc. If i don't use an SSL connection it successfully works despite platform was used. Scheduler on Linux and node on Windows and vice versa. Any combination works just fine. But problem comes when i try to use SSL. Here are commands i have been using to run test job: On Linux dispynode.py -d --certfile=/home/dismine/project/private.pem --clean On Windows python "C:\Program Files\Python3\Lib\site-packages\disp…
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48271838
has comment: http://stackoverflow.com/comment/83527784
tagged with: typeerror
answer count: 2
has body: While searching for a solution to my previous question (which was obviously solved) I got another problem which is still unsolved. I would be very thankful to anyone who could help me to solve it! There was a thought that I was using an outdated version of matplotlib 1.5.1, but I have updated it now to 2.1.1 as well as numpy to 1.14.0, this hasnt helped me, alas. So, once again. I have a CSV file as input: 16,59,55,51 13.8 17,00,17,27 13.7 17,00,39,01 13.6 17,01,01,06 13.4 And I run this python script on it: import matplotlib.pyplot as plt import csv from datetime import time x = [] y = [] with open('calibrated.csv','r') as csvfile: plots = csv.reader(csvfile, delimiter=' ') for row in plots: hours,minutes,seconds,milliseconds = [int(s) for s in row[0].split(",")] x.append(time(hours,minutes,seconds,milliseconds)) y.append(float(row[1])) plt.plot(x,y, marker='o', label='brightness') plt.gca().invert_yaxis() plt.xlabel('time [UT]') plt.ylabel('brightness [mag, CR]') plt.legend() plt.grid() plt.show() And I get this TypeError upon it (while the person who solved my previous question doesnt have it!): Traceback (most recent call last): File "lightcurve.py", line 16, in &lt;module&gt; plt.plot(x,y, marker='o', label='brightness') File "/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 3154, in plot ret = ax.plot(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/matplotlib/__init__.py", line 1812, in inner return func(ax, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_axes.py", line 1425, in plot self.add_line(line) File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 1708, in add_line self._update_line_limits(line) File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 1730, in _update_line_limits path = line.get_path() File "/usr/local/lib/python2.7/dist-packages/matplotlib/lines.py", line 925, in get_path self.recache() File "/usr/local/lib/python2.7/dist-package…
downvote count: 0
has comment: http://stackoverflow.com/comment/83527985
has comment: http://stackoverflow.com/comment/83527450
has comment: http://stackoverflow.com/comment/83527670
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83527546
linked to: http://stackoverflow.com/q/48251417
has comment: http://stackoverflow.com/comment/83527732
has comment: http://stackoverflow.com/comment/83527624
has comment: http://stackoverflow.com/comment/83527573
upvote count: 8
favorite count: 0
has title: Plotting with matplotlib: TypeError: float() argument must be a string or a number
score: 8
type: Question
has answer: http://stackoverflow.com/a/48272128
tagged with: numpy
has comment: http://stackoverflow.com/comment/83527757
has comment: http://stackoverflow.com/comment/83527454
has comment: http://stackoverflow.com/comment/83528115
linked to: http://stackoverflow.com/q/32832431
linked to: http://stackoverflow.com/q/48269859
has comment: http://stackoverflow.com/comment/83528362
has comment: http://stackoverflow.com/comment/83527604
tagged with: python
linked to: http://stackoverflow.com/q/47404653
has comment: http://stackoverflow.com/comment/83527775
has answer: http://stackoverflow.com/a/48271944
possible better answer: http://stackoverflow.com/a/48271944
accepted answer: http://stackoverflow.com/a/48272128
type: AnsweredQuestion

http://stackoverflow.com/q/48293374
type: UnansweredQuestion
tagged with: compiler-construction
upvote count: 6
score: 4
has comment: http://stackoverflow.com/comment/83572111
downvote count: 2
linked to: http://stackoverflow.com/q/9451929
answer count: 3
has answer: http://stackoverflow.com/a/48293523
has answer: http://stackoverflow.com/a/48293437
has body: I want to understand how Python works at a base level, and this will hopefully help me understand a bit more about the inner workings of other compiled/interpreted languages. Unfortunately, the compilers class is a bit away for now. From what I read on this site and elsewhere, people answering "What base language is Python written in" seem to convey that there's a difference between talking about the "rules" of a language versus how the language rules are implemented for usage. So, is it correct to say that Python (and other high-level languages) are all essentially just sets of rules "written" in any natural language? And then the matter of how they're actually used (where used means compiled/interpreted to actually create things) can vary, with various languages being used to implement compilers? So in this case, CPython, IronPython, and Jython would be syntactically equal languages which all follow the same set of rules, just that those rules are implemented themselves in their respective languages. Please let me know if my understanding of this is correct, if you have anything to add that might further solidify my understanding, or if I'm blatantly wrong.
favorite count: 0
has title: Is my understanding of how Python is written/implemented correct?
type: Question
has answer: http://stackoverflow.com/a/48293389
tagged with: python

http://stackoverflow.com/comment/83372795
has text: For that reason, I want to tag this as numpy but it looks like you're just using python lists (despite saying you have np arrays)?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48195845

http://stackoverflow.com/comment/83512776
type: Comment
score: 0
type: QuestionComment
has text: @netplay I am afraid that finding the intersection of two linear functions is not my primary problem. First, I have to find which two neighbouring points on each line provide the linear functions I have to intersect
comment on: http://stackoverflow.com/q/48264619

http://stackoverflow.com/comment/103240410
has text: And what this code do? From where you got those hex values and byte strings?
comment on: http://stackoverflow.com/a/48574049
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48199590
has comment: http://stackoverflow.com/comment/136007204
downvote count: 0
score: 6
has body: YAML does not have a way to specify ranges in its specification, so if you want a language-agnostic way to specify range, you'd have to invent your own encoding on top of native YAML. Some examples: list_field: start: 10 step: 5 stop: 50 list_field2: range: - 10 - 50 - 5 list_field3: range(10,50,5) If using something like pyyaml, you could then use a custom resolver and constructor to teach pyyaml how to always decode/encode these things as/from python range objects (python3) or python xrange objects (python2) If you don't care about other languages, you could also always just store your ranges as serialized objects, e.g. using tags, e.g. !!python/object/apply:builtins.range [10, 50, 5]. They won't look the prettiest, but will deserialize to a python range object without needing to write custom encoder/decoder code: &gt;&gt;&gt; import yaml &gt;&gt;&gt; print(yaml.dump({'list_field': range(10, 50, 5)})) list_field: !!python/object/apply:builtins.range [10, 50, 5] &gt;&gt;&gt; print(yaml.load(yaml.dump({'list_field': range(10, 50, 5)}))) {'list_field': range(10, 50, 5)} See also How to specify ranges in YAML?
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/48199439

http://stackoverflow.com/q/48179891
tagged with: python
has answer: http://stackoverflow.com/a/48180601
accepted answer: http://stackoverflow.com/a/48180601
has comment: http://stackoverflow.com/comment/83340126
favorite count: 0
has comment: http://stackoverflow.com/comment/83340060
score: 2
tagged with: qtextedit
type: AnsweredQuestion
downvote count: 0
has title: How to scroll text in QTextEdit automatically (animational effect)?
tagged with: pyqt5
type: Question
upvote count: 2
has body: I would like to ask how to make the text in QTextEdit scoll, to achieve an animational effect. The animational effect should be something like what in the video shows: https://www.youtube.com/watch?v=MyeuGdXv4XM With PyQt I want to get this effect: The text should be scolled automatically at a speed of 2 lines/second downwards, till it reaches the end and stops. In my code below, when the button is clicked, the text is shown in QTextEdit-Widget. The text is very long, so that the scroll bar is shown. My Problem: I dont know how to make the animation effect. Thus I would like to ask your help to correct my code. # -*- coding: utf-8 -*- from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys import time list_longText = [" long text 1 - auto scrolling " * 1000, " long text 2 - auto scrolling " * 2000] class Worker(QObject): finished = pyqtSignal() strTxt = pyqtSignal(str) def __init__(self, parent=None): super(Worker, self).__init__(parent) @pyqtSlot() def onJob(self): for i in range(2): self.strTxt.emit(list_longText[i]) time.sleep(2) class MyApp(QWidget): def __init__(self): super(MyApp, self).__init__() self.setFixedSize(600, 400) self.setObjectName("window") self.initUI() def initUI(self): self.txt = QTextEdit("", self) self.btn = QPushButton("Button", self) self.btn.clicked.connect(self.start) self.layout = QHBoxLayout(self) self.layout.addWidget(self.txt) self.layout.addWidget(self.btn) self.setLayout(self.layout) self.show() def start(self): self.thread = QThread() self.obj = Worker() self.obj.strTxt.connect(self.showText) self.obj.moveToThread(self.thread) self.obj.finished.connect(self.thread.quit) self.thread.started.connect(self.obj.onJob) self.thread.start() def showText(self, str): self.txt.setText("{}".format(str)) self.autoScroll() def autoScroll(self): vsb = self.txt.verticalScrollBar() if vsb.value() &lt;= vsb.maximum(): vsb.setValue(vsb.value() + 2) time.sleep(1) if __name__ == "__main__": app = QApplication(sys.a…
has comment: http://stackoverflow.com/comment/83340155
has comment: http://stackoverflow.com/comment/83340169
has comment: http://stackoverflow.com/comment/83340193
tagged with: pyqt
has comment: http://stackoverflow.com/comment/83340096
answer count: 1

http://stackoverflow.com/q/48317839
tagged with: regex
has body: I have the following script trying to get this url: https://clips-media-assets.twitch.tv/178569498.mp4 which is in between {"quality":"1080","source":" and a " but my regex doesn't seem to be working dt = """ [download] 28.2x of 57.90MiB at 1.54MiB/s ETA 00:26 """ pattern = re.compile(r'(?:\G(?!\A)|quality\":\"1080\",\"source\":\")(?:(?!\").)*', re.MULTILINE | re.DOTALL) clipHTML = BeautifulSoup(dt, "html.parser") scripts = clipHTML.findAll(['script']) for script in scripts: if script: match = pattern.search(script.text) if match: email = match.group(0) print(email)
score: 0
has comment: http://stackoverflow.com/comment/83621310
has comment: http://stackoverflow.com/comment/83641102
answer count: 1
has comment: http://stackoverflow.com/comment/83621784
upvote count: 1
has title: finding the regex to get a url between two phrases
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48318203

http://stackoverflow.com/comment/83400402
has text: Try `"PROGRAM S\d\d\S*"`
type: Comment
comment on: http://stackoverflow.com/q/48209706
type: QuestionComment
score: 1

http://stackoverflow.com/q/48257323
has answer: http://stackoverflow.com/a/48257413
has body: list1=[1,3,8,10,23,8,8,10,23,3,8,10,23,3,8,10,23] list2=[10,23,3] cnt=list1.count(list2[0]) cnt1=1 j=0 while (cnt1&lt;=cnt): list3=[] list3.append(list2[0]) i=1 k=list1.index(list2[0]) while (i&lt;len(list2)): list3.append(list1[k+i]) i=i+1 print (list3) if (list2==list3): print ("list2 is a subset") j=j+1 else: print ("list2 is not a subset") list1.remove(list2[0]) cnt1=cnt1+1 print (list2,"occurs",j,"times") I am getting this error. Traceback (most recent call last): File "C:\Python26\Lib\idlelib\sublist.py", line 12, in &lt;module&gt; list3.append(list1[k+i]) IndexError: list index out of range"
type: UnansweredQuestion
has title: To find out whether a list is a sublist of a list
has comment: http://stackoverflow.com/comment/83497362
has comment: http://stackoverflow.com/comment/83497322
score: 0
has answer: http://stackoverflow.com/a/48257466
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/48257395
type: Question
has comment: http://stackoverflow.com/comment/83497372
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83497359

http://stackoverflow.com/comment/83552927
type: QuestionComment
comment on: http://stackoverflow.com/q/48283960
has text: By the way, your question title is a little misleading since your question is not about different variables with the same name, but involves operations on a single variable.
score: 0
type: Comment

http://stackoverflow.com/q/48313615
has comment: http://stackoverflow.com/comment/83613001
tagged with: python
accepted answer: http://stackoverflow.com/a/48314099
type: Question
has answer: http://stackoverflow.com/a/48314099
has comment: http://stackoverflow.com/comment/83613329
downvote count: 0
answer count: 1
score: 1
tagged with: web-scraping
upvote count: 1
has title: Can't find a div that exists with 'inspect element' while scraping a website
favorite count: 0
tagged with: beautifulsoup
type: AnsweredQuestion
has body: I have a python script which downloads an html page. I'm looking for this div: &lt;data-a-target="clip-thumbnail-link" And that div is there when I inspect element on the webpage I see it. But its not showing up in my print statement in my script from bs4 import BeautifulSoup from urllib import urlopen BASE_URL = "https://www.twitch.tv/lethalfrag/clips" def get_category_links(section_url): html = urlopen(section_url).read() soup = BeautifulSoup(html, "lxml") print(soup) get_category_links(BASE_URL)

http://stackoverflow.com/comment/83337039
type: QuestionComment
has text: `df['col_name'].prod()` or `df.prod()` - for all numeric columns?
score: 1
comment on: http://stackoverflow.com/q/48178450
type: Comment

http://stackoverflow.com/q/48210662
type: Question
score: 0
has title: type(MyClass.myclassmethod) returns "method", not "classmethod"
tagged with: python
type: AnsweredQuestion
has body: I just stumbled over this strange behavior when the type of a method changes during subclassing: class A: def f(self, x): return x**2 class B(A): @classmethod def f(cls, x): return x**2 If I now ask for the type of B.f, I'll get the (supposedly) wrong answer: In [37]: type(B.f) Out[37]: method Whereas this works as expected: In [39]: type(B.__dict__["f"]) Out[39]: classmethod (Seen in Python 3.4 and 3.6.) Is this just a bug or is there a specific reason for this? What's the difference between the attribute f and the .__dict__["f"] item? I thought they were the same. In a testing suite, I was trying to support both types of methods inside a class to be tested. To be able to do that, I need to know the type in order to pass the correct number of arguments. If it's a normal method (i.e. self is the first argument), I'd just pass None explicitly, which by design shouldn't be used inside the method anyway, since it's not instance-dependent. Maybe there's a better way to do this, like duck typing the call to the method. But there might be cases where this is not so easy to do, like if the method had *args and **kwargs... Therefore I went with the explicit type check, but got stuck at this point.
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48210829
tagged with: class-method
accepted answer: http://stackoverflow.com/a/48210829
answer count: 1
tagged with: inheritance

utf
tag name: utf
tags question: http://stackoverflow.com/q/48272946
type: Tag

http://stackoverflow.com/a/48174842
has body: Import troubles If you have a file called Car.py and you call import Car, that will add the entire module to the current scope. import Car print(dir(Car)) # [ ... 'Car' ] This means you can also do things like: # import the module and alias it import Car as c # add class to local scope as `Car` Car = c.Car On the other hand, if you use the from keyword, you are getting something in that module and adding it to the current scope: from Car import Car corolla = Car.Car() corolla.say_state() What is this __name__ == '__main__' nonsense? When you call a file python <my-file-name> it sets the special variable __name__ to be the string __main__. if __name__ == '__main__' translates to "if someone is trying to run this as an independent script, then do the following". On the other hand, if someone calls import on that same file, that area will not trigger.
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/48174749
downvote count: 0

http://stackoverflow.com/a/50792698
has comment: http://stackoverflow.com/comment/88626903
score: 1
has comment: http://stackoverflow.com/comment/88634857
downvote count: 0
has body: Avoiding a bad restoration Restoring a model's state from a checkpoint only works if the model and checkpoint are compatible. For example, suppose you trained a DNNClassifier Estimator containing two hidden layers, each having 10 nodes: classifier = tf.estimator.DNNClassifier( feature_columns=feature_columns, hidden_units=[10, 10], n_classes=3, model_dir='models/iris') classifier.train( input_fn=lambda:train_input_fn(train_x, train_y, batch_size=100), steps=200) After training (and, therefore, after creating checkpoints in models/iris), imagine that you changed the number of neurons in each hidden layer from 10 to 20 and then attempted to retrain the model: classifier2 = tf.estimator.DNNClassifier( feature_columns=my_feature_columns, hidden_units=[20, 20], # Change the number of neurons in the model. n_classes=3, model_dir='models/iris') classifier.train( input_fn=lambda:train_input_fn(train_x, train_y, batch_size=100), steps=200) Since the state in the checkpoint is incompatible with the model described in classifier2, retraining fails with the following error: ... InvalidArgumentError (see above for traceback): tensor_name = dnn/hiddenlayer_1/bias/t_0/Adagrad; shape in shape_and_slice spec [10] does not match the shape stored in checkpoint: [20] To run experiments in which you train and compare slightly different versions of a model, save a copy of the code that created each model_dir, possibly by creating a separate git branch for each version. This separation will keep your checkpoints recoverable. copy from tensorflow checkpoints doc. https://www.tensorflow.org/get_started/checkpoints hope that can help you.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48191886

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/48184854
tags question: http://stackoverflow.com/q/48300504
tags question: http://stackoverflow.com/q/48217704
tags question: http://stackoverflow.com/q/48311862
tags question: http://stackoverflow.com/q/48278073
tags question: http://stackoverflow.com/q/48218891
tags question: http://stackoverflow.com/q/48247083
tags question: http://stackoverflow.com/q/48262123
tags question: http://stackoverflow.com/q/48312224
tags question: http://stackoverflow.com/q/48292500
tags question: http://stackoverflow.com/q/48236905
tags question: http://stackoverflow.com/q/48282599
tags question: http://stackoverflow.com/q/48256433
tags question: http://stackoverflow.com/q/48258696
tags question: http://stackoverflow.com/q/48308076
tags question: http://stackoverflow.com/q/48293930
tags question: http://stackoverflow.com/q/48216097
tags question: http://stackoverflow.com/q/48178942
tags question: http://stackoverflow.com/q/48292100
tags question: http://stackoverflow.com/q/48195232
tags question: http://stackoverflow.com/q/48205143
tags question: http://stackoverflow.com/q/48292618
tags question: http://stackoverflow.com/q/48177417
tags question: http://stackoverflow.com/q/48218245
tags question: http://stackoverflow.com/q/48236206
tags question: http://stackoverflow.com/q/48301862
tags question: http://stackoverflow.com/q/48318344
tags question: http://stackoverflow.com/q/48219626
tags question: http://stackoverflow.com/q/48230771
tags question: http://stackoverflow.com/q/48288076
tags question: http://stackoverflow.com/q/48283887
tags question: http://stackoverflow.com/q/48315092
tags question: http://stackoverflow.com/q/48292590
tags question: http://stackoverflow.com/q/48270813
tags question: http://stackoverflow.com/q/48313191
tags question: http://stackoverflow.com/q/48193919
tags question: http://stackoverflow.com/q/48231168
tags question: http://stackoverflow.com/q/48319914
tags question: http://stackoverflow.com/q/48287588
tags question: http://stackoverflow.com/q/48191071
tags question: http://stackoverflow.com/q/48291939
tags question: http://stackoverflow.com/q/48254269
tags question: http://stackoverflow.com/q/48238029
tags question: http://stackoverflow.com/q/48308933
tags question: http://stackoverflow.com/q/48176934
tags question: http://stackoverflow.com/q/48190255
tags question: http://stackoverflow.com/q/48271727
tags question: http://stackoverflow.com/q/48193028
tags question: http://stackoverflow.com/q/48269311
type: Tag
tags question: http://stackoverflow.com/q/48258241
tags question: http://stackoverflow.com/q/48199350
tags question: http://stackoverflow.com/q/48292887
tags question: http://stackoverflow.com/q/48298713

http://stackoverflow.com/q/48178289
tagged with: web-scraping
favorite count: 0
tagged with: beautifulsoup
type: Question
score: 3
possible better answer: http://stackoverflow.com/a/48178529
tagged with: http://stackoverflow.com/tag/html
has title: Data Scraping across 's
tagged with: python
has body: I am trying to extract information from a repeating set of rows containing many embedded 's. For the page, I am trying to write a scraper to get various elements from this page. For some reason, I can't find a way to get to the tag with the class that contains the information for each row. Further, I am not able to isolate the sections that I will need to extract the information. For reference, here is a sample of one row: Team Number: 11733 Team: Aqua Duckies Program: FIRST LEGO League Jr. The script I have started to build looks like the following: from urllib2 import urlopen as uReq from bs4 import BeautifulSoup as soup my_url = 'https://www.firstinspires.org/team-event-search#type=teams&sort=name&keyword=NJ&programs=FLLJR,FLL,FTC,FRC&year=2017' uClient = uReq(my_url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, "html.parser") rows = page_soup.findAll("div", {"class":"row team-event-result team-result"}) whenever I run len(rows), it always results in 0. I seem to have hit a wall and am having trouble. Thanks for your help!
accepted answer: http://stackoverflow.com/a/48181544
linked to: http://stackoverflow.com/q/40305678
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48181544
answer count: 3
upvote count: 3
has answer: http://stackoverflow.com/a/48178529
has answer: http://stackoverflow.com/a/48178602
downvote count: 0

python
tags question: http://stackoverflow.com/q/48211738
tags question: http://stackoverflow.com/q/48254454
tags question: http://stackoverflow.com/q/48285315
tags question: http://stackoverflow.com/q/48304365
tags question: http://stackoverflow.com/q/48264665
tags question: http://stackoverflow.com/q/48308776
tags question: http://stackoverflow.com/q/48312206
tags question: http://stackoverflow.com/q/48216137
tags question: http://stackoverflow.com/q/48213358
tags question: http://stackoverflow.com/q/48292804
tags question: http://stackoverflow.com/q/48206079
tags question: http://stackoverflow.com/q/48260934
tags question: http://stackoverflow.com/q/48253844
tags question: http://stackoverflow.com/q/48240956
tags question: http://stackoverflow.com/q/48241588
tags question: http://stackoverflow.com/q/48254115
tags question: http://stackoverflow.com/q/48266778
tags question: http://stackoverflow.com/q/48251271
tags question: http://stackoverflow.com/q/48180551
tags question: http://stackoverflow.com/q/48276192
tags question: http://stackoverflow.com/q/48189745
tags question: http://stackoverflow.com/q/48259290
tags question: http://stackoverflow.com/q/48209458
tags question: http://stackoverflow.com/q/48219852
tags question: http://stackoverflow.com/q/48255765
tags question: http://stackoverflow.com/q/48210714
tags question: http://stackoverflow.com/q/48223558
tags question: http://stackoverflow.com/q/48179417
tags question: http://stackoverflow.com/q/48300518
tags question: http://stackoverflow.com/q/48266912
tags question: http://stackoverflow.com/q/48323930
tags question: http://stackoverflow.com/q/48225118
tags question: http://stackoverflow.com/q/48327714
tags question: http://stackoverflow.com/q/48179498
tags question: http://stackoverflow.com/q/48213235
tags question: http://stackoverflow.com/q/48316706
tags question: http://stackoverflow.com/q/48257889
tags question: http://stackoverflow.com/q/48197083
tags question: http://stackoverflow.com/q/48235277
tags question: http://stackoverflow.com/q/48255432
tags question: http://stackoverflow.com/q/48252216
tags question: http://stackoverflow.com/q/48307712
tags question: http://stackoverflow.com/q/48292508
tags question: http://stackoverflow.com/q/48214014
tags question: http://stackoverflow.com/q/48294098
tags question: http://stackoverflow.com/q/48219414
tags question: http://stackoverflow.com/q/48193894
tags question: http://stackoverflow.com/q/48253860
tags question: http://stackoverflow.com/q/48215082
tags question: http://stackoverflow.com/q/48312123
tags question: http://stackoverflow.com/q/48235690
tags question: http://stackoverflow.com/q/48235809
tags question: http://stackoverflow.com/q/48296069
tags question: http://stackoverflow.com/q/48316017
tags question: http://stackoverflow.com/q/48295658
tags question: http://stackoverflow.com/q/48264157
tags question: http://stackoverflow.com/q/48188716
tags question: http://stackoverflow.com/q/48293509
tags question: http://stackoverflow.com/q/48292790
tags question: http://stackoverflow.com/q/48264539
tags question: http://stackoverflow.com/q/48308229
tags question: http://stackoverflow.com/q/48306087
tags question: http://stackoverflow.com/q/48186011
tags question: http://stackoverflow.com/q/48250092
tags question: http://stackoverflow.com/q/48253561
tags question: http://stackoverflow.com/q/48211318
tags question: http://stackoverflow.com/q/48192290
tags question: http://stackoverflow.com/q/48249119
tags question: http://stackoverflow.com/q/48237162
tags question: http://stackoverflow.com/q/48230646
tags question: http://stackoverflow.com/q/48314069
tags question: http://stackoverflow.com/q/48180690
tags question: http://stackoverflow.com/q/48235239
tags question: http://stackoverflow.com/q/48234438
tags question: http://stackoverflow.com/q/48241548
tags question: http://stackoverflow.com/q/48220410
tags question: http://stackoverflow.com/q/48238877
tags question: http://stackoverflow.com/q/48312800
tags question: http://stackoverflow.com/q/48268068
tags question: http://stackoverflow.com/q/48297722

http://stackoverflow.com/comment/83489786
type: QuestionComment
comment on: http://stackoverflow.com/q/48253264
has text: sir updated and same error when applied your query...
score: 0
type: Comment

http://stackoverflow.com/a/48203223
has comment: http://stackoverflow.com/comment/83388933
has comment: http://stackoverflow.com/comment/83390219
answers question: http://stackoverflow.com/q/48202943
has comment: http://stackoverflow.com/comment/83390944
upvote count: 2
downvote count: 0
type: Answer
score: 2
has body: Lists are modifiable sequences in Python so you can change them in place, which can make sense for large data sets. You can do that simply with 2 nested loops: for i, l in enumerate(new_arr): for j in range(len(l)): if old_arr[i][j] == 0: l[j] = 0

http://stackoverflow.com/a/48276340
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/83547208
has comment: http://stackoverflow.com/comment/83551701
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83566483
type: Answer
has comment: http://stackoverflow.com/comment/83546253
accepted answer of: http://stackoverflow.com/q/48272969
downvote count: 0
has comment: http://stackoverflow.com/comment/83554850
has comment: http://stackoverflow.com/comment/83566170
has comment: http://stackoverflow.com/comment/83565649
has comment: http://stackoverflow.com/comment/83564883
answers question: http://stackoverflow.com/q/48272969
has body: As you already know, yellow lines mean that some interactions with python happen, i.e. python functionality and not raw c-functionality is used, and you can look into the produced code to see, what happens and if it can/should be fixed/avoided. Not every interaction with python means a (measurable) slowdown. Let's take a look at this simplified function: %%cython cimport numpy as np def use_slices(np.ndarray[np.double_t] a): a[0:len(a)]=0.0 When we look into the produced code we see (I kept only the important parts): __pyx_t_1 = PyObject_Length(((PyObject *)__pyx_v_a)); __pyx_t_2 = PyInt_FromSsize_t(__pyx_t_1); __pyx_t_3 = PySlice_New(__pyx_int_0, __pyx_t_2, Py_None); PyObject_SetItem(((PyObject *)__pyx_v_a) So basically we get a new slice (which is a numpy-array) and then use numpy's functionality (PyObject_SetItem) to set all elements to 0.0, which is C-code under the hood. Let's take a look at version with hand-written for loop: cimport numpy as np def use_for(np.ndarray[np.double_t] a): cdef int i for i in range(len(a)): a[i]=0.0 It still uses PyObject_Length (because of length) and bound-checking, but otherwise it is C-code. When we compare times: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a=np.ones((500,)) &gt;&gt;&gt; %timeit use_slices(a) 100000 loops, best of 3: 1.85 µs per loop &gt;&gt;&gt; %timeit use_for(a) 1000000 loops, best of 3: 1.42 µs per loop &gt;&gt;&gt; b=np.ones((250000,)) &gt;&gt;&gt; %timeit use_slices(b) 10000 loops, best of 3: 104 µs per loop &gt;&gt;&gt; %timeit use_for(b) 1000 loops, best of 3: 364 µs per loop You can see the additional overhead of creating a slice for small sizes, but the additional checks in the for-version means it has more overhead in the long run. Let's disable these checks: %%cython cimport cython cimport numpy as np @cython.boundscheck(False) @cython.wraparound(False) def use_for_no_checks(np.ndarray[np.double_t] a): cdef int i for i in range(len(a)): a[i]=0.0 In the produced html we can see, that a[i] gets as si…

http://stackoverflow.com/comment/83546102
score: 0
comment on: http://stackoverflow.com/a/48280649
type: Comment
type: AnswerComment
has text: to be exact i have like this driver.find_element_by_id("Product").click() driver.find_element_by_id("id1").click() driver.find_element_by_id("id1").click() driver.find_element_by_id("id2").click() driver.find_element_by_id("id2").click() driver.find_element_by_id("id3").click() driver.find_element_by_id("id3").click() driver.find_element_by_id("id4").click() driver.find_element_by_id("id4").click()

http://stackoverflow.com/comment/83385680
comment on: http://stackoverflow.com/a/48196711
type: AnswerComment
score: 0
type: Comment
has text: @DanielF I've seen Divakar using that once or twice. Why the plus one?

http://stackoverflow.com/comment/83447097
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48232385
score: 0
has text: Do you want the bin widths to be **graphically** the same size, or **numerically** the same size?

http://stackoverflow.com/q/48293173
has title: count by condition after groupby in pandas
has body: df = pd.DataFrame({ 'id':[1,1,1,2,2,2], 'item':[200,200,201,333,333,334], 'page':[1,1,2,3,2,2] }) i want to convert df into df1 like this. df = pd.DataFrame({ 'id':[1,1,2,2,2], 'item':[200,201,333,333,334], 'page':[1,2,3,2,2], 'page1_cnt':[2,0,0,0,0] }) Question: size if page == 1 of groupby this is my way. can i get a more pythonic way? import numpy as np import pandas as pd df = pd.DataFrame({ 'id':[1,1,1,2,2,2], 'item':[200,200,201,333,333,334], 'page':[1,1,2,3,2,2] }) df['pageCnt'] = df.groupby(['id','item','page']).page.transform('size') df['page1Cnt'] = np.where(df.groupby(['id','item']).page.apply(lambda x: x==1), df.pageCnt, 0)
has answer: http://stackoverflow.com/a/48293860
accepted answer: http://stackoverflow.com/a/48293860
downvote count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83572348
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/48293209
possible better answer: http://stackoverflow.com/a/48293209
type: Question
score: 2
favorite count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83571474
upvote count: 2

http://stackoverflow.com/a/48213783
type: Answer
has body: Since OP didn't answer their own post, and the issue was resolved in the discussion, I'll recap the answer here. bytearray([0x03, 0x00, 0x11, 0x00, 0x00, 0x22, 0x01, 0x00, 0x00, 0x21, 0x8f, 0xf6, 0x82, 0xce, 0x8d, 0xad, 0x54]) and bytearray(b'\x03\x00\x11\x00\x00"\x01\x00\x00!\x8f\xf6\x82\xce\x8d\xadT') Are the same thing internally. The string representation is different to make the array shorter and more easily readable and it does not affect the actual internal structure of the bytearray. Any function / program that accepts the first bytearray as a parameter should accept the second one as well. This can be easily verified by comparing the two using the == operator.
accepted answer of: http://stackoverflow.com/q/48209760
score: 5
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48209760
upvote count: 5

http://stackoverflow.com/comment/132159527
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48205565
score: 0
has text: Is it possible to do sth like this: `format((key(i) for i in dict_var) = func(i))`? What I want it to be is, with `dict_var` being `{"key1": "value1", "key2": "value2"}` `sql.SQL('query').format(key1=sql.Identifier('value1'), key2=sql.Identifier('value2'))` (`from psycopg2 import sql` was used)

http://stackoverflow.com/a/48320539
has body: Sleeping in your worker thread is unnecessary. It's done sometimes in examples to visualize the flow of a multi-threaded program, but there's no reason you should do it in production code. When one thread has finished a task, it may as well pick up the next task immediately. It's not going to make your program faster that another thread takes the task instead. The only thing you would achieve is that the worker threads sit idle every now and then.
accepted answer of: http://stackoverflow.com/q/48319966
downvote count: 0
answers question: http://stackoverflow.com/q/48319966
type: AcceptedAnswer
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/q/48255849
has answer: http://stackoverflow.com/a/48256279
favorite count: 0
has body: I use heapq module in python, I find I only can the min heap, even if I use reverse=True I still get the min top heap from heapq import * h=[] merge(h,key=lambda e:e[0],reverse=True) heappush(h, (200, 1)) heappush(h, (300,2)) heappush(h, (400,3)) print(heappop(h)) I still get the result: (200, 1) I want to get result: (400,3) how to do it? which is the smallest element. I want pop the largest emelment? ps: this is part of question find the max and then divide into several elements and then put it back to the heap.
score: 13
has answer: http://stackoverflow.com/a/48255910
type: AnsweredQuestion
tagged with: heap
possible better answer: http://stackoverflow.com/a/48256279
tagged with: python
has title: how to get the max heap in python
upvote count: 13
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83495146
has comment: http://stackoverflow.com/comment/83494507
tagged with: max-heap
accepted answer: http://stackoverflow.com/a/48255910

pyqt
type: Tag
tags question: http://stackoverflow.com/q/48330016
tags question: http://stackoverflow.com/q/48330721
tags question: http://stackoverflow.com/q/48226392
tags question: http://stackoverflow.com/q/48178493
tags question: http://stackoverflow.com/q/48185135
tags question: http://stackoverflow.com/q/48290707
tags question: http://stackoverflow.com/q/48238204
tags question: http://stackoverflow.com/q/48328147
tags question: http://stackoverflow.com/q/48315501
tags question: http://stackoverflow.com/q/48235920
tags question: http://stackoverflow.com/q/48179891
tags question: http://stackoverflow.com/q/48191399
tags question: http://stackoverflow.com/q/48269688
tags question: http://stackoverflow.com/q/48299491
tags question: http://stackoverflow.com/q/48326817
tags question: http://stackoverflow.com/q/48221364
tags question: http://stackoverflow.com/q/48243522
tags question: http://stackoverflow.com/q/48262966
tags question: http://stackoverflow.com/q/48255567
tags question: http://stackoverflow.com/q/48243195
tags question: http://stackoverflow.com/q/48222530
tags question: http://stackoverflow.com/q/48262716
tags question: http://stackoverflow.com/q/48279901
tags question: http://stackoverflow.com/q/48180157
tags question: http://stackoverflow.com/q/48329703
tags question: http://stackoverflow.com/q/48325757
tags question: http://stackoverflow.com/q/48266801
tags question: http://stackoverflow.com/q/48273519
tag name: pyqt
tags question: http://stackoverflow.com/q/48267563
tags question: http://stackoverflow.com/q/48177181
tags question: http://stackoverflow.com/q/48255299
tags question: http://stackoverflow.com/q/48190404
tags question: http://stackoverflow.com/q/48244675
tags question: http://stackoverflow.com/q/48321743
tags question: http://stackoverflow.com/q/48193325
tags question: http://stackoverflow.com/q/48322332
tags question: http://stackoverflow.com/q/48312773

http://stackoverflow.com/comment/83533349
type: AnswerComment
has text: 1. I tried sending an empty json file when I used the gcloud command from Cloud Shell and then timed it using `time` and it took around 400ms, which doesn't account for the other 3000ms. 2. It's deployed on us-central1, I'm on the west coast. 3. The latency doesn't go down when I sent request spaced 30s apart (or even shorter intervals like 2s)
type: Comment
comment on: http://stackoverflow.com/a/48274806
score: 0

http://stackoverflow.com/comment/83508472
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48262754
has text: What is the type of your values in the np.array? all of them are ints or do you have a mix of ints and strings?

http://stackoverflow.com/comment/83606469
has text: @Wen I got TypeError: include and exclude must both be non-string sequences
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48310277

http://stackoverflow.com/comment/83762996
has text: If you added a splash screen to the main.py file in your application (even before most of the import statements), it still would not be displayed until the PyInstaller Bootloader was finished, which takes a considerable amount of time. One way to get around this may be to create a new application, whose only purpose is to display a splash screen and then launch your main application (bundled with pyinstaller) using the python subprocess.run command.
type: AnswerComment
comment on: http://stackoverflow.com/a/48326365
score: 1
type: Comment

http://stackoverflow.com/q/48218957
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
answer count: 0
has body: I have using matplotlib for a very long time (but maybe without professional usage). One thing bored me a lot is that matplotlib offering many operations but I do not know where it returns. For example when we draw a curve we use "plt.plot(...)", after which we use plt.show(). But this is a function and what can we obtained(OOP sense). It seems all the operations are acted on one object. When our requirements become complex and complexes, we use more and more complicated functions and structures. And sometimes unexpected, operations to other figures will also have influence at this one. I want to use matplotlib in this way: No matter what we want, it is a 2D graph. The final graph can be separated into different submission. We draw each graph independently and finally combine them or put one on another. And also we can change the ratio of each part. This kind of combination is not something like subplot indexed by several integer, but by using, for instance, coordinate x,y. Does this kind of general method exist? I know one way is to save all subfigures into arrays(RGB,...) and conduct operations to it. But this is somewhat too much.
has comment: http://stackoverflow.com/comment/83419983
linked to: http://stackoverflow.com/q/42783425
score: 1
downvote count: 0
upvote count: 1
has title: How to assign project into sub-projects in matplotlib in Python?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83420442
has comment: http://stackoverflow.com/comment/83440960
has comment: http://stackoverflow.com/comment/83428756

http://stackoverflow.com/q/48193254
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48221788
type: Question
score: 0
has body: I've a Bad gateway error whenever I try and upload my Django project to Digital ocean. I was following this guide https://pythonprogramming.net/django-web-server-publish-tutorial/ but I didn't update Django, I'm using version 1.8.7. Do I need to change the secret key on the server to the secret key on my project? This is the Nginx error message 2018/01/10 17:07:58 [error] 2210#2210: *5 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 86.167.15.195, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "159.65.16.251" 2018/01/10 17:08:45 [error] 2210#2210: *7 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 86.167.15.195, server: _, request: "GET / HTTP/1.1", upstream: I've changed allowed hosts in the settings file to = [159.65.16.251] Do I also need to change this our just leave it out? ALLOWED_HOSTS = ip_addresses() Url.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('personal.urls')), url(r'^blog/', include('blog.urls')), url(r'^writing/', include('writing.urls')), ] This is my nginx config user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k;…
type: UnansweredQuestion
has title: Error uploading Django project to Digital Ocean
answer count: 1

http://stackoverflow.com/comment/83519013
type: QuestionComment
comment on: http://stackoverflow.com/q/48266346
has text: If you can, then it might be possible. Feel free to edit the question and show us the padded version.
type: Comment
score: 1

http://stackoverflow.com/q/48272705
has title: Is there a reverse \n?
tagged with: python-3.5
answer count: 1
has comment: http://stackoverflow.com/comment/83529209
has comment: http://stackoverflow.com/comment/83529270
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48272740
score: 0
tagged with: argparse
has answer: http://stackoverflow.com/a/48272740
has body: I am making a dictionary application using argparse in Python 3. I'm using difflib to find the closest matches to a given word. Though it's a list, and it has newline characters at the end, like: ['hello\n', 'hallo\n', 'hell\n'] And when I put a word in, it gives a output of this: hellllok could be spelled as hello hellos hillock Question: I'm wondering if there is a reverse or inverse \n so I can counteract these \n's. Any help is appreciated.
tagged with: difflib
has comment: http://stackoverflow.com/comment/83529412
has comment: http://stackoverflow.com/comment/83529234
tagged with: python
has comment: http://stackoverflow.com/comment/83529241
has comment: http://stackoverflow.com/comment/83529298
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83529196

http://stackoverflow.com/comment/83457438
type: Comment
score: 0
type: AnswerComment
has text: You can try this xpath //input[@value=11]/parent::p//span[@class='label_show']
comment on: http://stackoverflow.com/a/48237202

continuous-integration
tags question: http://stackoverflow.com/q/48298292
type: Tag
tag name: continuous-integration

http://stackoverflow.com/comment/83555720
comment on: http://stackoverflow.com/a/48285327
type: Comment
score: 0
type: AnswerComment
has text: Have you tried the code outside VS-Code? In your terminal?

http://stackoverflow.com/a/48323703
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48322982
upvote count: 1
has body: It is maybe a not-naive concept, but to build a decorator with parameters you are coding a decorator that generates a decorator. To get you there let me spend a couple of words. In the case of a simple decorator you are usually going the way you are reporting: def decorator(function): def wrapper(*args, **kwargs): print("bar") function(*args, **kwargs) return wrapper @decorator def foo(word): print(word) foo('boo') result "bar" "boo" where foo gets executed inside wrapper as the 'value' of the variable function, which is assigned by mean of the annotation @decorator itself -without input. Given this, in case you want to have also decorator inputs, you need to issue another level, catching the input and wrapping it into a closure - which is the actual declaration of the decorator, wrapping the function. That's what happens in flask code. def decorator_factory(*a, **kw): def decorator(function): def wrapper(*args, **kwargs): print(a[0]) function(*args, **kwargs) return wrapper return decorator @decorator_factory('bar') def foo(word): print(word) foo('boo') results again in "bar" "boo"
answers question: http://stackoverflow.com/q/48322982
has comment: http://stackoverflow.com/comment/83634734
type: Answer
has comment: http://stackoverflow.com/comment/83634078

http://stackoverflow.com/a/48309472
score: 1
accepted answer of: http://stackoverflow.com/q/48309380
type: AcceptedAnswer
upvote count: 1
has body: Check all values We can use itertools.chain and use it in a rather self-explaining one liner: from itertools import chain if 'a' in chain.from_iterable(myDict.values()): # do something pass Here we will chain the .values() of a list together in an iterable, and thus check membership of 'a'. Note that this runs in linear time with the total number of values in the lists. In case you have to perform the membership check a single time, we can not do much about it, but in case we have to check it multiple times, it is better to cache the values in a set (given the values are hashable). Check a specific key In case you want to check a specific key, we can just lookup the corresponding value and check membership: if 'a' in myDict[0]: # do something pass In case it is not certain if the key is present in myDict, and we want to return False in that case, we can use .get(..) and use () (the empty tuple) as a fallback value: # will not error, but False in case key does not exists if 'a' in myDict.get(0, ()): # do something pass
answers question: http://stackoverflow.com/q/48309380
downvote count: 0
type: Answer

http://stackoverflow.com/q/48241606
upvote count: 2
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/83518100
tagged with: python
type: UnansweredQuestion
has body: My dataset is a set of features and one column which is essentially views, each element of this column being an arbitrary positive real number, like the following. Now in Python, I want to run a Keras model on it. I plan to use this column as output labels for training the classifier. The only solution I can think of is to scale it using sklearn and then conditionally somehow sort the scaled values into classes for enough training labels. Like for example, if 0.1 &lt; views &lt; 0.2: set_scale_to_0.1 and so on. Is this the best way to go about it? +-------+ | Views | +-------+ | 173 | +-------+ | 943 | +-------+
has comment: http://stackoverflow.com/comment/83516759
has comment: http://stackoverflow.com/comment/83480715
score: 0
tagged with: training-data
tagged with: machine-learning
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/48243685
has title: How do I transform a column of values into possibly discrete training output classes?
favorite count: 0
has answer: http://stackoverflow.com/a/48245483
type: Question

http://stackoverflow.com/a/65678451
answers question: http://stackoverflow.com/q/48276174
score: 0
has body: As one of the main developers of hickle: 3 years ago, it indeed did not support Python 3 yet. Nowadays on the other hand, it works just fine (and, in fact, has dropped support for Python 2.7 by now).
type: Answer

http://stackoverflow.com/a/48218865
has body: I would use set for comparison: set creates a collection of unique items, and comparisons between two sets are only True if all elements are shared across both sets. You can get a set of the row or column and then compare it to a set created from the len of the row or column (starting the range at 1). For accessing the columns, I would convert the list of lists to a numpy array. def check_row(square): for row in square: if set(row) != set(range(1, len(row) + 1)): print(False) return False print(True) def check_col(square): # Numpy array square = np.array(square) for i in range(square.shape[1]): # Select the column col = square[i, :] if set(col) != set(range(1, len(col) + 1)): print(False) return False print(True) This passes all the test cases you provided.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48218762

http://stackoverflow.com/comment/83547967
type: Comment
comment on: http://stackoverflow.com/a/48279403
type: AnswerComment
has text: @PaulPanzer I've added some Cython and sorting.
score: 0

http://stackoverflow.com/a/48279714
score: 8
accepted answer of: http://stackoverflow.com/q/48278489
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48278489
upvote count: 8
has comment: http://stackoverflow.com/comment/83592306
has comment: http://stackoverflow.com/comment/83583121
type: Answer
has body: Have a look at the pyspark.ml documentation. Tokenizer only splits by white spaces, but RegexTokenizer - as the name says - uses a regular expression to find either the split points or the tokens to be extracted (this can be configured by the parameter gaps). If you pass an empty pattern and leave gaps=True (which is the default) you should get your desired result: from pyspark.ml.feature import RegexTokenizer tokenizer = RegexTokenizer(inputCol="sentence", outputCol="words", pattern="") tokenized = tokenizer.transform(sentenceDataFrame)

xlsxwriter
tags question: http://stackoverflow.com/q/48261685
tags question: http://stackoverflow.com/q/48298427
tags question: http://stackoverflow.com/q/48176802
tags question: http://stackoverflow.com/q/48233266
type: Tag
tags question: http://stackoverflow.com/q/48304947
tags question: http://stackoverflow.com/q/48245185
tag name: xlsxwriter
tags question: http://stackoverflow.com/q/48290616

http://stackoverflow.com/a/48184020
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48181992
has body: I found an way to split them and store them in variables import re splitted = re.split(' ', var) print splitted The output will be in this format: ['Dec', '15', '09:57:27', '6con-dhcp-01', 'dhcpd:', 'DHCPREQUEST', 'for', '132.147.83.212', 'from', '44:d9:e7:41:ee:77', 'via', 'eth1\n'] With the code below i can store the separated part into variables Monthdatetime = splitted[0] + ' ' + splitted[1] + ' ' + splitted[2] print Monthdatetime The output would be: Dec 15 09:57:27
accepted answer of: http://stackoverflow.com/q/48181992
type: Answer

http://stackoverflow.com/a/48273231
has comment: http://stackoverflow.com/comment/98090635
has body: I think what you're looking for is the keyword in. The following is probably the most "pythonic" way. if letter.lower() in ['a','b','c']: That should do it for you. Although, if you're looking for speed, it would be better to create a dictionary or set and do lookups from that. As the complexity of the in operator is average O(n) for arrays and strings but average O(1) and worst case O(n) for sets and dictionaries. For example, chars = set(['a','b','c']) if letter.lower() in chars: If you're interested in reading a little more about the differences in complexities, here's a Python Time Complexity document that's very useful to know!
downvote count: 0
has comment: http://stackoverflow.com/comment/97369129
has comment: http://stackoverflow.com/comment/83530566
type: AcceptedAnswer
score: 6
accepted answer of: http://stackoverflow.com/q/48273222
type: Answer
has comment: http://stackoverflow.com/comment/83530300
upvote count: 6
answers question: http://stackoverflow.com/q/48273222

http://stackoverflow.com/q/48312224
has title: How to resolve FOREIGN KEY constraint failed
has answer: http://stackoverflow.com/a/70663637
has comment: http://stackoverflow.com/comment/83611951
has comment: http://stackoverflow.com/comment/83611039
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/83612774
has comment: http://stackoverflow.com/comment/83611424
answer count: 2
tagged with: django-admin
accepted answer: http://stackoverflow.com/a/50188409
has body: I am following a tutorial on a basic concept. How to customize a user in django. I don't want to use the built in auth user. I found this tutorial which seems to work until a point. I get through the whole tutorial with everything working. however when I run my project, log in and open the user in the admin area I click "Save and continue editing" This gives me the error The code I have in my project is EXACTLY the same as in the tutorial. I have tried removing my cache and migrations and starting again, even creating a new environment and reinstalling django. Nothing seems to work. Environment: Request Method: POST Request URL: http://localhost:8000/admin/accounts/user/1/change/ Django Version: 2.0.1 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/db/backends/base/base.py" in _commit 239. return self.connection.commit() The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception: File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/core/han…
downvote count: 0
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/70663637
score: 4
linked to: http://stackoverflow.com/q/41253106
has comment: http://stackoverflow.com/comment/83611275
favorite count: 0
type: AnsweredQuestion
tagged with: django-models
has answer: http://stackoverflow.com/a/50188409
has comment: http://stackoverflow.com/comment/83611671
has comment: http://stackoverflow.com/comment/83612031

http://stackoverflow.com/a/48249833
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83482291
has comment: http://stackoverflow.com/comment/83482355
answers question: http://stackoverflow.com/q/48249705
has body: The error you're getting is because Selenium's find_element_by_class_name does not support multiple classes. Use a CSS selector with find_elements_by_css_selector instead: driver.find_elements_by_css_selector('.jobs-wrapper.no-line.w-inline-block.w-clearfix') Will select all tags with your wanted class, then you can iterate over them and use click() or any other wanted action EDIT Following your comment, new snippet to help you do what you want: result = {} urls = [] # 'elements' is a the list you previously obtained using the css selector for element in elements: urls.append(element.get_attribute('href')) # Now you can iterate over all extracted hrefs: for url in urls: url_data = {} driver.get(url) field1 = driver.find_element_by_id('wanted_id_1') url_data['field1'] = field1 field2 = driver.find_element_by_id('wanted_id_2') url_data['field2'] = field2 result[url] = url_data Now, result is a dictionary in a structure similar to what you wanted. Note that field1 and field2 are of type WebElement so you'll probably need to do something with them first (extract attribute, text, etc). Also, on personal note, Look into the requests together with BeautifulSoup, they might be a way better fit than Selenium for this or future similar cases.
has comment: http://stackoverflow.com/comment/83482562
has comment: http://stackoverflow.com/comment/83482251
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/83482636
has comment: http://stackoverflow.com/comment/83482304
accepted answer of: http://stackoverflow.com/q/48249705
upvote count: 2

http://stackoverflow.com/q/48289874
has title: Correcting a list with a dictionary and a subsequent .sort() command displays wrong string order
type: Question
upvote count: 2
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48289976
tagged with: for-loop
has answer: http://stackoverflow.com/a/48290017
downvote count: 0
has answer: http://stackoverflow.com/a/48289952
accepted answer: http://stackoverflow.com/a/48289952
has comment: http://stackoverflow.com/comment/83564902
has body: sorry for the bad title. I am new to programming and I could not come up with a better description. So, I have this code: umw = {'T':10, 'J':11, 'Q':12, 'K':13, 'A':14} def card_ranks(ranks): "Return a list of the ranks, sorted with higher first." for i in ranks: if i in umw: index = ranks.index(i) ranks[index] = str(umw[i]) ranks.sort(reverse = True) return ranks print(card_ranks(['A', '3', '4', 'K'])) #should output [14, 13, 4, 3] This gives me the following result: ['4', '3', '14', '13'] clearing the "reverse = True" gives the following: ['13', '14', '3', '4'] If i do something like that: r = card_ranks(['A', '3', '4', 'K']) r[0] -&gt; gives me '4' but this doesnt work again: print(sorted(r)) -&gt; gives me ['4', '3', '14', '13'] all over again. So it seems, that the .sort() command views the 13 &amp; 14 as a unit and the 3 &amp; 4. Could somebody explain why that is? Thanks alot!
favorite count: 0
score: 2
has answer: http://stackoverflow.com/a/48290003
type: AnsweredQuestion
tagged with: list
answer count: 5
has answer: http://stackoverflow.com/a/48289983
possible better answer: http://stackoverflow.com/a/48289983
tagged with: python
tagged with: dictionary

http://stackoverflow.com/a/48180217
has comment: http://stackoverflow.com/comment/83341096
has body: You can use user defined function such as def isprime(n): if n &lt; 2: return False for i in range(2,(n**0.5)+1): if n % i == 0: return False return True it will return boolean values. You can use this function for verifying prime factors. OR you can continuously divide the number by 2 first n = 600851475143 while n % 2 == 0: print(2), n = n / 2 n has to be odd now skip 2 in for loop, then print every divisor for i in range(3,n**0.5+1,2): while n % i== 0: print(i) n = n / i at this point, n will be equal to 1 UNLESS n is a prime. So if n &gt; 1: print(n) to print itself as the prime factor. Have fun exploring
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83340919
score: 1
has comment: http://stackoverflow.com/comment/83375362
answers question: http://stackoverflow.com/q/48180096
has comment: http://stackoverflow.com/comment/83375409
type: Answer

http://stackoverflow.com/a/48331074
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/83649496
downvote count: 0
has comment: http://stackoverflow.com/comment/83649461
answers question: http://stackoverflow.com/q/48329092
has body: Unfortunately Dicom is horribly complex and things get implemented slightly differently depending on what company's scanner the data is from and how old the system is. In your first example it sounds like you have a simply formatted directory with individual slice files and no extra scout images so VTK is able to read in and render the slices and it looks fine. Your second example sound like there's a more complex structure that may contain multiple series and possibly things like scout images or even non-image type Dicom files. For dealing with this type of data you'll need some logic to read the meta-data and figure out which files you're interested in and how to assemble them. The meta-data for the entire set is contained in a single file named "dicomdir" which should be in the top level directory. This data is redundant with data in .dcm file headers but reading from this file saves you the trouble of scanning the header from every file individually. VTK is an image manipulation/display library not a Dicom system. I'm not sure they have good support for complex directory structures. You could try reader-&gt;SetFileName('dicomdir'); and see if they have logic to automatically handle this but I'd be a bit surprised if that worked. If you're going to be working with complex multi-series data like this you'll probably need to use another library to extract the info you want. I highly recommend DCMTK. It's a great open-source C++ library for working with Dicom, just don't expect it to be super simple.
has comment: http://stackoverflow.com/comment/83648423
type: Answer
has comment: http://stackoverflow.com/comment/83648121

http://stackoverflow.com/comment/83418389
has text: ive also written many many wx programs and dont understand what the question is :P
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48218189

http://stackoverflow.com/comment/83517763
comment on: http://stackoverflow.com/q/48267322
score: 0
type: Comment
type: QuestionComment
has text: There appears to be no reason for `validate` to be a method of a class rather than a simple function.

http://stackoverflow.com/q/48187556
has answer: http://stackoverflow.com/a/48187707
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83356470
has comment: http://stackoverflow.com/comment/83354881
answer count: 3
has title: Not repeating elements in repeated random choice
has body: I have two text files, students and questions. In students are students and in questions are questions. Each student corresponds to one question, but sometimes questions are the same and I want to not repeat questions. import random k = int(input("how many questions do you want ? -")) questions1 = open("question.txt",'r') studenti = open("students.txt",'r') splited = questions1.read().split('\n') splitedstud = student1.read().split('\n') for studens in splitedstud: file = open(studens + ".txt", "w") for i in range(int(k)): questiion = random.choice(splited) file.write(questiion + '\n') file1 = open(studens + ".txt", "r") f = file1.read() if questiion in f: continue file.close() questions.close() students.close()
has answer: http://stackoverflow.com/a/48187832
downvote count: 0
possible better answer: http://stackoverflow.com/a/48187707
has comment: http://stackoverflow.com/comment/83354845
has answer: http://stackoverflow.com/a/48187617
has comment: http://stackoverflow.com/comment/83356619
has comment: http://stackoverflow.com/comment/83354784
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83356228
accepted answer: http://stackoverflow.com/a/48187832
upvote count: 2
has comment: http://stackoverflow.com/comment/83356481
tagged with: python

http://stackoverflow.com/comment/83556456
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48285761
score: 1
has text: `request.DATA` is a good suggestion. However `request.POST` isn't going to work for json data, it only works for form encoded data.

http://stackoverflow.com/comment/83566512
has text: I don't get it. I checked you got answer for this problem in previous question but you still use the same incorrect code. Why ? Don't you read answers to your questions ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48290138
score: 0

http://stackoverflow.com/q/48291546
tagged with: pip
tagged with: virtualenv
score: 11
has comment: http://stackoverflow.com/comment/83568346
has comment: http://stackoverflow.com/comment/83568251
has comment: http://stackoverflow.com/comment/83568281
has comment: http://stackoverflow.com/comment/83818288
has comment: http://stackoverflow.com/comment/83568336
has comment: http://stackoverflow.com/comment/83568245
favorite count: 0
has comment: http://stackoverflow.com/comment/83710280
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83568591
has body: I've created a virtual environment with: $ virtualenv my_ven_test then let's activate the environment with: $ source my_ven_test/bin/activate now let's install a package: (my_ven_test) $ pip install mysql-connector==2.1.3 This last line does not take effect. In fact if I check: (my_ven_test) $ pip freeze I see no package installed (as well as the my_ven_test/lib/python/site-package directory doesn't contain the mysql-connector package) Could you guide me in solving this issue? Some notes: python version: 2.7 virtualenv version: 15.1.0
has comment: http://stackoverflow.com/comment/83722302
has answer: http://stackoverflow.com/a/60443946
possible better answer: http://stackoverflow.com/a/60443946
has answer: http://stackoverflow.com/a/48413794
has comment: http://stackoverflow.com/comment/83568357
has comment: http://stackoverflow.com/comment/83568260
has comment: http://stackoverflow.com/comment/83568536
has comment: http://stackoverflow.com/comment/83568444
has comment: http://stackoverflow.com/comment/83568204
tagged with: python
linked to: http://stackoverflow.com/q/6628476
has comment: http://stackoverflow.com/comment/83568757
answer count: 4
upvote count: 11
type: Question
has comment: http://stackoverflow.com/comment/83710063
has comment: http://stackoverflow.com/comment/83568883
has title: virtualenv activation doesn't work
has answer: http://stackoverflow.com/a/48413576
accepted answer: http://stackoverflow.com/a/48413794
has comment: http://stackoverflow.com/comment/83583512
has comment: http://stackoverflow.com/comment/83568478
has comment: http://stackoverflow.com/comment/83568420
has comment: http://stackoverflow.com/comment/83568559
downvote count: 0
has comment: http://stackoverflow.com/comment/83583102
has answer: http://stackoverflow.com/a/76889539

http://stackoverflow.com/q/48264056
has title: sub-millisecond pause in Python 3
tagged with: pause
has comment: http://stackoverflow.com/comment/83511367
has comment: http://stackoverflow.com/comment/83523283
has comment: http://stackoverflow.com/comment/83511022
score: 1
has comment: http://stackoverflow.com/comment/83513824
downvote count: 1
tagged with: sleep
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83511371
answer count: 0
upvote count: 2
tagged with: time
has body: I am trying to do some instrument control using Python, and I want to take the instrument reading once every, say 0.001 second. How can I pause the program / wait till that time has elapsed with high enough accuracy? (will need sub-millisecond accuracy if I want the interval to be 0.001s?) I read that time.sleep() is not very accurate, so I want to know if it is possible to get that level of accuracy.
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48255660
downvote count: 0
answer count: 1
upvote count: 7
has comment: http://stackoverflow.com/comment/83494444
has title: Python asyncio and aiohttp slowing down after 150+ requests
has comment: http://stackoverflow.com/comment/83494377
has comment: http://stackoverflow.com/comment/83494319
favorite count: 0
type: Question
tagged with: performance
tagged with: python-asyncio
has answer: http://stackoverflow.com/a/74179044
tagged with: python
has comment: http://stackoverflow.com/comment/83496174
score: 7
has comment: http://stackoverflow.com/comment/83494239
has comment: http://stackoverflow.com/comment/83510671
has comment: http://stackoverflow.com/comment/99641491
tagged with: aiohttp
has comment: http://stackoverflow.com/comment/83494402
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83494511
has body: I'm using asyncio and aiohttp to make a async scraper. For some reason after I hit 150+ request its start slowing down. The first async runs fine where i get the links. The second one is where i get the problem where the slowness happens. Like after 200 it needs 1min for one request. Any idea why? Am I using Asyncio or aiohttp incorrectly? Edit: I'm running this localy on a 7gb ram so I don't think im running out of memory. import aiohttp import asyncio import async_timeout import re from lxml import html import timeit from os import makedirs,chmod basepath = "" start = timeit.default_timer() novel = "" novel = re.sub(r"[^a-zA-Z0-9 ]+/", "", novel) novel = re.sub(r" ", "-", novel) novel_url = {} @asyncio.coroutine def get(*args, **kwargs): response = yield from aiohttp.request('GET', *args, **kwargs) return (yield from response.text()) def scrape_links(page): url = html.fromstring(page) links = url.xpath("") chapter_count = url.xpath("") dictonaries = dict(zip(chapter_count,links)) novel_url.update(dictonaries) def print_links(query): # Makedirs and apply chmod makedirs('%s/%s' % ( basepath,query ),exist_ok=True) makedirs('%s/%s/img' % (basepath, query),exist_ok=True) chmod('%s/%s' % ( basepath,query ), 0o765) chmod('%s/%s/img/' % ( basepath,query ), 0o765) url = 'https://www.examplesite.org/' + query page = yield from get(url, compress=True) magnet = scrape_links(page) loop = asyncio.get_event_loop() f = asyncio.wait([print_links(novel)]) loop.run_until_complete(f) ##### now getting chapters from links array def scrape_chapters(page, i): url = html.fromstring(page) title = url.xpath("") title = ''.join(title) title = re.sub(r"", "", title) chapter = url.xpath("") # Use this to join them insteed of looping though if it doesn't work in epub maker # chapter = '\n'.join(chapter) print(title) # file = open("%s/%s/%s-%s.html" % (basepath, novel, novel, i), 'w+') # file.write(" %s " % title) # for x in chapter: # file.write("\n %s " % x) # file.close() def print_chapters(…
has comment: http://stackoverflow.com/comment/83494351

http://stackoverflow.com/comment/83585963
comment on: http://stackoverflow.com/a/48300720
has text: @NickA No, but I do have reason to believe it may be the case based on their output, unless OP clarifies. :)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48279405
type: AnsweredQuestion
has title: converting object types columns into numeric type using pandas
tagged with: pandas
has comment: http://stackoverflow.com/comment/83542416
has comment: http://stackoverflow.com/comment/83542474
has comment: http://stackoverflow.com/comment/83542325
has answer: http://stackoverflow.com/a/48279506
has comment: http://stackoverflow.com/comment/83542470
favorite count: 0
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/83542566
accepted answer: http://stackoverflow.com/a/48279506
downvote count: 0
answer count: 1
has body: I am trying to clean the data using pandas. When I execute df.datatypes it shows that the columns are of type objects. I wish to convert them into numeric types. I tried various ways of doing so like; data'a','b' = data'a','b'.apply(pd.to_numeric, errors ='ignore') Then, data['c'] = data['c'].infer_objects() But nothing seems to be working. The interpreter does not throw any error but at the same time, it does not performs the desired conversion. Any help will be greatly appreciated. Thanking in advance.
tagged with: data-cleaning
has comment: http://stackoverflow.com/comment/83542622
has comment: http://stackoverflow.com/comment/83542647
has comment: http://stackoverflow.com/comment/83543020
tagged with: python
score: 4

http://stackoverflow.com/q/48204749
has body: I am currently a beginner is pythonand I want to know what's a simpler way doing this method below? for i in range (20100,20130): print ("s0", i, "@gmail.com", sep='') for i in range (20200,20230): print ("s0", i, "@gmail.com", sep='') for i in range (20300,20330): print ("s0", i, "@gmail.com", sep='') for i in range (20400,20430): print ("s0", i, "@gmail.com", sep='') for i in range (20500,20530): print ("s0", i, "@gmail.com", sep='') for i in range (20600,20630): print ("s0", i, "@gmail.com", sep='')
favorite count: 0
accepted answer: http://stackoverflow.com/a/48204860
type: Question
score: 0
has comment: http://stackoverflow.com/comment/83390492
has comment: http://stackoverflow.com/comment/83390601
upvote count: 1
tagged with: python
answer count: 1
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48204860
has title: Is there a simpler solution for this?

http://stackoverflow.com/a/73909899
has body: for union of sets you can use | location_dict['Camden'] | location_dict['Southwark']
answers question: http://stackoverflow.com/q/48282074
score: 7
type: Answer
downvote count: 0
upvote count: 7

http://stackoverflow.com/comment/83402649
score: 0
has text: @deceze, thanks.. Read the thread.. Didnt know that this was related to unbound and bound methods. It makes sense now. In my opinion, a lot of newbies will have similar questions, but wont know the technical name to describe the problem using `bound` or `unbound` methods. As a result, they wont directly go to that thread. So it maybe better to open this question and leave an answer point to unbound/bound methods and why this is related to the other thread..
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48208839

http://stackoverflow.com/q/48257382
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83497853
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/83498588
has comment: http://stackoverflow.com/comment/83498603
tagged with: python
has comment: http://stackoverflow.com/comment/83497541
has body: tweets = api.search(q="@mytwitter",count=100,include_entities=True) t = ['@mytwitter', '@MyTwitter'] for s in tweets: sn = s.user.screen_name m = "@%s message" % (sn) s = api.update_status(m, s.id) #print(dir(s)) for result in tweets: print str(result.text) for userName in result.text: if userName == "@mytwitter": result.text.remove(userName) print (userName) else: print("No username") Not sure why userName isn't removing my Twitter name from result.text. Am I missing something? The output I'm getting is "No username" repeated a bunch of times. If it helps the orginal output for result.text is "@mytwitter their message" I'm trying to remove the @mytwitter.
has answer: http://stackoverflow.com/a/48257510
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/48260048
has comment: http://stackoverflow.com/comment/83498434
has comment: http://stackoverflow.com/comment/83497598
has comment: http://stackoverflow.com/comment/83497907
downvote count: 0
upvote count: 1
has title: .remove not removing the given String

http://stackoverflow.com/q/48219141
has comment: http://stackoverflow.com/comment/83599988
has body: I am trying back propagation in neural networks with input features are 401 for a sample set of 5000. It has One hidden unit with a size of 25 and output layer of size 10. I initialize my weights and when I am running the backpropagation to update my weights, weights remains constant for second iteration onwards. Can somebody please help me to sort it out?
tagged with: python
has comment: http://stackoverflow.com/comment/83420254
score: 0
has title: BAckward propagation neural networks weight updation remains constant for every iteration
answer count: 0
has comment: http://stackoverflow.com/comment/83599131
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/83381273
has text: show your signup view where you are saving your user. Because this error occurs when your username or password is not correct.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48187740

http://stackoverflow.com/comment/139476736
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48191114
type: AnswerComment
has text: _"if you're using front/back slash it's a bit crucial"_ - It's actually not. `Path` being OS agnostic is kinda the whole point and that choice is irrelevant beyond the consideration of using backslashes inside strings. Using `Path('/etc/something')`, `Path('\\etc\\something')`, and `Path(r'\etc\something')` on Windows all return the same thing. You can even do `Path('/etc\\something')` if so inclined.

http://stackoverflow.com/comment/83442853
type: Comment
type: QuestionComment
has text: postgresql configuration seems like a promising avenue, but unfortunately maxconnections was 100 and raising it to 200 made no difference (even though not even 100 should have been used before).
score: 0
comment on: http://stackoverflow.com/q/48195549

http://stackoverflow.com/comment/83568536
comment on: http://stackoverflow.com/q/48291546
score: 0
type: Comment
type: QuestionComment
has text: did `pip install mysql-connector==2.1.3` execute without errors? when I run it in a new venv it fails.

http://stackoverflow.com/q/48199188
has comment: http://stackoverflow.com/comment/83380413
tagged with: beautifulsoup
type: Question
has title: Python 3.5 not cooperating with BeautifulSoup and variables
has answer: http://stackoverflow.com/a/48199552
type: UnansweredQuestion
has body: I'm trying to write a program that can check whether or not a YouTube video is in the music category or not. I have written some code but its almost as if Python is "lying" to me. Here is the code >>> from bs4 import BeautifulSoup >>> from urllib.request import urlopen >>> url = "https://www.youtube.com/watch?v=LXuNNqoo1WQ" >>> html = urlopen(url).read() >>> soup = BeautifulSoup(html, "html.parser") >>> tags = soup.find_all(class_="content watch-info-tag-list") >>> hasmusictag = 'href="/channel/UC-9-kyTW8ZkZNDHQJ6FgpwQ">Music' in tags[0] >>> print(hasmusictag) False >>> print(tags[0]) Music As you can see, hasmusictag should return true, but it is returning false. I have no idea why. All help is appreciated!
has comment: http://stackoverflow.com/comment/83379864
tagged with: python
has comment: http://stackoverflow.com/comment/83379685
score: 0
answer count: 1
tagged with: web-scraping
tagged with: variables

http://stackoverflow.com/comment/83447682
comment on: http://stackoverflow.com/q/48232573
type: QuestionComment
score: 1
has text: How do you feel about the built-in `filter()`?
type: Comment

http://stackoverflow.com/a/48191670
type: Answer
answers question: http://stackoverflow.com/q/48191071
score: 0
has body: You can annotate your queryset to calculate the average using your database from django.db.models import Avg Product.objects.all().annotate( rating=Avg('review_set__rating') ).order_by('rating') Now each Product object in the queryset will have an additional attribute rating If you must store this rating because it becomes expensive to calculate then @niklas' comment is the correct solution

http://stackoverflow.com/q/48327054
linked to: http://stackoverflow.com/q/27885397
has comment: http://stackoverflow.com/comment/83639512
has comment: http://stackoverflow.com/comment/83639652
tagged with: python
has comment: http://stackoverflow.com/comment/83640240
possible better answer: http://stackoverflow.com/a/48327216
has body: I'd like to install a certain python package with pip but because of the proxy I am sitting behind pip cannot connect to the internet. So my question is: Where does pip look for .whl files in order to download them? Can't I just use my browser (which can connect to the internet just fine) to download the .whl file? Installing the package with the downloaded .whl file would be not a problem then.
has comment: http://stackoverflow.com/comment/120884989
has comment: http://stackoverflow.com/comment/83639827
answer count: 2
downvote count: 0
has title: Where does pip download .whl files?
has answer: http://stackoverflow.com/a/48327216
has answer: http://stackoverflow.com/a/48327127
accepted answer: http://stackoverflow.com/a/48327127
score: 19
upvote count: 19
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83639635
has comment: http://stackoverflow.com/comment/83639970
has comment: http://stackoverflow.com/comment/83639515
type: AnsweredQuestion

http://stackoverflow.com/a/48222664
accepted answer of: http://stackoverflow.com/q/48221824
type: AcceptedAnswer
score: 3
has body: You can join strategies the same way you join sets. Example: strategy_bools_or_ints = st.booleans() | st.integers() In the test, you could join st.integers with st.none: st_input = st.integers(min_value=-1000, max_value=1000) st_input_optional = st_input | st.none() @given(start=st_input_optional, stop=st_input, step=st_input_optional) def test_XXX_for_integer(start, stop, step): assert myrange3(stop, start=start, step=step)
type: Answer
answers question: http://stackoverflow.com/q/48221824
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/48175967
has comment: http://stackoverflow.com/comment/83331717
has comment: http://stackoverflow.com/comment/83332360
has comment: http://stackoverflow.com/comment/83331675
has comment: http://stackoverflow.com/comment/83331689
has comment: http://stackoverflow.com/comment/83331648
has body: So when I'm trying to run this code. As you can see it asks for a number as an input. print('How old is Vini?') number= 17 guess= int(input('enter a number')) if guess== number: print('Bravo Vini is 17') elif guess &lt; number: print('Vini is older than '+guess) elif guess &gt; number: print('Vini younger than '+guess) Now if the number is equal to 17 it executes but if the number is higher or lower it gives me this error: When the number is higher: Traceback (most recent call last): File "C:\Users\ervin\Desktop\loja.py", line 9, in &lt;module&gt; print('Vini younger than '+guess) TypeError: must be str, not int When the number is lower: Traceback (most recent call last): File "C:\Users\ervin\Desktop\loja.py", line 7, in &lt;module&gt; print('Vini is older than '+guess) TypeError: must be str, not int
has comment: http://stackoverflow.com/comment/83331677
score: -6
has answer: http://stackoverflow.com/a/48176006
has comment: http://stackoverflow.com/comment/83331690
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83433996
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48176066
duplicate of: http://stackoverflow.com/q/25675943
tagged with: python
has comment: http://stackoverflow.com/comment/83331669
downvote count: 6
has comment: http://stackoverflow.com/comment/83331637
linked to: http://stackoverflow.com/q/33266134
has comment: http://stackoverflow.com/comment/83331993
upvote count: 0
has comment: http://stackoverflow.com/comment/83332911
answer count: 2
has title: Python code not running, do I need to reinstall python?

http://stackoverflow.com/comment/83422458
comment on: http://stackoverflow.com/q/48210675
type: Comment
type: QuestionComment
has text: @Gianluca: I had set the PYTHONPATH along with PATH but to no avail. Sorry for not including that in the question. Have updated it now.
score: 0

http://stackoverflow.com/q/48210010
has title: pandas - automate graph using the combination of two columns
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48210272
tagged with: pandas
has answer: http://stackoverflow.com/a/48210272
answer count: 1
type: Question
tagged with: graph
has body: What is the best way to automate the graph production in the following case: I have a data frame with different plan and type in the columns I want a graph for each combination of plan and type Dataframe: plan type hour ok notok other A cont 0 60.0 40.0 0.0 A cont 1 56.6 31.2 12.2 A vend 2 30.0 50.0 20.0 B test 5 20.0 50.0 30.0 For one df with only one plan and type, I wrote the following code: fig_ = df.set_index('hour').plot(kind='bar', stacked=True, colormap='YlOrBr') plt.xlabel('Hour') plt.ylabel('(%)') fig_.figure.savefig('p_hour.png', dpi=1000) plt.show() In the end, I would like to save one different figure for each combination of plan and type. Thanks in advance!
tagged with: python

http://stackoverflow.com/comment/83494944
type: Comment
has text: Unfortunately, your answer is now identical to: https://stackoverflow.com/a/48255963/4909087
type: AnswerComment
comment on: http://stackoverflow.com/a/48255956
score: 1

http://stackoverflow.com/q/48233012
has answer: http://stackoverflow.com/a/48233424
has body: I have a column on my dataframe that contains the following Wal-Mart Stores, Inc., Clinton, IA 52732 Benton Packing, LLC, Clearfield, UT 84016 North Coast Iron Corp, Seattle, WA 98109 Messer Construction Co. Inc., Amarillo, TX 79109 Ocean Spray Cranberries, Inc., Henderson, NV 89011 W R Derrick &amp; Co. Lexington, SC 29072 I am having problem to capture it using regex so far my regex works for first 2 lines: [A-Z][A-za-z-\s]+,\s{1}(Inc.|LLC) How do I split the column to 4 additional columns? i.e. Column1 = Company Name, Column 2 = City, Column 3 = State, Column 4 = Zipcode. Example of the output is shown below: Company_Name City State ZipCode Wal-Mart Stores, Inc. Clinton IA 52732
type: AnsweredQuestion
upvote count: 0
tagged with: pandas
downvote count: 1
has title: Python3 Pandas Dataframe Split Columns
answer count: 1
accepted answer: http://stackoverflow.com/a/48233424
favorite count: 0
type: Question
tagged with: python
score: -1

http://stackoverflow.com/comment/83455126
comment on: http://stackoverflow.com/q/48235513
type: Comment
type: QuestionComment
score: 0
has text: those are my indexes, I want to replace the whole row of data with multiple rows

http://stackoverflow.com/a/48294837
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48294273
has body: As for your 2nd example, where you want to assign values iteratively, you an do it this way. var = ['A1','B2','C3'] val = [1,2,3] for i in range(len(val)): df = df.replace({var[i]:val[i]}) # your calculations here...
type: Answer
score: 1

http://stackoverflow.com/comment/83393062
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48205282
has text: My Apologies, Seemed pretty much the same. @TimPietzcker

http://stackoverflow.com/comment/83496621
type: AnswerComment
score: 0
type: Comment
has text: Truly you are wise in the ways of science :)
comment on: http://stackoverflow.com/a/48256948

http://stackoverflow.com/comment/83512629
has text: @Moshe S., also, `>it will take around the 2 seconds` actually means that the [`socket`](https://docs.python.org/3.7/library/socket.html) (server-side) is busy for 2 seconds, not the GUI. For example, `on_off.write(b"S00QLE\n")` line is fast, because [`write`](https://docs.python.org/3.7/library/telnetlib.html#telnetlib.Telnet.write) doesn't blocks execution (only when connection is blocked, as stated in description). So pay attention to the functions that you use!
type: AnswerComment
comment on: http://stackoverflow.com/a/48263391
type: Comment
score: 0

http://stackoverflow.com/q/48196080
score: 0
tagged with: bash
answer count: 1
tagged with: gitlab-ci
has comment: http://stackoverflow.com/comment/83373341
accepted answer: http://stackoverflow.com/a/48196132
has comment: http://stackoverflow.com/comment/83373793
type: Question
has body: I am writing a bash script where the curl command returns a JSON array of objects and then I need to filter the required values out of those objects. So I need to iterate through the objects to check then and parse them and finally get the result. But inside my bash script if I do something like, for i in 1 2 3 4 do curl -XGET 'https://gitlab.com/user/api/v4/projects/1/pipelines/1/jobs' | python -c 'import sys, json; print(json.load(sys.stdin)[$i]["stage"])' done I get the following error: File "&lt;string&gt;", line 1 import sys, json; print($i) ^ SyntaxError: invalid syntax 100 3016 100 3016 0 0 18748 0 --:--:-- --:--:-- --:--:-- 19210 (23) Failed writing body Everything Ok if I remove the python part after the pipe, but why can't I use python in combination with curl ? what am I doing wrong here ?
has comment: http://stackoverflow.com/comment/83373836
has answer: http://stackoverflow.com/a/48196132
has title: How to pipe JSON output of curl to query a JSON value using python
has comment: http://stackoverflow.com/comment/83373265
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has comment: http://stackoverflow.com/comment/83373777
tagged with: curl
type: AnsweredQuestion

http://stackoverflow.com/q/48249512
has answer: http://stackoverflow.com/a/48249538
favorite count: 0
has body: One of the PyBites Code Challenges, simplified here, involves sorting a list of names by last name: &gt;&gt;&gt; names = ['Al Pacino', 'Matt Damon', 'Sandra Bullock', 'Keanu Reeves'] &gt;&gt;&gt; sorted(names, key=lambda x: x.split()[1]) ['Sandra Bullock', 'Matt Damon', 'Al Pacino', 'Keanu Reeves'] This approach works fine for the given example but breaks if any of the strings split into less than two parts. For example, adding "Madonna": &gt;&gt;&gt; names = ['Al Pacino', 'Madonna', 'Matt Damon', 'Sandra Bullock', 'Keanu Reeves'] &gt;&gt;&gt; sorted(names, key=lambda x: x.split()[1]) IndexError: list index out of range One could perhaps pad the split strings out to the required length with empty strings: def last_name(name, last_name_field=2): name_split = name.split() while len(name_split) &lt; 2: name_split.append('') return name_split[last_name_field - 1] such that: &gt;&gt;&gt; names = ['Al Pacino', 'Madonna', 'Matt Damon', 'Sandra Bullock', 'Keanu Reeves'] &gt;&gt;&gt; sorted(names, key=last_name) ['Madonna', 'Sandra Bullock', 'Matt Damon', 'Al Pacino', 'Keanu Reeves'] Is there a better way? Clarification: The answers to date offer alternative ways to sort on the last element in a split string. Thank you -- these are all very useful! However, as my question did not make sufficiently clear -- my fault -- what I actually want is a way to sort on a given element (or field) of split strings that will not raise an exception and fail if any of the split strings have less than the required number of fields. Essentially, I am looking for a way to get the same results as the Unix sort command, as in the following example, which sorts on field 2: $ sort +1 -2 Madonna.txt # sorts by field 2 Madonna # without a field 2, sorts before the others Leonardo Da Vinci # sorts on Da (before Damon) Matt Damon Robert Downey Jr # sorts on Downey, not Jr Scarlett Johansson Al Pacino My idea of "padding out" the split strings (see above) was based on the observation that empty strings…
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/83481590
possible better answer: http://stackoverflow.com/a/48249537
has comment: http://stackoverflow.com/comment/83498376
tagged with: python
has answer: http://stackoverflow.com/a/48249537
score: -1
tagged with: sorting
answer count: 6
has comment: http://stackoverflow.com/comment/83481599
has title: IndexError when sorting on "field x" in a string when not all strings split to "x" number of fields
has answer: http://stackoverflow.com/a/48249539
has comment: http://stackoverflow.com/comment/83481607
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48250903
accepted answer: http://stackoverflow.com/a/48268442
has comment: http://stackoverflow.com/comment/83481537
has comment: http://stackoverflow.com/comment/83482352
downvote count: 3
has answer: http://stackoverflow.com/a/48268442
has answer: http://stackoverflow.com/a/48249587

http://stackoverflow.com/comment/83539836
type: Comment
has text: @Kasramvd well, I had posted it before I saw you had already provided a solution, and perhaps I was too attached to it. I'm not sure an iterative solution would be necessary, honestly, if you are nesting more than 10 levels deep, you've got other problems
type: AnswerComment
comment on: http://stackoverflow.com/a/48276491
score: 1

http://stackoverflow.com/a/48234382
has body: Range creates a list [0, 2, 4, ..., 48] This meaans the i+=1 is superfluous. Your next step is to add the spaces, which, conveniently, you are supposed to have the number of spaces as the number being printed (I think). python conveniently has the ability to repeat a character with multiply, so the suggested code would be for i in range(0, 52, 2): print(" "*i+str(i))
answers question: http://stackoverflow.com/q/48234299
upvote count: 2
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/83626585
has text: Just read the introduction section of https://docs.python.org/3/library/sqlite3.html which already tells you why you're doing it double wrong.
type: Comment
type: QuestionComment
score: 6
comment on: http://stackoverflow.com/q/48320642

http://stackoverflow.com/q/48190530
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83361387
favorite count: 0
has title: Line following, finding the centroid, and having the robot stay on that center point
has comment: http://stackoverflow.com/comment/83361186
score: -2
type: Question
has body: I'm having trouble running the last part of my code here. Im using Raspberry Pi, OpenCV, PiCamera, and servo motors. NOT SHOWN i have the code to find the centroid, and from the centroid it will then determine how far off '160' it is. Im not totally sure if the centroid's middle point is 160, so do any of you know that? As well as I get a SyntaxError on the "if: cx>151 and cx&lt;169", would any of you know why that it, or could you help me to figure out a different approach to telling it how to follow the line? import RoboPiLib as RPL import setup motorL = 0 motorR = 1 #1500 = middle point #The closer to '1500' the slower it will go if: cx&gt;151 and cx&lt;169 print "straight" RPL.servoWrite(motorL, 1000) RPL.servoWrite(motorR, 2000) time.sleep(2) elif x&lt;=150 print "left" RPL.servoWrite(motorL, 1000) RPL.servoWrite(motorR, 1750) time.sleep(2) elif x&gt;=170 print "right" RPL.servoWrite(motorL, 1250) RPL.servoWrite(motorR, 1000) time.sleep(2) else print "stop"
has answer: http://stackoverflow.com/a/48190599
tagged with: raspberry-pi
tagged with: servo
upvote count: 0
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/122360822
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/66805058
has text: Why would the line of code shown as triggering the error use the 'Snowflake' connector or SSL in any way?
type: Comment

http://stackoverflow.com/q/48294381
score: -1
has body: I am new to Django and I am going to create a website with multiple same html pages. I got a text file which contains the number of how many same html pages is going to create. And the following one is the view.py. And the t=a.split()[7] get the number of pages needed to be created def bb(request): form=BBForm(request.POSt or None) if(form.is_valid()): my_file=open("./input_data.txt",'r') a=my_file.read(); my_file.close(); t=a.split()[7] form.save() context={"form":form} return render(request,'bb/bb.html',context) And the bb.html is like the following: &lt;form method='POST' action=''&gt; {% csrf_token %} {{ form.as_p }} &lt;input type='submit' value='submit /&gt; &lt;/form&gt; If I only use those code, I can generate the website with the form.However, it only appears once. What can I do if I want to create multiple same forms within one html page or multiple html page with the same html code
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48294626
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: django
downvote count: 1
has title: create multiple same html page in django
has comment: http://stackoverflow.com/comment/83573727
tagged with: http://stackoverflow.com/tag/html
tagged with: python

http://stackoverflow.com/comment/83383320
has text: Very good answer, but note that some requests might be more complex. For example, there is a hidden field ('sortAction') that you may have to submit, or you may have to use cookies, or change the uastring and other headers. Also this page relies too much on js (most jsp pages do), so it might not even be possible to use `requests` / `urllib`, and you may have to use `selenium`. Still +1, this answer should be very helpful to unexperienced users.
type: AnswerComment
comment on: http://stackoverflow.com/a/48199243
score: 0
type: Comment

http://stackoverflow.com/comment/83403231
has text: Hi Martijn, sorry about that. Please see above for an edited version.
comment on: http://stackoverflow.com/q/48209017
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83368070
score: 0
has text: The error is from bash. Does your command line even run from shell?
comment on: http://stackoverflow.com/q/48193768
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48316527
type: Question
has answer: http://stackoverflow.com/a/48356662
tagged with: robotframework
has comment: http://stackoverflow.com/comment/83625398
has comment: http://stackoverflow.com/comment/83624602
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/83620192
favorite count: 0
has comment: http://stackoverflow.com/comment/83621419
has title: How to add additional output info from code to robotframework *.html report
has comment: http://stackoverflow.com/comment/83624761
has body: in teardown() method i have a dictionary with key and value and i need to add this data in robot *.html report BUT each KEY-VALUE pair should be as separate keyword with KEY in header and VALUE in body. how can i do it?
tagged with: python
has comment: http://stackoverflow.com/comment/83620491

xvfb
type: Tag
tag name: xvfb
tags question: http://stackoverflow.com/q/48209231

pyspark
tags question: http://stackoverflow.com/q/48220001
tags question: http://stackoverflow.com/q/48174484
tags question: http://stackoverflow.com/q/48206622
tags question: http://stackoverflow.com/q/48229043
tags question: http://stackoverflow.com/q/48287223
tags question: http://stackoverflow.com/q/48179837
tags question: http://stackoverflow.com/q/48199167
tags question: http://stackoverflow.com/q/48228909
tags question: http://stackoverflow.com/q/48208193
tags question: http://stackoverflow.com/q/48196203
tags question: http://stackoverflow.com/q/48178039
tags question: http://stackoverflow.com/q/48274851
tags question: http://stackoverflow.com/q/48177406
tags question: http://stackoverflow.com/q/48243877
tags question: http://stackoverflow.com/q/48328855
tags question: http://stackoverflow.com/q/48185535
tags question: http://stackoverflow.com/q/48266749
tags question: http://stackoverflow.com/q/48176862
tags question: http://stackoverflow.com/q/48330983
tags question: http://stackoverflow.com/q/48286421
tags question: http://stackoverflow.com/q/48209667
tags question: http://stackoverflow.com/q/48262409
tags question: http://stackoverflow.com/q/48297678
tags question: http://stackoverflow.com/q/48232314
tags question: http://stackoverflow.com/q/48260412
tags question: http://stackoverflow.com/q/48270789
type: Tag
tags question: http://stackoverflow.com/q/48302090
tags question: http://stackoverflow.com/q/48195294
tags question: http://stackoverflow.com/q/48278489
tags question: http://stackoverflow.com/q/48298902
tags question: http://stackoverflow.com/q/48308586
tags question: http://stackoverflow.com/q/48185462
tag name: pyspark
tags question: http://stackoverflow.com/q/48318515
tags question: http://stackoverflow.com/q/48214293
tags question: http://stackoverflow.com/q/48304008
tags question: http://stackoverflow.com/q/48252181
tags question: http://stackoverflow.com/q/48234474
tags question: http://stackoverflow.com/q/48320449
tags question: http://stackoverflow.com/q/48311797
tags question: http://stackoverflow.com/q/48302123
tags question: http://stackoverflow.com/q/48180935

http://stackoverflow.com/comment/83461899
has text: Is there any way to work around this problem? I'm scraping websites and many websites use this syntax. Can I somehow change the way it reads the html? Beside: I'm able to put div-Elements inside h3, althought div is als not a "Phrasing content"-Element.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48237315
score: 0

http://stackoverflow.com/comment/83464309
type: Comment
type: QuestionComment
has text: `print("The Slope is {}".format(slope))`
comment on: http://stackoverflow.com/q/48241007
score: 0

http://stackoverflow.com/q/48272129
type: Question
score: 3
tagged with: nbconvert
has title: convert jupyter notebook saved as .HTML file back into .IPYNB
tagged with: python
accepted answer: http://stackoverflow.com/a/59555009
tagged with: ipython
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/59555009
type: AnsweredQuestion
upvote count: 3
has body: Can I convert a Jupyter Notebook saved as .HTML file back into .IPYNB file? The executable original notebooks were lost. The nbconvert docs don't have anything useful for this case. Currently I have to copy-paste bunch of cells into a new notebook, but this is very tedious and output cells will be lost this way. [EDIT] I found an interactive way to do this using BeautifulSoup: IPython notebook: Convert an HTML notebook to ipynb
answer count: 1
downvote count: 0
tagged with: jupyter
linked to: http://stackoverflow.com/q/28972614
favorite count: 0

http://stackoverflow.com/comment/83405708
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48211590
has text: Also can you include the exact error output

http://stackoverflow.com/comment/83338111
comment on: http://stackoverflow.com/q/48173820
has text: I will move the sql connect out of the def - it is there for reference only
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83524456
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48270296
type: QuestionComment
has text: Made it beefier, sorry about that. I didn't include what was needed and corrected it.

http://stackoverflow.com/comment/83600227
type: Comment
type: QuestionComment
has text: That is correct.
comment on: http://stackoverflow.com/q/48306887
score: 0

http://stackoverflow.com/comment/83473175
type: QuestionComment
has text: Indeed, this is a beginner mistake. You shouldn't remove list elements during iteration.
score: 0
comment on: http://stackoverflow.com/q/48245128
type: Comment

http://stackoverflow.com/q/48246117
tagged with: amazon-web-services
has body: I'm working on a project using Python(3.6) and Django(1.10) in which i need to use end user's account resource to make his code deployed on his aws account. I have set up 2 accounts(1 as my app &amp; 2nd as a user's account) and make authentication successful.But when I have passed this auth in another view it throws some errors. Here's what I have tried: From views.py: def boto3_with_role(role_arn, session_prefix, external_id, **kwargs): """ Create a partially applied session to assume a role with an external id. A unique session_name will be generated by {session_prefix}_{time} `session` can be passed, otherwise the default sesion will be used see: http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-api.html """ sts = boto3.client('sts') res = sts.assume_role( RoleArn=role_arn, RoleSessionName='{}_{}'.format(session_prefix, int(time.time())), ExternalId=external_id, *kwargs, ) creds = res['Credentials'] print(creds) return partial(boto3.session.Session, aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken'], ) class AwsAuthentication(LoginRequiredMixin, CreateView): def post(self, request, *args, **kwargs): AwsSession = boto3_with_role('arn:aws:iam::497736713165:role/IstiocloudCrossAccount', 'MyPrefix', 'abd37214@cloud') my_session = AwsSession() client = my_session.resource('s3') for bucket in client.buckets.all(): print(bucket.name) return render(request, 'dockerDep/aws/selectDeployment.html', {'bucket': bucket.name}) # return HttpResponse('Your Bucket is: {}'.format(bucket.name)) # From here AWS Deployments starting class AwSlsDeployment(LoginRequiredMixin, CreateView): def get(self, request, *args, **kwargs): AwsSession = boto3_with_role('arn:aws:iam::497736713165:role/IstiocloudCrossAccount', 'MyPrefix', 'abd37214@cloud') user_session = AwsSession() client = user_session.resource('s3') for bucket in client.buckets.all(): print(bucket.name) return render(request, 'doc…
has title: Implement AWS authentication to use end user's resources in Python & Django App
answer count: 0
downvote count: 0
score: 1
upvote count: 1
tagged with: authentication
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/a/48253180
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/83489099
answers question: http://stackoverflow.com/q/48252914
has body: you can rename the value of keys, add new key add remove the old ones: dic = {'New Year Day 2019\\xa0': 'Tuesday, January 1', 'Good Friday': 'Friday, March 30', 'New Year Day 2018\\xa0': 'Monday, January 1'} for key in dic: if key != key.replace('\\xa0', ''): dic[key.replace('\\xa0', '')] = dic[key] del dic[key] print(dic) the result will be: {'Good Friday': 'Friday, March 30', 'New Year Day 2019': 'Tuesday, January 1', 'New Year Day 2018': 'Monday, January 1'}

http://stackoverflow.com/a/48242325
answers question: http://stackoverflow.com/q/48242324
score: 244
type: Answer
upvote count: 244
has comment: http://stackoverflow.com/comment/126165381
accepted answer of: http://stackoverflow.com/q/48242324
type: AcceptedAnswer
downvote count: 0
has body: Assuming that you only want to go back one revision, use alembic downgrade with a relative migration identifier of -1: alembic downgrade -1 This will run the downgrade() method of your latest revision and update the alembic_version table to indicate the revision you're now at. If you need to go back multiple migrations, run alembic history to view a list of all the migrations in your project (from newest to oldest), then copy and paste the identifier of the migration you want to go back to: alembic downgrade 8ac14e223d1e There's currently no command to delete migrations from your versions directory, so if you want to completely wipe away all trace of your bad migration, you'll need to delete the version file (like 4c009570237e_add_widget_table.py) manually.

http://stackoverflow.com/comment/83512070
type: QuestionComment
comment on: http://stackoverflow.com/q/48262698
score: 1
type: Comment
has text: Where are you running this script from? Does that machine have internet access?

http://stackoverflow.com/comment/83562166
comment on: http://stackoverflow.com/q/48288171
score: 0
has text: See https://code.djangoproject.com/ticket/25582 and https://groups.google.com/forum/#!topic/django-developers/_ZuTpMEATiM/discussion
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48249734
has answer: http://stackoverflow.com/a/48249769
accepted answer: http://stackoverflow.com/a/48249802
linked to: http://stackoverflow.com/q/7961363
has body: my current output [1,2,3,4,5,6] [2,1,3,4,5,6] [3,2,1,4,5,6] ... [6,5,4,3,2,1] all numbers are same but i want like this output only one [1,2,3,4,5,6] how can i do this import os import sys numbers=[1,2,3,4,5,6] x=[] for i1 in numbers: for i2 in numbers: for i3 in numbers: for i4 in numbers: for i5 in numbers: for i6 in numbers: if i1 not in (i2,i3,i4,i5,i6) and i2 not in (i1,i3,i4,i5,i6) and i3 not in (i1,i2,i4,i5,i6) and i4 not in (i1,i2,i3,i5,i6) and i5 not in (i1,i2,i3,i4,i6) and i6 not in (i1,i2,i3,i4,i5): x.append([i1,i2,i3,i4,i5,i6]) i=0 while i &lt; len(x): print x[i] i=i+1
has comment: http://stackoverflow.com/comment/83481988
has answer: http://stackoverflow.com/a/48249802
favorite count: 0
type: Question
has title: I want to not listing duplicated numbers of arrays
has comment: http://stackoverflow.com/comment/83481987
has answer: http://stackoverflow.com/a/48250007
possible better answer: http://stackoverflow.com/a/48249769
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/83483019
has comment: http://stackoverflow.com/comment/83482008
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83482331
answer count: 3
has comment: http://stackoverflow.com/comment/83481997
upvote count: 0
downvote count: 3

http://stackoverflow.com/comment/83459739
score: 0
has text: ohhh man, why are you using `lambda` here and why `globals`? It is a big NO NO... why not just `pdsql.sqldf(str2)`?
comment on: http://stackoverflow.com/q/48238702
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48206683
has body: range copies the parameters given to it for internal use. So changes to those afterwards have no effect. Same as with the loop variable, which is only created from the internal values every time. That's different though if you use a mutable object like a list to iterate over: a = [1,2,3] for i in a: a.append(i) This loop will indeed run infinitely.
has comment: http://stackoverflow.com/comment/83394268
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/48206443
has comment: http://stackoverflow.com/comment/83394298
type: Answer
upvote count: 2

http://stackoverflow.com/q/48247858
type: Question
answer count: 0
tagged with: candlestick-chart
type: UnansweredQuestion
has title: matplotlib.candlestick2_ohlc weird unequal bar width and line position
has comment: http://stackoverflow.com/comment/83481848
tagged with: python
score: 0
has body: Here is what I got: Basically just with candlestick2_ohlc(ax, df.open, df.high, df.low, df.close, colorup='r', colordown='c', width=0.4) I only changed the line color in candlestick2_ohlc function to colorup if Open&lt;=Close and colordown if Open > Close. Did you notice that the bar width are not the same? And line positions in each bar are not at the center, and the line segment inside the bar's body are not in line with the line segments outside the bar's body. Let me zoom in: Anyone knows why this is happening? How to address this?
has comment: http://stackoverflow.com/comment/83495382
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83503561

http://stackoverflow.com/comment/83502329
type: QuestionComment
has text: You do not decode anything, so what would you expect?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48259726

http://stackoverflow.com/q/48259497
downvote count: 0
has title: Selecting image region based on boolean image mask values
answer count: 1
tagged with: python
has body: I have a rgb image, for example img_rgb[:,:,0] = [ 125 160; 130 125]; img_rgb[:,:,1] = [ 125 160; 130 125]; img_rgb[:,:,2] = [ 125 160; 130 125]; and a mask boolean image whose size equals the size of img_rgb e.g mask[:,:] = [ 1 0; 0 1] for every zero value of mask, I would like to associate a nan value in the img-rgb, thus obtaining the following img_rgb[:,:,0] = [ 125 nan; nan 125] img_rgb[:,:,1] = [ 125 nan; nan 125] img_rgb[:,:,2] = [ 125 nan; nan 125] Since my image array is really big (length size 10000px) I would like to do that as fast as possible and thus avoiding a double for cycle. In Matlab I would use the logical operator img_rgb(repmat(mask,1,1,3)==0)=nan; how can I do something similar in python? python v.2.7 Thanks in advance
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48260040
accepted answer: http://stackoverflow.com/a/48260040
score: 1
upvote count: 1
tagged with: image-processing
tagged with: image
favorite count: 0
type: Question

http://stackoverflow.com/q/48250053
accepted answer: http://stackoverflow.com/a/48377833
has answer: http://stackoverflow.com/a/48377833
score: 18
tagged with: python
upvote count: 18
has comment: http://stackoverflow.com/comment/83512704
has comment: http://stackoverflow.com/comment/83511199
type: AnsweredQuestion
has body: So this is a minimal code which illustrates the issue: This is the Dataset: class IceShipDataset(Dataset): BAND1='band_1' BAND2='band_2' IMAGE='image' @staticmethod def get_band_img(sample,band): pic_size=75 img=np.array(sample[band]) img.resize(pic_size,pic_size) return img def __init__(self,data,transform=None): self.data=data self.transform=transform def __len__(self): return len(self.data) def __getitem__(self, idx): sample=self.data[idx] band1_img=IceShipDataset.get_band_img(sample,self.BAND1) band2_img=IceShipDataset.get_band_img(sample,self.BAND2) img=np.stack([band1_img,band2_img],2) sample[self.IMAGE]=img if self.transform is not None: sample=self.transform(sample) return sample And this is the code which fails: PLAY_BATCH_SIZE=4 #load data. There are 1604 examples. with open('train.json','r') as f: data=f.read() data=json.loads(data) ds=IceShipDataset(data) playloader = torch.utils.data.DataLoader(ds, batch_size=PLAY_BATCH_SIZE, shuffle=False, num_workers=4) for i,data in enumerate(playloader): print(i) It gives that weird open files error in the for loop… My torch version is 0.3.0.post4 If you want the json file, it is available at Kaggle (https://www.kaggle.com/c/statoil-iceberg-classifier-challenge) I should mention that the error has nothing to do with the state of my laptop: yoni@yoni-Lenovo-Z710:~$ lsof | wc -l 89114 yoni@yoni-Lenovo-Z710:~$ cat /proc/sys/fs/file-max 791958 What am I doing wrong here?
tagged with: pytorch
has comment: http://stackoverflow.com/comment/83510289
answer count: 1
downvote count: 0
favorite count: 0
has title: PyTorch's dataloader "too many open files" error when no files should be open
type: Question
has comment: http://stackoverflow.com/comment/83508851
tagged with: python-3.x

http://stackoverflow.com/a/48283050
has body: The empty parenthesis indicate a function call with no arguments. In both cases you mention this is consistent with the way you would call the object/member, had they any arguments. circle = Circle(10) squared = square_me(2) The first case is special to object oriented programming: it is a constructor call. These are specified by the __init__-method in Python. In this case the constructor takes no arguments. The concept of calling with no arguments makes sense in Python because functions with no arguments typically have observable side-effects, e.g., print_line_of_ones(), or on an object do something based on the object state, e.g., circle.getArea(). In Python a class-member function takes self, the object itself, as first argument. There are some languages which allow you to omit the parenthesis if there are not arguments (e.g. Scala), but Python requires you to use them, which is reasonable given that it can otherwise be difficult to distinguish them from members, and Python does not statically check this.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48282664
has comment: http://stackoverflow.com/comment/83771957
has comment: http://stackoverflow.com/comment/83792855

http://stackoverflow.com/comment/83584981
comment on: http://stackoverflow.com/q/48300027
score: 0
type: Comment
type: QuestionComment
has text: @Spangen Actually no! The blog version will always comes before the actual root domain. I kinda messed up above. There will 2 occurrence of the website just like I mentioned above (for example: 'https://techcrunch.com/event-info/sessions-robotics/' AND 'https://techcrunch.com'). Yes, the protocol will always be the same for both root and the blog version.

http://stackoverflow.com/a/48233054
has body: Since you state you can use tuples, I would recommend making each of your sub-lists into tuples and then making a set of these tuples. Then, searching the set will be an O(1) lookup. Initial construction of the set may be costly, though, but if you do many lookups it is worth it. &gt;&gt;&gt; set_of_sublists = {tuple(sublist) for sublist in orignal_list} &gt;&gt;&gt; tuple(sublist_to_check_for_membership) in set_of_sublists I want to acknowledge that @BrettBeatty originally gave this answer as well but has deleted it subsequently.
accepted answer of: http://stackoverflow.com/q/48232080
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48232080
has comment: http://stackoverflow.com/comment/83448774

http://stackoverflow.com/a/67234749
answers question: http://stackoverflow.com/q/48270385
type: Answer
has body: For me, I opened the nested folder of my Django project. So, Django couldn't find the modules of venv. Just mentioning, I thought it might be helpful to someone.
score: 0

http://stackoverflow.com/a/48259859
score: 1
upvote count: 1
has body: Regex is overkill here; you can simply append a space to each string before comparing them to get the same result. You also don't need to sort the data. It's more efficient to simply loop over every value. def find_longest_matching_option(option, options): # append a space so that find_longest_matching_option("a b", ["a b"]) # works as expected option += ' ' longest = None for valid_option in options: # append a space to each option so that only complete # words are matched valid_option += ' ' if option.startswith(valid_option): # remember the longest match if longest is None or len(longest) &lt; len(valid_option): longest = valid_option if longest is not None: # remove the trailing space longest = longest[:-1] return longest
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48259500

http://stackoverflow.com/q/48179417
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83339124
answer count: 1
tagged with: database
tagged with: python
has comment: http://stackoverflow.com/comment/83339051
has comment: http://stackoverflow.com/comment/83339175
has body: Situation: Need to deal with large amounts of data (~260MB CSV datafile of about 50B of data per line) Problem: If I just read from the file every time I need to deal with it, it will take a long time. So I decided to push everything into a database. I need a fast database infrastructure to handle the data as I need to do a lot of reading and writing. Question: What are the faster choices for database in Python? Additional information 1: The data comprises of 3 columns and I do not see myself needing anymore than that. Would this mean that a NoSQL database is preferred? Additional information 2: However, if in the future I do need more than one database working together, would it be better to go for a SQL database? Additional information 3: I think it would help to mention that I am looking at a few different DBs (MongoDB, SQLite, tinydb), but do suggest other DBs that you know are faster.
downvote count: 0
has answer: http://stackoverflow.com/a/70135068
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83339096
has comment: http://stackoverflow.com/comment/83339293
has title: Fast database solutions for Python Programming

http://stackoverflow.com/a/48328564
accepted answer of: http://stackoverflow.com/q/48328012
score: 19
upvote count: 19
answers question: http://stackoverflow.com/q/48328012
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86499002
has body: You'll have to cook up your own serialization/deserialization recipe. Fortunately, logistic regression can basically be captured by the coefficients and the intercept. However, the LogisticRegression object keeps some other metadata around which we might as well capture. I threw together the following functions that does the dirty-work. Keep in mind, this is still rough: import numpy as np import json from sklearn.linear_model import LogisticRegression def logistic_regression_to_json(lrmodel, file=None): if file is not None: serialize = lambda x: json.dump(x, file) else: serialize = json.dumps data = {} data['init_params'] = lrmodel.get_params() data['model_params'] = mp = {} for p in ('coef_', 'intercept_','classes_', 'n_iter_'): mp[p] = getattr(lrmodel, p).tolist() return serialize(data) def logistic_regression_from_json(jstring): data = json.loads(jstring) model = LogisticRegression(**data['init_params']) for name, p in data['model_params'].items(): setattr(model, name, np.array(p)) return model Note, with just 'coef_', 'intercept_','classes_' you could do the predictions yourself, since logistic regression is a straight-forward linear model, it's simply matrix-multiplication.
has comment: http://stackoverflow.com/comment/86497355
downvote count: 0
type: Answer

http://stackoverflow.com/q/48180685
linked to: http://stackoverflow.com/q/38454403
has comment: http://stackoverflow.com/comment/83341339
favorite count: 0
linked to: http://stackoverflow.com/q/29387137
has comment: http://stackoverflow.com/comment/83341320
type: AnsweredQuestion
upvote count: 9
tagged with: pandas
tagged with: python
has title: changing all dates to standard date time in dataframe
has body: I have a dataframe with date column where it looks like this. There are more than one date column such as end date, fiscal year date etc. Plan Start Date 8/16/2017 0:00 5/31/2017 0:00 5/31/2017 0:00 5/31/2017 0:00 5/31/2017 0:00 4/21/2016 0:00 2/25/2016 0:00 12/15/2016 0:00 12/15/2016 0:00 12/15/2016 0:00 42373 42373 42367 42367 42367 42367 42460 42460 42460 42460 42460 42759 42333 I am trying to write a function where it basically changes those integrers to appropriate date format and format this column as datetime[64]. this column format is current object type. I have written below function def change_date_df(df): format_dates_df = [col for col in df.columns if 'Date' in col]; for date in format_dates_df: df[date] = pd.to_datetime(df[date]).apply(lambda x: x.strftime('%d-%m-%y')if not pd.isnull(x) else ''); return df; Its giving back now a ValueError: mixed datetimes and integers in passed array Im guessing these numbers are not being converted to dates. but Im not sure how else i can adjust my code. Any idea? Adam
accepted answer: http://stackoverflow.com/a/48180826
tagged with: date
has comment: http://stackoverflow.com/comment/118640604
has answer: http://stackoverflow.com/a/48180826
has comment: http://stackoverflow.com/comment/83341381
type: Question
has comment: http://stackoverflow.com/comment/83341350
score: 9
has comment: http://stackoverflow.com/comment/83341513
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48284884
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51086351
tagged with: python
has answer: http://stackoverflow.com/a/49252290
linked to: http://stackoverflow.com/q/48595240
has body: I am working on building an object detection model which I would like to create with 22 new classes (most of them are not in COCO or PETS datasets) What I've already done is: Prepared images with multiple labels using LabelIMG. Decrease image size in 2 for images that are bigger than 500k Convert XML to CSV file Convert CSV and images to TFRecord Using the Tensorflow sample config files I've trained with several pretrained checkpoints. Results: SSD_Mobilenet and SSD_Inception resulted in no classes found(loss ~10.0) while faster RCNN Inception did succeed to detect some of the objects(loss ~0.7). My questions are: What is the difference between train.py from Object detection, which I used in the above, to retrain.py from image_retraining to train_image_classifier.py from Slim? Which is better for my task? Or should I do it in a different way? While running the train.py on FRCNN inception I found that the loss was around 0.7 and not going lower even after 100k steps. Is there any goal in terms of loss to achieve? How do you suggest to change the config file to improve this? I found other models for instance Inception V4 etc... which doesn't have sample config files - TF slim. Should I try them and if so how can I use them? I am pretty new in this field and I need some support in understanding the terms and actions. BTW: I am using GTX 1060 (GPU) for training but eval is not working in parallel so I can't get the mAP for validation. I tried to force eval for CPU but with no success. Thanks.
tagged with: object
has answer: http://stackoverflow.com/a/49190349
score: 0
has comment: http://stackoverflow.com/comment/83594215
answer count: 3
tagged with: object-detection
has title: Improve accuracy with Tensorflow Object detection pretrained model
tagged with: tensorflow
type: Question
tagged with: detection

http://stackoverflow.com/comment/83363240
has text: @SergeyA do you mean the content? Starts with: ???x__TEXT??__text__TEXT?XS??__stubs__TEXT?c???__stub_helper__TEXTth?th?__gcc_except_tab__TEXT<l<l__cstring__TEXT?ti?t__const__TEXT`z?`z__unwind_info__TEXT
comment on: http://stackoverflow.com/q/48191350
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48255941
tagged with: flask
linked to: http://stackoverflow.com/q/31945329
score: 2
upvote count: 2
has title: How can I clear values from WTF form upon submission?
duplicate of: http://stackoverflow.com/q/31945329
downvote count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83495324
has body: I have two questions with respect of flask and wtforms: Where are the values entered in the form stored after submission? How can i clear those values upon submission? Currently, my form successfully submits the input values, but they are retained somewhere. So, when I submit the form and then I reload the page, the values are submitted a second time. Below are the relevant snippets of the python code. It is still WIP, so you will see a bunch of illogical things. from wtforms import Form from wtforms import StringField, PasswordField, BooleanField, SelectField, DecimalField, SubmitField from wtforms import validators class WeightForm(Form): num = DecimalField(u'Weight (lb):', [validators.number_range()]) note = StringField(u'Notes:') submit = SubmitField(u'Submit') def actvityLogQuery(): query = """ INSERT INTO public.activity_log (user_id, activity_type_id, effective_date, numerical, notes) VALUES (%s,%s,%s,%s,%s);""" return query @app.route('/activitylog/', methods=['GET', 'POST']) def actvityLogPage(): cur, conn = connection() weightForm = WeightForm(request.form) if request.method == "POST" and weightForm.validate(): num = weightForm.num.data note = weightForm.note.data unow = datetime.utcnow() Q = actvityLogQuery() cur.execute(Q, (13, 1, unow, num, note)) conn.commit() flash("Activity entered successfully") cur.close() conn.close() gc.collect() return render_template('activityLog.html', weightForm=weightForm) The relevant snippet of the HTML file: Log Weight: {% from "_formhelpers.html" import render_field %} {{render_field(weightForm.num)}} {{render_field(weightForm.note)}} {% if error %} Error:{{error}} {% endif %} Thanks!
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: wtforms
tagged with: python
tagged with: psycopg2

http://stackoverflow.com/a/48429593
type: Answer
has body: I'd use Dijkstra's algorithm for this. It finds the shortest distance between a source node and every other node by exploring nearer nodes before farther nodes. Seed a Dijkstra search at each of your P-nodes and halt the search when you either find the first F-node or exceed your distance constraint. Since you don't have a graph, per se, you can generate neighbours using offsets. For instance if you have a cell (x,y) you can define some offsets dx = [-1,-1, 0, 1,1,1,0,-1] dy = [ 0,-1,-1,-1,0,1,1, 1] and then take (x+dx[i], y+dy[i]) for i∈[0,7] to generate the neighbours of a given cell. You can define a separate 2D array/matrix for tracking whether cells have been visited.
score: 0
answers question: http://stackoverflow.com/q/48324806

http://stackoverflow.com/q/48230706
has answer: http://stackoverflow.com/a/72338681
possible better answer: http://stackoverflow.com/a/50280414
downvote count: 0
answer count: 7
accepted answer: http://stackoverflow.com/a/50280264
has answer: http://stackoverflow.com/a/57779688
has title: How to remove password for Jupyter Notebooks and set token again
tagged with: jupyter
has answer: http://stackoverflow.com/a/78508352
tagged with: ipython
has answer: http://stackoverflow.com/a/57822773
upvote count: 25
tagged with: jupyter-notebook
favorite count: 0
type: Question
tagged with: pycharm
has answer: http://stackoverflow.com/a/50280414
has answer: http://stackoverflow.com/a/50280264
tagged with: python
has body: I need to do this for Pycharm. Here are the steps that I did which I'm not able to undo. I added a password for authentication using: $ jupyter notebook password I then used the below command to comment all the code in jupyter_notebook_config.py $ jupyter notebook --generate-config Then I removed the hashed password generated in the jupyter_notebook_config.json which now looks like this { "NotebookApp": { "password": "" } } I then did the following changes in jupyter_notebook_config.py file c.NotebookApp.password = '' c.NotebookApp.token = '&lt; generated>' Now, There is no token getting generated and there is no password as well when I start the Jupyter notebook. Pycharm git:(master) ✗ jupyter notebook [I 21:53:35.158 NotebookApp] Serving notebooks from local directory: /Users/... [I 21:53:35.158 NotebookApp] 0 active kernels [I 21:53:35.158 NotebookApp] The Jupyter Notebook is running at: [I 21:53:35.158 NotebookApp] http://localhost:8888/?token=%3Cgenerated%3E Copy/paste this URL into your browser when you connect for the first time, to login with a token: http://localhost:8888/?token=%3Cgenerated%3E Now, how do I make it like the way it was or how do I get the token back?? PS - I even tried jupyter notebook list, but still the same URL is coming. Also, I'm doing this on a mac, so please advise accordingly.
score: 25
has answer: http://stackoverflow.com/a/49099457
type: AnsweredQuestion

http://stackoverflow.com/q/48231792
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83445840
upvote count: 1
tagged with: psychopy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48231921
has body: I'm doing an experimentation where the participant needs to pressed the keyboard. I would like to know if the participant : 1) pressed the good key 2) wrong key 3) no response I have this line of code : if key_resp_4.keys == response: thisExp.addData('correct', 1) elif key_resp_4.keys == 'None': thisExp.addData('correct', -1) else: thisExp.addData('correct', 0) I tried to change 'None' for '', None, but I always get a 0 in my correct column even if I did not pressed any key. Thanks
has comment: http://stackoverflow.com/comment/83445880
has title: Psychopy no response keyboard
tagged with: python
type: UnansweredQuestion

gabor-filter
type: Tag
tags question: http://stackoverflow.com/q/48322461
tag name: gabor-filter

http://stackoverflow.com/q/48252470
tagged with: python
has body: I am working on replicating a tkinter interface in flask. I have pandas dataframes that are displayed on the page using "to_html()". I used [this tutorial][1]. But I need to create buttons to download the dataframes. The functions that create, and download, the dataframes are in a custom module in its own directory "/testmodule". The functions for downloading the dataframes are separate from the function that creates and displays the dataframes. Here is the example code for testmodule.py: import pandas as pd from Flask import render_template def df_test(): df1 = pd.DataFrame( { 'terms' : ['term1','term2'], 'code1': ['1234x', '4321y'], 'code2': ['2345x','5432y'], 'code3': ['3456x','6543y'] } ) df2 = pd.DataFrame( { 'name': ['Dan','Sara','Conroy'], 'rate': ['3','3.5','5.2'], 'location': ['FL','OH','NM'], 'code': ['4444g','6543y','2345x'] }) return render_template('view.html',tables=[df1.to_html(classes='female'), df2.to_html(classes='male')], titles = ['na', 'Codes', 'People']) def download_df(): output_file = 'codes_people.xlsx' writer = pd.ExcelWriter(output_file, engine='xlsxwriter') df1.to_excel(writer, sheet_name="Codes") df2.to_excel(writer, sheet_name="People") workbook = writer.book worksheet1 = writer.sheets['Codes'] worksheet2 = writer.sheets['People'] writer.save() I have tried writing a route for the download, but get errors that dataframe values aren't defined, which I understand, because I'm importing a function call for download_df separately from the function that created the dfs. I just don't know how to pass the values of df1 and df2 from the first function into the second function once it is in routes.py I am going to have buttons that will allow for downloads of new dfs made from columns of the existing 2. Can the buttons call the download function (download_df) from the template itself, or can this only be done by setting a function in routes.py? If routes.py, how do I pass the df variables to routes? Or, do I need to create a temp file? [1]: http…
type: AnsweredQuestion
score: 0
tagged with: python-routes
answer count: 1
tagged with: flask
accepted answer: http://stackoverflow.com/a/48388962
type: Question
has answer: http://stackoverflow.com/a/48388962
has title: pandas/flask: buttons to download dataframes
tagged with: pandas
tagged with: dataframe

http://stackoverflow.com/comment/83514894
type: Comment
type: QuestionComment
has text: So you want to create 1000 or so empty files concurrently and then them to be deleted when done?
comment on: http://stackoverflow.com/q/48265736
score: 0

http://stackoverflow.com/comment/83481524
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48249459
has text: Yes, I am working on it now, will post it soon.
score: 0

http://stackoverflow.com/comment/83547979
has text: @Ta946 I've added a new Cython solution.
type: AnswerComment
comment on: http://stackoverflow.com/a/48277234
score: 1
type: Comment

pandas
tags question: http://stackoverflow.com/q/48197803
tags question: http://stackoverflow.com/q/48318356
tags question: http://stackoverflow.com/q/48235420
tags question: http://stackoverflow.com/q/48281285
tags question: http://stackoverflow.com/q/48247016
tags question: http://stackoverflow.com/q/48209065
tags question: http://stackoverflow.com/q/48302066
tags question: http://stackoverflow.com/q/48208180
tags question: http://stackoverflow.com/q/48291400
tags question: http://stackoverflow.com/q/48176462
tags question: http://stackoverflow.com/q/48195207
tags question: http://stackoverflow.com/q/48270074
tags question: http://stackoverflow.com/q/48301809
tags question: http://stackoverflow.com/q/48308743
tags question: http://stackoverflow.com/q/48262123
tags question: http://stackoverflow.com/q/48209383
tags question: http://stackoverflow.com/q/48187664
tags question: http://stackoverflow.com/q/48192903
tags question: http://stackoverflow.com/q/48324715
tags question: http://stackoverflow.com/q/48273971
tags question: http://stackoverflow.com/q/48305527
tags question: http://stackoverflow.com/q/48197234
tags question: http://stackoverflow.com/q/48277351
tags question: http://stackoverflow.com/q/48224916
tags question: http://stackoverflow.com/q/48318578
tags question: http://stackoverflow.com/q/48281836
tags question: http://stackoverflow.com/q/48175172
tags question: http://stackoverflow.com/q/48209914
tags question: http://stackoverflow.com/q/48211424
tags question: http://stackoverflow.com/q/48192168
tags question: http://stackoverflow.com/q/48174398
tags question: http://stackoverflow.com/q/48248821
tags question: http://stackoverflow.com/q/48294729
tags question: http://stackoverflow.com/q/48265455
tags question: http://stackoverflow.com/q/48290863
tags question: http://stackoverflow.com/q/48312541
tags question: http://stackoverflow.com/q/48222810
tags question: http://stackoverflow.com/q/48197747
tags question: http://stackoverflow.com/q/48298991
tags question: http://stackoverflow.com/q/48287296
tags question: http://stackoverflow.com/q/48200837
tags question: http://stackoverflow.com/q/48175334
tags question: http://stackoverflow.com/q/48196707
tags question: http://stackoverflow.com/q/48312954
tags question: http://stackoverflow.com/q/48313420
tags question: http://stackoverflow.com/q/48314588
tags question: http://stackoverflow.com/q/48326627
tags question: http://stackoverflow.com/q/48188716
tags question: http://stackoverflow.com/q/48218665
tags question: http://stackoverflow.com/q/48186624
tags question: http://stackoverflow.com/q/48330147
tags question: http://stackoverflow.com/q/48175666
tags question: http://stackoverflow.com/q/48266653
tags question: http://stackoverflow.com/q/48254563
tags question: http://stackoverflow.com/q/48304927
tags question: http://stackoverflow.com/q/48304580
tags question: http://stackoverflow.com/q/48272318
tags question: http://stackoverflow.com/q/48211798
tags question: http://stackoverflow.com/q/48222566
tags question: http://stackoverflow.com/q/48254575
tags question: http://stackoverflow.com/q/48305570
tags question: http://stackoverflow.com/q/48198021
tags question: http://stackoverflow.com/q/48177174
tags question: http://stackoverflow.com/q/48276456
tags question: http://stackoverflow.com/q/48307535
tags question: http://stackoverflow.com/q/48271643
tags question: http://stackoverflow.com/q/48307663
tags question: http://stackoverflow.com/q/48272816
tags question: http://stackoverflow.com/q/48236866
tags question: http://stackoverflow.com/q/48257144
tags question: http://stackoverflow.com/q/48317102
tags question: http://stackoverflow.com/q/48217392
tags question: http://stackoverflow.com/q/48180087
tags question: http://stackoverflow.com/q/48314971
tags question: http://stackoverflow.com/q/48233812
tags question: http://stackoverflow.com/q/48196510
tags question: http://stackoverflow.com/q/48270609
tags question: http://stackoverflow.com/q/48254732
tags question: http://stackoverflow.com/q/48179687
tags question: http://stackoverflow.com/q/48255079

http://stackoverflow.com/q/48193118
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48193327
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/83366762
has body: Trying to figure out regex which detects URLs in text except those surrounded by ... already and surround them by tags. input: "http://google.sk this is an url" result: "http://google.sk this is an url" input: "http://google.sk this is an url" result: "http://google.sk this is an url" This answer has helped me a lot but it does not expect already surrounded URLs. def fix_urls(text): pat_url = re.compile( r''' (?x)( # verbose identify URLs within text (https|http|ftp|gopher) # make sure we find a resource type :// # ...needs to be followed by colon-slash-slash (\w+[:.]?){2,} # at least two domain groups, e.g. (gnosis.)(cx) (/?| # could be just the domain name (maybe w/ slash) [^ \n\r"]+ # or stuff then space, newline, tab, quote [\w/]) # resource name ends in alphanumeric or slash (?=[\s\.,>)'"\]]) # assert: followed by white or clause ending ) # end of match group ''') for url in re.findall(pat_url, text): text = text.replace(url[0], '%(url)s' % {"url" : url[0]}) return text If there is any tag inside text, this function wraps it's URLs again which I don't want. Do you know how to make it work?
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83366873
has title: Python - find all URLs not surrounded by a tags already
has comment: http://stackoverflow.com/comment/83366756
type: Question
linked to: http://stackoverflow.com/q/1071191

http://stackoverflow.com/comment/83503361
has text: I know, still thanks... just tried to convey a conceptual understanding
type: Comment
comment on: http://stackoverflow.com/a/48260209
type: AnswerComment
score: 0

http://stackoverflow.com/a/48193279
has comment: http://stackoverflow.com/comment/83368770
has comment: http://stackoverflow.com/comment/83375667
has comment: http://stackoverflow.com/comment/83367948
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83375770
answers question: http://stackoverflow.com/q/48193148
score: 1
type: Answer
has body: You only have two capturing groups in your regex: (?: # non-capturing group ( # group 1 [0-1]?[0-9]{0,2}|2?[0-4]?[0-9]|25[0-5]? )\. ){3} ( # group 2 [0-1]?[0-9]{0,2}|2?[0-4]?[0-9]|25[0-5]? ) That the first group can be repeated 3 times doesn't make it capture 3 times. The regex engine will only ever return 2 groups, and the last match in a given group will fill that group. If you want to capture each of the parts of an IP address into separate groups, you'll have to explicitly define groups for each: pattern = ( r'([0-1]?[0-9]{0,2}|2?[0-4]?[0-9]|25[0-5]?)\.' r'([0-1]?[0-9]{0,2}|2?[0-4]?[0-9]|25[0-5]?)\.' r'([0-1]?[0-9]{0,2}|2?[0-4]?[0-9]|25[0-5]?)\.' r'([0-1]?[0-9]{0,2}|2?[0-4]?[0-9]|25[0-5]?)') def fun(st, p=re.compile(pattern)): return p.findall(st) You could avoid that much repetition with a little string and list manipulation: octet = r'([0-1]?[0-9]{0,2}|2?[0-4]?[0-9]|25[0-5]?)' pattern = r'\.'.join([octet] * 4) Next, the pattern will just as happily match the 25 portion of 255. Better to put matching of the 200-255 range at the start over matching smaller numbers: octet = r'(2(?:5[0-5]|[0-4]\d)|[01]?[0-9]{1,2})' pattern = r'\.'.join([octet] * 4) This still allows leading 0 digits, by the way, but is If all you are doing is passing in single IP addresses, then re.findall() is overkill, just use p.match() (matching only at the string start) or p.search(), and return the .groups() result if there is a match;) def fun(st, p=re.compile(pattern + '$')): match = p.match(st) return match and match.groups() Note that no validation is done on the surrounding data, so if you are trying to extract IP addresses from a larger body of text you can't use re.match(), and can't add the $ anchor and the match could be from a larger number of octets (e.g. 22.22.22.22.22.22). You'd have to add some look-around operators for that: # only match an IP address if there is no indication that it is part of a larger # set of octets; no leading or trailing dot or digits pattern = r'(?&lt;!…
has comment: http://stackoverflow.com/comment/83367884

http://stackoverflow.com/q/48260568
score: 0
has body: I am trying to use TensorFlow to build an artificial neural network which can identify features in a CAD model. Using the CAD model data I have computed the adjacency between certain faces and plotted it on a graph where each node is a face, each edge between faces represents adjacency and weights of 0 and 1 represent a convex and concave relationship respectively. Below is the code which draws the adjacency graph: import networkx as nx import matplotlib.pyplot as plt %matplotlib inline G=nx.Graph() #adding nodes G.add_nodes_from(range(1, 10)) #adding edges G.add_weighted_edges_from([(1, 2, 0), (1, 3, 0), (1, 6, 1), (1, 8, 1), (2, 5, 1), (2, 6, 1), (2, 8, 1), (3, 4, 1),(3, 6, 1), (3, 8, 1), (4, 6, 1), (4, 7, 1), (4, 8, 1), (5, 6, 1), (5, 8, 1), (5, 9, 1), (6, 7, 1), (6, 9, 1), (6, 10, 1), (7, 8, 1), (7, 10, 1), (8, 9, 1), (8, 10, 1), (9, 10, 1)]) #draw AAG nx.draw_circular(G, node_color = 'bisque', with_labels=True) My question is: is it possible to feed the adjacency graphs into a neural network in TensorFlow, teaching it which faces make up the 'features' present in the model? Any help on the subject would be appreciated
answer count: 1
tagged with: tensorflow
has title: TensorFlow - Using networkx graph as input
type: Question
tagged with: graph-theory
type: UnansweredQuestion
tagged with: machine-learning
has answer: http://stackoverflow.com/a/48365352
tagged with: python
tagged with: networkx

http://stackoverflow.com/a/48309387
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48270953
has body: While probably not the best solution, this worked for me and brought run time down to a total of 4.8 s vs the previous 52s. I ended up grouping in pandas, then running the correlation using numpy. groups = df.groupby(['course_id', 'activity_id']) np_arr = [] for (cor_id,act_id), group in groups: np_arr.append([cor_id, act_id, np.corrcoef(group.A.as_matrix(), group.perform.as_matrix())[0,1], np.corrcoef(group.B.as_matrix(), group.perform.as_matrix())[0,1], np.corrcoef(group.C.as_matrix(), group.perform.as_matrix())[0,1], np.corrcoef(group.D.as_matrix(), group.perform.as_matrix())[0,1]]) df = pd.DataFrame(data=np.array(np_arr), columns=['course_id', 'activity_id', 'A', 'B', 'C', 'D']) This was effective at reducing my runtime, and I am going to type my variables using cython to further increase speed.
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48270953

http://stackoverflow.com/a/48302083
has body: I believe you need first escape values and then join by | and as @cᴏʟᴅsᴘᴇᴇᴅ pointed remove \ from values in BAD_CHARS: import re BAD_CHARS = ['.', '&amp;', '(', ')', ';', '-'] pat = '|'.join(['({})'.format(re.escape(c)) for c in BAD_CHARS]) df = df[~df['words'].str.contains(pat)] print (df) words frequency 1 CONDUCTED 3 3 EXPERIMENT 6 8 3D 5 9 ABLE 5 10 ABSTRACT 3 11 ACCOMPANIED 5 12 ACTIVITY 11 13 AD 5 14 ADULTS 6 because this return empty frame: df[~df['word'].str.contains('|'.join(BAD_CHARS))]
type: Answer
accepted answer of: http://stackoverflow.com/q/48302066
has comment: http://stackoverflow.com/comment/83589648
downvote count: 0
has comment: http://stackoverflow.com/comment/83588775
answers question: http://stackoverflow.com/q/48302066
has comment: http://stackoverflow.com/comment/83589224
score: 5
has comment: http://stackoverflow.com/comment/83589135
type: AcceptedAnswer
upvote count: 5

http://stackoverflow.com/comment/83440057
has text: Oh and yes, you don't need to have a module per class either...
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48228804

http://stackoverflow.com/q/48288773
has body: i am trying to learn how to deal with files through python3 so i reached this problem, where i couldn't know which part of my code is not working! i am trying to print the contents of the same file twice using different ways, i believe that i have done multiple mistakes here, file = open("exp.py", "w") file.write("this has been written to a file")#it wil print(file.read()) file.close() print('first sanad') with open("exp.py") as f: print(f.read()) #it will be closed automatically print('second sanad') # f is a temp variable within the block Error 36-32\writing to a file with w.py", line 3, in &lt;module&gt; print(file.read()) io.UnsupportedOperation: not readable
has comment: http://stackoverflow.com/comment/83562478
favorite count: 0
type: AnsweredQuestion
has title: opening files using with statemnt instead of assigning the open to a variable
has comment: http://stackoverflow.com/comment/83562533
answer count: 1
has comment: http://stackoverflow.com/comment/83566840
tagged with: python
type: Question
tagged with: python-3.x
downvote count: 4
has comment: http://stackoverflow.com/comment/83566627
has comment: http://stackoverflow.com/comment/83562458
upvote count: 0
has answer: http://stackoverflow.com/a/48289426
score: -4
accepted answer: http://stackoverflow.com/a/48289426
has comment: http://stackoverflow.com/comment/83565942

http://stackoverflow.com/a/48184283
has body: Please check whether this works - import collections dicti_1 = {'2017-09-01': ['PRUEBAPRUEBA', 'PRUEBA123123'], '2017-11-08': ['PRUEBAPRUEBA', 'PRUEBA123123'], '2017-10-03': ['PRUEBAPRUEBA', 'PRUEBA123123'], '2017-12-03': ['PRUEBA123123']} dicti_2 = collections.OrderedDict(sorted(dicti_1.items())) print(dicti_2) my_dict2 = { z:x for x,y in dicti_2.items() for z in y } print(my_dict2) output = {} for key, value in my_dict2.items(): if value in output: output[value].append(key) else: output[value] = [key] print(output)
answers question: http://stackoverflow.com/q/48183810
type: Answer
score: 0

http://stackoverflow.com/q/48176665
has comment: http://stackoverflow.com/comment/83333740
has comment: http://stackoverflow.com/comment/83334225
has body: I am experiencing error with beautiful soup module. I was selecting some data on a website, and I can get data with tags, no issues there, but whenever I try it it fails, it treats variable like a list, although as I understood from bs4 it should not. Here is the code: novsajt = requests.get(prpage, headers={'User-Agent': 'Mozilla/5.0'}) novasupa = soup(novsajt.text, "html.parser") nesto = novasupa.find_all('p', class_='name product-title') for b_tag in nesto: for a_tag in b_tag: product_linkovi = a_tag['href'] source11 = requests.get(product_linkovi, headers={'User-Agent': 'Mozilla5.0'}) soup11 = soup(str(source11), "html.parser") productName = soup11.select("main#main h1").get_text() listaproizvoda.append("productName" + str(productName)+ ";") synonims = soup11.select("main#main div.product-short-description &gt; table &gt; tbody &gt; tr:nth-of-type(1) &gt; td:nth-of-type(2)").get_text() listaproizvoda.append("synonims" + str(synonims)+ ";") Application = soup11.select("main#main div.product-short-description &gt; table &gt; tbody &gt; tr:nth-of-type(2) &gt; td:nth-of-type(2)").get_text() listaproizvoda.append("Application" + str(Application)+ ";") So, how do you recommend extraction of text without tags? What type of mistake I am making?
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/83334049
has comment: http://stackoverflow.com/comment/83334121
tagged with: beautifulsoup
type: Question
has title: Eror in a code with beautiful soup, .gettext method
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83336349
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/83336319
answer count: 0
has comment: http://stackoverflow.com/comment/83333965

opengl
tags question: http://stackoverflow.com/q/48306896
type: Tag
tag name: opengl
tags question: http://stackoverflow.com/q/48187981

http://stackoverflow.com/a/48638741
has comment: http://stackoverflow.com/comment/122050979
has body: Documentation for Transcribe API is available here https://docs.aws.amazon.com/transcribe/latest/dg/what-is-transcribe.html
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48317680
score: -6
upvote count: 0
accepted answer of: http://stackoverflow.com/q/48317680
type: Answer
downvote count: 6

http://stackoverflow.com/a/48326089
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48325912
has body: Here you go, just use the following syntax to get a new column in the dataframe. No need to write code to loop over the rows. However, if you must loop, df.iterrows() returns or df.itertuples() provide nice functionality to accomplish similar objectives. &gt;&gt;&gt; df = pd.read_clipboard(sep='\t') &gt;&gt;&gt; df.head() country capital 0 India New Delhi 1 Indonesia Jakarta 2 Islamic Republic of Iran Tehran 3 Iraq Baghdad 4 Ireland Dublin &gt;&gt;&gt; df.columns Index(['country', 'capital'], dtype='object') &gt;&gt;&gt; df['both'] = df['country'] + " " + df['capital'] &gt;&gt;&gt; df.head() country capital both 0 India New Delhi India New Delhi 1 Indonesia Jakarta Indonesia Jakarta 2 Islamic Republic of Iran Tehran Islamic Republic of Iran Tehran 3 Iraq Baghdad Iraq Baghdad 4 Ireland Dublin Ireland Dublin
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/83638616

http://stackoverflow.com/a/48300623
has comment: http://stackoverflow.com/comment/83586714
accepted answer of: http://stackoverflow.com/q/48300379
has comment: http://stackoverflow.com/comment/83585841
has comment: http://stackoverflow.com/comment/83586647
answers question: http://stackoverflow.com/q/48300379
type: Answer
has comment: http://stackoverflow.com/comment/83586245
has body: Write global users inside the function to change values in the users variable. Otherwise you can only read it but not change the value inside it. lis = [] def a(): lis = [1,2] a() print(lis) will print [] where as : lis = [] def a(): global lis lis = [1,2] a() print(lis) will print [1,2] With reference to your program as per my understanding.. this might help.. username = '' user = [] def register(): global username global users username = input("Enter a username: ").lower() firstName = input("Enter your first name: ").lower() surname = input("Enter your surname: ").lower() age = input("Enter your age: ") yearGroup = input("Enter your year group: ") users =firstName, surname, age, yearGroup def resultsFunction(): score = 5 results = score, username results.extend(users) print(results) register() resultsFunction() will output :- Enter a username: Foo Enter your first name: Bar Enter your surname: Baz Enter your age: 00 Enter your year group: 00 [[5, 'foo'], ['bar', 'baz', '00', '00']]
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/83634448
has text: Aha! Great find - thanks. You can post this as an answer and I'll accept.
score: 0
comment on: http://stackoverflow.com/q/48211632
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48287812
tagged with: parallel-processing
score: 0
answer count: 1
tagged with: image-processing
tagged with: multiprocessing
type: Question
has answer: http://stackoverflow.com/a/48288090
type: UnansweredQuestion
has title: Python PIL paralellism(parallel map)
has body: I want to open an image with PIL and map every pixel to a new color(trough a more complicated function that in essence takes rgb values as a tuple an returns a new tuple of rgb values), let's say I want every pixel mapped to a random RGB color(the argument is there only to make it compatible with map): import random def rand_rgb(*_) -&gt; tuple: return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255) What I would like to do is to use some for of(preferably) high level parallelism such as multiprocessing: import multiprocessing def row_rand_rgb(pixelrow: list) -&gt; list: return list(map(rand_rgb, pixelrow) with PIL.Image.open(imgname) as im: width, height = im.size pixelaccess = im.load() pixelaccess = multiprocessing.Pool().map(row_rand_rgb, pixelaccess) im.save() If pixelaccess was a "normal" Python matrix, meaning a list of lists, then something of this sort would have worked, and each row of pixels in the image would have been processed separately, however this does not exactly work since from what I could see, a pixel access object is not a list of lists. How should I go about parallelizing this?
tagged with: python
tagged with: image
linked to: http://stackoverflow.com/q/6915106

http://stackoverflow.com/comment/83417127
comment on: http://stackoverflow.com/q/48217471
has text: @viraptor if `n != m` the answer is `False` straight away...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83541444
type: QuestionComment
has text: You're not returning the result of the recursive call. Also your indentation is way off.
comment on: http://stackoverflow.com/q/48279003
type: Comment
score: 6

http://stackoverflow.com/q/48264676
has answer: http://stackoverflow.com/a/50063464
tagged with: machine-learning
tagged with: resnet
has title: TensorFlow ValueError: The channel dimension of the inputs should be defined. Found `None`
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48618066
has body: I am trying to implement a "Dilated Residual Network" as described in this Paper in TensorFlow (s. PyTorch Implementation here) to train it on the CityScapes Dataset and use it for Semantic Image Segmentation. Unfortunately I get an error when trying to train and can't seem to find a fix. Since this type of network can be seen as an extension to ResNet, I used the official TensorFlow ResNet Model (Link) and modified the architecture by changing strides, adding dilation (as a parameter in the tf.layers.conv2d function) and removing residual connections. To train this network I wanted to use the same approach as in the TensorFlow ResNet Model: tf.estimator in combination with input_fn (can be found at the end of this post). Now when I want to train this network with the CityScapes Dataset I get following error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-19-263240bbee7e&gt; in &lt;module&gt;() ----&gt; 1 main() &lt;ipython-input-16-b57cd9b52bc7&gt; in main() 27 print('Starting a training cycle.') 28 drn_classifier.train( ---&gt; 29 input_fn=lambda: input_fn(True, _BATCH_SIZE, _EPOCHS_PER_EVAL),hooks=[logging_hook]) 30 31 print(2) ~\Anaconda3\envs\master-thesis\lib\site-packages\tensorflow\python\estimator\estimator.py in train(self, input_fn, hooks, steps, max_steps, saving_listeners) 300 301 saving_listeners = _check_listeners_type(saving_listeners) --&gt; 302 loss = self._train_model(input_fn, hooks, saving_listeners) 303 logging.info('Loss for final step: %s.', loss) 304 return self ~\Anaconda3\envs\master-thesis\lib\site-packages\tensorflow\python\estimator\estimator.py in _train_model(self, input_fn, hooks, saving_listeners) 709 with ops.control_dependencies([global_step_read_tensor]): 710 estimator_spec = self._call_model_fn( --&gt; 711 features, labels, model_fn_lib.ModeKeys.TRAIN, self.config) 712 # Check if the user created a loss summary, and add one if they didn't…
tagged with: python
score: 12
upvote count: 12
answer count: 2
tagged with: deep-learning
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48183066
has body: I wrote a basic program using pyserial to send and receive data. import serial ser = serial.Serial() ser.port='COM9' ser.open() ser.write(b'hello\n') data = ser.read() print data However the program is not printing any output and not terminating in the command prompt.
has comment: http://stackoverflow.com/comment/124890914
favorite count: 0
score: 2
has answer: http://stackoverflow.com/a/48183477
tagged with: serial-port
has answer: http://stackoverflow.com/a/48183392
type: Question
answer count: 2
tagged with: pyserial
upvote count: 3
type: UnansweredQuestion
has title: PySerial Send and Receive
tagged with: python
downvote count: 1

pong
tag name: pong
type: Tag
tags question: http://stackoverflow.com/q/48273725

http://stackoverflow.com/comment/126169808
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-answer).
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/71380813

http://stackoverflow.com/comment/83620015
type: Comment
comment on: http://stackoverflow.com/q/48317150
score: 0
has text: doh, if you input it like that, that's not newline character, that's 2 characters of \ and n. You pressed enter for newline character.
type: QuestionComment

http://stackoverflow.com/a/48221373
answers question: http://stackoverflow.com/q/48220819
score: 0
has body: This attempt is using datetime and pytz modules. First parse them as 'US/Pacific' and then simply convert them to UTC. Also, you need to unpack tuples(using *) and then provide them to datetime constructor. from datetime import datetime import pytz time_stamps = [(2017, 10, 22, 15, 19, 23), (2017, 10, 22, 15, 19, 35)] my_timezone = pytz.timezone('US/Pacific') for time_stamp in time_stamps: date = datetime(*time_stamp).replace(tzinfo=my_timezone) print (date.astimezone(pytz.utc))
has comment: http://stackoverflow.com/comment/83429766
type: Answer

http://stackoverflow.com/q/48302684
type: UnansweredQuestion
has title: How to memory map a part of a binary file?
has comment: http://stackoverflow.com/comment/83592080
has body: I am using mmap library and want to memory map a specific part of a binary file. From the mmap help I get that the mmap.mmap has the following fields: mmap(fileno, length, access=ACCESS_WRITE, offset) So I am trying to memory map the file from 10th byte till the end of the file. with open(fileName, "r+b") as f: mm = mmap.mmap(f.fileno(), length=0, offset=16) but when I try to do this I get the following error: OSError: [WinError 1132] The base address or the file offset specified does not have the proper alignment Have anyone done something like that before and/or have any ideas what I am doing wrong here? Most probably it is the way I am using the offset.
tagged with: binaryfiles
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83590397
has comment: http://stackoverflow.com/comment/83590495
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/83590337
has comment: http://stackoverflow.com/comment/83590015
tagged with: mmap
has comment: http://stackoverflow.com/comment/83594189
has comment: http://stackoverflow.com/comment/83591690
has comment: http://stackoverflow.com/comment/83591954
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/a/48176328
score: 2
has body: Ideally, you should probably avoid using threads altogether, as mentioned in the comments. However, if you are going to use threads, consider using a mutex to ensure that multiple threads are not trying to write to stdout at the same time. For example: # setup at the beginning: from threading import Thread, Lock mutex = Lock() # surrounding each print statement: mutex.acquire() try: print('text') finally: mutex.release()
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48176160
upvote count: 2
answers question: http://stackoverflow.com/q/48176160
has comment: http://stackoverflow.com/comment/83332919
type: Answer

http://stackoverflow.com/a/48203759
answers question: http://stackoverflow.com/q/48203600
has comment: http://stackoverflow.com/comment/83388677
type: Answer
has body: I'm not sure why you think there's a contradiction here. The RequestsCookieJar class implements the dictionary interface by subclassing collections.MutableMapping, so you can access items by key.
score: 0
has comment: http://stackoverflow.com/comment/83388941

http://stackoverflow.com/q/48255336
tagged with: python-3.x
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I'm trying to send a PM on a forum that I use, but it's not sending - no error code received. This is the HTML that I think is causing the issue : &lt;div style="margin-top:6px"&gt; &lt;input type="hidden" name="s" value=""&gt; &lt;input type="hidden" name="securitytoken" value="1515973553-20dc0500315dc868c0bad3384f0d0adb6b85fdd6"&gt; &lt;input type="hidden" name="do" value="insertpm"&gt; &lt;input type="hidden" name="pmid" value=""&gt; &lt;input type="hidden" name="forward" value=""&gt; &lt;input type="submit" class="button" name="sbutton" id="vB_Editor_001_save" value="Submit Message" accesskey="s" tabindex="1"&gt; &lt;input type="submit" class="button" value="Preview Message" accesskey="r" name="preview" tabindex="1"&gt; &lt;/div&gt; In any case, here's the page: http://forum.toribash.com/private.php?do=newpm But you'd need an account on the forum to access that page, by default. Here's my payload, using requests: msg_data = { 'title': "Discord registration request", 'message': "TEST", 'securitytoken': auth_final, 'do': "insertpm", } r = session_requests.post(url, data=msg_data) result = session_requests.get(url,headers = dict(referer = url)) tree_pm_send = html.fromstring(result.content) I'm 100% sure that security token variable I entered is correct, but nothing appears in my sent inbox after that.
has comment: http://stackoverflow.com/comment/83493476
score: 0
tagged with: vbulletin
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83493513
has title: Python - How to send private message form using requests? (vBulletin forum)

iterator
tags question: http://stackoverflow.com/q/48312081
tags question: http://stackoverflow.com/q/48234658
tag name: iterator
tags question: http://stackoverflow.com/q/48219116
tags question: http://stackoverflow.com/q/48218412
tags question: http://stackoverflow.com/q/48180209
tags question: http://stackoverflow.com/q/48254115
tags question: http://stackoverflow.com/q/48257280
type: Tag
tags question: http://stackoverflow.com/q/48302926

http://stackoverflow.com/comment/83409729
has text: @Mika copy/paste a subset of the data from your `.xlsx` file in a code block
comment on: http://stackoverflow.com/q/48211975
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48280629
has comment: http://stackoverflow.com/comment/83546405
has comment: http://stackoverflow.com/comment/83544929
linked to: http://stackoverflow.com/q/41699494
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83546522
has comment: http://stackoverflow.com/comment/83545394
tagged with: python
has title: Matplotlib: Why is plot_surface not opaque despite "alpha=1"?
has comment: http://stackoverflow.com/comment/83546304
has comment: http://stackoverflow.com/comment/83545156
answer count: 0
has comment: http://stackoverflow.com/comment/83545061
score: 0
tagged with: matplotlib
type: Question
has body: Running the code below (Python 3, matplotlib 2.0.2), I get the following output: I would prefer, and expect, the graph to cover some of the paths below it. What is going wrong? import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D paths = np.cumsum(np.random.normal(size=(10,10)),axis=0) ax=plt.figure().gca(projection='3d') ax.plot(np.tile(range(10),(10,1)).T,paths) N=30 Y = np.linspace(-5,5, N) X = np.linspace(0,10,N) XX, YY = np.meshgrid(X,Y) ZZ = YY**2 ax.plot_surface(XX, YY, ZZ, alpha=1) plt.show()

http://stackoverflow.com/comment/83605966
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48310058
type: Comment
has text: Can you add sample data to your question?

http://stackoverflow.com/comment/83467222
type: Comment
comment on: http://stackoverflow.com/q/48228722
score: 0
has text: Of tensorflow's cnn? here it is: https://www.tensorflow.org/tutorials/deep_cnn
type: QuestionComment

http://stackoverflow.com/a/48258054
has comment: http://stackoverflow.com/comment/83498696
score: 2
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48257994
downvote count: 1
answers question: http://stackoverflow.com/q/48257994
has comment: http://stackoverflow.com/comment/83499040
has comment: http://stackoverflow.com/comment/83498592
has comment: http://stackoverflow.com/comment/83514438
type: Answer
has body: I think curl and head would work better than a Python solution here: curl https://my.website.com/file.txt | head -c 512 &gt; header.txt EDIT: Also, if you absolutely must have it in a Python script, you can use subprocess to perform the curl piped to head command execution EDIT 2: For a fully Python solution: The urlopen function (urllib2.urlopen in Python 2, and urllib.request.urlopen in Python 3) returns a file-like stream that you can use the read function on, which allows you to specify a number of bytes. For example, urllib2.urlopen(my_url).read(512) will return the first 512 bytes of my_url

http://stackoverflow.com/comment/83393397
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48205670
has text: is readonly ok? Or do you actually want to allocate that much memory?
score: 0

http://stackoverflow.com/comment/83434281
type: QuestionComment
comment on: http://stackoverflow.com/q/48225786
score: 0
type: Comment
has text: Hello. Ok I will try. When user is in FilteredReclamationListView view he can make some filter. The parameters of filter is in url ex. http://127.0.0.1:8000/?id=1&group=1 but when user go to another view and go back to FilteredReclamationListView view the parameter like id=1&group=1 are not remember. I would like to remember this and when user go back to view he will go back to http://127.0.0.1:8000/?id=1&group=1 not http://127.0.0.1:8000

http://stackoverflow.com/q/48271576
answer count: 2
has answer: http://stackoverflow.com/a/48271667
downvote count: 0
accepted answer: http://stackoverflow.com/a/48271782
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/48271782
favorite count: 0
type: AnsweredQuestion
has body: I have a simple script here: from multiprocessing import Process def one(): x = 1 while x &lt; 100: x +=1 print(x) def two(): y = 100 while y &lt; 200: y += 1 print(y) if __name__=='__main__': p1 = Process(target = one) p1.start() p2 = Process(target = two) p2.start() It works correctly and prints out a list of numbers fine. I've been searching but so far have been unable to find any answer here. I'm wondering if its possible to print results in such def one and two return on the same line so I can compare the output. Something like: 1, 100 2, 101 3, 102 4, 103 ... ... 100, 200 Maybe I'm missing something obvious or its not even possible.
tagged with: python
tagged with: multiprocessing
type: Question
possible better answer: http://stackoverflow.com/a/48271667
has title: Python multiprocess output same line

http://stackoverflow.com/q/48293781
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/83573262
has title: How to use pandas.DataFrame.assign() to add new column based on a different dataframe
type: Question
tagged with: numpy
has body: I have two data frames. df1: filename|data fileA|1 fileB|33 fileC|343 df2: path|filesize|filetype /tmp/fileA.csv|123|csv /tmp/fileB.csv|123|csv /tmp/fileC.csv|3534|csv /tmp/fileD.csv|234|csv I want the result to be filename|data|path fileA|1|/tmp/fileA.csv fileB|33|/tmp/fileB.csv fileC|343|/tmp/fileC.csv fileD|3243|/tmp/fileD.csv This seems extremely simple but I can't seem to get it to work with .assign(). I need to match each row that is in df1.filename with what is in df2.filepath and then add df1['filepath'] to df1. I tried the following, but it complains that Series is not "hashable" df1.assign(path = lambda x: df2[df2.path.str.contains(x.filename + ".csv")][path]) {TypeError}'Series' objects are mutable, thus they cannot be hashed I tested to make sure my df1.assign() was correct by doing df1.assign(path = lambda x: x.filename) and it worked and just appended the filename on the df1 (which is what I would expect). I'm assuming that the problem area is the `contains(x.filename + ".csv") being a "Series". If I change it to x.filename.values I then get {TypeError}unhashable type: 'numpy.ndarray'. I don't understand what "x" is. I assume its a Series object, but no idea how to tell which "row" its associated with if it is. I could brute-force this and just loop over df1 but df1 is 2M+ records and loops seem to be generally frowned upon for performance reasons with pandas. Can someone point me into what I'm doing wrong?
has comment: http://stackoverflow.com/comment/83572665
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/13636848
tagged with: python
has comment: http://stackoverflow.com/comment/83572780
has answer: http://stackoverflow.com/a/48294299

http://stackoverflow.com/comment/83425779
comment on: http://stackoverflow.com/a/48181043
has text: Have you ever thought of the possibility that`display window:*` would be printed at the bottom?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48272798
has comment: http://stackoverflow.com/comment/83529620
tagged with: selenium
has body: i started playing with selenium, since i practiced bs4 a lot. So i imported selenium, added chrome driver, it opens everything properly - so far so good! problem came when i decided to pick some elemenit by css selector and i did it on this site like this: driver = webdriver.Chrome() driver.get("https://shop.foretagsakvarium.se/product/aquamedic-xenia-100") x = driver.find_element_by_css_selector("main#main-content span.amount") and instead of element output i got this: &lt;selenium.webdriver.remote.webelement.WebElement (session="8b7719f12f537bf845f6e82e58d391d3", element="0.27049897880791063-1")&gt; &gt;&gt;&gt; [10348:7764:0116/020724.433:ERROR:process_metrics.cc(105)] NOT IMPLEMENTED [10348:7764:0116/020724.434:ERROR:process_metrics.cc(105)] NOT IMPLEMENTED [10348:7764:0116/020724.434:ERROR:process_metrics.cc(105)] NOT IMPLEMENTED [10348:7764:0116/020724.434:ERROR:process_metrics.cc(105)] NOT IMPLEMENTED what and where i did wrong? have i frogot to import something? Everything that i imported is: &gt;&gt;&gt; import selenium &gt;&gt;&gt; from selenium import webdriver
has comment: http://stackoverflow.com/comment/83529608
has comment: http://stackoverflow.com/comment/83529873
has comment: http://stackoverflow.com/comment/83531213
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83529504
has answer: http://stackoverflow.com/a/48274396
has title: Started playing with selenium, somethings wrong with get by css method
tagged with: python
answer count: 1
tagged with: css
has comment: http://stackoverflow.com/comment/83530452
has comment: http://stackoverflow.com/comment/83529572
accepted answer: http://stackoverflow.com/a/48274396
type: Question
score: 0

http://stackoverflow.com/q/48274772
has comment: http://stackoverflow.com/comment/83543765
tagged with: scipy
has comment: http://stackoverflow.com/comment/83545724
type: Question
has body: I have a set of simple linear equations and am using sciprog to solve it. Objective function is to minimize x(i)*c. where : c is defined below(constants) i ranges from 1 to 28 I also have equality constraints(14 equations) based on which I could I need a solution. Infact the solution is very straightforward. Expected solution is mentioned in excel. But when I use linprog to solve this, it fails. Any reason to check for ? from scipy.optimize import linprog A_eq = [[1211.881188118812, 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, 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, 3599.9999999999995, 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, 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, 2006.5573770491803, 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, 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, 2185.714285714286, 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, 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, 2147.3684210526317, 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, 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, 290.04739336492895, 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, 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, 382.5, 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, 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, 181.87221396731056, 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, 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, 382.5, 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, 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, 291.4285714285714, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.…
tagged with: python
has comment: http://stackoverflow.com/comment/83545748
has answer: http://stackoverflow.com/a/48281448
accepted answer: http://stackoverflow.com/a/48281448
tagged with: optimization
has comment: http://stackoverflow.com/comment/83534003
type: AnsweredQuestion
score: 0
has title: Scipy Linprog - not giving expected solution
answer count: 1
tagged with: linear-programming

http://stackoverflow.com/q/48194461
accepted answer: http://stackoverflow.com/a/48195496
has answer: http://stackoverflow.com/a/48195496
type: Question
tagged with: python
has title: Expected behaviour of custom instance method sort
has body: In Python 2.7, list objects implement a sort method taking the three arguments cmp, key, and reverse, as described here (see note 8), the first two of which default to the value None, and the last defaulting to False. Suppose one is interested in implementing a class providing an instance method named sort with the same signature, i.e., taking the same arguments, as list.sort. For list.sort, the cmp and key arguments may induce different orders on the list to be sorted and may therefore be incompatible. My question is whether there is a best practice one should follow in implementing the instance method sort in the case where both cmp and key are different from None? For clarity, consider the following example scenario: class Table(object): """Stores data by rows.""" def __init__(self, *rows): self._rows = list(rows) def sort(self, cmp=None, key=None, reverse=False): """Sort table rows.""" if cmp and key: # What behaviour would an experienced Python programmer # expect in this situation? Raise a ValueError? Prefer # one of cmp and key? Or is there no best practice here? raise ValueError('I am partial to raising a ValueError.') # The implementation could be more involved than pushing the # call to sort forward to self._rows, for instance if data was # stored by columns. self._rows.sort(cmp, key, reverse) Note: The question raised here is not an issue in Python 3.6, where the argument cmp is not supported by list.sort (source).
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 1

http://stackoverflow.com/a/48234867
has comment: http://stackoverflow.com/comment/83452504
score: 1
answers question: http://stackoverflow.com/q/48234092
has body: I thought someone posted an answer here... df.applymap(lambda x: x.v) Basically, accessing the value for v in Cell. Edit: This was @JohnE's solution; not sure what the etiquette is here? It would have taken me a little while to get there.
type: Answer
has comment: http://stackoverflow.com/comment/83452374
accepted answer of: http://stackoverflow.com/q/48234092
has comment: http://stackoverflow.com/comment/83452378
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83387030
has text: Inside your function you are doing `np.dot(x, theta)` where `x` is an array of shape `(100, 1)` and `theta` is of shape `(2,)`. This will not work. Can you try to explain the math you are trying to do here?
comment on: http://stackoverflow.com/q/48202525
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83520561
comment on: http://stackoverflow.com/q/48242164
type: QuestionComment
score: 0
has text: @MaxAndMax I didn't create it myself, but it's plenty instructions all over internet. For example - https://stackoverflow.com/a/15330139/1113207
type: Comment

http://stackoverflow.com/a/48262677
has body: This is my approach (I am not sure about how numpy array elements are accessed) X1 = [5] # Since, X1[0] = 5 X2 = [] for i in range(len(delta_X)): X2.append(X1[i] + delta_X[i]) X1.append(X2[-1])
answers question: http://stackoverflow.com/q/48262526
score: 0
has comment: http://stackoverflow.com/comment/83508493
type: Answer
has comment: http://stackoverflow.com/comment/83511663

http://stackoverflow.com/q/48177725
has comment: http://stackoverflow.com/comment/83335648
has answer: http://stackoverflow.com/a/48177826
has answer: http://stackoverflow.com/a/48177798
type: Question
has comment: http://stackoverflow.com/comment/83335640
has body: I currently have a python program that uses regular expressions to make a list of all the email addresses in a document and put them each on their own line in a new document. Works like this: with open (self.originalEntry.get(), 'r') as doc: text = doc.read() match = re.findall(r'[\w\.-]+@[\w\.-]+', text) with open (self.namesEntry.get(), 'a') as pi: for i in match: i = str(i) pi.write(i+ '\n') I want to change it to make a list of every email address except those from a given domain (i.e. anyone@thiswebsite.com.) I've been looking everything I can find about RE operators on python's site and can't find a way to build in an exception to the re.findall operator. Is it possible to write an expression to find all email addresses minus ones from a certain domain this way, or should I do something else?
type: UnansweredQuestion
has title: Can I add an exception to re.findall()
tagged with: python
tagged with: regex
score: 0
answer count: 2

http://stackoverflow.com/a/48205079
type: Answer
answers question: http://stackoverflow.com/q/48204717
has body: nltk library has HMM model which does exactly what you are trying to do. see the following link for better understanding: https://gist.github.com/blumonkey/007955ec2f67119e0909
score: 0
has comment: http://stackoverflow.com/comment/83394052
has comment: http://stackoverflow.com/comment/83391580

http://stackoverflow.com/comment/83546938
score: 0
type: QuestionComment
has text: the data is tweets /twitter data /sentence but also has emoji in it.
type: Comment
comment on: http://stackoverflow.com/q/48281341

http://stackoverflow.com/q/48277722
tagged with: python
accepted answer: http://stackoverflow.com/a/48278030
type: AnsweredQuestion
has title: Django: best way to define a form to insert long texts?
answer count: 3
has comment: http://stackoverflow.com/comment/83539995
upvote count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/48277810
has comment: http://stackoverflow.com/comment/83538906
has answer: http://stackoverflow.com/a/48278916
has body: I am working with Django1.8 and Python 2.7.+ I want to define a form that has text field where the user can insert a text as long as he needs to. The first thing that I tried was defining a forms.TextField, but it turns out TextField only exists under models, not under forms. This is how I have defined it: selected_services = forms.CharField(label="Selected_services *", max_length=999999999, widget=forms.Textarea()) But the max_length=999999999, looks terrible. What would be a more elegant way of defining a form field to store very long texts?
tagged with: django-forms
has answer: http://stackoverflow.com/a/48277810
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/48278030
has comment: http://stackoverflow.com/comment/83541159
tagged with: django

http://stackoverflow.com/comment/83568872
comment on: http://stackoverflow.com/q/48291543
type: Comment
has text: @schwobaseggl no - the example I gave is what I wanted to give. Your example would also be a valid combination. But I showed ((3,9),(9,11),(21,18)) because I wanted to demonstrate that a valid combination does not need to connect.
score: 0
type: QuestionComment

http://stackoverflow.com/q/48195442
has answer: http://stackoverflow.com/a/48198650
type: Question
tagged with: opencv
tagged with: python
tagged with: object-detection
accepted answer: http://stackoverflow.com/a/48198650
type: AnsweredQuestion
has body: I have a collection of images featuring ships on or near the horizon in open ocean. I am trying to create an image that removes the ship(s) from the image while leaving most of the background intact. My initial attempt was to scan each row and column of the blurred image in black and white and replace the value in it with the median of the row if the value exceeds a certain threshold: colorImage= cv2.imread(path,1) # where path is the directory to my image gray = cv2.cvtColor(colorImage, cv2.COLOR_BGR2GRAY) gray= cv2.GaussianBlur(gray, (21,21), 0) bkgd= gray imageHeight, imageWidth= bkgd.shape for row in range(0, imageHeight): for column in range(0, imageWidth): if bkgd[row, column] &gt; 100: bkgd[row, column]= int(np.median(bkgd[row])) 100 is an arbitrary value that I chose that closely resembles the minimum value the sky would be in a blurred b/w image, thus leaving all the noise from the ocean intact (desired for comparing the original with the ship to the one without). This process slow and produces erratic results when there is noise from clouds in the sky. Is there a better method available in OpenCV or some other library to accomplish what I'm trying to produce?
score: 0
answer count: 1
has title: Editing out part of an image in python

http://stackoverflow.com/comment/84318552
type: AnswerComment
has text: @RasmusBidstrup It does not. Pass `search='^zipcode$'`, the regex pattern specifies full word matching. Or else, you can use `x.eq('zipcode')` in the lambda.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48254658

http://stackoverflow.com/comment/83568699
has text: I think you actually mean `if b1 > a1 and b1 < a2` according to the conditional in his question.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48291757
type: AnswerComment

http://stackoverflow.com/comment/83331378
comment on: http://stackoverflow.com/q/48175393
score: 0
type: Comment
has text: i don’t get it .. you’re calling a constructor in the `if` expression so that expression will always be true.. therefore all the `if` cases will execute each iteration of the `for`... anyway i’m not sure what the syntax is for establishing relationships is but you’re also only ever calling `relationship` on one node at a time?
type: QuestionComment

http://stackoverflow.com/comment/83526253
comment on: http://stackoverflow.com/a/48264544
score: 0
type: Comment
has text: Yes it is doable. I suggest to first write down your problem in mathematical notation. Once the mathematical model makes sense, then try to transcribe it into a form required by the solver.
type: AnswerComment

http://stackoverflow.com/q/48279878
has title: How to access python return value from bash script
tagged with: bash
has body: I'm trying to understand how to access from a bash script the return value of a python script. Clarifying through an example: foo.py def main(): print ("exec main..") return "execution ok" if __name__ == '__main__': main() start.sh script_output=$(python foo.py 2&gt;&amp;1) echo $script_output If I run the bash script, this prints the message "exec main..". How can I store in script_output the return value (execution ok)? If I direct execution ok to stdout, the script_output will capture all the stdout (so the 2 print statement). Is there any way to implement this? Thanks! Alessio
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/48280096
tagged with: shell
possible better answer: http://stackoverflow.com/a/48280063
has answer: http://stackoverflow.com/a/48280092
favorite count: 0
type: Question
tagged with: linux
score: 5
has comment: http://stackoverflow.com/comment/83543379
accepted answer: http://stackoverflow.com/a/48280096
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/48280063
type: AnsweredQuestion

http://stackoverflow.com/comment/83535563
type: Comment
score: 1
type: QuestionComment
has text: deleting while iteration. It's wrong
comment on: http://stackoverflow.com/q/48276015

http://stackoverflow.com/comment/83555136
has text: You can't shuffle an infinite generator (like `itertools.cycle`) but it seems like what you actually want to do is simply draw a random selection of filenames, which you can do with the `random` module
comment on: http://stackoverflow.com/q/48285315
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83461357
has text: Exactly. Thanks a lot :)
comment on: http://stackoverflow.com/a/48230029
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83482313
type: AnswerComment
has text: Yeah haha, quite strange I think it's url lib or json related. 99% of error 400 questions seem to be resolved that way at least. Hmmm....
type: Comment
comment on: http://stackoverflow.com/a/48245057
score: 0

http://stackoverflow.com/a/48215368
has body: Here you go: from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder import os Builder.load_string(""" &lt;MyWidget&gt;: id: my_widget input_text: input_text Button text: "open" on_release: my_widget.open(filechooser.path, filechooser.selection) TextInput: id: input_text text: '??????' FileChooserListView: id: filechooser on_selection: my_widget.selected(filechooser.selection) """) class MyWidget(BoxLayout): def open(self, path, filename): with open(os.path.join(path, filename[0])) as f: contents=f.read() self.input_text.text=contents def selected(self, filename): print ("selected: %s" % filename[0]) class MyApp(App): def build(self): return MyWidget() if __name__ == '__main__': MyApp().run() There were three errors. In the kivy code you need to add id of your text_input at the top level: import os Builder.load_string(""" &lt;MyWidget&gt;: id: my_widget input_text: input_text # NOTE THIS LINE TextInput: id: input_text text: '??????' """) You shouldn't use MyWidget.input_text.text=contents because MyWidget is a class name, not the instance you're working on. Use self.input_text.text=contents And finally after you callprint(f.read()) you cannot read from the file anymore unless you rewind it so next line contents=f.read() will result with empty contents variable. Also TextInput.text needs to be quoted but I assume you know that.
answers question: http://stackoverflow.com/q/48213987
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/83432439
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48213987
has comment: http://stackoverflow.com/comment/83431268

http://stackoverflow.com/a/48228160
downvote count: 0
has body: I do not know about a function, but it is easy to write yourself. import numpy as np np.all(np.less_equal(low, observation)) and np.all(np.greater_equal(observation, high)) This checks if all observations are inside the specified bounds. If you omit the np.all you can see which dimension was the problem.
type: Answer
answers question: http://stackoverflow.com/q/48227667
score: 2
upvote count: 2

http://stackoverflow.com/q/48244322
upvote count: 5
tagged with: python
type: Question
linked to: http://stackoverflow.com/q/5111040
score: 2
has title: listen() method parameters in python
type: UnansweredQuestion
tagged with: sockets
answer count: 1
downvote count: 3
has body: I'm new to Python and interested in socket programming these days. From the youtube videos, I'm building a simple server but I didn't get listen() method very well. I know "it listens" incoming connections but I didn't get the the idea of "maximum queued connections" in the document. Could you explain this concept in layman's terms so that I can understand better?
favorite count: 0
has answer: http://stackoverflow.com/a/48245691

http://stackoverflow.com/q/48316387
has comment: http://stackoverflow.com/comment/83619147
has answer: http://stackoverflow.com/a/48316676
type: AnsweredQuestion
score: 0
tagged with: pandas
has title: Plotting two date histograms with pandas
answer count: 1
type: Question
has body: I have two datetime series, which I'm trying to plot side by side with a shared X-axis. dates1 = ['2015-02-02', '2016-06-29', '2016-06-01', '2015-07-19', '2016-08-17', '2016-11-22', '2016-07-24', '2016-10-30', '2015-02-01', '2017-01-29', '2015-03-19', '2016-09-06', '2016-11-23', '2016-06-21', '2016-10-05', '2016-02-23', '2016-11-24', '2016-10-05', '2015-07-16', '2016-06-07', '2016-07-31', '2016-11-01', '2016-11-02', '2016-08-16', '2015-06-09', '2016-04-11', '2017-02-09', '2015-05-20', '2016-05-17', '2016-09-12', '2015-08-05', '2017-02-19'] dates2 = ['2016-03-22', '2016-03-16', '2015-07-02', '2016-09-13', '2014-09-04', '2016-07-12', '2016-05-08', '2016-02-18', '2014-07-10', '2016-05-10', '2016-05-02', '2016-11-20', '2015-05-19', '2016-01-06', '2016-06-21', '2015-03-25', '2016-06-09', '2016-12-07', '2016-10-18', '2016-03-27', '2017-03-19', '2016-10-27', '2017-01-12', '2015-12-31', '2016-05-05', '2016-07-17', '2016-07-10', '2017-06-14', '2015-12-27', '2016-03-01', '2016-05-04', '2017-05-15'] ser1 = pd.Series(dates1, dtype=np.datetime64) ser2 = pd.Series(dates2, dtype=np.datetime64) fig, axes = plt.subplots(1, 2, figsize=(20, 10), sharex=True) ser1.groupby([ser1.dt.year, ser1.dt.month]).count().plot(kind='bar', ax=axes[0]) ser2.groupby([ser2.dt.year, ser2.dt.month]).count().plot(kind='bar', ax=axes[1]) plt.show() As seen in the image, it appears that ser1 has (2014, 7) values, but its first actual value is 2015-02-01. For reference, the two plots with sharex=False: fig, axes = plt.subplots(1, 2, figsize=(20, 10), sharex=False) ser1.groupby([ser1.dt.year, ser1.dt.month]).count().plot(kind='bar', ax=axes[0]) ser2.groupby([ser2.dt.year, ser2.dt.month]).count().plot(kind='bar', ax=axes[1]) plt.show() Any simple way to solve this, without manually limiting the X-axis?
tagged with: python
accepted answer: http://stackoverflow.com/a/48316676

http://stackoverflow.com/a/48237811
has body: You need rename_axis with reset_index: df_count=df.Age.value_counts().rename_axis('Age').reset_index(name='Count') Altrnative solution with rename: d = {'index':'Age','Age':'Count'} df_count=df.Age.value_counts().reset_index().rename(columns=d)
upvote count: 2
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/83458128
answers question: http://stackoverflow.com/q/48237795
score: 2
has comment: http://stackoverflow.com/comment/83458099
accepted answer of: http://stackoverflow.com/q/48237795
downvote count: 0

http://stackoverflow.com/comment/83419448
has text: Perhaps it should. I generally try and avoid asking two questions to solve one problem, but given i didn't describe the full problem above, i've added a second question [here](https://stackoverflow.com/questions/48218781/open-csv-file-from-website-directly-in-pandas-without-downloading-to-folder)
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48207141

http://stackoverflow.com/comment/83595562
comment on: http://stackoverflow.com/a/48304512
score: 1
has text: Sample Node.JS code has `var key = Buffer(secret, 'base64');` which looks like important. Can Python follow that convention ?
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48175325
has title: Use Django OAuth2 provider with JupyterHub
accepted answer: http://stackoverflow.com/a/48235195
tagged with: oauth
has body: I'm attempting to run a Django web application that pairs with a JupyterHub server, where users enter via the web app and are then granted access to a notebook server once they've signed in. To facilitate this, I'm attempting to use OAuth2, where Django provides the authentication and JupyterHub verifies users against that. I'm using django-oauth-toolkit to provide the authentication service and linking against it using the Generic OAuthenticator. A docker-compose reference implementation is available here. Currently, the authorize redirect works, but some part of the token retrieval process throws the following error: jupyterhub_1 | [I 2018-01-07 18:53:41.763 JupyterHub log:124] 302 GET /hub/oauth_login?next= → http://localhost:8000/o/authorize?client_id=5hICA5iNiBhBuROGzxGJqGQ7Ur7yH8dHi53aPLB5&amp;response_type=code&amp;state=eyJuZXh0X3VybCI6ICIiLCAic3RhdGVfaWQiOiAiYWQ0NDc3MGVmZmY5NDMyOGEzODBlNThjMGI5YWQ0ZTcifQ%3D%3D&amp;redirect_uri=http%3A%2F%2Flocalhost%3A8001%2Fhub%2Foauth_callback (@172.22.0.1) 3.98ms django_1 | [07/Jan/2018 18:53:41] "GET /o/authorize?client_id=5hICA5iNiBhBuROGzxGJqGQ7Ur7yH8dHi53aPLB5&amp;response_type=code&amp;state=eyJuZXh0X3VybCI6ICIiLCAic3RhdGVfaWQiOiAiYWQ0NDc3MGVmZmY5NDMyOGEzODBlNThjMGI5YWQ0ZTcifQ%3D%3D&amp;redirect_uri=http%3A%2F%2Flocalhost%3A8001%2Fhub%2Foauth_callback HTTP/1.1" 301 0 django_1 | [07/Jan/2018 18:53:41] "GET /o/authorize/?client_id=5hICA5iNiBhBuROGzxGJqGQ7Ur7yH8dHi53aPLB5&amp;response_type=code&amp;state=eyJuZXh0X3VybCI6ICIiLCAic3RhdGVfaWQiOiAiYWQ0NDc3MGVmZmY5NDMyOGEzODBlNThjMGI5YWQ0ZTcifQ%3D%3D&amp;redirect_uri=http%3A%2F%2Flocalhost%3A8001%2Fhub%2Foauth_callback HTTP/1.1" 200 3159 django_1 | [07/Jan/2018 18:53:42] "POST /o/authorize/?client_id=5hICA5iNiBhBuROGzxGJqGQ7Ur7yH8dHi53aPLB5&amp;response_type=code&amp;state=eyJuZXh0X3VybCI6ICIiLCAic3RhdGVfaWQiOiAiYWQ0NDc3MGVmZmY5NDMyOGEzODBlNThjMGI5YWQ0ZTcifQ%3D%3D&amp;redirect_uri=http%3A%2F%2Flocalhost%3A8001%2Fhub%2Foauth_callback HTTP/1.1" 302 0 jupyterhub_1 | [W 2018-01…
has answer: http://stackoverflow.com/a/48235195
downvote count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: docker-compose
upvote count: 3
answer count: 1
tagged with: jupyter
favorite count: 0
type: Question

http://stackoverflow.com/comment/83483234
comment on: http://stackoverflow.com/q/48250225
type: QuestionComment
score: 0
has text: Yes thats exactly what I want
type: Comment

http://stackoverflow.com/comment/83351232
comment on: http://stackoverflow.com/q/48185575
score: 0
type: Comment
type: QuestionComment
has text: What does your text file look like?

http://stackoverflow.com/a/48194214
score: 0
has body: I think you can avoid the enumerate and iloc by using the column names. I will also suggest using a string-&gt;lambda map to store the operations and use the apply function. It will help when you have multiple operation strings operations = {'STD': lambda x : min_max_scaler.fit_transform(x), 'non': lambda x : x} # Operations map for colName in DFa.columns.values: transformStr = DFb.Transformation[DFb.Name == colName] #Get the transform string by matching column name with Name column if transformStr.shape[0] &gt; 1 or transformStr.shape[0] == 0: # Make sure that only one operation is selected raise(Exception('Invalid transform string %s',transformStr)) DFa[colName] = DFa[colName].apply(operations[transformStr.iloc[0]])
type: Answer
answers question: http://stackoverflow.com/q/48192903

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

http://stackoverflow.com/a/48284779
type: Answer
answers question: http://stackoverflow.com/q/48284642
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/83553657
has comment: http://stackoverflow.com/comment/83554728
downvote count: 1
has body: Regex: [^\s\|\t]+ Details: [^\s|] Match a single character not present in the list + Matches between one and unlimited times \s matches any whitespace character \| matches the character | \t matches a tab character Regex demo
has comment: http://stackoverflow.com/comment/83553762

http://stackoverflow.com/comment/83652196
has text: I updated the answer with example. check the tutorials as well.
score: 0
comment on: http://stackoverflow.com/a/48318926
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48288286
has comment: http://stackoverflow.com/comment/83561421
favorite count: 0
has comment: http://stackoverflow.com/comment/83565739
tagged with: optimization
type: Question
has body: I have to solve an integer linear optimization problem in Python with pulp. I solved the basic problem and now I have to add additional constraints. Is anybody who can help me with adding the condition with a logical indicator? The logical restriction is: B>5 if A>20 Here is my code: from pulp import * prob = LpProblem("The Optimization Problem", LpMaximize) A = LpVariable("A", 0, 100) B = LpVariable("B", 0, 200) C = LpVariable("C", 0, 100) R1 = LpVariable("R1", 0) R2 = LpVariable("R2", 0) R1 = 0.1 * A + 0.2 * B + 0.075 * C R2 = 0.05 * A + 0.1 * B + 0.05 * C prob += 2 * A + 3 * B + 2.55 * C - 0.6 * R1 - 0.8 * R2 prob += 0.5 * A + 0.8 * B + C &lt;= 100, "T1" prob += 0.8 * A + 0.6 * B + 0.2 * C &lt;= 100, "T2" prob.writeLP("OptimizationModel.lp") prob.solve() print("Status:", LpStatus[prob.status]) for v in prob.variables(): print(v.name, "=", v.varValue)
has answer: http://stackoverflow.com/a/48320955
tagged with: python
linked to: http://stackoverflow.com/q/33360898
score: 2
upvote count: 2
has title: Linear optimization with PuLP, additional condition on variables
has comment: http://stackoverflow.com/comment/83565602
type: UnansweredQuestion
tagged with: integer-programming
answer count: 1
downvote count: 0
tagged with: pulp
has comment: http://stackoverflow.com/comment/83566475

http://stackoverflow.com/a/48192572
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/83366888
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48192547
has comment: http://stackoverflow.com/comment/83388441
has body: Try: llb = request.form['lbs'] lw = (int(llb)*16) return lw Since your request.form['lbs'] is str type you need to cast it to int type before multiplication. Multiplication sign * works with strings in such a way that it copies them given amount of times. Example: '^'*5 &gt;&gt; '^^^^^' EDIT Your problem seems to be that you have overwritten the built-in int with some other variable. Example: &gt;&gt;&gt; lbs = '2' &gt;&gt;&gt; lbs '2' &gt;&gt;&gt; lw = lbs*16 &gt;&gt;&gt; lw '2222222222222222' &gt;&gt;&gt; lw = int(lbs)*16 &gt;&gt;&gt; lw 32 &gt;&gt;&gt; int = 7 &gt;&gt;&gt; lw = int(lbs)*16 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'int' object is not callable &gt;&gt;&gt; del int &gt;&gt;&gt; lw = int(lbs)*16 &gt;&gt;&gt; lw 32 You should never overwrite built-in names such as int, list, set, dict and so on: Why can you assign values to built-in functions in Python?

networkx
tags question: http://stackoverflow.com/q/48272595
tags question: http://stackoverflow.com/q/48274278
tags question: http://stackoverflow.com/q/48242837
tags question: http://stackoverflow.com/q/48203552
tags question: http://stackoverflow.com/q/48240021
tags question: http://stackoverflow.com/q/48176462
tags question: http://stackoverflow.com/q/48260568
tags question: http://stackoverflow.com/q/48203528
tag name: networkx
tags question: http://stackoverflow.com/q/48235215
tags question: http://stackoverflow.com/q/48321963
tags question: http://stackoverflow.com/q/48232304
tags question: http://stackoverflow.com/q/48197199
type: Tag

http://stackoverflow.com/comment/83623951
comment on: http://stackoverflow.com/a/48318935
score: 0
type: Comment
has text: Mozilla has a [good writeup for Firefox](https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor)
type: AnswerComment

http://stackoverflow.com/q/48179448
tagged with: python
has body: x = pd.DataFrame(index = pd.date_range(start="2017-1-1", end="2017-1-13"), columns="a b c".split()) x.ix[0:2, "a"] = 1 x.ix[5:10, "a"] = 1 x.ix[9:12, "b"] = 1 x.ix[1:3, "c"] = 1 x.ix[5, "c"] = 1 a b c 2017-01-01 1 NaN NaN 2017-01-02 1 NaN 1 2017-01-03 NaN NaN 1 2017-01-04 NaN NaN NaN 2017-01-05 NaN NaN NaN 2017-01-06 1 NaN 1 2017-01-07 1 NaN NaN 2017-01-08 1 NaN NaN 2017-01-09 1 NaN NaN 2017-01-10 1 1 NaN 2017-01-11 NaN 1 NaN 2017-01-12 NaN 1 NaN 2017-01-13 NaN NaN NaN Given the above dataframe, x, I want to return the average of the number of occurences of 1s within each group of a, b, and c. The average for each column is taken over the number of blocks that contains consecutive 1s. For example, column a will output the average of 2 and 5, which is 3.5. We divide it by 2 because there are 2 consecutive 1s between Jan-1 and Jan-2, then 5 consecutive 1s between Jan-06 and Jan-10, 2 blocks of 1s in total. Similarly, for column b, we will have 3 because only one consecutive sequence of 1s occur once between Jan-10 and Jan-13. Finally, for column c, we will have the average of 2 and 1, which is 1.5. Expected output of the toy example: a b c 3.5 3 1.5
has comment: http://stackoverflow.com/comment/83339785
accepted answer: http://stackoverflow.com/a/48179630
type: AnsweredQuestion
score: 2
has title: How to count occurrences of consecutive 1s by column and take mean by block
has answer: http://stackoverflow.com/a/48179630
has answer: http://stackoverflow.com/a/48179813
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48179827
answer count: 4
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48179827
upvote count: 2
has answer: http://stackoverflow.com/a/48180121
downvote count: 0

http://stackoverflow.com/comment/83506033
comment on: http://stackoverflow.com/q/48261569
type: Comment
has text: copy pasted your code, i could not replicate
type: QuestionComment
score: 0

http://stackoverflow.com/a/48187184
has body: As far as I am aware this is not possible out of the box. The problem is that each tree of the ensemble would have different features, which the algorithm is not made for (to my best knowledge). What you could do instead is train a model with your Dmatrix, do your feature selection/ generation and create a new Dmatrix including the new features and train a new boosted tree model. Just glancing over the paper I'd say what they propose is mostly what I suggested above. They do not include the new features for previous base learners and basically the learner can be any model (it's probably just that gradient boosted trees did perform exceptionally well in recent times - aside from CNNs). The result of their algorithm is just a set of "base" models. They call it an ensemble of boosted trees (so an ensemble of an ensemble). Their method is mostly a wrapper variant of ordinary feature selection procedures with the special part that they create synthetic features in addition. On a side note, their results don't really look that good, sure it's significant but what isn't given enough data. You can just as well use the original XGBoost algorithm and will most likely not end up worse in terms of real world performance (just my two cents).
type: Answer
answers question: http://stackoverflow.com/q/48186709
accepted answer of: http://stackoverflow.com/q/48186709
type: AcceptedAnswer
score: 0

odoo-10
tags question: http://stackoverflow.com/q/48265712
tags question: http://stackoverflow.com/q/48324176
tags question: http://stackoverflow.com/q/48305356
tag name: odoo-10
tags question: http://stackoverflow.com/q/48297082
type: Tag
tags question: http://stackoverflow.com/q/48229868
tags question: http://stackoverflow.com/q/48220939
tags question: http://stackoverflow.com/q/48199519

http://stackoverflow.com/q/48320229
tagged with: python
has comment: http://stackoverflow.com/comment/83627074
type: Question
tagged with: numpy
has title: How to convert 2d numpy array to 4d numpy array
answer count: 0
linked to: http://stackoverflow.com/q/14476415
has comment: http://stackoverflow.com/comment/83625704
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83627974
has body: I have NumPy array of float X_train shape: (6000,2304) I need to convert it into (6000,48,48,1) I have read image data from CSV file which has row vector of all images. I made NumPy array from that but I need to pass this into the convolutional neural network which needs 4D array.
tagged with: matrix

http://stackoverflow.com/q/48246315
has answer: http://stackoverflow.com/a/48246337
tagged with: python
type: Question
score: 0
upvote count: 2
has body: I have a list of tuples: [('fruit', 'O'), ('is', 'O'), ('the', 'O'), ('subject', 'O'), ('of', 'O'), ('a', 'O'), ('Roald', 'PERSON'), ('Dahl', 'PERSON'), ('children', 'O'), ("'s", 'O'), ('book', 'O'), ('?', 'O')]` I want to reduce this list to: [('fruit', 'O'), ('is', 'O'), ('the', 'O'), ('subject', 'O'), ('of', 'O'), ('a', 'O'), ('Roald Dahl', 'PERSON'), ('children', 'O'), ("'s", 'O'), ('book', 'O'), ('?', 'O')]` That is, any consecutive tuples whose second value is not 'O' should have their first values concatenated. This should work for a list of any length, and for any number of consecutive tuples to be joined. Attempt def join_tags(list_tags): res = [] last_joined = None last_seen = (None, None) for tup in list_tags: if tup[1] == 'O': res.append(tup) last_joined = None else: if tup[1] == last_seen[1]: if last_joined: new_tup = (last_joined[0] + ' ' + tup[0], tup[1]) last_joined = new_tup res.append(new_tup) else: new_tup = (tup[0] + ' ' + tup[0], tup[1]) res.append(new_tup) last_joined = new_tup else: res.append(tup) last_joined = None last_seen = tup return res
downvote count: 2
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/48244632
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83476217
has comment: http://stackoverflow.com/comment/83475276
accepted answer: http://stackoverflow.com/a/48246337
has comment: http://stackoverflow.com/comment/83475865
has title: Concatenating elements of tuples in a list

http://stackoverflow.com/a/73304939
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48198021
has body: If mylist contains some column names which are not in mydata.columns, you will get an error like KeyError: "['fff'] not in index" In this case, you can use the df.filter function: mydata.filter(['nnn', 'mmm', 'yyy', 'fff'])
type: Answer

http://stackoverflow.com/q/48184930
has comment: http://stackoverflow.com/comment/83349869
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/83350327
has title: Subplot a dataframe according to a column's values
has comment: http://stackoverflow.com/comment/83349900
has body: I want to subplot a dataframe according to the values of the column id. datafr = pd.DataFrame(columns = ["timestamp", "id", "col1","col2","col3"], data = [[1,"a", 1, 2, 3], [1,"b", 1, 2, 3], [1,"c", 1, 2, 3], [2,"a", 1, 2, 3], [2,"b", 1, 2, 3], [2,"c", 1, 2, 3]] ) I need to have 3 subplots corresponding to a, b, c which are the values of the column id. Data in each subplot is data of col1, col2, col3 . Is it possible to do this without pivoting my dataframe? EDIT : I need timestamp column in my x_axis. In the post Plotting grouped data in same plot using Pandas , it is completely the inverse, they want to have one plot for two classes. Thank you in advance.
has comment: http://stackoverflow.com/comment/83349821
duplicate of: http://stackoverflow.com/q/29975835
has comment: http://stackoverflow.com/comment/83350629
has comment: http://stackoverflow.com/comment/83350347
type: Question
has comment: http://stackoverflow.com/comment/83349859
has comment: http://stackoverflow.com/comment/83350638
linked to: http://stackoverflow.com/q/29975835
type: UnansweredQuestion
tagged with: matplotlib
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/28293028
score: 0

http://stackoverflow.com/comment/83436825
type: QuestionComment
comment on: http://stackoverflow.com/q/48227100
has text: @larsks, yeah, thet's even the problem. I could easily get the url if there was a redirect.
score: 0
type: Comment

http://stackoverflow.com/comment/83610206
comment on: http://stackoverflow.com/q/48312141
score: 0
type: QuestionComment
has text: I tried that and I get the same result
type: Comment

http://stackoverflow.com/comment/83549537
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48282888
has text: If `pair` is a boolean, and you want to continue while `pair` is `false` then `while not pair` should work. If it doesn't then you have another problem somewhere. You're going to need to show a code sample of what doesn't work.

http://stackoverflow.com/q/48230230
tagged with: text
tagged with: numpy
has answer: http://stackoverflow.com/a/58528039
linked to: http://stackoverflow.com/q/37713484
has comment: http://stackoverflow.com/comment/83443016
has answer: http://stackoverflow.com/a/52741977
type: UnansweredQuestion
tagged with: save
has comment: http://stackoverflow.com/comment/83442798
tagged with: arrays
downvote count: 0
has body: I have the following array: X = np.array([image_array_to_vector1,image_array_to_vector2,image_array_to_vector3,image_array_to_vector4]) A print out of X looks as follows: [array([167, 167, 169, ..., 1, 1, 1], dtype=uint8) array([42, 43, 43, ..., 41, 36, 34], dtype=uint8) array([0, 0, 0, ..., 0, 0, 0], dtype=uint8) array([0, 0, 0, ..., 0, 0, 0], dtype=uint8)] When I try to save the data as txt: X_to_text_file = np.savetxt('x.txt',X) I get the following: File "/Library/Python/2.7/site-packages/numpy/lib/npyio.py", line 1258, in savetxt % (str(X.dtype), format)) TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e') Why is that? How can I solve the issue? Thanks.
favorite count: 0
has title: TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e')
type: Question
score: 51
has answer: http://stackoverflow.com/a/48231106
upvote count: 51
tagged with: python
has answer: http://stackoverflow.com/a/48232044
answer count: 4

http://stackoverflow.com/comment/83572144
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48286952
type: Comment
has text: tf.Print - it still resulted in print of the object not of the value of the object. it has to do with the fact that i am working with tf.placeholders not actual variables or constants. similar behavior was reported in other posts. Do you know how to make it work with tf.placeholders?

search
tags question: http://stackoverflow.com/q/48313993
tags question: http://stackoverflow.com/q/48278091
tags question: http://stackoverflow.com/q/48271024
tags question: http://stackoverflow.com/q/48195361
type: Tag
tags question: http://stackoverflow.com/q/48303136
tag name: search

http://stackoverflow.com/a/48236339
score: 1
downvote count: 0
upvote count: 1
has body: Don't give your files the same name as the modules you are importing. You are having this problem because your filename is "discord.py". Just change it and the code should work. Also, you should avoid posting your token...
answers question: http://stackoverflow.com/q/48236181
type: Answer

http://stackoverflow.com/a/48286462
has body: Does it do what you want: unique_counts = df.nunique() lowest_distinct = unique_counts.min() lowest_distinct_columns = unique_counts[unique_counts == lowest_distinct].index.tolist() result = pd.DataFrame({col: df[col].unique() for col in lowest_distinct_columns})
type: Answer
has comment: http://stackoverflow.com/comment/83558400
accepted answer of: http://stackoverflow.com/q/48286221
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48286221
has comment: http://stackoverflow.com/comment/83558604
has comment: http://stackoverflow.com/comment/83579944

http://stackoverflow.com/q/48216379
has comment: http://stackoverflow.com/comment/83415461
has comment: http://stackoverflow.com/comment/83417700
tagged with: python
tagged with: lambda
tagged with: amazon-web-services
has body: I'm struggling to get a Lambda function working. I have a python script to access twitter API, pull information, and export that information into an excel sheet. I'm trying to transfer python script over to AWS/Lambda, and I'm having a lot of trouble. What I've done so far: Created AWS account, setup S3 to have a bucket, and poked around trying to get things to work. I think the main area I'm struggling is how to go from a python script that I'm executing via local CLI and transforming that code into lambda-capable code. I'm not sure I understand how the lambda_handler function works, what the event or context arguments actually mean (despite watching a half dozen different tutorial videos), or how to integrate my existing functions into Lambda in the context of the lambda_handler, and I'm just very confused and hoping someone might be able to help me get some clarity! Code that I'm using to pull twitter data (just a sample): import time import datetime import keys import pandas as pd from twython import Twython, TwythonError import pymysql def lambda_handler(event, context): def oauth_authenticate(): twitter_oauth = Twython(keys.APP_KEY, keys.APP_SECRET, oauth_version=2) ACCESS_TOKEN = twitter_oauth.obtain_access_token() twitter = Twython(keys.APP_KEY, access_token = ACCESS_TOKEN) return twitter def get_username(): """ Prompts for the screen name of targetted account """ username = input("Enter the Twitter screenname you'd like information on. Do not include '@':") return username def get_user_followers(username): """ Returns data on all accounts following the targetted user. WARNING: The number of followers can be huge, and the data isn't very valuable """ #username = get_username() #import pdb; pdb.set_trace() twitter = oauth_authenticate() datestamp = str(datetime.datetime.now().strftime("%Y-%m-%d")) target = twitter.lookup_user(screen_name = username) for y in target: target_id = y['id_str'] next_cursor = -1 index = 0 followersdata = {} while next_cursor: try: …
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/83454091
has comment: http://stackoverflow.com/comment/83451110
has title: AWS Lambda - How do I convert my code to work in AWS?
type: Question
has comment: http://stackoverflow.com/comment/83416627
type: UnansweredQuestion

http://stackoverflow.com/a/48239068
score: 3
type: Answer
has body: Inner Frame (self.devices) is element on Canvas, not part of external frame nor any other widget/windows so you shouldn't do self.devices.pack(side=tk.LEFT, padx=3, pady=3) Remove this line and it will work correctly.
answers question: http://stackoverflow.com/q/48237211
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/48312979
tagged with: statsmodels
accepted answer: http://stackoverflow.com/a/48314666
has body: I'm new to using statsmodels to do statistical analyses. I'm getting expected answers most of the time but there are some things I don't quite understand about the way that statsmodels defines endog (dependant) variables for logistic regression when entered as strings. An example Pandas dataframe to illustrate the issue can be defined as shown below. The yN, yA and yA2 columns represent different ways to define an endog variable: yN is a binary variable coded 0, 1; yA is a binary variable coded 'y', 'n'; and yA2 is a variable coded 'x', 'y' and 'w': import pandas as pd df = pd.DataFrame({'yN':[0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1], 'yA':['y','y','y','y','y','y','y','n','n','n','n','n','n','n','n','n','n','n','n','n',], 'yA2':['y','y','y','w','y','w','y','n','n','n','n','n','n','n','n','n','n','n','n','n',], 'xA':['a','a','b','b','b','c','c','c','c','c','a','a','a','a','b','b','b','b','c','c']}) The dataframe looks like: xA yA yA2 yN 0 a y y 0 1 a y y 0 2 b y y 0 3 b y w 0 4 b y y 0 5 c y w 0 6 c y y 0 7 c n n 1 8 c n n 1 9 c n n 1 10 a n n 1 11 a n n 1 12 a n n 1 13 a n n 1 14 b n n 1 15 b n n 1 16 b n n 1 17 b n n 1 18 c n n 1 19 c n n 1 I can run a 'standard' logistic regression using a 0/1 encoded endog variable and a categorical exog variable (xA) as follows: import statsmodels.formula.api as smf import statsmodels.api as sm phjLogisticRegressionResults = smf.glm(formula='yN ~ C(xA)', data=df, family = sm.families.Binomial(link = sm.genmod.families.links.logit)).fit() print('\nResults of logistic regression model') print(phjLogisticRegressionResults.summary()) This produces the following results, which are exactly as I'd expect: Generalized Linear Model Regression Results ============================================================================== Dep. Variable: yN No. Observations: 20 Model: GLM Df Residuals: 17 Model Family: Binomial Df Model: 2 Link Function: logit Scale: 1.0 Method: IRLS Log-Likelihood: -12.787 Date: Thu, 18 Jan 2018 Deviance: 25.575 Ti…
has title: How does statsmodels encode endog variables entered as strings?
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 5
score: 5
downvote count: 0
has answer: http://stackoverflow.com/a/48314666
answer count: 1
tagged with: logistic-regression
type: AnsweredQuestion

http://stackoverflow.com/comment/83466185
score: 0
comment on: http://stackoverflow.com/q/48240927
type: Comment
type: QuestionComment
has text: Be careful. It seems some basics are missing! If you are trying to solve a convex continuous opt problem, you can achieve a global optimum in polynomial time. cvxopt, if you can express it in some of the supported forms, as well as any nonlinear-optimizer achieving local-opt convergence (as local-opt = global-opt in convex optimization) like SLSQP will do that (quite differently!). In this case using Basinhopping and co. is completely unnecessary (and wrong). If it's non-convex; cvxopt can't tackle it. General nonlinear-optimizers will do and achieve local-opts.

http://stackoverflow.com/comment/83482389
has text: I get this error `StaleElementReferenceException: Message: {"errorMessage":"Element does not exist in cache","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"116","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:47807","User-Agent":"Python http auth"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"tag name\", \"sessionId\": \"b2ddb140-f92c-11e7-86cf-2bfda6dce865\", \"id\": \":wdc:1515935604720\", \"value\": \"a\"}"`
type: Comment
comment on: http://stackoverflow.com/a/48249819
score: 0
type: AnswerComment

zappa
tags question: http://stackoverflow.com/q/48272415
type: Tag
tag name: zappa

http://stackoverflow.com/comment/83548908
has text: Try using scrapy with splash or scrapy with selenium...
type: Comment
comment on: http://stackoverflow.com/q/48282539
score: 0
type: QuestionComment

http://stackoverflow.com/q/48252015
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/10373660
has body: Referring to this very popular question regarding groupby to dataframe. Unfortunately, I do not think this particular use case is the most useful, here's mine: Suppose you have what could be a hierarchical dataset in a flattened form, e.g. key val 0 'a' 2 1 'a' 1 2 'b' 3 3 'b' 4 what I wish to do is convert that dataframe to this structure 'a' 'b' 0 2 3 1 1 4 I thought this would be as simple as pd.DataFrame(df.groupby('key').groups) but it isn't. How can I make this transformation?
answer count: 5
linked to: http://stackoverflow.com/q/19736080
has answer: http://stackoverflow.com/a/48252193
has comment: http://stackoverflow.com/comment/83489675
tagged with: group-by
linked to: http://stackoverflow.com/q/34702815
tagged with: python
has comment: http://stackoverflow.com/comment/83489806
has answer: http://stackoverflow.com/a/48253174
has answer: http://stackoverflow.com/a/48252080
has title: Pandas: GroupBy to DataFrame
linked to: http://stackoverflow.com/q/48265340
score: 2
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/136637698
accepted answer: http://stackoverflow.com/a/48252193
has answer: http://stackoverflow.com/a/48252118
has comment: http://stackoverflow.com/comment/83489426
has answer: http://stackoverflow.com/a/48252111
possible better answer: http://stackoverflow.com/a/48252111
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/12860421

http://stackoverflow.com/comment/83648079
score: 0
has text: It would be helpful if you could post what you think the `.csv` file should look like. Such files generally have a fixed number of columns but it seems to me you want an output file with a variable number of columns. But I don't really understand what you want. Is `'identifier'` a literal value in your file, or is it a symbolic placeholder for `myidentifer1`, `myidentifer2` etc? Are there always 4 values? Why do you want to add one extra column if there are 4 extra values? Explain and exemplify, please.
type: Comment
comment on: http://stackoverflow.com/q/48330915
type: QuestionComment

http://stackoverflow.com/a/48188480
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48177771
has body: If you're not using an already ready library it 'saves' the training only if you write a part of code to save it. The simplest way is to generate a TXT with a list of all the weights after the training and load it with a specific function.
downvote count: 0
score: 1

http://stackoverflow.com/comment/83341214
type: AnswerComment
comment on: http://stackoverflow.com/a/48180596
score: 0
type: Comment
has text: It's weird that numpy doesn't supply a way to make multidensional polynomials in a simple way. I thought the option would be available and I must be doing something wrong.

numpy
tags question: http://stackoverflow.com/q/48272969
tags question: http://stackoverflow.com/q/48266118
tags question: http://stackoverflow.com/q/48310744
tags question: http://stackoverflow.com/q/48233402
tags question: http://stackoverflow.com/q/48213729
tags question: http://stackoverflow.com/q/48288269
tags question: http://stackoverflow.com/q/48255273
tags question: http://stackoverflow.com/q/48326979
tags question: http://stackoverflow.com/q/48224726
tags question: http://stackoverflow.com/q/48190973
tags question: http://stackoverflow.com/q/48208866
tags question: http://stackoverflow.com/q/48241909
tags question: http://stackoverflow.com/q/48286673
tags question: http://stackoverflow.com/q/48227037
tags question: http://stackoverflow.com/q/48180041
tags question: http://stackoverflow.com/q/48259726
tags question: http://stackoverflow.com/q/48290758
tags question: http://stackoverflow.com/q/48204194
tags question: http://stackoverflow.com/q/48195376
tags question: http://stackoverflow.com/q/48298170
tags question: http://stackoverflow.com/q/48227667
tags question: http://stackoverflow.com/q/48230230
tags question: http://stackoverflow.com/q/48176514
tags question: http://stackoverflow.com/q/48321394
tags question: http://stackoverflow.com/q/48264157
tags question: http://stackoverflow.com/q/48293509
tags question: http://stackoverflow.com/q/48245364
tags question: http://stackoverflow.com/q/48252297
tags question: http://stackoverflow.com/q/48275038
tags question: http://stackoverflow.com/q/48288366
tags question: http://stackoverflow.com/q/48268453
tags question: http://stackoverflow.com/q/48185749
tags question: http://stackoverflow.com/q/48226089
tags question: http://stackoverflow.com/q/48202407
tags question: http://stackoverflow.com/q/48193107
tags question: http://stackoverflow.com/q/48235169
tags question: http://stackoverflow.com/q/48251448
tags question: http://stackoverflow.com/q/48282748
tags question: http://stackoverflow.com/q/48291711
tags question: http://stackoverflow.com/q/48330144
tags question: http://stackoverflow.com/q/48310067
tags question: http://stackoverflow.com/q/48214357
tags question: http://stackoverflow.com/q/48312205
tags question: http://stackoverflow.com/q/48218766
tags question: http://stackoverflow.com/q/48196567
tags question: http://stackoverflow.com/q/48266869
tags question: http://stackoverflow.com/q/48247522
tags question: http://stackoverflow.com/q/48329815
tags question: http://stackoverflow.com/q/48174172
tags question: http://stackoverflow.com/q/48195277
tags question: http://stackoverflow.com/q/48245765
tags question: http://stackoverflow.com/q/48291170
tags question: http://stackoverflow.com/q/48241666
tags question: http://stackoverflow.com/q/48303711
tags question: http://stackoverflow.com/q/48221710
tags question: http://stackoverflow.com/q/48221841
tags question: http://stackoverflow.com/q/48244097
tags question: http://stackoverflow.com/q/48207685
tags question: http://stackoverflow.com/q/48279206
tags question: http://stackoverflow.com/q/48285773
tags question: http://stackoverflow.com/q/48289528
tags question: http://stackoverflow.com/q/48251534
tags question: http://stackoverflow.com/q/48212186
tags question: http://stackoverflow.com/q/48247606
tags question: http://stackoverflow.com/q/48191873
tags question: http://stackoverflow.com/q/48273451
tags question: http://stackoverflow.com/q/48274129
tags question: http://stackoverflow.com/q/48262389
tags question: http://stackoverflow.com/q/48173470
type: Tag
tags question: http://stackoverflow.com/q/48250981
tags question: http://stackoverflow.com/q/48178086
tags question: http://stackoverflow.com/q/48179693
tags question: http://stackoverflow.com/q/48266346
tags question: http://stackoverflow.com/q/48202923
tags question: http://stackoverflow.com/q/48258552
tags question: http://stackoverflow.com/q/48233897
tags question: http://stackoverflow.com/q/48325006
tags question: http://stackoverflow.com/q/48267586
tags question: http://stackoverflow.com/q/48322740

http://stackoverflow.com/comment/83501957
has text: What do you mean `application logs`? There are two loggers which are `access` and `error` but no `application`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48259567
score: 0

http://stackoverflow.com/a/48284304
has body: This is not difficult, but it does require several steps: parse the incoming time format, find the difference in seconds, and the calculate the different time units of the difference. Given d1=20180110141907 d2=20180111162211 GNU awk gawk -v start="$d1" -v stop="$d2" ' function str2time(time, re, arr, t) { re = "([[:digit:]]{4})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})" t = -1 if (match(time, re, arr)) t = mktime(arr[1] " " arr[2] " " arr[3] " " arr[4] " " arr[5] " " arr[6]) return t } BEGIN { t1 = str2time(start) t2 = str2time(stop) diff = t2 - t1 if (diff &lt; 0) diff = -diff #awk does not have abs() days = int(diff / 86400); diff %= 86400 hours = int(diff / 3600); diff %= 3600 mins = int(diff / 60); diff %= 60 printf("%d days %d hours %d mins %d secs\n", days, hours, mins, diff) } ' 1 days 2 hours 3 mins 4 secs Perl perl -MTime::Piece -sE ' $t1 = Time::Piece-&gt;strptime($start, "%Y%m%d%H%M%S"); $t2 = Time::Piece-&gt;strptime($stop, "%Y%m%d%H%M%S"); $diff = abs($t2 - $t1); $days = int($diff / 86400); $diff %= 86400; $hours = int($diff / 3600); $diff %= 3600; $mins = int($diff / 60); $diff %= 60; printf "%d days %d hours %d mins %d secs\n", $days, $hours, $mins, $diff; ' -- -start="$d1" -stop="$d2" 1 days 2 hours 3 mins 4 secs
answers question: http://stackoverflow.com/q/48282476
type: Answer
score: 0

http://stackoverflow.com/q/48320766
tagged with: bots
upvote count: 2
has body: Because the command and the answer are the same my bot just spams the server with "k" until I shut it down. How do I stop it? The code: @client.event async def on_message(message): if message.content ==("k"): await client.send_message(message.channel, "k") await client.process_commands(message)
downvote count: 0
accepted answer: http://stackoverflow.com/a/48483793
has comment: http://stackoverflow.com/comment/83627164
has title: How to stop Discord bot respond to itself/all other bots?
favorite count: 0
has answer: http://stackoverflow.com/a/68917433
type: Question
possible better answer: http://stackoverflow.com/a/48341940
has comment: http://stackoverflow.com/comment/83658232
has comment: http://stackoverflow.com/comment/83627262
answer count: 3
has answer: http://stackoverflow.com/a/48341940
tagged with: python
tagged with: discord
has answer: http://stackoverflow.com/a/48483793
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/83470843
score: 0
type: Comment
type: QuestionComment
has text: UDS is the normal way to solve this sort of problem. Why can't you use it? (Note that UDS does not involve a network connection.)
comment on: http://stackoverflow.com/q/48242731

http://stackoverflow.com/q/48263541
score: 0
tagged with: snakemake
has body: this is a slightly more complicated case than the one reported here. My input files are the following: ont_Hv1_2.5+.fastq ont_Hv2_2.5+.fastq pacBio_Hv1_1-1.5.fastq pacBio_Hv1_1.5-2.5.fastq pacBio_Hv1_2.5+.fastq pacBio_Hv2_1-1.5.fastq pacBio_Hv2_1.5-2.5.fastq pacBio_Hv2_2.5+.fastq pacBio_Mv1_1-1.5.fastq pacBio_Mv1_1.5-2.5.fastq pacBio_Mv1_2.5+.fastq I would like to process only existing input files, i.e. automatically skip those wildcard combinations that correspond to non-existing input files. My Snakefile looks like this: import glob import os.path from itertools import product #make wildcards regexps non-greedy: wildcard_constraints: capDesign = "[^_/]+", sizeFrac = "[^_/]+", techname = "[^_/]+", # get TECHNAMES (sequencing technology, i.e. 'ont' or 'pacBio'), CAPDESIGNS (capture designs, i.e. Hv1, Hv2, Mv1) and SIZEFRACS (size fractions) variables from input FASTQ file names: (TECHNAMES, CAPDESIGNS, SIZEFRACS) = glob_wildcards("{techname}_{capDesign}_{sizeFrac}.fastq") # make lists non-redundant: CAPDESIGNS=set(CAPDESIGNS) SIZEFRACS=set(SIZEFRACS) TECHNAMES=set(TECHNAMES) # make list of authorized wildcard combinations (based on presence of input files) AUTHORIZEDCOMBINATIONS = [] for comb in product(TECHNAMES,CAPDESIGNS,SIZEFRACS): if(os.path.isfile(comb[0] + "_" + comb[1] + "_" + comb[2] + ".fastq")): tup=(("techname", comb[0]),("capDesign", comb[1]),("sizeFrac", comb[2])) AUTHORIZEDCOMBINATIONS.append(tup) # Function to create filtered combinations of wildcards, based on the presence of input files. # Inspired by: # https://stackoverflow.com/questions/41185567/how-to-use-expand-in-snakemake-when-some-particular-combinations-of-wildcards-ar def filter_combinator(whitelist): def filtered_combinator(*args, **kwargs): for wc_comb in product(*args, **kwargs): for ac in AUTHORIZEDCOMBINATIONS: if(wc_comb[0:3] == ac): print ("SUCCESS") yield(wc_comb) break return filtered_combinator filtered_product = filter_combinator(AUTHORIZEDCOMBINATIONS) rule all: input: expand(…
answer count: 1
has title: How to use expand in snakemake when some combinations of wildcards are not desired (missing input files), with a "merge" rule?
type: Question
linked to: http://stackoverflow.com/q/41185567
tagged with: python
accepted answer: http://stackoverflow.com/a/48323515
tagged with: wildcard
has answer: http://stackoverflow.com/a/48323515
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48443572

http://stackoverflow.com/a/48185048
upvote count: 1
has comment: http://stackoverflow.com/comment/83350798
accepted answer of: http://stackoverflow.com/q/48184854
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48184854
has body: I don't know django-fsm at all, but with a quick look at the documentation there is a post_transition signal which is triggered after an instance changes its state. So you could define one that listens to Bar, then checks that the instance's Foo object has only completed Bars. Something like: @receiver(post_transition, sender=Bar) def check_completed(sender, instance, name, source, target): if target == 'completed': if not instance.foo.bar_set.filter(state='draft').exists(): instance.foo.state = 'completed' instance.foo.save()
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48229639
score: 4
has comment: http://stackoverflow.com/comment/83463978
has body: As usual, I got beaten to the punch by @ImportanceOfBeingErnest, but I have a slightly different approach, which I thinks works as well. I created a separate axe for the color bar, and I created a standalone color bar using the example from matplotlib's documentation. This requires to know the extend of the color scale before hand though. Then I just plot the contourf in the animation using the same colorbar and normalization. #Generate some lists def f(x,y,a): return a*(x**2+y**2) avals = list(np.linspace(0,1,10)) xaxis = list(np.linspace(-2,2,9)) yaxis = list(np.linspace(-2,2,9)) xy = list(itertools.product(xaxis,yaxis)) xy = list(map(list,xy)) xy = np.array(xy) x = xy[:,0] y = xy[:,1] x = list(x) y = list(y) zlist = [] for a in avals: z = [] for i, xval in enumerate(x): z.append(f(x[i],y[i],a)) zlist.append(z) xi = np.linspace(min(x),max(x),len(x)) yi = np.linspace(min(y), max(y), len(y)) fig,[ax,cax] = plt.subplots(1,2, gridspec_kw={"width_ratios":[10,1]}) # Set the colormap and norm to correspond to the data for which # the colorbar will be used. cmap = mpl.cm.hsv norm = mpl.colors.Normalize(vmin=0, vmax=10) cb1 = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm, orientation='vertical') def animate(index): zi = ml.griddata(x, y, zlist[index], xi, yi, interp='linear') ax.clear() contourplot = ax.contourf(xi, yi, zi, cmap=cmap, norm=norm, origin='lower') #cbar = plt.colorbar(contourplot) ax.set_title('%03d'%(index)) return ax ani = animation.FuncAnimation(fig,animate,np.array([0,1,2,3,4,5,6,7,8,9]),interval=200,blit=False)
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/83455184
answers question: http://stackoverflow.com/q/48228692
downvote count: 0

http://stackoverflow.com/q/48249119
has body: I am trying to understand why this sample Neural Network with Numpy does not learn non-linear data. Even a simple NN is supposed to learn non-linear data right? I want my NN to learn that if the input is 1 then 0 if the input is greater than 1 and less than 4 then 1. If value > 4 then 0. I have tried many sample NN codes with numpy from google, I seem to get this problem. The below code does not learn, but learn well with input [2,2,0,0] desired [1,1,0,0]. import numpy as np # #sigmoid function def nonlin(x,deriv=False): if(deriv==True): return x*(1-x) return 1/(1+np.exp(-x)) # input dataset X = np.array([ [1], [2], [3], [4] ]) # #output dataset y = np.array([[0,1,1,0]]).T # #seed random numbers to make calculation # #deterministic (just a good practice) np.random.seed(1) # #initialize weights randomly with mean 0 syn0 = 2*np.random.random((1,1)) - 1 for iter in range(10000): # #forward propagation l0 = X l1 = nonlin(np.dot(l0,syn0)) # #how much did we miss? l1_error = y - l1 # multiply how much we missed by the # slope of the sigmoid at the values in l1 l1_delta = l1_error * nonlin(l1,True) # #update weights syn0 += np.dot(l0.T,l1_delta) print ("Output After Training:") print (l1)
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48256375
tagged with: machine-learning
has answer: http://stackoverflow.com/a/50422075
type: Question
type: UnansweredQuestion
has title: Simple Neural Network does not learn non linear data?
tagged with: neural-network
tagged with: python

http://stackoverflow.com/comment/83470074
comment on: http://stackoverflow.com/q/48240437
has text: »flush does not imply commit, so something else is up«, and I am trying to look that up in the ghini.desktop code and I don't recognize it. and that code is far from Minimal.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83545680
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/48280846
has text: `.encode().decode('utf-8')` is entirely useless here, why even mention it (and get the order in the description wrong on top)?
type: Comment

http://stackoverflow.com/q/48282599
tagged with: django-rest-framework
has body: from rest_framework import serializers from .models import Stock class StockSerializer(serializers.ModelSerializer): class Meta: model = Stock #field = ('ticker','volume') field = '__all__' I am getting an exception value on running application : ("Creating a ModelSerializer without either the 'fields' attribute or the 'exclude' attribute has been deprecated since 3.3.0, and is now disallowed. Add an explicit fields = '__all__' to the StockSerializer serializer.",)
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/72285925
has answer: http://stackoverflow.com/a/48282774
tagged with: django-models
upvote count: 13
tagged with: python
has answer: http://stackoverflow.com/a/48282760
accepted answer: http://stackoverflow.com/a/48282760
type: AnsweredQuestion
answer count: 3
possible better answer: http://stackoverflow.com/a/48282774
downvote count: 0
has comment: http://stackoverflow.com/comment/83548838
has title: Getting an Assertion error in my django application(1.8.4)
has comment: http://stackoverflow.com/comment/83549196
score: 13

http://stackoverflow.com/comment/83623890
score: 0
comment on: http://stackoverflow.com/a/48318935
has text: Using my browser's dev tools Network tab. In most browsers, you bring this up with the `F12` key or by right-clicking anywhere and selecting the `inspect` (or similar) option. You should see a `Network` tab that will show you all the requests that are made between the browser and server.
type: Comment
type: AnswerComment

curve-fitting
tags question: http://stackoverflow.com/q/48324239
tag name: curve-fitting
tags question: http://stackoverflow.com/q/48216974
tags question: http://stackoverflow.com/q/48226089
type: Tag
tags question: http://stackoverflow.com/q/48322740

http://stackoverflow.com/q/48228060
tagged with: pandas
has title: Filter pandas dataframe from tuples
answer count: 1
score: 16
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48228107
accepted answer: http://stackoverflow.com/a/48228107
tagged with: python
upvote count: 16
type: AnsweredQuestion
has body: AB_col = [(0,230), (10,215), (15, 200), (20, 185), (40, 177), (0,237), (10,222), (15, 207), (20, 192), (40, 184)] sales = [{'account': 'Jones LLC', 'A': 0, 'B': 230, 'C': 140}, {'account': 'Alpha Co', 'A': 20, 'B': 192, 'C': 215}, {'account': 'Blue Inc', 'A': 50, 'B': 90, 'C': 95 }] df = pd.DataFrame(sales) print df result Now the above dataframe has to be filtered by the AB_col list of tuples. I tried something like df[df["A","B"].zip.isin(AB_col)] But it did not work, How to filter the above dataframe to the one like below

http://stackoverflow.com/a/48264705
has body: import sys def getcmdlineargv(argv): """Function to get values from cmd line and converted into dictionary""" opts = {} # dictionary to store key-value pairs. while argv: # until arguments left to parse... if argv[0][0] == '-': # Found a "-name value" pair. opts[argv[0]] = argv[1] # Add key and value to the dictionary. argv = argv[1:] # Reduce the argument list by copying it starting from index 1. return opts argvDict = getcmdlineargv(sys.argv) print(argvDict) &gt;&gt;&gt; python filename.py -sock connectmode -rport 10000 &gt;&gt;&gt; {'-sock': 'connectmode', '-rport': '10000'} Using argument parser: import argparse parser = argparse.ArgumentParser() parser.add_argument("-sock", type=str, help='') parser.add_argument("-rport", type=int, help='') parsarg = vars(parser.parse_args()) print(parsarg.get('rport')) &gt;&gt;&gt; python filename.py -sock connectmode -rport 10000 &gt;&gt;&gt; 10000 Hope this will solve your problem to get command line argument.
downvote count: 1
has comment: http://stackoverflow.com/comment/83512365
type: Answer
answers question: http://stackoverflow.com/q/48264081
has comment: http://stackoverflow.com/comment/83514678
upvote count: 2
score: 1

python-2.7
tags question: http://stackoverflow.com/q/48281285
tags question: http://stackoverflow.com/q/48216930
tags question: http://stackoverflow.com/q/48272906
tags question: http://stackoverflow.com/q/48313035
tags question: http://stackoverflow.com/q/48239021
tags question: http://stackoverflow.com/q/48236364
tags question: http://stackoverflow.com/q/48259271
tags question: http://stackoverflow.com/q/48219852
tags question: http://stackoverflow.com/q/48264157
tags question: http://stackoverflow.com/q/48234438
tags question: http://stackoverflow.com/q/48202117
tags question: http://stackoverflow.com/q/48279684
tags question: http://stackoverflow.com/q/48258674
tags question: http://stackoverflow.com/q/48215731
tags question: http://stackoverflow.com/q/48226958
tags question: http://stackoverflow.com/q/48327661
tags question: http://stackoverflow.com/q/48313837
tags question: http://stackoverflow.com/q/48243369
tags question: http://stackoverflow.com/q/48297082
tags question: http://stackoverflow.com/q/48207478
tags question: http://stackoverflow.com/q/48297678
tags question: http://stackoverflow.com/q/48218912
tags question: http://stackoverflow.com/q/48174916
tags question: http://stackoverflow.com/q/48290132
tags question: http://stackoverflow.com/q/48231397
tags question: http://stackoverflow.com/q/48246033
tags question: http://stackoverflow.com/q/48229849
tags question: http://stackoverflow.com/q/48205972
tags question: http://stackoverflow.com/q/48287404
tags question: http://stackoverflow.com/q/48183643
tags question: http://stackoverflow.com/q/48326141
tags question: http://stackoverflow.com/q/48196521
tags question: http://stackoverflow.com/q/48250037
tags question: http://stackoverflow.com/q/48238432
tags question: http://stackoverflow.com/q/48251534
tags question: http://stackoverflow.com/q/48241585
type: Tag
tags question: http://stackoverflow.com/q/48282596
tags question: http://stackoverflow.com/q/48216128
tags question: http://stackoverflow.com/q/48214382
tags question: http://stackoverflow.com/q/48240489
tags question: http://stackoverflow.com/q/48283740
tags question: http://stackoverflow.com/q/48256779
tags question: http://stackoverflow.com/q/48248121
tags question: http://stackoverflow.com/q/48306993
tags question: http://stackoverflow.com/q/48233868
tags question: http://stackoverflow.com/q/48265555
tags question: http://stackoverflow.com/q/48246110
tags question: http://stackoverflow.com/q/48322058
tags question: http://stackoverflow.com/q/48233796
tags question: http://stackoverflow.com/q/48285191
tags question: http://stackoverflow.com/q/48201057
tags question: http://stackoverflow.com/q/48177753
tags question: http://stackoverflow.com/q/48251646
tags question: http://stackoverflow.com/q/48217182
tags question: http://stackoverflow.com/q/48298074
tags question: http://stackoverflow.com/q/48217706
tags question: http://stackoverflow.com/q/48237282
tags question: http://stackoverflow.com/q/48327398
tags question: http://stackoverflow.com/q/48298807
tags question: http://stackoverflow.com/q/48316055
tags question: http://stackoverflow.com/q/48312791
tags question: http://stackoverflow.com/q/48205540
tags question: http://stackoverflow.com/q/48251032
tags question: http://stackoverflow.com/q/48274890
tags question: http://stackoverflow.com/q/48195126
tags question: http://stackoverflow.com/q/48249253
tags question: http://stackoverflow.com/q/48259680
tags question: http://stackoverflow.com/q/48184200
tags question: http://stackoverflow.com/q/48260253
tags question: http://stackoverflow.com/q/48205775
tags question: http://stackoverflow.com/q/48262517
tags question: http://stackoverflow.com/q/48286609
tags question: http://stackoverflow.com/q/48302857
tags question: http://stackoverflow.com/q/48269790
tags question: http://stackoverflow.com/q/48305356
tags question: http://stackoverflow.com/q/48227100
tags question: http://stackoverflow.com/q/48309840
tags question: http://stackoverflow.com/q/48260084
tags question: http://stackoverflow.com/q/48189736

http://stackoverflow.com/q/48216978
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/48216994
has title: Pandas inverse of pivot table
answer count: 1
has body: I have a DataFrame (e.g., df_p) which has already converted into a pivot table: import pandas as pd df = pd.DataFrame({'start_year':[2000, 2001, 2002], 'end_year':[2010, 2011, 2012], 'price':[1.0, 2.0, 3.0]}) # end_year price start_year # 0 2010 1.0 2000 # 1 2011 2.0 2001 # 2 2012 3.0 2002 df_p = df.pivot('start_year', 'end_year', 'price') # end_year 2010 2011 2012 # start_year # 2000 1.0 NaN NaN # 2001 NaN 2.0 NaN # 2002 NaN NaN 3.0 How should I convert df_p back to df?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83416036
accepted answer: http://stackoverflow.com/a/48216994
has comment: http://stackoverflow.com/comment/83419368
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3

http://stackoverflow.com/comment/83488792
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48253140
has text: ahhh got it, thanks. I missed the obvious, there are no quotes around lloyd, alice, tyler in the students list []. So clearly they are referencing other objects. Thank you for pointing that out. Now it's clearer to me
type: AnswerComment

http://stackoverflow.com/comment/83546609
has text: What have you tried so far? Can you provide a sample of the input data? Why is the dictionary defined this way, and not with the emoji as the keys, which seems more logical given your use case?
type: Comment
comment on: http://stackoverflow.com/q/48281341
score: 0
type: QuestionComment

http://stackoverflow.com/q/48320590
has title: Django REST "GET" query params serializer
tagged with: python
linked to: http://stackoverflow.com/q/16870663
favorite count: 0
score: 2
linked to: http://stackoverflow.com/q/25341945
has comment: http://stackoverflow.com/comment/83627795
upvote count: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83626430
tagged with: django
has body: I want to receive get query and filter dataset with query params (if present). I'm currently using dumb method listed below. In this case I don't like the fact it's not checking that dates is actually could be parsed. In another method I may want to receive only numeric string which could be parsed to int. Is there some cool pythonic way to do it without writing a bunch of boilerplate code? class TrackList(APIView): @token_required def get(self, request, pk, **kwargs): # read query params date_from = self.request.query_params.get('date_from') date_to = self.request.query_params.get('date_to') # if present then filter if date_from and date_to: points = Track.objects.filter(user_id=pk, date__range=[date_from, date_to]) # otherwise don't filter else: points = Track.objects.filter(user_id=pk) points.order_by('date') serializer = TrackListSerializer(points, many=True) return Response(serializer.data, status=status.HTTP_200_OK) UPD: The question is not actually about dateutil.parser, it is about general query params parser. Maybe I should use Django rest serializers?
has comment: http://stackoverflow.com/comment/83626391
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48322448
has answer: http://stackoverflow.com/a/48322448
has comment: http://stackoverflow.com/comment/83626419

http://stackoverflow.com/comment/83573140
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48233427
type: QuestionComment
has text: also: how big is your filed unzipped? you basically keep the file in memory (at least the id (line[7]), and line[4] and line[5] from which you say they are "long"). Maybe you run into RAM saturation?

http://stackoverflow.com/a/48316241
upvote count: 3
score: 3
downvote count: 0
type: Answer
has body: the problem was solved with a 64-bit python interpreter. Thank you Jiaaro!
answers question: http://stackoverflow.com/q/48259461

web-scraping
tags question: http://stackoverflow.com/q/48281000
tags question: http://stackoverflow.com/q/48215623
tags question: http://stackoverflow.com/q/48176377
tags question: http://stackoverflow.com/q/48222941
tags question: http://stackoverflow.com/q/48216663
tags question: http://stackoverflow.com/q/48239112
tags question: http://stackoverflow.com/q/48224350
tags question: http://stackoverflow.com/q/48288376
tags question: http://stackoverflow.com/q/48226763
tags question: http://stackoverflow.com/q/48313021
tags question: http://stackoverflow.com/q/48194230
tags question: http://stackoverflow.com/q/48185476
tags question: http://stackoverflow.com/q/48193010
tags question: http://stackoverflow.com/q/48324107
tags question: http://stackoverflow.com/q/48289959
tags question: http://stackoverflow.com/q/48329534
tag name: web-scraping
tags question: http://stackoverflow.com/q/48270466
tags question: http://stackoverflow.com/q/48277281
tags question: http://stackoverflow.com/q/48176802
tags question: http://stackoverflow.com/q/48329753
tags question: http://stackoverflow.com/q/48278071
tags question: http://stackoverflow.com/q/48312123
tags question: http://stackoverflow.com/q/48199188
tags question: http://stackoverflow.com/q/48254058
tags question: http://stackoverflow.com/q/48235445
tags question: http://stackoverflow.com/q/48195079
type: Tag
tags question: http://stackoverflow.com/q/48273472
tags question: http://stackoverflow.com/q/48206402
tags question: http://stackoverflow.com/q/48215222
tags question: http://stackoverflow.com/q/48208307
tags question: http://stackoverflow.com/q/48270742
tags question: http://stackoverflow.com/q/48178289
tags question: http://stackoverflow.com/q/48216114
tags question: http://stackoverflow.com/q/48242928
tags question: http://stackoverflow.com/q/48318730
tags question: http://stackoverflow.com/q/48284024
tags question: http://stackoverflow.com/q/48197776
tags question: http://stackoverflow.com/q/48326551
tags question: http://stackoverflow.com/q/48285971
tags question: http://stackoverflow.com/q/48264917
tags question: http://stackoverflow.com/q/48208905
tags question: http://stackoverflow.com/q/48313615
tags question: http://stackoverflow.com/q/48187592
tags question: http://stackoverflow.com/q/48176665
tags question: http://stackoverflow.com/q/48208220
tags question: http://stackoverflow.com/q/48235825
tags question: http://stackoverflow.com/q/48240345
tags question: http://stackoverflow.com/q/48236581
tags question: http://stackoverflow.com/q/48286382
tags question: http://stackoverflow.com/q/48269968
tags question: http://stackoverflow.com/q/48183599
tags question: http://stackoverflow.com/q/48197250

http://stackoverflow.com/q/48227848
tagged with: tuples
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48229206
has comment: http://stackoverflow.com/comment/83437578
has comment: http://stackoverflow.com/comment/83437683
has comment: http://stackoverflow.com/comment/83438620
has answer: http://stackoverflow.com/a/48229206
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83437651
favorite count: 0
has comment: http://stackoverflow.com/comment/83438816
type: Question
has title: Using for / list comprehension for creating a tuple from any amount of other tuples
has comment: http://stackoverflow.com/comment/83439916
tagged with: robotics
upvote count: 1
tagged with: python
tagged with: list-comprehension
has body: With the following code I'm looking at how to create the TRACKS[0] and ARM[0] tuples (or even a whole set, e.g. ARM), as they are very similar - I think something like a list comprehension would work (as I'm picturing a for each loop). # MOTORS: all, m1, m2, m3, m4, m5 (+, -) MOTORS = ( ( (0b01010101, 0b00000001, 0b00000000), (0b10101010, 0b00000010, 0b00000000) ), ( (2**0, 0, 0), (2**1, 0, 0) ), ( (2**2, 0, 0), (2**3, 0, 0) ), ( (2**4, 0, 0), (2**5, 0, 0) ), ( (2**6, 0, 0), (2**7, 0, 0) ), ( (0, 2**0, 0), (0, 2**1, 0) ) ) LED = (0,0,1) # TRACKS: both, left, right (forward, reverse) TRACKS = ( ( (MOTORS[4][0][0] | MOTORS[5][0][0], MOTORS[4][0][1] | MOTORS[5][0][1], MOTORS[4][0][2] | MOTORS[5][0][2]), (MOTORS[4][1][0] | MOTORS[5][1][0], MOTORS[4][1][1] | MOTORS[5][1][1], MOTORS[4][1][2] | MOTORS[5][1][2]) ), MOTORS[4], MOTORS[5] ) # ARM: all, elbow, wrist, grip (forward/open, reverse/close) ARM = ( ( (MOTORS[1][0][0] | MOTORS[2][0][0] | MOTORS[3][0][0], MOTORS[1][0][1] | MOTORS[2][0][1] | MOTORS[3][0][1], MOTORS[1][0][2] | MOTORS[2][0][2] | MOTORS[3][0][2]), (MOTORS[1][1][0] | MOTORS[2][1][0] | MOTORS[3][1][0], MOTORS[1][1][1] | MOTORS[2][1][1] | MOTORS[3][1][1], MOTORS[1][1][2] | MOTORS[2][1][2] | MOTORS[3][1][2]) ), MOTORS[1], MOTORS[2], MOTORS[3] ) def motormsk (motor_id, motor_config): return (motor_config[motor_id][0][0] | motor_config[motor_id][1][0], motor_config[motor_id][0][1] | motor_config[motor_id][1][1], motor_config[motor_id][0][2] | motor_config[motor_id][1][2]) The motormsk function does a logical OR to create a mask of the values passed in and I thought that it could be used recursively to generate the mask, the function would need to take any number of tuples. This configuration is used to interface with a USB motor control interface (as in the OWI-535 Robotic Arm Edge), that I'm adding virtual system config (ARM and TRACKS) to allow me to change them around / re-purpose them easily. USAGE: sending MOTORS[0][0] starts all motors forward, TRACKS[0][1…

http://stackoverflow.com/comment/83485718
has text: I want to take the value from the dictionary. Let's say 0.5, 2, 1, 2.5, 3. Sort them into ascending order so 0.5, 1, 2, 2.5, 3. Then round the first half of floats (0.5) up regardless and second half of floats (2.5) down regardless. But I need them to remain assigned to the same key. The above code does this, but assigns values to a different key which isn't what I want.
type: AnswerComment
comment on: http://stackoverflow.com/a/48251338
score: 0
type: Comment

http://stackoverflow.com/q/48284982
possible better answer: http://stackoverflow.com/a/48285123
accepted answer: http://stackoverflow.com/a/48285034
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83554116
has body: x=1 type(x) x="sss" type(x) The Output is only str.. Why aren't there two outputs; int and str? Im using Jupyter notebook
answer count: 3
score: -4
has title: Python Type()function returning only Changed Variable Type
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48285034
downvote count: 4
has comment: http://stackoverflow.com/comment/83554412
upvote count: 0
has comment: http://stackoverflow.com/comment/83554127
has answer: http://stackoverflow.com/a/48287954
has comment: http://stackoverflow.com/comment/83554112
tagged with: python
has comment: http://stackoverflow.com/comment/83554394
has comment: http://stackoverflow.com/comment/83554338
has answer: http://stackoverflow.com/a/48285123

http://stackoverflow.com/comment/83436257
comment on: http://stackoverflow.com/a/48227027
score: 0
type: Comment
type: AnswerComment
has text: @Dark, hmm, i think i'd need a bigger sample data set to play with... Is it much slower compared to `str.get_dummies()` approach?

http://stackoverflow.com/q/48279091
upvote count: 3
answer count: 1
downvote count: 0
has body: Looking to use a include a redis server for storing application specific data with my pyinstaller bundled application. Before getting into it hands-on, need some guidance. Are these the steps to follow for it? (1) Bundle redis-server executable. And run it as a standalone application via some script in my bundled package. (2) Use redis client packages in python to connect to the redis-server I guess (2) should surely work. But is there any easy way of doing (1).
favorite count: 0
has title: Bundling redis server with pyinstaller
type: Question
tagged with: redis
tagged with: pyinstaller
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/41251850
has answer: http://stackoverflow.com/a/48312528
tagged with: python
score: 3

http://stackoverflow.com/comment/83540398
score: 0
type: Comment
type: QuestionComment
has text: This looks almost like a virtual machine for python. I plan on taking this program, and just being able to jump on a fresh install of windows, and open an executable file of my program that does not require the user to have Python or any referenced libraries installed. @Timothy Wong
comment on: http://stackoverflow.com/q/48278418

http://stackoverflow.com/a/48322111
answers question: http://stackoverflow.com/q/48322058
downvote count: 0
type: Answer
has body: ''.join(map(max, a, b)) Demo: &gt;&gt;&gt; a = '0 8 9' &gt;&gt;&gt; b = '0 * 5 6' &gt;&gt;&gt; ''.join(map(max, a, b)) '0 * 8 9'
score: 3
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48322058

http://stackoverflow.com/q/48216057
type: Question
has comment: http://stackoverflow.com/comment/83415794
has title: Turn list of dictionaries into pandas dataframe
has comment: http://stackoverflow.com/comment/83414202
has comment: http://stackoverflow.com/comment/83415644
score: -2
accepted answer: http://stackoverflow.com/a/48216720
has comment: http://stackoverflow.com/comment/83415237
tagged with: python
has body: I have a list of dictionaries of stock tickers and dates that looks like the below. I'd like to make a pandas dataframe with the ticker on the left and the date on the top. How can I do that? [{'GOOG': [{'01-10-2018': '0.08388400'}, {'01-11-2018': '0.08787100'}]}, {'AAPL': [{'01-10-2018': '0.01660500'}, {'01-11-2018': '0.01715700'}]}]
type: AnsweredQuestion
tagged with: pandas
upvote count: 0
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/48216720
favorite count: 0

http://stackoverflow.com/comment/83470355
score: 0
type: Comment
type: QuestionComment
has text: why dont you use [numpy matrix](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matrix.html)?
comment on: http://stackoverflow.com/q/48243928

http://stackoverflow.com/comment/83638530
type: AnswerComment
comment on: http://stackoverflow.com/a/48326438
score: 0
has text: This worked perfectly as described. Nice answer with complete example and image.
type: Comment

image
tags question: http://stackoverflow.com/q/48280845
tags question: http://stackoverflow.com/q/48255038
tags question: http://stackoverflow.com/q/48220817
tags question: http://stackoverflow.com/q/48268522
tags question: http://stackoverflow.com/q/48211632
tags question: http://stackoverflow.com/q/48218934
tags question: http://stackoverflow.com/q/48323556
tags question: http://stackoverflow.com/q/48288081
tags question: http://stackoverflow.com/q/48308776
tags question: http://stackoverflow.com/q/48283090
tags question: http://stackoverflow.com/q/48287812
tags question: http://stackoverflow.com/q/48275038
tags question: http://stackoverflow.com/q/48267084
tags question: http://stackoverflow.com/q/48266869
tags question: http://stackoverflow.com/q/48259497
tags question: http://stackoverflow.com/q/48299218
tags question: http://stackoverflow.com/q/48313282
tags question: http://stackoverflow.com/q/48265569
tags question: http://stackoverflow.com/q/48263961
tags question: http://stackoverflow.com/q/48259239
tags question: http://stackoverflow.com/q/48226260
tags question: http://stackoverflow.com/q/48210544
tags question: http://stackoverflow.com/q/48294464
tag name: image
tags question: http://stackoverflow.com/q/48257639
tags question: http://stackoverflow.com/q/48279745
tags question: http://stackoverflow.com/q/48180327
tags question: http://stackoverflow.com/q/48191738
tags question: http://stackoverflow.com/q/48229849
type: Tag
tags question: http://stackoverflow.com/q/48229318

http://stackoverflow.com/comment/83573049
score: 0
has text: @wim That makes sense. Added non-test method.
comment on: http://stackoverflow.com/q/48292332
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48447182
has body: So, thanks to MuertoExcobito i succeed doing my check and i would like to add to his answer that if you want to get the correct PID as written in the task manager. that would work : hwnd = ctypes.windll.user32.GetForegroundWindow() lpdw_process_id = ctypes.c_ulong() result = ctypes.windll.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(lpdw_process_id)) process_id = lpdw_process_id.value print process_id
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48217182

http://stackoverflow.com/comment/83517455
has text: There’s nothing that shouts “inefficient” in your code. If by “very large” lists, do you mean millions or billions of items? If so, you’re probably best off either 1) using a library (built in or third party) that can help you do some of this in C code, which will be faster. `itertools` might work. 2) rewriting this in a compiled language, such as C, C++, or Java. Plain Python is inherently slower than these languages, and writing a small chunk of code might fix your problem.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48266566
type: QuestionComment

http://stackoverflow.com/q/48243928
accepted answer: http://stackoverflow.com/a/48245516
has comment: http://stackoverflow.com/comment/83470368
has body: Suppose I want to compute the quadratic form x^T A y, where x and y are NumPy vectors, and I have stored A as a SciPy csc_matrix for efficiency. It seems that one way to perform the computation is (x * A).dot(y) since SciPy uses * for matrix products, and NumPy uses .dot instead. While this approach gives me the correct answer, it seems rather counter-intuitive to me, and I wonder if there's a more readable/efficient approach?
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48245516
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83470531
has comment: http://stackoverflow.com/comment/83495639
has comment: http://stackoverflow.com/comment/83470355
has title: Matrix multiplication of a sparse SciPy matrix with two NumPy vectors
has comment: http://stackoverflow.com/comment/83495655
tagged with: scipy
has comment: http://stackoverflow.com/comment/83470423
favorite count: 0
tagged with: matrix-multiplication
type: Question
tagged with: numpy
score: 2
upvote count: 2

http://stackoverflow.com/comment/83646185
score: 0
type: Comment
type: QuestionComment
has text: Sorry I am not being clear, it is just hard to explain. As you can see in the picture I linked above, there are more products that starts with "Sta" then the one that is actually shown in the box. However, that is the only one that is shown in the box because its manufacturer also starts with "Sta". I need the QCompleter to ignore the first word in the string list that I supply.
comment on: http://stackoverflow.com/q/48330016

http://stackoverflow.com/q/48319753
type: Question
tagged with: matplotlib
tagged with: python
has body: I am trying to do a simple plot interface that allows me to click to add points to a list and then with another key or another click, call the triangulation of those points. Matplotlib offers a small example for adding points to a line but I dont know how to make it so that I simply add points to a list and then call a function to triangulate from matplotlib import pyplot as plt class LineBuilder: def __init__(self, line): self.line = line self.xs = list(line.get_xdata()) self.ys = list(line.get_ydata()) self.cid = line.figure.canvas.mpl_connect('button_press_event', self) def __call__(self, event): print('click', event) if event.inaxes!=self.line.axes: return self.xs.append(event.xdata) self.ys.append(event.ydata) self.line.set_data(self.xs, self.ys) self.line.figure.canvas.draw() fig = plt.figure() ax = fig.add_subplot(111) ax.set_title('click to build line segments') line, = ax.plot([0], [0]) # empty line linebuilder = LineBuilder(line) plt.show() I use scikit delunay triangulation import numpy as np from scipy.spatial import Delaunay points=np.array([[134,30],[215,114],[160,212],[56,181],[41,78]]) tri = Delaunay(points) plt.triplot(points[:,0], points[:,1], tri.simplices.copy()) plt.plot(points[:,0], points[:,1], 'o') plt.show() Thank you
has comment: http://stackoverflow.com/comment/83624985
score: 2
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48320193
accepted answer: http://stackoverflow.com/a/48320193
has title: Interactive point triangulation with Python and Matplotlib
downvote count: 0
tagged with: interactive
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83625141

http://stackoverflow.com/q/48228755
has answer: http://stackoverflow.com/a/62918843
has comment: http://stackoverflow.com/comment/83441465
answer count: 1
has comment: http://stackoverflow.com/comment/84450114
has comment: http://stackoverflow.com/comment/83439528
score: 0
has body: I need a little help with the code below, I have been tasked with changing the insertion sort to use the given binary search function. def binarySearch(aList, start, end, value): #Return the position where value is or should be inserted. while start &lt;= end: mid = (start + end) // 2 if aList[mid] == value: return mid if value &lt; aList[mid]: end = mid - 1 else: start = mid + 1 return start def insertionSort(aList): #Sort aList in ascending order. for index in range(1, len(aList)): key = aList[index] pos = index while pos &gt; 0 and aList[pos - 1] &gt; key: aList[pos] = aList[pos - 1] pos = pos - 1 aList[pos] = key The code I am using to test the function is: numbers = [71, 32, 22, 19, 18, 1, 15, 40] insertionSort(numbers) print(numbers) Any help is appreciated as I am having a mind blank
has title: Insertion sort using binary search in python
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/83440606
type: UnansweredQuestion

http://stackoverflow.com/q/48297082
tagged with: odoo-10
tagged with: odoo
has title: how to edit discount field access rights?
upvote count: 1
has answer: http://stackoverflow.com/a/48297414
downvote count: 1
favorite count: 0
type: Question
has body: I want to make sales manager only one who can give discounts in sales order line in odoo 10. Edit: I need to make it displayed for all but only one who can modify I have created the logic for discount and digits... discount = fields.Float(string='Discount (%)', digits=dp.get_precision('Discount'), groups="Sales Manager", default=0.0) Any Suggestions will be helpful Thanks!
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48297511
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/48297504
has comment: http://stackoverflow.com/comment/83584209
answer count: 3

http://stackoverflow.com/a/67223576
type: Answer
downvote count: 0
has body: With Arrow it's quite easy actually import arrow def get_quarter_start_end_dates(dt, quarters_ago): date_in_past = arrow.get(dt).shift(quarters=-quarters_ago) quarter_start_date = date_in_past.floor('quarter').datetime quarter_end_date = date_in_past.ceil('quarter').datetime return quarter_start_date, quarter_end_date
answers question: http://stackoverflow.com/q/48234157
upvote count: 1
score: 1

http://stackoverflow.com/a/48235109
type: Answer
accepted answer of: http://stackoverflow.com/q/48234851
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48234851
has comment: http://stackoverflow.com/comment/83520610
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83520914
has body: Create a mask for your condition. Select the rows to be removed based on the condition using boolean indexing. Then reassign df1 to by inverting the mask using ~ (not). mask = df1['letter'] == 'a' removed_rows = df1[mask] df1 = df1[~mask] &gt;&gt;&gt; df1 letter 1 b 2 c 3 d &gt;&gt;&gt; removed_rows letter 0 a 4 a 5 a

http://stackoverflow.com/comment/83434850
type: Comment
type: QuestionComment
has text: Why isn't `list` field `vlen`? I haven't played with `vlen` much except for the linked answer (and maybe 1 or 2 newer), but I think the resulting dtype has to be compatible with both numpy and hdf5.
comment on: http://stackoverflow.com/q/48221841
score: 0

python-imageio
type: Tag
tags question: http://stackoverflow.com/q/48302783
tag name: python-imageio

http://stackoverflow.com/comment/83553907
has text: While I feel with you and emphatically see the obvious relation between extremely deeply nested XML documents and AUTOSAR, you should really consider explaining that relation or (because it is not really required for understanding your question) deleting the AUTOSAR tag. You could also add a desired result.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48278144

http://stackoverflow.com/a/48304473
has comment: http://stackoverflow.com/comment/83593969
has comment: http://stackoverflow.com/comment/83594332
type: Answer
has comment: http://stackoverflow.com/comment/83594249
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/83594141
score: 4
has comment: http://stackoverflow.com/comment/83594068
has body: A simple List comprehension using slicing : &gt;&gt;&gt; [ var[:i]+var[i+1:] for i,_ in enumerate(var) ] Or &gt;&gt;&gt; [ var[:i]+var[i+1:] for i in range(len(var)) ] #driver values : IN : var = [0, 1, 2, 3, 4] OUT : [[1, 2, 3, 4], [0, 2, 3, 4], [0, 1, 3, 4], [0, 1, 2, 4], [0, 1, 2, 3]]
answers question: http://stackoverflow.com/q/48304411
has comment: http://stackoverflow.com/comment/83594020

http://stackoverflow.com/comment/83614517
score: 0
type: Comment
has text: glad could help you bro :) @yuchenhuang
comment on: http://stackoverflow.com/a/48314203
type: AnswerComment

http://stackoverflow.com/comment/83361265
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48190358
has text: What's your question?
score: 1

http://stackoverflow.com/comment/83620200
has text: OH ,What a stupid mistake. Thank you so much!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48317302

http://stackoverflow.com/a/48406064
has body: OMG i've found the answer myself. I just don't get it why :D The function have to be called outside the If clause... if message.UnRead == True: #do something magical message.UnRead = False message.Move(donebox) does Python check the clause for every line of code? I've just developed some things in Java an there is the clause only checked once...
has comment: http://stackoverflow.com/comment/84951748
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48328486
has comment: http://stackoverflow.com/comment/83846604
answers question: http://stackoverflow.com/q/48328486
score: 3
has comment: http://stackoverflow.com/comment/84749944
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/48266472
has comment: http://stackoverflow.com/comment/83526380
has comment: http://stackoverflow.com/comment/83544132
has comment: http://stackoverflow.com/comment/83526292
score: 0
has comment: http://stackoverflow.com/comment/83521113
has body: my user is interacting with a gtk2 GUI (Presenter/View/Model), and I want to let them import several records in the database, keep the interface responsive, let the user cancel the operation at any time, and when the longish operation is complete, let the user decide whether or not to commit the whole import. I'm doing this by running the import action in a separate thread, the GUI stays responsive, in the separate thread I create database objects, add them to the session (owned by the presenter), the importing thread adds log records to a gtk.ListStore, linked to a gtk.TreeView, and this is fine as far as the GUI is concerned. When the thread finalises, the 'ok' button is enabled. Since this is part of a fairly large program I've adopted, there's settings I can't change without reviewing the whole lot. One of them is autoflush, which is disabled in all sessions. now I have this smallish example with a surprising behaviour: from sqlalchemy import Column, Unicode, Integer from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Location(Base): __tablename__ = 'location' code = Column(Unicode(64), index=True, primary_key=True) def __init__(self, code=None): self.code = code def __repr__(self): return self.code from sqlalchemy import create_engine engine = create_engine('sqlite:///joindemo.db') Base.metadata.create_all(engine) from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine, autoflush=False) session = Session() session.query(Location).delete() session.commit() us = session.query(Location).all() print us def run_me_in_other_thread_1(): session.autoflush = True u1 = Location(code=u'mario') u2 = Location(code=u'silla') session.add_all([u1, u2]) session.autoflush = False def run_me_in_other_thread_2(): u1 = Location(code=u'mario') u2 = Location(code=u'silla') session.add_all([u1, u2]) session.flush() import threading t = threading.Thread(target=run_me_in_other_thread_1) t.start() t.join() session.commit() us = sessi…
has answer: http://stackoverflow.com/a/48270938
has comment: http://stackoverflow.com/comment/83547371
has comment: http://stackoverflow.com/comment/83547057
tagged with: multithreading
tagged with: sqlite
answer count: 1
linked to: http://stackoverflow.com/q/34009296
has comment: http://stackoverflow.com/comment/83525617
has comment: http://stackoverflow.com/comment/83520970
has title: how are autoflush and flush different
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/83524396
has comment: http://stackoverflow.com/comment/83533466
type: Question
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4201455
tagged with: python
has comment: http://stackoverflow.com/comment/83526990

http://stackoverflow.com/q/48250092
type: Question
has comment: http://stackoverflow.com/comment/83483134
has answer: http://stackoverflow.com/a/54584537
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83483192
has comment: http://stackoverflow.com/comment/83482812
tagged with: python
score: -1
tagged with: flask
answer count: 2
tagged with: angular
upvote count: 0
has comment: http://stackoverflow.com/comment/83487284
has title: How to upload excel XLSX file to python flask api from angular2
has body: How do I upload a excel .xlsx file to python flask from angular2? I upload something but it can't be read when I open the excel file. html for upload dialog: Upload file Submit ts code for sending post to the api: fileChange(event){ let reader = new FileReader(); let file = event.target.files[0]; this.filename = file.name; reader.readAsDataURL(file); reader.onload = () => { let data = atob(reader.result.toString().split(',')[1]); this.is_file=false; var token = localStorage.getItem('token') let headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'Access-Control-Allow-Origin':'*', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Methods': 'POST', 'Authorization': 'bearer ' + token }); let options = new RequestOptions({ headers: headers }); options.responseType = ResponseContentType.Blob; let ran = Math.floor(Math.random() * 10000) + 1; this.http.post(environment.API_URL + '/test/model/expsoure/excel/' + 'model_id' + '?cache=' + ran.toString(),data,options) .subscribe(service_data => { }); } }// end fileChange Python code for saving data: class exposureExcelId(Resource): method_decorators = [jwt_required()] def post(self,mid): user_id = str(current_identity.id) f = open('/Users/data/wtf.xlsx','wb') f.write(request.data) f.close() Error I get when I try and load the file from the upload in excel is: excel could not open wtf.xlsx because some of the content is unreadable
has answer: http://stackoverflow.com/a/48253002
downvote count: 1
favorite count: 0

merge
type: Tag
tags question: http://stackoverflow.com/q/48202174
tags question: http://stackoverflow.com/q/48281593
tags question: http://stackoverflow.com/q/48254692
tag name: merge
tags question: http://stackoverflow.com/q/48202955
tags question: http://stackoverflow.com/q/48253360
tags question: http://stackoverflow.com/q/48312567
tags question: http://stackoverflow.com/q/48312790
tags question: http://stackoverflow.com/q/48209667
tags question: http://stackoverflow.com/q/48224916

http://stackoverflow.com/comment/83353195
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48186358
has text: from 2007-1-1 to 2007-12-31 is just fine.

http://stackoverflow.com/q/48273631
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83562423
has comment: http://stackoverflow.com/comment/83564741
favorite count: 0
has answer: http://stackoverflow.com/a/78251662
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/78251662
has title: How to manipulate VCF contacts using VObject?
has body: suppose i have built a VObject called vobj (e.g., built via vobject.readComponents(vcfStr)) and want to add a new key:value pair to it: print('k=%s v=%s' % (k,v)) try: stmnt1 = "vobj.add('%s')" % (k) print('stmnt1:"%s"' % stmnt1) eval(stmnt1) print('vobj after add\n'+20*'#'+'\n') vobj.prettyPrint() stmnt2 = "vobj.%s.value = '%s'" % (k,v) print('\n'+20*'#'+('\nstmnt2:"%s"' % stmnt2)) eval(stmnt2) except Exception as e: print('wazzup?!',e) all the extra prints and the try:except are because i can't make it work! here's the output produced: k=bday v=1931-02-10 stmnt1:"vobj.add('bday')" vobj after add #################### VCARD VERSION: 3.0 PRODID: -//Apple Inc.//Mac OS X 10.12.3//EN N: Foo Bar FN: Foo Bar EMAIL: foo@bar.com params for EMAIL: TYPE ['INTERNET', 'WORK', 'pref'] ... BDAY: #################### stmnt2:"vobj.bday.value = '1931-02-10'" wazzup?! invalid syntax (&lt;string&gt;, line 1) i have three specific questions: VObject makes use of object.attribute "dot" notation, and the only way i've found to handle arbitrary key names is using eval(). there must be a more pythonic way? evaluation of the first statement stmnt1 works, and changes vobj as expected, producing an unbound slot for BDAY. but stmnt2 fails with bad syntax and i don't know why. i have also tried stmnt2 = "vobj.%s.value = ['%s']" % (k,v), making the value a list, because of the two alternatives on the VObject README: j.email.value = 'jeffrey@osafoundation.org' ... j.org.value = ['Open Source Applications Foundation'] does it matter whether a string atom or list is used?
linked to: http://stackoverflow.com/q/2220699
tagged with: vobject

http://stackoverflow.com/comment/94806489
type: QuestionComment
comment on: http://stackoverflow.com/q/48283875
score: 0
type: Comment
has text: For the record: Pycharm provides a data source properties dialogue. If for some reason it is out of sync with settings, use the properties "test connection" button to fix the issue

http://stackoverflow.com/comment/83375080
has text: Can we kindly ask why you need to retain quotes? Such values will be considered string objects.
score: 0
comment on: http://stackoverflow.com/q/48195202
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48231089
type: AnsweredQuestion
score: 0
has body: For a part of a Python exam I have coming up, I have to write the output of given code as it would be executed in a Python shell. I'm having trouble understanding this question: alist = [1] * 10 #[1, 1, 1, 1, 1, 1, 1, 1, 1, 1] for i in range(1, 10): #from 1 up to and not including 10 - 1 2 3 4 5 6 7 8 9 alist[i] += alist[i-1] print(alist) My understanding of this question is for each i in range(1, 10), 1 - 9, the index of i in alist is equal to the index of i + the index of i-1. My original output was: [1, 2, 5, 7, 9, 11, 13, 15, 17] The actual output is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] To try and understand what was happening, I tried replacing the [i-1] with [i] and got the output: [1, 2, 2, 2, 2, 2, 2, 2, 2, 2] I have tried various written outputs to attempt to match the correct answer but I can't seem to find the correct method. If anyone could help me to understand what is happening at alist[i] += alist[i-1] or if my understanding is mistaken elsewhere I would greatly appreciate it.
has comment: http://stackoverflow.com/comment/83444616
answer count: 1
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83444436
accepted answer: http://stackoverflow.com/a/48231339
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83444456
has answer: http://stackoverflow.com/a/48231339
has title: in range() for loop, changing values in a list with indexes
tagged with: python
has comment: http://stackoverflow.com/comment/83444526

http://stackoverflow.com/comment/83395756
has text: Thanks for your help! What can I do if I have letters in my list? For example: data = [ ['A', '-160'], ['B', '-3000'], ['C', '-2'], ['D', '0.27'], ] How can they be ignored?
type: AnswerComment
comment on: http://stackoverflow.com/a/48206064
score: 0
type: Comment

http://stackoverflow.com/q/48230216
has comment: http://stackoverflow.com/comment/83442710
type: Question
has body: I have a function: def csvToList( filename ): with open(filename, 'r') as fp: reader = csv.reader(fp) myList = list(reader) return myList and call it with: fruitList = csvToList('fruit.csv') The contents of fruit.csv is: apple,orange,kiwi,tomato The value of fruitList is a list of lists: 'apple', 'orange', 'kiwi', 'tomato' Why does this code produce a list of lists and not just a simple "flat" list, like this: ['apple', 'orange', 'kiwi', 'tomato']
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/17262256
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83442487
tagged with: import
favorite count: 0
score: -1
has title: Why Does This Code Produce a List of Lists?
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48230248
has comment: http://stackoverflow.com/comment/83442525
downvote count: 2
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/83517825
comment on: http://stackoverflow.com/a/48266482
score: 0
type: Comment
has text: Thanks for the response! I've tried this exactly as is but the same error is returned.
type: AnswerComment

http://stackoverflow.com/q/48300501
tagged with: duplicates
tagged with: python
has answer: http://stackoverflow.com/a/48300546
answer count: 4
possible better answer: http://stackoverflow.com/a/48300601
type: Question
has comment: http://stackoverflow.com/comment/83585443
has comment: http://stackoverflow.com/comment/83585474
has comment: http://stackoverflow.com/comment/83585620
upvote count: 3
has comment: http://stackoverflow.com/comment/83585652
score: 3
downvote count: 0
linked to: http://stackoverflow.com/q/7961363
favorite count: 0
has title: How to remove duplicate tuples from a list in python?
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48300601
has answer: http://stackoverflow.com/a/48300639
linked to: http://stackoverflow.com/q/480214
has body: I have a list that contains list of tuples as follows. mylist = [['xxx', 879], ['yyy', 315], ['xxx', 879], ['zzz', 171], ['yyy', 315]] I want to remove the duplicate tuples from mylist and get an output as follows. mylist = [['xxx', 879], ['yyy', 315], ['zzz', 171]] It seems like set in python does not work for it. mylist = list(set(mylist)) Is there any fast and easy way of doing this in python (perhaps using libraries)?
has answer: http://stackoverflow.com/a/48300720
accepted answer: http://stackoverflow.com/a/48300546

http://stackoverflow.com/comment/83418312
score: 0
type: QuestionComment
has text: It is totally unclear what you're trying to do here. Are you trying to move dataframes?
type: Comment
comment on: http://stackoverflow.com/q/48218076

http://stackoverflow.com/comment/83535368
has text: ... so they want the values of the the `"message"` key to be a *json string* that looks like a tuple of json-objects? EDIT: nope, just as I suspect it, they want a json-array of json-objects...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48275942

http://stackoverflow.com/comment/83418313
comment on: http://stackoverflow.com/q/48214852
type: Comment
type: QuestionComment
score: 0
has text: [Why you don't want to dynamically create variables](http://stupidpythonideas.blogspot.cl/2013/05/why-you-dont-want-to-dynamically-create.html)

http://stackoverflow.com/comment/83513457
has text: Hey @bivouac0, thank you for the answer. I've also asked on CodeReview, here's the [full code](https://codereview.stackexchange.com/questions/185042/parallelize-a-for-loop-that-sums-up-different-elements-from-an-array)
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48193130

http://stackoverflow.com/q/48294434
linked to: http://stackoverflow.com/q/10593651
tagged with: python
has comment: http://stackoverflow.com/comment/83573805
has comment: http://stackoverflow.com/comment/83573773
type: AnsweredQuestion
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48294558
score: 0
has title: Equivalent to dictionary d.items()[0] in Python 3
answer count: 2
duplicate of: http://stackoverflow.com/q/10593651
has answer: http://stackoverflow.com/a/48294558
has body: Say I have a large dictionary d and I want to display some random element (say my terminal will crash if I try to __repr__ the whole thing). In Python 2 I would call d.items()[0]; what do I do in Python 3 ... is the Pythonic equivalent next(iter(d.items()))?
has comment: http://stackoverflow.com/comment/83573761
type: Question
accepted answer: http://stackoverflow.com/a/48294513
has answer: http://stackoverflow.com/a/48294513

http://stackoverflow.com/comment/83329905
type: QuestionComment
has text: trying to figure out if the search query is a number
score: 0
comment on: http://stackoverflow.com/q/48174955
type: Comment

http://stackoverflow.com/q/48271394
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48271425
tagged with: sprite
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83526790
score: 1
tagged with: python
tagged with: pygame
has body: So I have a function that keeps the sprite from moving off screen which is:` def move_extent(self, x, y): if self.rect.right &gt; 700: self.rect.right = 700 elif self.rect.left &lt; 0: self.rect.left = 0 elif self.rect.y &lt; 275: self.rect.y = 275 elif self.rect.y &gt; 275: self.rect.y = 275` And it keeps the sprite from moving past the x coords, and for the most part, the y coords. But if the sprite is on either the far left or far right (0 or 700 x), it will still go up or down. Heres the main game loop: while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True keys = pygame.key.get_pressed() if keys[pygame.K_a]: protag.moveLeft(3) if keys[pygame.K_d]: protag.moveRight(3) if keys[pygame.K_w]: protag.moveUp(3) if keys[pygame.K_s]: protag.moveDown(3) all_sprites_list.update() screen.blit(background, (0, 0)) all_sprites_list.draw(screen) move_extent(protag, x_coord, y_coord) pygame.display.flip() clock.tick(60) pygame.quit()
favorite count: 0
type: Question
has title: PygameSprites moving off screen even with function setting parameters not to
accepted answer: http://stackoverflow.com/a/48271425
answer count: 1

http://stackoverflow.com/q/48327168
type: Question
has body: I am trying to write a piece of C# code which makes use of a small portion of Python code, and then try to output the Python code within my application. The goal is to have a Python RSS, which produces few lines of data and outputs it. I hoped that a C# code would execute this code and capture all of the lines that are produced, but it captures only first one. Here is a sample of what python output looks like: Business Superjumbo jet future secured by Emirates order. A big order from Emirates airline saves the A380 after Airbus threatened to stop making the plane. Business Banks create funds for firms hit by Carillion collapse. Lloyds and RBS will provide cash for struggling small firms as Nationwide takes on Carillion staff. Politics Theresa May meets Macron with pledge of extra £44m for border. The UK pledges an extra £44m for channel border security ahead of the Anglo-French summit. This is a short excerpt of the produced data, but C# ( result variable) only captures first line, sometimes two. Am I doing something wrong or is not possible to get all prints using this method? C# code start.Arguments = "../test/smallWebCrawl.py"; start.UseShellExecute = false;// Do not use OS shell start.CreateNoWindow = true; // We don't need new window start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions) try { using (Process process = Process.Start(start)) { using (StreamReader reader = process.StandardOutput) { string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script //Console.WriteLine(stderr); string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test") Console.WriteLine(result); } } } catch (Exception) { Console.WriteLine("Error. Wrong python path"); }
tagged with: python
accepted answer: http://stackoverflow.com/a/48389413
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48389413
has title: Capture multiline Python output in C#
answer count: 1
tagged with: c#

http://stackoverflow.com/comment/83444418
comment on: http://stackoverflow.com/q/48230590
score: 0
has text: Yeah, it should just be `polls.apps`, not `polls.apps.PollsConfig`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/131570763
type: AnswerComment
has text: You are my ....
score: 0
comment on: http://stackoverflow.com/a/56585740
type: Comment

http://stackoverflow.com/a/48256436
has comment: http://stackoverflow.com/comment/83513485
type: Answer
accepted answer of: http://stackoverflow.com/q/48256315
has comment: http://stackoverflow.com/comment/83509251
has body: Not too beautiful, but to combine both conditions, you can use the | operator. Note the parenthesis around both box conditions. box1_cond = (bottom &lt;= df.lat) &amp; (df.lat &lt;= top) &amp; (left &lt;= df.lng) &amp; (df.lng &lt;= right) box2_cond = (bottom2 &lt;= df.lat) &amp; (df.lat &lt;= top2) &amp; (left2 &lt;= df.lng) &amp; (df.lng &lt;= right2) accounts = df[box1_cond | box2_cond]
has comment: http://stackoverflow.com/comment/83495796
has comment: http://stackoverflow.com/comment/83495735
answers question: http://stackoverflow.com/q/48256315
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83497125

http://stackoverflow.com/q/48239076
tagged with: signals
tagged with: pyqt5
has body: I'm trying to update QLineEdit() with setText. However, that is made through a signal thread class (A) that is able to send every time signal to a widget class (B) [deputy to change the text]. let see an example: classB(QWidget): def __init__(self, parent = None): super(classB, self).__init__(parent) self.lineLayout = QGridLayout() self.textbox = QLineEdit("") self.lineLayout.addWidget(self.textbox, 0, 0) self.setLayout(self.lineLayout) def setInt(self,intVal): # The shell displays this value perfectly print(intVal) # it does not display the change in QWidget that lives in MainWidget self.textbox.setText("val: " + str(intVal)) def paintEvent(self, event): painter = QPainter() painter.begin(self) While the class A's code: classA(QThread): sendVal = QtCore.pyqtSignal(int) def __init__(self,serial): QThread.__init__(self) def do_stuff(self): cont = 0 while True: self.sendVal(cont) cont += 1 So we connect the signal: class MainWidget(QtWidgets.QWidget): getClassA = classA() getClassB = classB() getClassA.sendVal.connect(getClassB.setInt) I have observed the following behaviors: The int signal is perfectly received within the [setInt] function of class B; The real problem is that everything that happens inside the setInt function stays in setInt. I can not even change a hypothetical class variable (In def init of classB)
favorite count: 0
tagged with: qlineedit
type: Question
has comment: http://stackoverflow.com/comment/83468198
has title: PyQt5 setText with a signal class
tagged with: python
score: 2
upvote count: 2
tagged with: settext
answer count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48273748
has comment: http://stackoverflow.com/comment/83531743
type: Question
has comment: http://stackoverflow.com/comment/83531922
answer count: 0
type: UnansweredQuestion
tagged with: machine-learning
tagged with: tensorflow
has title: My model trains good, but produces bad MSE?
score: 0
has comment: http://stackoverflow.com/comment/83533545
tagged with: linear-regression
tagged with: python
has body: I am getting very bad number from mine MSE and I do not understand where I am doing wrong. I know I cannot judge by my training but I believe my model is trained well. Optimization Finished! MSE: 3593717153792.000000 Training Time: 81.99638080596924 I hope you can give me an idea where to look and maybe what to do? This is how my model looks like: # Parameters learning_rate = 0.0001 training_epochs = 100 batch_size = 500 display_step = 1 # Network Parameters n_hidden_1 = 480 # 1st layer number of features n_hidden_2 = 240 # 2nd layer number of features n_hidden_3 = 240 # 3rd layer number of features n_hidden_4 = 256 # 4th layer number of features n_out = 1 n_input = X_train.shape[1] total_len = X_train.shape[0] All the layers are with RELU as activation function except the Output layer which is with linear. This is my cost function: cost = tf.reduce_mean(tf.abs(tf.transpose(pred) - y) / y) this is my data testing: pred_y = sess.run(pred, feed_dict={x: X_test}) mse = tf.reduce_mean(tf.abs(tf.transpose(pred_y) - Y_test)) print("MSE: %4f" % sess.run(mse)) My data consists best 59 features (out of 90) and predicts one continuous value only. For training I am using 105566 normalized samples of data. My normalization was done using sklearn: batch_x_norm = preprocessing.scale(batch_x) And my validation set is 13196 samples. Thank you in advance for the help!.

http://stackoverflow.com/comment/83470950
type: QuestionComment
has text: no. not trying to rename. only remove extension
comment on: http://stackoverflow.com/q/48244160
score: 0
type: Comment

http://stackoverflow.com/a/48202266
accepted answer of: http://stackoverflow.com/q/48202174
type: Answer
answers question: http://stackoverflow.com/q/48202174
has comment: http://stackoverflow.com/comment/83386467
has comment: http://stackoverflow.com/comment/83385765
score: 1
has body: This should do: list1=['String-1', 'String-2', 'String-1', 'String-1', 'String-2', 'String-2', 'String-1', 'String-2', 'String-1', 'String-2'] list2=['TEXT-1', 'TEXT-1', 'TEXT-1', 'TEXT-1', 'TEXT-1'] list3=['TEXT-2', 'TEXT-2', 'TEXT-2', 'TEXT-2', 'TEXT-2'] list2chosen,list3chosen = 0,0 finallist = [] for n in list1: if n == "String-1": finallist.append(list2[list2chosen]) list2chosen += 1 elif n == "String-2": finallist.append(list3[list3chosen]) list3chosen += 1 print(finallist)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83386293
upvote count: 1
has comment: http://stackoverflow.com/comment/83386763
has comment: http://stackoverflow.com/comment/83385845

beautifulsoup
tags question: http://stackoverflow.com/q/48247200
tags question: http://stackoverflow.com/q/48280586
tags question: http://stackoverflow.com/q/48199188
tags question: http://stackoverflow.com/q/48310129
tags question: http://stackoverflow.com/q/48254058
tags question: http://stackoverflow.com/q/48291996
tags question: http://stackoverflow.com/q/48318154
tags question: http://stackoverflow.com/q/48300303
type: Tag
tags question: http://stackoverflow.com/q/48271293
tags question: http://stackoverflow.com/q/48325562
tags question: http://stackoverflow.com/q/48252094
tags question: http://stackoverflow.com/q/48208307
tags question: http://stackoverflow.com/q/48197987
tags question: http://stackoverflow.com/q/48230684
tags question: http://stackoverflow.com/q/48176990
tags question: http://stackoverflow.com/q/48226763
tags question: http://stackoverflow.com/q/48178289
tags question: http://stackoverflow.com/q/48329749
tags question: http://stackoverflow.com/q/48318730
tags question: http://stackoverflow.com/q/48265247
tags question: http://stackoverflow.com/q/48190135
tags question: http://stackoverflow.com/q/48197776
tags question: http://stackoverflow.com/q/48268571
tags question: http://stackoverflow.com/q/48180718
tags question: http://stackoverflow.com/q/48310534
tags question: http://stackoverflow.com/q/48264917
tags question: http://stackoverflow.com/q/48246400
tags question: http://stackoverflow.com/q/48176532
tags question: http://stackoverflow.com/q/48208905
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/48313615
tags question: http://stackoverflow.com/q/48281285
tags question: http://stackoverflow.com/q/48329730
tags question: http://stackoverflow.com/q/48329753
tags question: http://stackoverflow.com/q/48176665
tags question: http://stackoverflow.com/q/48248653
tags question: http://stackoverflow.com/q/48312123
tags question: http://stackoverflow.com/q/48314206
tags question: http://stackoverflow.com/q/48272778
tags question: http://stackoverflow.com/q/48225334
tags question: http://stackoverflow.com/q/48288374
tags question: http://stackoverflow.com/q/48273472
tags question: http://stackoverflow.com/q/48281000
tags question: http://stackoverflow.com/q/48270742
tags question: http://stackoverflow.com/q/48293541
tags question: http://stackoverflow.com/q/48237272
tags question: http://stackoverflow.com/q/48199455
tags question: http://stackoverflow.com/q/48216573
tags question: http://stackoverflow.com/q/48303583
tags question: http://stackoverflow.com/q/48194230
tags question: http://stackoverflow.com/q/48296381
tags question: http://stackoverflow.com/q/48180458
tags question: http://stackoverflow.com/q/48326551
tags question: http://stackoverflow.com/q/48193010
tags question: http://stackoverflow.com/q/48253733
tags question: http://stackoverflow.com/q/48255333
tags question: http://stackoverflow.com/q/48272960
tags question: http://stackoverflow.com/q/48200341
tags question: http://stackoverflow.com/q/48180690

http://stackoverflow.com/comment/83485833
comment on: http://stackoverflow.com/a/48251672
has text: Preciously what I needed. Thanks for the quick response!
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83697069
type: QuestionComment
comment on: http://stackoverflow.com/q/48274890
score: 0
has text: A reminder that some emoji consist of more than one Unicode codepoint (involving combining characters and zero width joiners). It should be possible to write a regex to capture that, but it's not going to be trivial (and I'm not even going to attempt the feat).
type: Comment

http://stackoverflow.com/q/48301802
score: 2
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48303037
downvote count: 0
has body: Hi guys I recently discovered spaCY as an interesting way to recognize grammar in sentences, I tried with something easy and it works, but when I try to let it recognize the "it" subject in a short sentence it doesn't work very well, is there a way to improve the accuracy? the sentence I'm talking about is "do you like it?" where "it" is in this case the real subject. When I start the program spaCY recognizes "you" as a subject instead of "it". What is a good way to avoid this kind of "errors"? here's the simple code: import spacy sentence = input('insert sentence: \n\n') nlp = spacy.load('en') sent = sentence doc=nlp(sent) sub_toks = [tok for tok in doc if (tok.dep_ == "nsubj") ] print(sub_toks) print()
tagged with: machine-learning
answer count: 1
favorite count: 0
type: Question
tagged with: python
tagged with: artificial-intelligence
tagged with: recurrent-neural-network
has title: recognize "it" subject in spaCY
accepted answer: http://stackoverflow.com/a/48303037
tagged with: spacy

http://stackoverflow.com/comment/83465323
comment on: http://stackoverflow.com/q/48241302
has text: @PatrickArtner what you suggest is a post that helps those who already know what `zip()` is, and look for something very specific. You had known the answer and thus found a post that answers it as well, but I did not find a post with a similar *question*
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/48215892
has comment: http://stackoverflow.com/comment/83415086
has answer: http://stackoverflow.com/a/48216891
type: UnansweredQuestion
tagged with: linkedin-api
has comment: http://stackoverflow.com/comment/83414320
tagged with: selenium
has comment: http://stackoverflow.com/comment/83413985
type: Question
score: 0
has comment: http://stackoverflow.com/comment/83414023
has answer: http://stackoverflow.com/a/48329391
has comment: http://stackoverflow.com/comment/83414479
has title: Selenium (Python) clicking an element within a frame
has body: I'm having an issue within LinkedIn. Once you click a "Connect" button, a frame comes up that looks like this: I'm trying to click the "Send now" button, which says it's not visible. I've tried to switch frames by every known id/class. The error says that switching frames cannot be satisfied because the frame cannot be found. Anyone know what I'm doing wrong? You can customize this invitation Close <g class="large-icon" style="fill: currentColor"> </g> LinkedIn members are more likely to accept invitations that include a personal note. Add a note Send now I've tried: WebDriverWait(driver, 15).until(EC.visibility_of_element_located(By.XPATH("//butto‌​n[@class='button-pri‌​mary-large ml1']"))) and get this error: TypeError: 'str' object is not callable
tagged with: python
tagged with: frame
answer count: 2

http://stackoverflow.com/q/48302839
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53896243
downvote count: 0
favorite count: 0
has body: Running on a mac I am trying to use browsermob-proxy to monitor connections during python-selenium tests. I downloaded the java implementation 2.1.4 from here and pip installed the python wrapper ( browsermobproxy). The full example code is here (following examples found a lot): from browsermobproxy import Server server = Server("/Users/adietz/Projects/Invest/browsermob/browsermob-proxy-2.1.4/browsermob-dist/src/main/scripts/browsermob-proxy") server.start() proxy = server.create_proxy() from selenium import webdriver profile = webdriver.FirefoxProfile() profile.set_proxy(proxy.selenium_proxy()) driver = webdriver.Firefox(firefox_profile=profile) proxy.new_har("google") driver.get("http://www.google.co.in") proxy.har server.stop() driver.quit() But when running this code with python 3.6.2 gives the following error: Traceback (most recent call last): File "tester1.py", line 3, in &lt;module&gt; server.start() File "/Users/adietz/Projects/Invest/browsermob/browsermob/lib/python3.6/site-packages/browsermobproxy/server.py", line 127, in start raise ProxyServerError("Can't connect to Browsermob-Proxy") Is there a way to fix this error and be able to use browsermob-proxyon a mac?
has title: How to fix "Can't connect to Browsermob-Proxy" on a mac?
tagged with: python
has answer: http://stackoverflow.com/a/56769578
tagged with: browsermob-proxy
type: Question
score: 2
answer count: 2
upvote count: 2

http://stackoverflow.com/a/48312048
accepted answer of: http://stackoverflow.com/q/48311704
has comment: http://stackoverflow.com/comment/83621904
has body: This code will work only if you run python Forum.py in the same directory in which the Forum directory lives. UPD: I recreated your case on my laptop, and everything works fine. Please check the code: Posts.py: index = 'Forum/Topics/index.txt' def loadTopicNames(): with open(index, 'r') as file: data = file.readlines() for row in data: print(row) Forum.py: import Posts Posts.loadTopicNames() index.txt: test text Project directory: $ ls -R Forum Forum.py Posts.py ./Forum: Topics ./Forum/Topics: index.txt Run &amp; output: $ pwd /Users/myuser/Forum $ python Forum.py test text
has comment: http://stackoverflow.com/comment/83633534
has comment: http://stackoverflow.com/comment/83623314
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83627498
has comment: http://stackoverflow.com/comment/83621661
answers question: http://stackoverflow.com/q/48311704
has comment: http://stackoverflow.com/comment/83627934
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83633723
type: Answer

http://stackoverflow.com/comment/83399024
comment on: http://stackoverflow.com/a/48207535
has text: Err, sorry yes I actually missed the part in your post about you wanting to avoid the "visit each key recursively" solution.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48179542
tagged with: python
has comment: http://stackoverflow.com/comment/83341256
has title: Issue with installing xmltodict on python 3.6.3 on Windows 7
linked to: http://stackoverflow.com/q/47459747
score: 0
has answer: http://stackoverflow.com/a/48180669
has body: I want to install xmltodict module on my existing python 3.6.3 on Windows 7 machine. I tried the below steps but getting error. Please help me. Python version: C:\Users\MaS&gt;pythona Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32 Tried the below steps: Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\MaS\AppData\Local\Programs\Python\Python36-32\Scripts&gt;pip.exe install xmltodict Collecting xmltodict Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError '&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x033ACD30&gt;: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/xmltodict/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError'&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x033ACF70&gt;: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/xmltodict/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError'&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x033ACE70&gt;: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/xmltodict/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError'&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x033ACDB0&gt;: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',)': /simple/xmltodict/ Retrying (…
has comment: http://stackoverflow.com/comment/83339825
answer count: 1
has comment: http://stackoverflow.com/comment/83340745
has comment: http://stackoverflow.com/comment/83340661
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83341323
type: UnansweredQuestion

http://stackoverflow.com/comment/83420663
score: 0
type: Comment
type: QuestionComment
has text: @PatrickHaugh that thought had crossed my mind however my google foo is failing me on how to pass the arguments separately, hence I did it this way, could you give me an example or a resource to go read on how to do it correctly?
comment on: http://stackoverflow.com/q/48219403

http://stackoverflow.com/q/48236271
answer count: 0
has comment: http://stackoverflow.com/comment/83455300
tagged with: selenium
duplicate of: http://stackoverflow.com/q/47142311
has comment: http://stackoverflow.com/comment/83457820
type: Question
has body: I have been trying to run my selenium script on a VPS server which as a dedicated RAM of 1GB, but i am always getting error driver = webdriver.Chrome(chrome_options=chrome_options, executable_path='/root/chromedriver') File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/chrome/webdriver.py", line 75, in __init__ desired_capabilities=desired_capabilities) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 154, in __init__ self.start_session(desired_capabilities, browser_profile) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 243, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute self.error_handler.check_response(response) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 237, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.26.436382 (70eb799287ce4c2208441fc057053a5b07ceabac),platform=Linux 3.13.0-24-generic x86_64) Here is a snippet of my code:` def automate_test(self): # instantiate a chrome options object so you can set the size and headless preference chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument('--no-sandbox') chrome_options.add_argument("--window-size=1920x1080") driver = webdriver.Chrome(chrome_options=chrome_options, executable_path='/root/chromedriver') driver.get("https://google.com") ` Thanks
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/47142311
tagged with: selenium-webdriver
has title: How to Fix Message: unknown error: Chrome failed to start: exited abnormally - Python
score: 0

http://stackoverflow.com/a/50937339
accepted answer of: http://stackoverflow.com/q/48264157
type: Answer
has body: First, you dont seem to be using t anywhere in your 'func' function. Second, the length of the returned set of values must match the length of Y0. Here you are returning a single value from func (1, just like the error states), and Y0 has a length of two (just like the error states).
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48264157

http://stackoverflow.com/q/48315785
has title: Pyinstaller adding splash screen or visual feedback during file extraction
has answer: http://stackoverflow.com/a/68616926
tagged with: python
has comment: http://stackoverflow.com/comment/137382020
has answer: http://stackoverflow.com/a/68075564
has answer: http://stackoverflow.com/a/53320412
answer count: 5
has comment: http://stackoverflow.com/comment/111800843
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48326365
upvote count: 21
favorite count: 0
type: Question
has body: I create a single file python application with Pyinstaller using --onefile parameters. Everything work as expected but the startup time is around 10 seconds on my machine. The problems is that during the file unpacking process of Pyinstaller package there are no visual feedback, so you don't know if the application is starting or even if you really clicked the icon. This problem became worse if the machine is slow (on my test with a very old machine i need almost 20 seconds to see the first login of my application) There is a way to create some splash screen or visual feedback (like a progress bar as on unpackers) during the Pyinstaller bootstrap sequence? Please note the question is about Pyinstaller unpacking process BEFORE the real application will be executed not by the application itself that already has is own splash screen thank you 19.01.2018 - UPDATE1 My application is FULL GUI so i prefer to not use the console as "visual feedback" during the unpacking process.
has answer: http://stackoverflow.com/a/68666505
linked to: http://stackoverflow.com/q/5971038
tagged with: pyinstaller
score: 21

http://stackoverflow.com/a/48252411
has comment: http://stackoverflow.com/comment/128307719
type: Answer
has body: There's an element of randomness to (most?) Decision Tree algorithms, and your training set is very small which might be exaggerating the effect. The randomness is typically used to determine how many/which samples to use, and in your case there are very few samples. Try setting the random_state to some fixed integer when you create the DecisionTreeClassifier. If you want a repeatable result for testing, you'll need to use the same "seed" value each time. They use a random seed of zero in the example docs: clf = DecisionTreeClassifier(random_state=0)
upvote count: 12
has comment: http://stackoverflow.com/comment/83490160
downvote count: 0
score: 12
answers question: http://stackoverflow.com/q/48252295

recursion
type: Tag
tags question: http://stackoverflow.com/q/48177815
tags question: http://stackoverflow.com/q/48256088
tags question: http://stackoverflow.com/q/48304562
tags question: http://stackoverflow.com/q/48285534
tags question: http://stackoverflow.com/q/48235938
tags question: http://stackoverflow.com/q/48290519
tags question: http://stackoverflow.com/q/48288699
tags question: http://stackoverflow.com/q/48254504
tag name: recursion
tags question: http://stackoverflow.com/q/48184778
tags question: http://stackoverflow.com/q/48201057
tags question: http://stackoverflow.com/q/48245128
tags question: http://stackoverflow.com/q/48262059
tags question: http://stackoverflow.com/q/48308910
tags question: http://stackoverflow.com/q/48260352
tags question: http://stackoverflow.com/q/48243446
tags question: http://stackoverflow.com/q/48222139
tags question: http://stackoverflow.com/q/48208911
tags question: http://stackoverflow.com/q/48328951
tags question: http://stackoverflow.com/q/48276011
tags question: http://stackoverflow.com/q/48326565

http://stackoverflow.com/q/48207711
has answer: http://stackoverflow.com/a/48208451
has title: Python Flask Button to get Unique values
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: flask
has answer: http://stackoverflow.com/a/48208249
downvote count: 1
tagged with: post
favorite count: 0
type: Question
has body: I am trying to get a list sets of information : Name: Date: Status: It will be displayed in the HTML page so e.g Name: John Date: 11 January 2018 Status: Pending Name: Alex Date: 10 January 2018 Status: Pending There will be a button for each of the above data named 'Confirm'. How do I go about so that when I click the 'Confirm' button on one of the data above, it will only process and make use of that data? e.g if I click the button on Name : Alex, it will only get the info of Alex. How do I go about doing this in Python Flask? I can do a POST but how do I capture that the data being sent is from that specific set? Please give me some suggestions. Thank you
answer count: 2

http://stackoverflow.com/comment/83376091
type: QuestionComment
score: 0
has text: @user2357112 ok, i'll fix that, thank you so much!
comment on: http://stackoverflow.com/q/48197173
type: Comment

http://stackoverflow.com/q/48190628
has answer: http://stackoverflow.com/a/48191104
possible better answer: http://stackoverflow.com/a/48191104
linked to: http://stackoverflow.com/q/7965743
score: 2
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48191258
accepted answer: http://stackoverflow.com/a/48191258
has title: Aspect ratio of a plot
has comment: http://stackoverflow.com/comment/83364665
downvote count: 1
favorite count: 0
type: Question
has body: I try to change my aspect ratio in python. I know this has been discussed in many other cases (e.g. with figaspect), but I don't get it like I want to have it. If I use figaspect, I get the error: 'Figure' object is not callable. Without it I have this code: fig, ax = plt.subplots() ax.plot(y_test1, linewidth=0.5, linestyle="-", label='Test1') ax.plot(y_test2, linewidth=0.5, linestyle="-", label='Test2') legend = ax.legend(loc='right center',prop={'size': 5}, shadow=True, fontsize='medium') plt.xlabel('images') plt.ylabel('error') plt.grid() plt.axis([0,100, 0, 20]) It works, but I need an other aspect ratio. How do I get a plot that is three times wider than high?
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/83361661
answer count: 3
linked to: http://stackoverflow.com/q/14907062
has answer: http://stackoverflow.com/a/68571520
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83361435
tagged with: python
has comment: http://stackoverflow.com/comment/83377970
has comment: http://stackoverflow.com/comment/92983870

makemessages
tag name: makemessages
type: Tag
tags question: http://stackoverflow.com/q/48242738

http://stackoverflow.com/q/48178814
has body: Using django-taggit-templatetags2, I can display all the tags associated for a test vlog in a template page. I have vlogs stored in the db that are not yet released to the public (only displayed after a certain date), so that I can store numerous vlog details in the db and then automatically release each individual vlog on a certain day (say Tuesday of each week). This means that the django-taggit-templatetags2 display all code of {% for tag in vlog_tags %} will include tags for vlog entries that are not yet displayed to the user in the vlog but are stored in the db. How can I only display the tags and the count for vlog entries where the vlog_date_published is not greater than now? There may be the same tags that are used for published and not-yet published vlog entries. So this should be factored in to the display of the tag. Here is my models code: from taggit.managers import TaggableManager class VlogDetails(models.Model): .... vlog_date_published = models.DateField(null=False, blank=False, default=datetime.now, help_text='The date the vlog video will be made public.') vlog_tags = TaggableManager(blank=True, help_text='To make a new tag, add a comma after the new tag name.') .... Here is the display all tags template code: {% load taggit_templatetags2_tags %} {% get_taglist as vlog_tags %} {% for tag in vlog_tags %} {% if tag.num_times &gt; 0 %} &lt;a class='u-tags-v1 g-color-grey g-bg-grey-opacity-0_1 g-bg-grey--hover g-color-white--hover g-rounded-50 g-py-4 g-px-15' href="{% url 'vlog_tag' tag %}" hreflang="en" rel="tooltip" title="{% blocktrans %}Display all vlog entries containing this tag.{% endblocktrans %}"&gt;&lt;i class="fa fa-tag icon_padding"&gt;&lt;/i&gt; {{tag}} x {{tag.num_times}}&lt;/a&gt; {% endif %} {% endfor %} EDIT Here are the screen shots from the database referring to the tag that is displayed to the user even though the vlog is not yet displayed to the user, but is stored in the db waiting to be automatically published based on the vlog_da…
has answer: http://stackoverflow.com/a/48915676
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84838635
has answer: http://stackoverflow.com/a/48849421
upvote count: 5
tagged with: python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84144977
possible better answer: http://stackoverflow.com/a/48849421
answer count: 2
score: 5
has title: django-taggit - display all tags based on date vlog published
tagged with: django-taggit
downvote count: 0
linked to: http://stackoverflow.com/q/48572184
accepted answer: http://stackoverflow.com/a/48915676
tagged with: django

list
tags question: http://stackoverflow.com/q/48257451
tags question: http://stackoverflow.com/q/48325433
type: Tag
tags question: http://stackoverflow.com/q/48183646
tags question: http://stackoverflow.com/q/48205282
tags question: http://stackoverflow.com/q/48198646
tags question: http://stackoverflow.com/q/48293503
tags question: http://stackoverflow.com/q/48250436
tags question: http://stackoverflow.com/q/48329751
tags question: http://stackoverflow.com/q/48240762
tags question: http://stackoverflow.com/q/48328504
tags question: http://stackoverflow.com/q/48292058
tags question: http://stackoverflow.com/q/48301468
tags question: http://stackoverflow.com/q/48218505
tags question: http://stackoverflow.com/q/48246653
tags question: http://stackoverflow.com/q/48255651
tags question: http://stackoverflow.com/q/48245128
tags question: http://stackoverflow.com/q/48254918
tags question: http://stackoverflow.com/q/48206785
tags question: http://stackoverflow.com/q/48270080
tags question: http://stackoverflow.com/q/48252809
tags question: http://stackoverflow.com/q/48290831
tags question: http://stackoverflow.com/q/48277357
tags question: http://stackoverflow.com/q/48254096
tags question: http://stackoverflow.com/q/48176021
tags question: http://stackoverflow.com/q/48327826
tags question: http://stackoverflow.com/q/48262059
tags question: http://stackoverflow.com/q/48253396
tags question: http://stackoverflow.com/q/48195350
tags question: http://stackoverflow.com/q/48202174
tags question: http://stackoverflow.com/q/48259680
tags question: http://stackoverflow.com/q/48260253
tags question: http://stackoverflow.com/q/48243018
tags question: http://stackoverflow.com/q/48255911
tags question: http://stackoverflow.com/q/48242220
tags question: http://stackoverflow.com/q/48232511
tags question: http://stackoverflow.com/q/48281284
tags question: http://stackoverflow.com/q/48193344
tags question: http://stackoverflow.com/q/48300891
tags question: http://stackoverflow.com/q/48266566
tags question: http://stackoverflow.com/q/48281988
tags question: http://stackoverflow.com/q/48295547
tags question: http://stackoverflow.com/q/48203600
tags question: http://stackoverflow.com/q/48187822
tags question: http://stackoverflow.com/q/48183771
tags question: http://stackoverflow.com/q/48287127
tags question: http://stackoverflow.com/q/48330400
tags question: http://stackoverflow.com/q/48193704
tags question: http://stackoverflow.com/q/48254311
tags question: http://stackoverflow.com/q/48282388
tags question: http://stackoverflow.com/q/48321394
tags question: http://stackoverflow.com/q/48223587
tags question: http://stackoverflow.com/q/48235809
tags question: http://stackoverflow.com/q/48292790
tags question: http://stackoverflow.com/q/48183073
tags question: http://stackoverflow.com/q/48303829
tags question: http://stackoverflow.com/q/48177247
tags question: http://stackoverflow.com/q/48280197
tags question: http://stackoverflow.com/q/48234889
tags question: http://stackoverflow.com/q/48289874
tags question: http://stackoverflow.com/q/48181747
tags question: http://stackoverflow.com/q/48242432
tags question: http://stackoverflow.com/q/48250995
tags question: http://stackoverflow.com/q/48194944
tags question: http://stackoverflow.com/q/48225583
tags question: http://stackoverflow.com/q/48273628
tags question: http://stackoverflow.com/q/48205972
tags question: http://stackoverflow.com/q/48240820
tags question: http://stackoverflow.com/q/48288998
tags question: http://stackoverflow.com/q/48322070
tags question: http://stackoverflow.com/q/48220423
tags question: http://stackoverflow.com/q/48327000
tags question: http://stackoverflow.com/q/48295381
tags question: http://stackoverflow.com/q/48243665
tags question: http://stackoverflow.com/q/48304333
tags question: http://stackoverflow.com/q/48178560
tags question: http://stackoverflow.com/q/48233950
tags question: http://stackoverflow.com/q/48270260
tags question: http://stackoverflow.com/q/48215072
tags question: http://stackoverflow.com/q/48252855

http://stackoverflow.com/comment/83540803
has text: What are you trying to achieve? Perhaps, you can take a look at [itertools](https://docs.python.org/3.6/library/itertools.html) module of python.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48278369
score: 0

http://stackoverflow.com/comment/83572994
type: AnswerComment
comment on: http://stackoverflow.com/a/48293938
has text: thank you , i though have a small problem i used now ` regexp="^\[esmaster\]" insertafter="^#?\[esmaster\]" ` , which actually doesn't insert the ip after the esmaster, but overwrites on top of it
score: 0
type: Comment

http://stackoverflow.com/q/48178805
has body: I cannot get my very basic SQL query to work as it returns 0 values despite the fact that there are clearly nulls query SELECT * FROM leads AS l JOIN closes c ON l.id = c.lead_id WHERE c.close_date IS NULL DDL CREATE TABLE closes ( id INT AUTO_INCREMENT PRIMARY KEY, lead_id INT NOT NULL, close_date DATETIME NULL, close_type VARCHAR(255) NULL, primary_agent VARCHAR(255) NULL, price FLOAT NULL, gross_commission FLOAT NULL, company_dollar FLOAT NULL, address VARCHAR(255) NULL, city VARCHAR(255) NULL, state VARCHAR(10) NULL, zip VARCHAR(10) NULL, CONSTRAINT closes_ibfk_1 FOREIGN KEY (lead_id) REFERENCES leads (id) ) ENGINE = InnoDB; CREATE INDEX lead_id ON closes (lead_id); I should mention that I am inserting the data with a python web scraper and SQLAlchemy. If the data is not scraped it will be None on insert. Here is a screenshot of datagrip showing a null value in the row EDIT Alright so I went ahead and ran the following on some of the entries in the table where the value was already &lt;null&gt; UPDATE closes SET close_date = NULL WHERE lead_id = &lt;INTEGERVAL&gt; ; What is interesting now is that when running the original query I do actually return the 2 records that I ran the update query for (the expected outcome). This would lead me to believe that the issues is with how my SQLAlchemy model is mapping the values on insert. models.py class Close(db.Model, ItemMixin): __tablename__ = 'closes' id = db.Column(db.Integer, primary_key=True) lead_id = db.Column(db.Integer, db.ForeignKey('leads.id'), nullable=False) close_date = db.Column(db.DateTime) close_type = db.Column(db.String(255)) primary_agent = db.Column(db.String(255)) price = db.Column(db.Float) gross_commission = db.Column(db.Float) company_dollar = db.Column(db.Float) address = db.Column(db.String(255)) city = db.Column(db.String(255)) state = db.Column(db.String(10)) zip = db.Column(db.String(10)) def __init__(self, item): self.build_from_item(item) def build_from_item(self, item): for k, v in item.i…
answer count: 1
has title: MySQL datetime column WHERE col IS NULL fails
tagged with: mysql
tagged with: scrapy
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/83339677
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83339236
tagged with: python
has answer: http://stackoverflow.com/a/48178940
score: 0

http://stackoverflow.com/comment/83470204
type: QuestionComment
has text: This... isn't something that can work. Importing a class into another class doesn't make it magically get all its methods. Are you perhaps looking for inheritance?
comment on: http://stackoverflow.com/q/48243829
score: 2
type: Comment

http://stackoverflow.com/comment/83565602
type: Comment
has text: could you please verify if I thinking correctly? I've put variable f: `f = LpVariable('f', cat="binary")` and I have added the conditions: `prob += A - 20 <= f * 5, prob += B >= f` is it ok?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48288286

http://stackoverflow.com/a/68726244
has body: *** Variables *** ${A} A ${B} B ${C} c *** Keywords *** Test Log To Console ${A} Log To Console ${B} Log To Console ${C} [Return] ${A} ${B} ${C} *** Test Cases *** Test1 ${A0} ${B0} ${C0} Test Log To Console ${A0} Log To Console ${B0} Log To Console ${C0} When you are calling the keyword in the test case u can assign the return variables as above.`
type: Answer
answers question: http://stackoverflow.com/q/48199388
score: 0

http://stackoverflow.com/comment/83589434
type: Comment
comment on: http://stackoverflow.com/a/48301522
score: 0
has text: I tried to provide a simple toy example. Unfortunately for this toy example this is really the issue. however, for the real problem this is not the case (IMHO). I'm updating the question to reflect the real problem. Note, I had already an extended version online but was asked to shrink it. I'm very sorry for the inconvenient.
type: AnswerComment

http://stackoverflow.com/comment/83538126
comment on: http://stackoverflow.com/q/48277357
score: 0
type: Comment
type: QuestionComment
has text: `['a', 'b'] + [i for i in range(1,4)] + ['c']` ?

http://stackoverflow.com/q/48317305
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48317779
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48317779
accepted answer: http://stackoverflow.com/a/50757628
type: AnsweredQuestion
has body: python 3.5.2 run cmd ( virtualenv -p python3 venv) Already using interpreter /usr/bin/python3 Using base prefix '/usr' New python executable in /var/www/html/python3_virtualenv/bin/python3 Also creating executable in /var/www/html/python3_virtualenv/bin/python Installing setuptools, pip, wheel... stay of execution
has answer: http://stackoverflow.com/a/50757628
downvote count: 4
answer count: 2
upvote count: 0
score: -4
has title: Using Python 3 in virtualenv not working properly
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/41573587

http://stackoverflow.com/comment/83393994
type: Comment
score: 0
type: QuestionComment
has text: @Bartłomiej i approached your suggestions. But this did not return sufficient results, please see the code above
comment on: http://stackoverflow.com/q/48204730

http://stackoverflow.com/q/48243369
has comment: http://stackoverflow.com/comment/83469471
upvote count: 2
tagged with: algorithm
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/83469506
has comment: http://stackoverflow.com/comment/83469493
tagged with: python
has comment: http://stackoverflow.com/comment/83469275
tagged with: python-2.7
downvote count: 4
has comment: http://stackoverflow.com/comment/83469255
has body: I have a this list in the Python. dates= [6,15],[8,24] I want to subtract values from this list. For example [6,15] is [month,day] so I want to subtract 15 to 10. I want to get [6,5], well this operation will repeat after that I want to get [5, 26] like this. How can I do this code?
has title: Subtract "n" days from a list of format [month, day]
has answer: http://stackoverflow.com/a/48243514
has comment: http://stackoverflow.com/comment/83469326
has comment: http://stackoverflow.com/comment/83469158
has answer: http://stackoverflow.com/a/48243448
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83469240
answer count: 2
has comment: http://stackoverflow.com/comment/83469222

http://stackoverflow.com/comment/83544991
type: QuestionComment
has text: Yes, this is how Python 2.7 unicode characters will be represented when you print a list containing them. Is this an issue for any particular reason? The actual strings aren't changing...
score: 0
comment on: http://stackoverflow.com/q/48280759
type: Comment

http://stackoverflow.com/a/48299077
type: Answer
has body: This helps import datetime d = datetime.datetime.strptime('2014-5-28', '%Y-%m-%d') d.strftime('%Y-%m-%d')
downvote count: 0
answers question: http://stackoverflow.com/q/48298760
score: 1
upvote count: 1

http://stackoverflow.com/q/48254674
type: Question
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83491993
tagged with: probability
has title: find probability of occurrence pandas scipy
has comment: http://stackoverflow.com/comment/83493687
tagged with: statistics
score: 0
has body: How can I find the probability of occurrence for the pandas df below? I am trying to find the probability of a beer being associated to one store over others? My current event time is one day. I have a dataframe like below: eventtime name src_store January 14, 2018 4:57:35 budlight NaN January 14, 2018 4:51:31 coors 5-119 January 14, 2018 4:31:32 pabst NaN January 14, 2018 4:57:31 budlight 5-118 January 14, 2018 4:58:21 coors 5-119 January 14, 2018 4:57:37 NaN 5-120 January 14, 2018 4:18:31 budlight 5-118 January 14, 2018 4:57:31 coors 5-119 January 14, 2018 4:57:52 NaN 5-120 Some code to give me a comparison matrix: pd.crosstab(df.name, df.src_store) src_store 5-118 5-119 5-120 NONE name NONE 0 0 2 0 budlight 2 0 0 1 coors 0 3 0 0 pabst 0 0 0 1 Trying to get the pvalues from this: Name with src_store Name without src_store src_store with name src_store without name Overall goal is to find the probability a beer is correlated to a specific src_store. Expected output (NOT The actual p_values): eventtime name src_store p_value January 14, 2018 4:57:35 budlight NaN 0.01 January 14, 2018 4:51:31 coors 5-119 0.02 January 14, 2018 4:31:32 pabst NaN 0 January 14, 2018 4:57:31 budlight 5-118 0.002 January 14, 2018 4:58:21 coors 5-119 0.004 January 14, 2018 4:57:37 NaN 5-120 0.005 January 14, 2018 4:18:31 budlight 5-118 0.006 January 14, 2018 4:57:31 coors 5-119 0.007 January 14, 2018 4:57:52 NaN 5-120 0.008
tagged with: pandas
linked to: http://stackoverflow.com/q/32732582
tagged with: python

http://stackoverflow.com/a/48176374
type: Answer
upvote count: 2
has body: This might help: def guess(): import random rand = random.randint (0, 100) cubed = rand*rand*rand # Forming the input question question = "What is the cube root of {cubed} ?".format(cubed=cubed) user = int(input(question)) if user == rand: print ("\nCorrect!") else: print ("\tIncorrect!, the cube root of", cubed, "is", rand) choice = 'y' while choice == 'y': guess() choice = input("Would you like to play again ?").lower() else: print("Goodbye") You were storing return value of print function (which is None) in question and then passing question to input function which was printing it
score: 2
answers question: http://stackoverflow.com/q/48176103
downvote count: 0

http://stackoverflow.com/q/48305898
type: Question
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83597127
has comment: http://stackoverflow.com/comment/83619287
has comment: http://stackoverflow.com/comment/83596835
has comment: http://stackoverflow.com/comment/83596804
has title: Evaluating undefined variables as strings in Python 3.6
has comment: http://stackoverflow.com/comment/83597199
downvote count: 5
has comment: http://stackoverflow.com/comment/83599399
tagged with: python
has comment: http://stackoverflow.com/comment/83602743
has body: If I am trying to evaluate a list of comma separated values, where the strings are not surrounded by quotes, for example: list = [54, 25, 1, 3467, 9, 45, 69, 420, 45, 65987, bob, 0, -5, 47.2, john, y] Python obviously wants to parse the items [bob], [john], and [y] as variables. Since they are undefined, Python will throw a traceback error. Is it possible to convert those items to strings when, or before the error occurs?
has comment: http://stackoverflow.com/comment/83602953
answer count: 2
has answer: http://stackoverflow.com/a/48306285
possible better answer: http://stackoverflow.com/a/48306285
has comment: http://stackoverflow.com/comment/83602547
has comment: http://stackoverflow.com/comment/83602812
score: -4
has comment: http://stackoverflow.com/comment/83598568
has comment: http://stackoverflow.com/comment/83602595
upvote count: 1
has answer: http://stackoverflow.com/a/48306348
has comment: http://stackoverflow.com/comment/83599016
accepted answer: http://stackoverflow.com/a/48306348
has comment: http://stackoverflow.com/comment/83599359
favorite count: 0

http://stackoverflow.com/comment/83339429
type: AnswerComment
comment on: http://stackoverflow.com/a/48179533
type: Comment
has text: @user1179317 do you want to calculate the distance between every point on a grid to a fixed point `(x, y)`?
score: 0

http://stackoverflow.com/comment/83394830
type: AnswerComment
comment on: http://stackoverflow.com/a/48206902
type: Comment
has text: Can anyone elaborate on why str() needs to be called explicitly? (The object is referenced in a string context, so why doesn't it use `__str__`?)
score: 2

http://stackoverflow.com/q/48213518
tagged with: python
tagged with: lines
accepted answer: http://stackoverflow.com/a/48215308
has body: I plotted point correspondences in two subplots. Between these correspondences I want to draw lines that start and end exactly in the points. I have the problem that ConnectionPatch of matplotlib only starts next to the given coordinates what looks silly. The data is of the form: pts1: 1823.63 464.198 1079.02 473.459 1078.44 481.124 1066.56 487.062 1073.3 516.349 1089.75 527.747 1096.95 571.923 1216.69 572.146 1143.79 586.804 1632.08 598.465 1266.59 600.856 pts2: 1825.54 466.379 1084.3 477.044 1083.53 485.376 1070.61 489.98 1076.97 519.565 1094.11 529.739 1100.92 574.527 1221.61 574.427 1148.73 589.611 1634.8 600.363 1271.47 603.339 My code: fig = plt.figure(2,figsize=(20, 20)) ax1 = fig.add_subplot(121) ax1.plot(pts1[:,0],pts1[:,1], 'c+', ms = 7) ax1.axis('off') ax2 = fig.add_subplot(122) ax2.plot(pts2[:,0],pts2[:,1], '.', color = '#DC189B', ms = 7) ax2.axis('off') for i in range(len(pts1)): xy1 = (pts1[i,0],pts1[i,1]) xy2 = (pts2[i,0],pts2[i,1]) con = ConnectionPatch(xyA=xy1, xyB=xy2, coordsA="data", coordsB="data", axesA=ax2, axesB=ax1, color='#53F242') ax2.add_artist(con) plt.subplots_adjust(wspace=0, hspace=0) plt.show() Is the function ConnectionPatch the problem? Or is there a way to make the drawings of this function more accurate? If not is there a possible solution without using this function?
tagged with: draw
type: AnsweredQuestion
score: 0
tagged with: matplotlib
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/48215308
tagged with: subplot
has title: Improving accuracy of drawn lines using ConnectionPatch? (Matplotlib)

http://stackoverflow.com/a/48284117
has comment: http://stackoverflow.com/comment/83561884
has comment: http://stackoverflow.com/comment/83562200
has body: It doesn't resolve your problem but it shows how I would organize data and code - and maybe it helps you to resolve problem. First: I keep data in dictionaries so I can use easily get data["easy"] or data["hard"] (the same with solved["easy"]) or using variable data[difficalty] and solved[difficalty] Next: for empty button I use 0 instead of "". And I use own field in button b.value to keep this value. Next I can easily calculate next value (modulo 10) and put empty string when value is 0. At start I create board with empty buttons (all_buttons) and use function to reset buttons parameters using zip(all_buttons, data["easy"]). This way I can easily change difficalty. import tkinter as tk data = { "easy": [ [8,0,0,0,4,0,6,7,0], [0,3,0,6,7,0,5,0,8], [0,7,2,0,0,0,0,3,4], [1,0,3,7,0,4,8,0,5], [0,6,5,0,1,8,4,9,0], [0,4,8,0,5,6,0,2,0], [5,9,0,4,2,0,0,0,0], [2,0,7,0,3,0,1,0,6], [3,0,4,0,6,0,2,0,9], ], "hard": [ [0,8,0,3,0,5,0,1,0], [1,0,0,0,0,0,0,0,0], [0,0,3,2,0,0,6,0,0], [0,0,7,0,0,0,0,9,8], [8,0,2,0,5,0,4,0,3], [4,1,0,0,0,0,2,0,0], [0,0,4,0,0,8,9,0,0], [0,0,0,0,0,0,0,0,1], [0,9,0,7,0,6,0,8,0], ], } solved = { "easy": [ [8,5,1,9,4,3,6,7,2], [4,3,9,6,7,2,5,1,8], [6,7,2,1,8,5,9,3,4], [1,2,3,7,9,4,8,6,5], [7,6,5,2,1,8,4,9,3], [9,4,8,3,5,6,7,2,1], [5,9,6,4,2,1,3,8,7], [2,8,7,5,3,9,1,4,6], [3,1,4,8,6,7,2,5,9], ], "hard": [ [2,8,6,3,4,5,7,1,9], [1,4,5,6,9,7,8,3,2], [9,7,3,2,8,1,6,4,5], [3,5,7,4,6,2,1,9,8], [8,6,2,1,5,9,4,7,3], [4,1,9,8,7,3,2,5,6], [6,3,4,5,1,8,9,2,7], [7,2,8,9,3,4,5,6,1], [5,9,1,7,2,6,3,8,4], ], } def left_click(widget): ''' process button click ''' # get next value (modulo 10) widget.value = (widget.value+1) % 10 # if zero then put empty string if widget.value == 0: widget['text'] = '' else: widget['text'] = widget.value def create_empty_board(master): ''' create board with empty buttons ''' # create black lines master['bg'] = '#444' master.columnconfigure(3, minsize=3) master.columnconfigure(7, minsize=3) master.rowconfigure(3, minsize=3) master.rowconfigure…
has comment: http://stackoverflow.com/comment/83562319
has comment: http://stackoverflow.com/comment/83556891
type: Answer
answers question: http://stackoverflow.com/q/48282073
has comment: http://stackoverflow.com/comment/83563137
score: 0
has comment: http://stackoverflow.com/comment/83563749

performance
tags question: http://stackoverflow.com/q/48297178
tags question: http://stackoverflow.com/q/48290687
tags question: http://stackoverflow.com/q/48237410
tags question: http://stackoverflow.com/q/48248821
tags question: http://stackoverflow.com/q/48266653
tags question: http://stackoverflow.com/q/48235781
tags question: http://stackoverflow.com/q/48233812
tags question: http://stackoverflow.com/q/48240579
tags question: http://stackoverflow.com/q/48174383
tags question: http://stackoverflow.com/q/48304369
tags question: http://stackoverflow.com/q/48256433
tags question: http://stackoverflow.com/q/48195845
tags question: http://stackoverflow.com/q/48253210
tags question: http://stackoverflow.com/q/48230473
tag name: performance
tags question: http://stackoverflow.com/q/48258260
tags question: http://stackoverflow.com/q/48268522
tags question: http://stackoverflow.com/q/48282462
tags question: http://stackoverflow.com/q/48300891
tags question: http://stackoverflow.com/q/48296019
tags question: http://stackoverflow.com/q/48242168
tags question: http://stackoverflow.com/q/48204194
tags question: http://stackoverflow.com/q/48315768
type: Tag
tags question: http://stackoverflow.com/q/48255660
tags question: http://stackoverflow.com/q/48266869
tags question: http://stackoverflow.com/q/48252232
tags question: http://stackoverflow.com/q/48323955
tags question: http://stackoverflow.com/q/48263740
tags question: http://stackoverflow.com/q/48285248
tags question: http://stackoverflow.com/q/48245987
tags question: http://stackoverflow.com/q/48293456
tags question: http://stackoverflow.com/q/48234169
tags question: http://stackoverflow.com/q/48271906

http://stackoverflow.com/comment/83508547
type: AnswerComment
comment on: http://stackoverflow.com/a/48262734
has text: Actually i need to do the same logic in R. But I am unable to do so
score: 0
type: Comment

http://stackoverflow.com/comment/83557097
type: QuestionComment
has text: Shouldn't you be using `for obj in bucket.objects.all()` instead of `for obj in bucket.objects()`. Refer this link: http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.objects
comment on: http://stackoverflow.com/q/48286217
score: 3
type: Comment

http://stackoverflow.com/a/58832516
downvote count: 0
answers question: http://stackoverflow.com/q/48272437
upvote count: 10
score: 10
type: Answer
has comment: http://stackoverflow.com/comment/116144583
has body: The best part about matplotlib/seaborn libraries is that everything is plotted in the same figure until you clear it. You can use the mask argument in sns.heatmap to get a diagonal heatmap plot. To get a "mixed" heatmap, such that you can have two different types of data plotted with different colormaps, you can do something like this: from sklearn.datasets import load_iris import seaborn as sns import pandas as pd import numpy as np data = load_iris() df= pd.DataFrame(data.data,columns = data.feature_names) df['target'] = data.target df_0 = df[df['target']==0] df_1 = df[df['target']==1] df_0.drop('target',axis=1,inplace=True) df_1.drop('target',axis=1,inplace=True) matrix_0 = np.triu(df_0.corr()) matrix_1 = np.tril(df_1.corr()) import seaborn as sns from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable from mpl_toolkits.axes_grid1.colorbar import colorbar sns.heatmap(df_0.corr(),annot=True,mask=matrix_0,cmap="BuPu") sns.heatmap(df_1.corr(),annot=True,mask=matrix_1,cmap="YlGnBu") Hope this is what your second idea was. Note that this will only work when you have same column names.

http://stackoverflow.com/q/48260456
accepted answer: http://stackoverflow.com/a/48260559
has answer: http://stackoverflow.com/a/48260559
tagged with: time-series
has title: Python Pandas: weekly columns(int) to Timestamp columns conversion (in weeks)
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
tagged with: timestamp
type: Question
tagged with: pandas
tagged with: python
has body: I have a df with weekly columns as below. I want to change my column index to timestamp. Here is my df.columns df.columns: Int64Index([201601, 201602, 201603, 201604, 201605, 201606, 201607, 201608, 201609, ...], dtype='int64', name='timeline', length=104) df.columns[0]: 201553 I want to change my df.columns into timestamp as below df.columns: DatetimeIndex(['2016-01-04', '2016-01-11', '2016-01-18', '2016-01-25', '2016-02-01', '2016-02-08', '2016-02-15', '2016-02-22', '2016-02-29'.....], dtype='int64', name='timeline', length=104) df.columns[0]: Timestamp('2016-01-04 00:00:00') Bottom line is that my df.columns are in int format that indicates the yyyyww value. From this int, I want to change it to Timestamp that shows date of Monday of each week. Please let me know a good way to change this. THank you
linked to: http://stackoverflow.com/q/29262859

http://stackoverflow.com/q/48237880
has comment: http://stackoverflow.com/comment/83459017
tagged with: raspberry-pi3
has comment: http://stackoverflow.com/comment/83466386
type: Question
has title: pyblue failed to execute mgmt cmd 'scanend' on raspberry pi3
has body: The code is following, which copied from either pyblue or somewhere else, the hciconfig or bluetoothctl can see the device, and do lescan, but the following python code can not do the scan and getting the error below: from bluepy.btle import Scanner, DefaultDelegate class ScanDelegate(DefaultDelegate): def __init__(self): DefaultDelegate.__init__(self) def handleDiscovery(self, dev, isNewDev, isNewData): if isNewDev: print ("Discovered device", dev.addr) elif isNewData: print ("Received new data from", dev.addr) scanner = Scanner().withDelegate(ScanDelegate()) devices = scanner.scan(10.0) for dev in devices: print ("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)) for (adtype, desc, value) in dev.getScanData(): print (" %s = %s" % (desc, value)) I am getting the following error File "/usr/local/lib/python2.7/dist-packages/bluepy/btle.py", line 679, in scan self.start(passive=passive) File "/usr/local/lib/python2.7/dist-packages/bluepy/btle.py", line 624, in start self._mgmtCmd(self._cmd()+"end") File "/usr/local/lib/python2.7/dist-packages/bluepy/btle.py", line 276, in _mgmtCmd "Failed to execute mgmt cmd '%s'" % (cmd))
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83459078
tagged with: python
tagged with: bluetooth
score: 0
answer count: 0

http://stackoverflow.com/comment/83484922
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48251121
has text: Thank you, now I understand.

http://stackoverflow.com/q/48308487
tagged with: simplehttpserver
tagged with: python
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/71803885
has body: I have a small demo page served with http.server. I tried sharing with my coworkers but discovered that http.server remains blocked on any open connection, so concurrent users can't be served. Is there a way to run http.server to handle concurrent connections? I found nothing useful here: https://docs.python.org/3/library/http.server.html
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/73682483
downvote count: 0
tagged with: httpserver
score: 4
tagged with: http
linked to: http://stackoverflow.com/q/46210672
favorite count: 0
answer count: 3
has title: Can python -m http.server be configured to handle concurrent requests?
has answer: http://stackoverflow.com/a/48328943

http://stackoverflow.com/comment/83388925
score: 0
has text: I like the two solutions, but what if I don't know the length of the list, and I have numbers left over? - like if I wanted slices with 4 numbers each instead of 3?
comment on: http://stackoverflow.com/a/48203398
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48243094
tagged with: python
has comment: http://stackoverflow.com/comment/83468719
type: AnsweredQuestion
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/48243456
upvote count: 3
has answer: http://stackoverflow.com/a/48243186
possible better answer: http://stackoverflow.com/a/48243186
downvote count: 3
tagged with: string
linked to: http://stackoverflow.com/q/35366457
favorite count: 0
has answer: http://stackoverflow.com/a/48243135
type: Question
accepted answer: http://stackoverflow.com/a/48243135
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83469153
has body: I am trying to to write a code that takes input, splits it into a list, and then assigns a number to each string in the list. For example: If my input was "hello hello goodbye hello" Then it would output "1121". This is the code I have written so far: sentence = input("What is your sentence? ").lower() list_s = str.split(sentence) for i in range(len(list_s)):
has title: Assign a number to each string in a list. Python 3.6

http://stackoverflow.com/comment/83473781
comment on: http://stackoverflow.com/q/48245151
score: 0
has text: Now indentation is exactly like in my code. There is the following problem: `File "C:/......../test.py", line 16, in <module> xc.append(row[0]) IndexError: list index out of range`
type: Comment
type: QuestionComment

configuration-files
type: Tag
tags question: http://stackoverflow.com/q/48256306
tags question: http://stackoverflow.com/q/48214327
tag name: configuration-files

http://stackoverflow.com/a/48293103
score: 1
type: Answer
has body: I'm not too familiar with discord.py (since I use discord.js), but if this is similar to discord.js there should be a message event. This event will run on every message, which is ideal for what you are searching for now. Now for the pseudocode... //written in javascript Message event: On each message { if(message.attachments.size &lt;= 0) { message.delete(); } } The general idea is that using the message event, (so on each message), you check if the message's attachments list is greater than 0 (meaning it contains a file or image) and if it is not, call the delete() function in python to delete the message.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48255732

http://stackoverflow.com/q/48180363
has comment: http://stackoverflow.com/comment/83344090
downvote count: 0
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/48180745
favorite count: 0
has body: Suppose such a list l = ['1\xa0My Cll to Adventure: 1949–1967', '2\xa0Crossing the Threshold: 1967–1979', '3\xa0My Abyss: 1979–1982', '4\xa0My Rod of Trils: 1983–1994', '5\xa0The Ultimte Boon: 1995–21', '6\xa0Returning the Boon: 211–215', '7\xa0My Lst Yer nd My Gretest Chllenge: 216–217', '8\xa0Looking Bck from Higher Level'] The result I want is [' 1.My Cll to Adventure: 1949–1967', ' 2.Crossing the Threshold: 1967–1979', ' 3.My Abyss: 1979–1982', ' 4.My Rod of Trils: 1983–1994', ' 5.The Ultimte Boon: 1995–21', ' 6.Returning the Boon: 211–215', ' 7.My Lst Yer nd My Gretest Chllenge: 216–217', ' 8.Looking Bck from Higher Level'] I tried with codes import re In [114]: [re.sub(r'\d\xa0', r' \d.', i) for i in l] Out[114]: [' \\d.My Cll to Adventure: 1949–1967', ' \\d.Crossing the Threshold: 1967–1979', ' \\d.My Abyss: 1979–1982', ' \\d.My Rod of Trils: 1983–1994', ' \\d.The Ultimte Boon: 1995–21', ' \\d.Returning the Boon: 211–215', ' \\d.My Lst Yer nd My Gretest Chllenge: 216–217', ' \\d.Looking Bck from Higher Level'] It failed to substitute with numerics as I intended. How to accomplish such a task?
has comment: http://stackoverflow.com/comment/83340672
has answer: http://stackoverflow.com/a/48180745
type: Question
has title: Substitute `1 ` with ` 1.`
has comment: http://stackoverflow.com/comment/83343817
accepted answer: http://stackoverflow.com/a/48180417
tagged with: python
tagged with: regex
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/48180417

http://stackoverflow.com/comment/83523591
type: Comment
comment on: http://stackoverflow.com/q/48269809
type: QuestionComment
score: 0
has text: Wich serializer ? the issue is not with drf, instead it works as intended with drf, but no with class based view, then i don't wich serializer your refer

http://stackoverflow.com/q/48181073
has body: I want find two types of files with two different extensions: .jl and .jsonlines. I use from pathlib import Path p1 = Path("/path/to/dir").joinpath().glob("*.jl") p2 = Path("/path/to/dir").joinpath().glob("*.jsonlines") but I want p1 and p2 as one variable not two. Should I merge p1 and p2 in first place? Are there other ways to concatinate glob's patterns?
upvote count: 24
favorite count: 0
score: 24
type: Question
has answer: http://stackoverflow.com/a/59160121
has answer: http://stackoverflow.com/a/48181906
answer count: 8
has answer: http://stackoverflow.com/a/73733385
accepted answer: http://stackoverflow.com/a/48181294
possible better answer: http://stackoverflow.com/a/57893015
has comment: http://stackoverflow.com/comment/86062117
has answer: http://stackoverflow.com/a/66905507
has answer: http://stackoverflow.com/a/48181294
downvote count: 0
has answer: http://stackoverflow.com/a/57893015
has answer: http://stackoverflow.com/a/74978022
tagged with: pathlib
has answer: http://stackoverflow.com/a/72925868
has title: How to glob two patterns with pathlib?
has comment: http://stackoverflow.com/comment/99816907
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/4568580
tagged with: python

http://stackoverflow.com/q/48289809
has title: Celery logger configuration
has answer: http://stackoverflow.com/a/53547002
has comment: http://stackoverflow.com/comment/84451434
answer count: 3
has body: I'm using Django 1.10, python 3.5 and celery 4.1.0 I'm trying to log celery tasks info into a file. So I tried as suggested in celery documentation - from celery.utils.log import get_task_logger logger = get_task_logger(__name__) and tried to log a message inside the task - logger.info(message) I expected it to log to my default logger. But it didn't. So I added to settings a dedicated logger named 'celery.task' (as I understand from documentation): LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, 'require_test_false': { '()': 'myapp.utils.classes.logging.RequireTestFalse', }, 'suppress_deprecated': { '()': 'myapp.utils.classes.logging.SuppressDeprecated' } }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'json', 'filters': ['suppress_deprecated'] }, 'celery_file': { 'level': 'INFO', 'class': 'myapp.utils.classes.logging.SBRotatingFileHandler', 'maxBytes': 1024 * 1024 * 200, # 200 MB 'backupCount': 10, 'formatter': 'json', 'filename': BASE_DIR + '/../log/celery.log', } }, 'loggers': { 'django': { 'handlers': ['console', 'file'], 'level': LOG_LEVEL, 'propagate': True, }, 'celery.task': { 'handlers': ['console', 'celery_file'], 'level': 'INFO', 'propagate': True, }, } But I still don't see logs from celery task not in the celery.log file nor in the default log file. Only when starting celery worker with '-f' - it writes logs to that file Any ideas? EDIT: I'm trying to use 'after_setup_task_logger' to update the celery.task logger handler to use a handler that exists in my logging.config (in settings) unsuccessfully. I've tried the following: @celery.signals.after_setup_task_logger.connect def after_setup_logging(logger, **kwargs): logging_settings = settings.LOGGING celery_handler = logging_settings['handlers']['celery_file'] logger.addHandler(celery_handler) …
has answer: http://stackoverflow.com/a/53201244
downvote count: 1
has comment: http://stackoverflow.com/comment/139447522
favorite count: 0
upvote count: 30
type: Question
has comment: http://stackoverflow.com/comment/84454907
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48370737
score: 29
tagged with: django
tagged with: python
tagged with: logging
tagged with: celery

http://stackoverflow.com/q/48207763
tagged with: django
tagged with: python
has title: Possibilites in writing in LDAP using Django
has comment: http://stackoverflow.com/comment/83401226
score: 0
has comment: http://stackoverflow.com/comment/83398384
answer count: 0
tagged with: authentication
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: ldap
has comment: http://stackoverflow.com/comment/83400827
has body: Is it possible to change attributes of a user in LDAP via django? As of now, I can't find any solution on the Internet. I have the django-auth-ldap backend and I can log in as a user (GUI). But I can't change any of their attributes, i.e. I can't change the name. What do I have to write or extend? If you have any idea let me know. Do I have to write in my views, models, forms or whatever?
type: UnansweredQuestion

http://stackoverflow.com/comment/83446939
has text: Whoops I could have sworn I clicked on a javascript link my mistake, this will work.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48232236

http://stackoverflow.com/comment/83562458
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48288773
has text: Please do not post links, post code that we can read, and copy ourselves if necessary. Is the `read` inside or outside the `with` block?

http://stackoverflow.com/q/48253975
score: 4
type: Question
has body: I tried installing mysqlclient on python today but it gets all messy and gives me this error ***raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found*** then I tried to edit the mysql.config file by adding ***#Create options libs="-L$pkglibdir" libs="$libs -lmysqlclient -lssl -lcrypto"*** but still it gives me the same error. I am on mac version 10.6.8. The details of the error are: ****Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/private/var/folders/s4/s4O4m-85EgGDXYYsUzcvNU+++TQ/-Tmp-/pip- build-s7w0agk6/mysqlclient/setup.py", line 17, in &lt;module&gt; metadata, options = get_config() File "/private/var/folders/s4/s4O4m-85EgGDXYYsUzcvNU+++TQ/-Tmp-/pip- build-s7w0agk6/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/private/var/folders/s4/s4O4m-85EgGDXYYsUzcvNU+++TQ/-Tmp-/pip- build-s7w0agk6/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found**** I will really appreciate any help.
linked to: http://stackoverflow.com/q/13922955
downvote count: 0
has title: OSError: mysql_config not found
type: UnansweredQuestion
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/87010758
tagged with: python
has answer: http://stackoverflow.com/a/48258244
favorite count: 0
tagged with: mysql
upvote count: 4

http://stackoverflow.com/comment/83572811
has text: Thanks for this solution. I had been struggling with various loops to get to this list. Anyway, this solution worked when I used it on web-app (Jupyter notebook) but it returns all zero matrix when I am executing the code through terminal. I am not able to figure out the reason for this.
comment on: http://stackoverflow.com/a/48276194
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48281466
has comment: http://stackoverflow.com/comment/83548610
has comment: http://stackoverflow.com/comment/83546853
has comment: http://stackoverflow.com/comment/83546705
has body: The error doesn't have to do anything with Pygame. Your call to glob glob.glob("characters\\Naruto\\Standing\\naruto_s*.png") returns an empty array. Check what directory your script is executed in and whether the files at the specified path actually exist.
has comment: http://stackoverflow.com/comment/83556674
has comment: http://stackoverflow.com/comment/83548775
has comment: http://stackoverflow.com/comment/83548251
accepted answer of: http://stackoverflow.com/q/48281284
type: Answer
answers question: http://stackoverflow.com/q/48281284
has comment: http://stackoverflow.com/comment/83547258
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83564771
type: QuestionComment
comment on: http://stackoverflow.com/q/48289803
has text: You might want to type "ASCII" to your favorite search engine.
score: 0
type: Comment

http://stackoverflow.com/q/48193344
score: 0
has comment: http://stackoverflow.com/comment/83367205
tagged with: list
has title: Python: Searching a list inside a list 1 index at a time
answer count: 3
has answer: http://stackoverflow.com/a/48194265
has comment: http://stackoverflow.com/comment/83367213
has comment: http://stackoverflow.com/comment/83367305
type: Question
has answer: http://stackoverflow.com/a/48196200
has comment: http://stackoverflow.com/comment/83367145
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48193453
has body: I am a quite new python coder and would like some help with going through list entries 1 by 1. In my current code, I have a multiple lists inside a main "ballots" list and would like to go each entry 1 at a time. If the first entry is a 1, can1v1 would +=1. If it's a 2, can1v2 would +=1. If it's a 3 can1v3+=1. This would continue for each position in its list (if the 2nd index of the first lis is a 1, can2v1+=1, if it's a 2 can2v2+=1, if it's a 3 can2v3+=1 and this would continue until the last position of each list where it it's a 1 2 or a 3, the can5vsomething would +=1. I would like the code to continue doing this for each list inside of the main ballot list. Please can anyone help me with how I can do this where I go through each list and position individually? My code is as follows: pastebin.com/Pi3NwWaq This is the list: [['1', '2', '3', '0', '0'], ['1', '3', '0', '2', '0'], ['1', '2', '3', '0', '0'], ['0', '3', '2', '0', '1'], ['1', '3', '0', '2', '0'], ['2', '0', '3', '1', '0'], ['0', '0', '2', '1', '3'], ['0', '1', '2', '3', '0'], ['0', '1', '0', '2', '3'], ['2', '3', '1', '0', '0'], ['3', '2', '0', '0', '1'], ['0', '1', '3', '2', '0'], ['0', '0', '1', '2', '3'], ['0', '0', '3', '2', '1'], ['1', '2', '3', '0', '0'], ['2', '1', '3', '0', '0'], ['0', '3', '2', '1', '0'], ['0', '2', '3', '0', '1'], ['1', '2', '3', '0', '0'], ['1', '0', '0', '3', '2'], ['2', '1', '3', '0', '0'], ['3', '1', '2', '0', '0'], ['2', '3', '0', '1', '0'], ['0', '0', '3', '1', '2'], ['0', '3', '1', '0', '2'], ['2', '1', '0', '0', '3'], ['2', '0', '0', '1', '3'], ['2', '0', '0', '1', '3'], ['3', '0', '1', '0', '2']]
tagged with: python
has comment: http://stackoverflow.com/comment/83367283
has comment: http://stackoverflow.com/comment/83367271

http://stackoverflow.com/a/48196815
has body: Define your sum columns and mean columns - s = ['Subastas', 'Impresiones_exchange', 'Importe_a_pagar_a_medio'] m = ['Fill_rate', 'ECPM_medio'] Next, slice and compute - i = df1[s].sum() i Subastas 26823038.00 Impresiones_exchange 143590.00 Importe_a_pagar_a_medio 63.74 dtype: float64 j = df1[m].mean() j Fill_rate 0.606 ECPM_medio 0.450 dtype: float64 Concatenate the two - v = pd.concat([i, j]) v Subastas 2.682304e+07 Impresiones_exchange 1.435900e+05 Importe_a_pagar_a_medio 6.374000e+01 Fill_rate 6.060000e-01 ECPM_medio 4.500000e-01 dtype: float64 And reshape your output - df = pd.DataFrame(v.values[:, None].T, index=['Total'], columns=v.index) df Subastas Impresiones_exchange Importe_a_pagar_a_medio Fill_rate \ Total 26823038.0 143590.0 63.74 0.606 ECPM_medio Total 0.45 To write to an existing CSV, use the append mode - df.to_csv('file.csv', mode='a')
accepted answer of: http://stackoverflow.com/q/48196510
answers question: http://stackoverflow.com/q/48196510
type: Answer
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48313205
answer count: 2
has title: Keras Dense Net Overfitting
tagged with: classification
downvote count: 1
tagged with: neural-network
has comment: http://stackoverflow.com/comment/83612332
favorite count: 0
tagged with: keras
type: Question
has answer: http://stackoverflow.com/a/48315212
has body: I am attempting to use keras to build an activity classifier from accelerometer signals. However, I am experiencing extreme overfitting of the data even with the most simplistic of models. The input data is of shape (10,3) and contains roughly .1 second of data from the accelerometer in 3 dimensions. The model is simply model = Sequential() model.add(Flatten(input_shape=(10,3))) model.add(Dense(2, activation='softmax')) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) The model should output the label [1,0] for walking activities and [0,1] for non-walking activities. After training I get 99.8% accuracy (if only it was real...). When I attempt to predict on data that wasn't used for training, I get 50% accuracy, verifying that the net isn't really "learning" anything except to predict a single class value. The data is being prepared from 100hz triaxial accelerometer signals. I am not preprocessing the data in any way except for windowing it into bins on length 10 that overlap with the previous bin by 50%. What measures can I take to make the network produce actual predictions? I have tried increasing the window size but the results remain the same. Any advice/general tips are greatly appreciated. Ian
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48313269
tagged with: python
has comment: http://stackoverflow.com/comment/83613055
has comment: http://stackoverflow.com/comment/83612877
upvote count: 2

http://stackoverflow.com/comment/83632453
type: AnswerComment
comment on: http://stackoverflow.com/a/48323528
has text: i ran with this same answer and yes it is, i was able to find i can use pip2 and pip3 it solve the problems however set-alias is not persistent whenever i try to do py3 or py2 it wont work unless is set again
type: Comment
score: 0

http://stackoverflow.com/q/48202050
accepted answer: http://stackoverflow.com/a/48202807
linked to: http://stackoverflow.com/q/4544784
tagged with: python
has answer: http://stackoverflow.com/a/48202807
type: AnsweredQuestion
tagged with: cprofile
tagged with: ansible
upvote count: 0
tagged with: performance-testing
downvote count: 2
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83385183
has title: how to reduce {time.sleep} time in ansible playbook performance tuning
has body: I am working on ansible playbook performance tuning with the following playbook --- # simplespeedtest.yml - hosts: localhost connection: local gather_facts: false tasks: - command: echo 1 - command: echo 2 - command: echo 30 I have test the running time of the playbook and every task in the playbook by tasts_profile modules, the result is as follow: # time $ANSIBLE_HOME/bin/ansible-playbook -i hosts simplespeed_localhost.yml PLAY [localhost] ******************************************************************************** TASK [command] ******************************************************************************** Thursday 11 January 2018 15:29:45 +0800 (0:00:00.091) 0:00:00.091 ****** changed: [localhost] TASK [command] ******************************************************************************** Thursday 11 January 2018 15:29:45 +0800 (0:00:00.316) 0:00:00.407 ****** changed: [localhost] TASK [command] ******************************************************************************** Thursday 11 January 2018 15:29:46 +0800 (0:00:00.205) 0:00:00.613 ****** changed: [localhost] PLAY RECAP ******************************************************************************** localhost : ok=3 changed=3 unreachable=0 failed=0 Thursday 11 January 2018 15:29:46 +0800 (0:00:00.187) 0:00:00.800 ****** =============================================================================== command ---------------------------------- 0.32s command ----------------------------------- 0.21s command ----------------------------------- 0.19s Playbook run took 0 days, 0 hours, 0 minutes, 0 seconds real 0m1.894s user 0m1.652s sys 0m0.220s and total time to execute the task is 0.72s, but the total time to execute the playbook is 1.894s which is bigger the the task total time, I want to know how to reduce this time. By running the following command: time python -m cProfile -o test1.out -s time $ANSIBLE_HOME/bin/ansible-playbook -i hosts simplespeed_localhost.yml I got the python cprofile file nca…
score: -2

http://stackoverflow.com/a/48328736
has body: Assuming the ordering isn't important, the following might be enough - get the list of files, figure out all the prefixes and suffixes (split on the _), then for each prefix, rename each file from prefix_suffix to count_suffix: from os import listdir, rename from os.path import join suffixes = ['PersonalInformationSheet', 'Resume', 'ShortResponses', 'Essay', 'AcademicSummary'] filedir = "/tmp/foo" prefixes = set(prefix.split('_')[0] for prefix in listdir(filedir)) for count, prefix in enumerate(prefixes): for suffix in suffixes: rename( join(filedir, "{}_{}".format(prefix, suffix)), join(filedir, "{}_{}".format(count+1, suffix)) )
has comment: http://stackoverflow.com/comment/83643548
type: Answer
has comment: http://stackoverflow.com/comment/83643646
answers question: http://stackoverflow.com/q/48328526
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48250644
has body: I am trying to use linprog in order to optimise the following problem (uploaded in Google Drive). The dataset itself is uploaded here So far I have the written the following implementation in Python: import pandas as pd import numpy as np df = pd.read_csv('Supplier Specs.csv') from scipy.optimize import linprog def fromPandas(dataframe, colName): return dataframecolName.values.reshape(1,11)[0] ## A_ub * x &lt;= b_ub ## A_eq * x == b_eq A_eq = [1.0]*11 u_eq = [600.0] # demand ## reading the actual numbers from the pandas dataframe and then converting them to vectors BAR = fromPandas(df, 'Brix / Acid Ratio') acid = fromPandas(df, 'Acid (%)') astringency = fromPandas(df, 'Astringency (1-10 Scale)') color = fromPandas(df, 'Color (1-10 Scale)') price = fromPandas(df, 'Price (per 1K Gallons)') shipping = fromPandas(df, 'Shipping (per 1K Gallons)') upperBounds = fromPandas(df, 'Qty Available (1,000 Gallons)') lowerBounds = [0]*len(upperBounds) # list with length 11 and value 0 lowerBounds[2] = 0.4*u_eq[0] # adding the Florida tax bound bnds = [(0,0)]*len(upperBounds) # bounds for i in range(0,len(upperBounds)): bnds[i] = (lowerBounds[i], upperBounds[i]) c = price + shipping # objective function coefficients print("------------------------------------- Debugging Output ------------------------------------- \n") print("Objective function coefficients: ", c) print("Bounds: ", bnds) print("Equality coefficients: ", A_eq) print("BAR coefficients: ", BAR) print("Astringency coefficients: ", astringency) print("Color coefficients: ", color) print("Acid coefficients: ", acid) print("\n") A_ub = [BAR, acid, astringency, color, -BAR, -acid, -astringency, -color] # coefficients for inequalities b_ub = np.array([12.5, 1.0, 4.0, 5.5, -11.5, -0.75, 0, -4.5]) # limits for the inequalities b_ub = b_ub * u_eq[0] # scaling the limits with the demand xOptimized = linprog(c, A_ub, b_ub, [A_eq], u_eq, bounds=(bnds)) print(xOptimized) # the amounts of juice which we need to buy from each su…
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48251641
favorite count: 0
type: Question
has title: Linear programming with scipy.optimize.linprog returns Optimization failed
has comment: http://stackoverflow.com/comment/83484409
has comment: http://stackoverflow.com/comment/83484230
tagged with: python
tagged with: simplex-algorithm
tagged with: optimization
type: AnsweredQuestion
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48251641

http://stackoverflow.com/q/48326817
accepted answer: http://stackoverflow.com/a/48335016
tagged with: python
tagged with: qthread
type: AnsweredQuestion
downvote count: 0
tagged with: pyqt
score: 1
upvote count: 1
answer count: 1
tagged with: pyqt5
favorite count: 0
type: Question
has body: I'm trying to use a QTimer in a QThread but it doesn't call the function I need it to call. I read something about garbage collection and that the timer is being thrown out before it has a chance to be used (from my understanding). I tried the many ways I found in other code examples but I'm misunderstanding something as those examples didn't help. The run() method is triggered by a button from the Main_Window class. Moving the instantiation of the timer to the run() method didn't help. What is the problem here? #Main_Window class is here class TheThread(QThread): def __init__(self, Main_Window): QThread.__init__(self) #some code above self.timeTaken = 0 self.myTimer = QTimer() self.myTimer.timeout.connect(self.track_time) def track_time(self): #Not being called self.timeTaken += 0.1 def run(self): #some code above self.myTimer.start(1000) #code in a while loop below if __name__ == "__main__": app = QApplication(sys.argv) main = Main_Window() sys.exit(app.exec_())
tagged with: qtimer
has title: PyQt5 QTimer in QThread is being "garbage collected"?
has answer: http://stackoverflow.com/a/48335016

http://stackoverflow.com/comment/84694303
type: Comment
has text: Have the same question of yours, need to try solutions like https://www.nist.gov/services-resources/software/nist-biometric-image-software-nbis NIST software... or openCV
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48306299

http://stackoverflow.com/comment/83623731
type: AnswerComment
has text: Ok. so the real problem that is happening after 4th line in inputfile is that the script gets to invalid url. so i need to add url validation.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48309853

http://stackoverflow.com/a/53923249
type: Answer
score: 33
has comment: http://stackoverflow.com/comment/94688284
upvote count: 33
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/94688179
has comment: http://stackoverflow.com/comment/94688260
accepted answer of: http://stackoverflow.com/q/48260412
has body: By the way, if you use PyCharm, you could add PYSPARK_PYTHON and PYSPARK_DRIVER_PYTHON to run/debug configurations per image below
has comment: http://stackoverflow.com/comment/102586604
answers question: http://stackoverflow.com/q/48260412

http://stackoverflow.com/comment/83529504
type: QuestionComment
comment on: http://stackoverflow.com/q/48272798
score: 3
has text: This seems an issue caused by latest chrome driver, have a look at issue on github: https://github.com/SeleniumHQ/selenium/issues/5189
type: Comment

scikit-learn
tags question: http://stackoverflow.com/q/48223192
tags question: http://stackoverflow.com/q/48320396
tags question: http://stackoverflow.com/q/48231995
tags question: http://stackoverflow.com/q/48244219
tags question: http://stackoverflow.com/q/48312206
tags question: http://stackoverflow.com/q/48253844
tags question: http://stackoverflow.com/q/48213235
tag name: scikit-learn
tags question: http://stackoverflow.com/q/48288367
tags question: http://stackoverflow.com/q/48183271
tags question: http://stackoverflow.com/q/48232331
tags question: http://stackoverflow.com/q/48211590
tags question: http://stackoverflow.com/q/48232129
tags question: http://stackoverflow.com/q/48239242
tags question: http://stackoverflow.com/q/48302463
tags question: http://stackoverflow.com/q/48313387
tags question: http://stackoverflow.com/q/48219751
tags question: http://stackoverflow.com/q/48185580
type: Tag
tags question: http://stackoverflow.com/q/48329849
tags question: http://stackoverflow.com/q/48216574
tags question: http://stackoverflow.com/q/48270363
tags question: http://stackoverflow.com/q/48183231
tags question: http://stackoverflow.com/q/48258552
tags question: http://stackoverflow.com/q/48323926
tags question: http://stackoverflow.com/q/48241606
tags question: http://stackoverflow.com/q/48216358
tags question: http://stackoverflow.com/q/48239856
tags question: http://stackoverflow.com/q/48252006
tags question: http://stackoverflow.com/q/48230180
tags question: http://stackoverflow.com/q/48271342
tags question: http://stackoverflow.com/q/48305143
tags question: http://stackoverflow.com/q/48300822
tags question: http://stackoverflow.com/q/48288047
tags question: http://stackoverflow.com/q/48249057
tags question: http://stackoverflow.com/q/48269248
tags question: http://stackoverflow.com/q/48291032
tags question: http://stackoverflow.com/q/48188865
tags question: http://stackoverflow.com/q/48252295
tags question: http://stackoverflow.com/q/48290623
tags question: http://stackoverflow.com/q/48236866
tags question: http://stackoverflow.com/q/48328012
tags question: http://stackoverflow.com/q/48237821
tags question: http://stackoverflow.com/q/48270073
tags question: http://stackoverflow.com/q/48241127
tags question: http://stackoverflow.com/q/48323397
tags question: http://stackoverflow.com/q/48202410
tags question: http://stackoverflow.com/q/48325729
tags question: http://stackoverflow.com/q/48225494
tags question: http://stackoverflow.com/q/48227180
tags question: http://stackoverflow.com/q/48310058
tags question: http://stackoverflow.com/q/48241916
tags question: http://stackoverflow.com/q/48272152
tags question: http://stackoverflow.com/q/48193130
tags question: http://stackoverflow.com/q/48273112
tags question: http://stackoverflow.com/q/48264720
tags question: http://stackoverflow.com/q/48191823
tags question: http://stackoverflow.com/q/48285635
tags question: http://stackoverflow.com/q/48318828
tags question: http://stackoverflow.com/q/48245809

http://stackoverflow.com/comment/83521381
type: Comment
comment on: http://stackoverflow.com/q/48179371
score: 1
type: QuestionComment
has text: Possible to get a sample repo with minimal test code reproducing the issue?

http://stackoverflow.com/q/48252227
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83496247
score: 0
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/83490397
has title: Scipy Optimizer or heuristic approach, which to choose for bottleneck capacity
accepted answer: http://stackoverflow.com/a/48256228
answer count: 1
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48256228
downvote count: 1
favorite count: 0
tagged with: optimization
has body: I am not able to formulate the below problem into scipy's linprog or minimize due to complex constraint condition. So wanted to check if there are other modules that allow below format of block constraints. Since, this also checks for the bottleneck capacity(which is taken care of by constraints in B14) my check was whether we should go for direct solvers or take a heuristic approach where we assign random numbers and keep re-balancing towards the slowest process. Iterating till numbers seem to converge ?. Details of the problem : Objective : F9, F10, F11 each individually and such that all are almost same(it's a constraint) - Background is that consider p1,p2 and p3 as serial processes and so I want maximum throughput from each and the same.(factoring bottleneck) Variables : C6:E8. These are percentage allocation and hence should be between (0,1)(bound) Constraint : i)Mentioned in 'objective' - the total output for each process should be the same. i.e. F9 = F10 = F11. ii)Also sum of allocation for a specific machine should be 100%. i.e. sum(C6:C8) = 1, sum(D6:D8) = 1 and sum(E6:E8) = 1 I need help in formulating the first constraint. How can I add a equation to ensure equality of those 3 cells(F9:F11) ?

http://stackoverflow.com/q/48326309
has answer: http://stackoverflow.com/a/76164920
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/48326639
tagged with: python
tagged with: docker
type: AnsweredQuestion
has title: How do I install python3 in docker with golang as my base image?
tagged with: docker-compose
answer count: 3
accepted answer: http://stackoverflow.com/a/48326639
has body: My docker file looks something like this: # Start from a Debian image with the latest version of Go installed # and a workspace (GOPATH) configured at /go. FROM golang # Install our Go dependencies RUN go get -u golang.org/x/oauth2... ENTRYPOINT /go/bin/... My base application will be running on golang,but I need to access a python script from golang for some processing. How do I install python3 in my docker container and install some of python dependencies using pip .
downvote count: 0
possible better answer: http://stackoverflow.com/a/67612446
has answer: http://stackoverflow.com/a/67612446
favorite count: 0
type: Question

http://stackoverflow.com/q/48189414
possible better answer: http://stackoverflow.com/a/48189617
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83359061
has comment: http://stackoverflow.com/comment/83360585
has answer: http://stackoverflow.com/a/48189617
has comment: http://stackoverflow.com/comment/83358853
type: Question
has comment: http://stackoverflow.com/comment/83359081
answer count: 2
downvote count: 4
upvote count: 3
has title: text file to dictionary as keys
accepted answer: http://stackoverflow.com/a/48189742
has comment: http://stackoverflow.com/comment/83361994
has answer: http://stackoverflow.com/a/48189742
favorite count: 0
type: AnsweredQuestion
has body: How can I convert file's words to dictionary as it's keys, directly, without using the list? Here is my code: def abc(f): with open(f, "r")as f: dict = {} lst = [] for line in f: lst += line.strip().split() for item in lst: dict[item] = "" return dict print(abc("file.txt")) Example of input "file.txt": abc def ghi jkl mno pqr Output: {"abc":"", "def":"", "ghi":"", "jkl":"", "mno":"", "pqr":""} The output of split() is a list. So, by use of that I need to read the data from file, store it on a list and then define it as dictionary's keys. My question is how can we ignore the list, and after reading data from file, put them directly to the dictionary?
has comment: http://stackoverflow.com/comment/83359096
has comment: http://stackoverflow.com/comment/83359679
has comment: http://stackoverflow.com/comment/83358858

wireless
type: Tag
tag name: wireless
tags question: http://stackoverflow.com/q/48227539

http://stackoverflow.com/comment/83561472
type: QuestionComment
has text: I thing metaclass is ok, you should overwrite __getattr__ in the metaclass and then get the value somehow. (Overwriting __new__ and just saving the kwargs in your case)
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48288163

http://stackoverflow.com/q/48185104
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83350415
has comment: http://stackoverflow.com/comment/83350188
has title: Fault Module Name : tcl85.dll
type: Question
has body: I have an application that was written in python (GUI by Tkinter module). I run by cmd (ex. python myprogram.py) but when my program open for 1-2 days it has a error "python.exe has stop working" In error details message in below picture. Does anyone know what it mean or how to fix this error?
tagged with: tkinter
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83350221

http://stackoverflow.com/a/48310519
accepted answer of: http://stackoverflow.com/q/48310109
upvote count: 3
answers question: http://stackoverflow.com/q/48310109
type: AcceptedAnswer
downvote count: 0
has body: This kinda reminds me of monads. Anyway, you can make a transparent generic logging decorator: def log(callback): def logger(fn): def logwrapper(*args, **kwargs): value = fn(*args, **kwargs) callback(value) return value return logwrapper return logger csv_callback = lambda x: print('writing {} to a csv file'.format(x)) xlsx_callback = lambda x: print('writing {} to an xlsx file'.format(x)) @log(csv_callback) @log(xlsx_callback) def test(a, b): return a + b In [2]: test(1, 2) writing 3 to an xlsx file writing 3 to a csv file Out[2]: 3 In [3]: test(2, 3) writing 5 to an xlsx file writing 5 to a csv file Out[3]: 5 You can also just pass several callbacks into the logger to avoid excessive nesting def log(*callbacks): def logger(fn): def logwrapper(*args, **kwargs): value = fn(*args, **kwargs) for callback in callbacks: callback(value) return value return logwrapper return logger @log(csv_callback, xlsx_callback) def test(a, b): return a + b
score: 3
type: Answer

http://stackoverflow.com/comment/83360309
has text: And `os.rename()` is *enough to move the file*, why use `shutil.move()` too? `shutil.move` is useful to move a *hierarchy of files*, not for individual files.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48190109

http://stackoverflow.com/comment/83457372
type: AnswerComment
comment on: http://stackoverflow.com/a/48237385
has text: Yes, Ive fixed that. Thank you though! It seems like after the fix the code runs, but is not random. Ive edited my original question above..please read and help :)
score: 0
type: Comment

http://stackoverflow.com/comment/137980337
type: AnswerComment
has text: @brad-martsberger: you seem far more knowledgeable than most on those questions. Could you have a look at this question: https://stackoverflow.com/questions/78230762/django-how-to-annotate-average-of-average
comment on: http://stackoverflow.com/a/48253635
score: 0
type: Comment

http://stackoverflow.com/comment/83330915
type: AnswerComment
has text: I like this. I’d use the method where though, personal preference . df.assign(col2=df.col2.where(mask, 7))
comment on: http://stackoverflow.com/a/48175426
score: 0
type: Comment

http://stackoverflow.com/a/48200238
score: 0
answers question: http://stackoverflow.com/q/48200075
type: Answer
has body: You have hanging DB connections, you need to close() the db at the end of your request. @rpc def get_feature(self, url): sql = 'select title_seg, entity_seg, title_entity_vec from article_feature where url_md5 = md5(\'{}\')'.format(url) self.cursor.execute(sql) result = self.cursor.fetchone() self.db.close() if result == None: return '' return '\t'.join(result)

http://stackoverflow.com/comment/83361648
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48190738
type: AnswerComment
has text: Load your images before the while loop starts, because it's slow to load them from the hard disk every frame.

http://stackoverflow.com/comment/83576695
score: 1
type: QuestionComment
type: Comment
has text: By definition, if you are not saving the whole object, you will be losing information. For example, on a later date, I suddenly want to compare weights of 3rd best model to the weights of 5th best model. Now instead of `pickle.load()` I must rerun those models again. Must I not? Also, I don't want to be attached to `sklearn`, since I'd like to use other hyperparam optimizers in a later date.
comment on: http://stackoverflow.com/q/48295661

http://stackoverflow.com/a/48204332
answers question: http://stackoverflow.com/q/48204075
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/83390077
has comment: http://stackoverflow.com/comment/83390472
has comment: http://stackoverflow.com/comment/83392330
has body: You are close. Use this class Step(object): pass class Derive1(Step): pass class Derive2(Step): pass _STEPS_BY_NAME = { 'foo': Step, 'bar': Derive1, 'bar': Derive2 } def get_step_by_name(name): return _STEPS_BY_NAME[name] Warning: there might be better approaches depending on what you are trying to achieve. Such a mapping from strings to methods is a maintenance nightmare. If you want to change the name of a method, you would have to remember to change it in multiple place. You won't get any autocomplete help from your IDE either.

http://stackoverflow.com/q/48201033
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/83385325
has title: How should I manage url versioning in Django
score: 0
tagged with: versioning
has body: I have a doubt about the optimal structure of my files. Right now, I have all my urls in a file api.py. The endpoints for a new version of the app are being located in a new api_v2.py file, only the urls that require a new version, is that ok? Also, if a new functionality is added to the app, should I put the new urls directly on api_v2.py? or maybe on the base api.py and keep the api_v2.py for the urls that have a "new version" of themselves? Any advice will help.
tagged with: python
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/83383388

http://stackoverflow.com/a/52497283
type: Answer
has comment: http://stackoverflow.com/comment/134779263
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48198894
has body: You're not the only one with this problem. It is in their FAQ: https://pipenv.readthedocs.io/en/latest/diagnose/#pipenv-does-not-respect-pyenvs-global-and-local-python-versions In short: Pipenv by default will not look at the pyenv python version. It'll use the version defined in the PIPENV_DEFAULT_PYTHON_VERSION env var. To make Pipenv respect the version set by pyenv, there are 3 way of doing that. You can either: Update your Pipfile with the correct version: [requires] python_version = "3.6.4" Manually specify the exact python with the --python option: pipenv --python 3.6.4 Set pipenv to always use the pyenv python version, regardless of what's in the Pipfile. To do that, set the PIPENV_PYTHON enviroment var to $PYENV_ROOT/shims/python

http://stackoverflow.com/comment/83574090
comment on: http://stackoverflow.com/a/48293676
score: 0
type: AnswerComment
has text: Yep it's fixed now, no exception is coming , you are legend man, thanks a ton But I am still clueless about what were doing wrong earlier ? Why there were exceptions with our code ??
type: Comment

http://stackoverflow.com/comment/90428206
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48249910
type: Comment
has text: How can I pass a variable to filter the values with a field?

http://stackoverflow.com/comment/83422972
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48220717
has text: It'd be helpful if you can guide me to add that image to the model database as ImageField.

http://stackoverflow.com/q/48323576
linked to: http://stackoverflow.com/q/45313301
answer count: 1
has title: Check if all rows in one array are present in another bigger array
favorite count: 0
type: Question
upvote count: 2
tagged with: numpy
linked to: http://stackoverflow.com/q/8317022
tagged with: arrays
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48323639
downvote count: 0
accepted answer: http://stackoverflow.com/a/48323639
has body: I have a large numpy array X= np.random.rand(1000,1000) then I have a smaller numpy array, which in this example could be generated by Y =X [[3,7,921],:] I would like to check programmatically whether all the rows of Y are in X. The solution should scale up well. Possibly without requiring additional dependencies. Inspired by: Get intersecting rows across two 2D numpy arrays So far I have tried: np.all([s in set([tuple(X) for x in X]) for s in set([tuple(y) for y in Y])]) but my logic must be flawed since I still get False when it should be True

http://stackoverflow.com/q/48185439
has comment: http://stackoverflow.com/comment/83350997
type: UnansweredQuestion
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/48186654
has body: I have a Python package I installed locally, thrift-sasl, but because of Python 3 compatibility issues I had to change the source code slightly, so I now have a "custom" version of thrift-sasl. I work with conda environments, and if I create a new one where I want to use thrift-sasl I don't want to have to make that manual change each time. Is a wheel the right way to "repackage" this library and if so, how do I do it? The wheel documentation doesn't obviously address this use case so I'm unsure.
has comment: http://stackoverflow.com/comment/83351373
downvote count: 0
has comment: http://stackoverflow.com/comment/83352681
upvote count: 1
answer count: 1
tagged with: pip
has title: How do I create a wheel from a manually altered Python package?
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83350759

http://stackoverflow.com/q/48234450
has answer: http://stackoverflow.com/a/48234646
tagged with: python
linked to: http://stackoverflow.com/q/8358533
has title: What is the equivalent of '\r\x1b[K' on Windows cmd.exe in Python?
has comment: http://stackoverflow.com/comment/83451751
type: AnsweredQuestion
score: 1
answer count: 1
upvote count: 1
linked to: http://stackoverflow.com/q/2048509
favorite count: 0
type: Question
has body: According to https://jcastellssala.com/2012/07/20/python-command-line-waiting-feedback-and-some-background-on-why/, '\r\x1b[K' is an escaping sequence that erases the current line in the console and rewrites something in Python. But when I tried to use the sequence on Windows cmd, it prints out weird characters instead. In Python, is there an equivalent sequence/action on Windows cmd where I can erase the last line I print out to the console?
accepted answer: http://stackoverflow.com/a/48234646
downvote count: 0

http://stackoverflow.com/a/48260294
downvote count: 0
has comment: http://stackoverflow.com/comment/83578984
score: 9
has body: str.startswith() accepts a tuple: &gt;&gt;&gt; a = ["let","test","g"] &gt;&gt;&gt; b = ["letter", "testing","good","egg","protest"] &gt;&gt;&gt; a = tuple(a) &gt;&gt;&gt; [item for item in b if item.startswith(a)] ['letter', 'testing', 'good']
upvote count: 9
type: Answer
answers question: http://stackoverflow.com/q/48260253

http://stackoverflow.com/comment/83494928
type: Comment
has text: like my homie @cᴏʟᴅsᴘᴇᴇᴅ said, please also see [link](https://stackoverflow.com/help/mcve)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48256062

http://stackoverflow.com/comment/83560581
comment on: http://stackoverflow.com/q/48287316
type: QuestionComment
score: 0
has text: @Usernamenotfound I tried it using pandas but i am not able to do it for a csv file. i am able to do it for individual sentences. Thank you
type: Comment

http://stackoverflow.com/comment/83464952
score: 1
comment on: http://stackoverflow.com/q/48241274
has text: Python 3 two kinds of division: division resulting in floats `/` and division resulting in ints `//`. I suspect you were looking for the latter
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48217059
has body: I want to add an image to a topframe in tkinter. It works on the MainMenu, but not on the SideMenu. When run, it should show _test.gif on the first menu, and when the button is pressed, open the second menu and show _test2.gif. Currently, the second menu is blank - no image. Code: import tkinter as tk class MainMenu(object): def __init__(self): self.launch_MainMenu() def launch_MainMenu(self): self._mainMenuWindow = tk.Tk() self.imageGIF = tk.PhotoImage(file="_test.gif"); self.imageLabel = tk.Label(self._mainMenuWindow,image=self.imageGIF) self.imageLabel.grid(row=0,column=1,padx=10,pady=10) tk.Button(self._mainMenuWindow,text="Next Menu", command=SideMenu).grid(row=0,column=2,padx=10) tk.mainloop() class SideMenu(object): def __init__(self): self.launch_sideMenu() def launch_sideMenu(self): self._sideWindow = tk.Toplevel() self.imageGIF2 = tk.PhotoImage(file="_test2.gif") self.imageLabel2 = tk.Label(self._sideWindow,image=self.imageGIF2) self.imageLabel2.grid(row=0,column=1,padx=10,pady=10)
score: 2
accepted answer: http://stackoverflow.com/a/48217515
type: AnsweredQuestion
answer count: 2
tagged with: tkinter
has answer: http://stackoverflow.com/a/48217515
linked to: http://stackoverflow.com/q/27049315
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83416412
has answer: http://stackoverflow.com/a/48217544
linked to: http://stackoverflow.com/q/16115378
favorite count: 0
has title: Embedding a tkinter image into a Toplevel
has comment: http://stackoverflow.com/comment/83416893
type: Question
has comment: http://stackoverflow.com/comment/83416762
tagged with: oop
has comment: http://stackoverflow.com/comment/83418440
possible better answer: http://stackoverflow.com/a/48217544
tagged with: python
has comment: http://stackoverflow.com/comment/83416444
has comment: http://stackoverflow.com/comment/83416391

http://stackoverflow.com/comment/83565649
has text: @BehzadJamali Basically I give the information that the compiler, that the data is continuous in the memory. That helps compiler to optimize code, thus `double[::1]` can be sometimes faster (but never slower). Actually for this example `double[::1]` is somewhat faster.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48276340

http://stackoverflow.com/q/48180251
answer count: 4
has comment: http://stackoverflow.com/comment/83421757
type: AnsweredQuestion
has title: Cannot upgrade sklearn, pip pointing to python3
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/48180307
has comment: http://stackoverflow.com/comment/83359049
score: 0
has answer: http://stackoverflow.com/a/48180307
has comment: http://stackoverflow.com/comment/83340511
tagged with: pip
accepted answer: http://stackoverflow.com/a/48180616
has answer: http://stackoverflow.com/a/49040985
has comment: http://stackoverflow.com/comment/83358992
has answer: http://stackoverflow.com/a/48180616
type: Question
has comment: http://stackoverflow.com/comment/83359113
has body: I wanted to upgrade sklearn in python 2.7 with pip but I couldn't because since a day or two pip seems to be pointing to python 3.4, not python 2.7: &gt; pip install -U scikit-learn Requirement already up-to-date: scikit-learn in /home/kinkyboy/.local/lib/python3.4/site-packages Cleaning up... This shows my current pip* commands: &gt; pip -V pip 1.5.4 from /usr/lib/python3/dist-packages (python 3.4) &gt; pip2 -V pip 1.5.4 from /usr/lib/python2.7/dist-packages (python 2.7) &gt; pip3 -V pip 1.5.4 from /usr/lib/python3/dist-packages (python 3.4) and this shows that python is using python 2.7: &gt; which python python is /usr/bin/python python is /home/kinkyboy/conda/bin/python &gt; ls -l /usr/bin/python lrwxrwxrwx 1 root root 9 Jan 6 2016 /usr/bin/python -&gt; python2.7* I managed to upgrade sklearn using pip2, but how to point pip back to python 2.7? Update: I tried the following and I get a permission denied error. &gt; python -m pip install -U --force-reinstall pip Collecting pip Using cached pip-9.0.1-py2.py3-none-any.whl Installing collected packages: pip Found existing installation: pip 9.0.1 Uninstalling pip-9.0.1: Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 778, in install requirement.uninstall(auto_confirm=True) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 754, in uninstall paths_to_remove.remove(auto_confirm) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path) File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 267, in renames shutil.move(old, new) File "/usr/lib/python2.7/shutil.py", line 303, in move os.unlink(src) OSError: [Errno 13] Permissi…
tagged with: python
has answer: http://stackoverflow.com/a/48198766

http://stackoverflow.com/comment/83367892
comment on: http://stackoverflow.com/q/48193704
score: 0
has text: `for letters in letters` is the culprit. change your loop variable name, specially in an inner loop (or reset `letters` inside the outer loop). Anyway, it should be `for letter in letters`.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48210367
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/83453660
has comment: http://stackoverflow.com/comment/83454339
has body: Why not simply encapsulate your Logic within a try :: except Block like so: iNumber = input ("Please, enter a Number: \n") try : # TRY CASTING THE ENTERED DATA TO A FLOAT... iNumber = float(iNumber) print ("Now your number is {} and its type is {}".format(iNumber, type(iNumber))) except: # IF CASTING FAILS, THEN YOU KNOW IT'S A STRING OR SO... # DO SOMETHING - THROW AN EXCEPTION OR WHATEVER... print ("Non Numeric Data is not acceptable...") UPDATE: If you wish to handle Complex Number Inputs (like you mentioned in your comment)... you could just wrap the Code above in an if - else block like so: import re iNumber = input ("Please, enter a Number: \n") # MATCH A SOMEWHAT COMPLEX NUMBER PATTERN if re.match(r"\d{1,}[ \-\+]*\d{1,}[a-z]", iNumber): print("Not possible to convert a complex number to float: {}".format(iNumber)) else: try : # TRY CASTING THE ENTERED DATA TO A FLOAT... iNumber = float(iNumber) print ("Now your number is {} and its type is {}".format(iNumber, type(iNumber))) except: # IF CASTING FAILS, THEN YOU KNOW IT'S A STRING OR SO... # DO SOMETHING - THROW AN EXCEPTION OR WHATEVER... print ("Non Numeric Data is not acceptable...")
answers question: http://stackoverflow.com/q/48209796

http://stackoverflow.com/comment/83451024
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48234193
type: AnswerComment
has text: It is deliberated, I'm forcing myself to avoid for and while loops, as I want to learn and practice pure functional programming workflows.

http://stackoverflow.com/comment/83478460
has text: So, are the variable names always at the end in curly braces?
score: 1
comment on: http://stackoverflow.com/q/48247844
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48298628
answer count: 0
upvote count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/83582223
downvote count: 0
has comment: http://stackoverflow.com/comment/83582147
has comment: http://stackoverflow.com/comment/83582588
has comment: http://stackoverflow.com/comment/83582617
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83582192
has comment: http://stackoverflow.com/comment/83600653
has comment: http://stackoverflow.com/comment/83581796
type: UnansweredQuestion
has title: Pandas error: cannot reindex from a duplicate axis
has comment: http://stackoverflow.com/comment/83581817
has comment: http://stackoverflow.com/comment/83603116
tagged with: python
score: 2
has body: I have a dateframe named Mj_rank, with date as Datetime and index which looks like this: A B C ... date 2016-01-29 False False True 2016-01-30 False False True 2016-02-01 True True True .... 2017-12-29 False True True Currently, the data is daily, but I would like to resample the data into a new df that contains every 6 months nth. Therefore I did: Mj_rank_s = Mj_rank.resample('6M').asfreq().tail() which gives me this output: ValueError: cannot reindex from a duplicate axis strangely enough, if I use other methods like max() or min() it works fine, but not "asfreq()". I tried different ways based on existing stackoverflow suggestions like adding in front, but didn't work : Mj_rank = Mj_rank.reset_index() Mj_rank['date'] = pd.to_datetime(Mj_rank['date']) Mj_rank = Mj_rank.set_index('date') Thanks a lot! Edit: Thanks to @jezrael he pointed out I had problems with duplicates using Mj_rank[Mj_rank.index.duplicated(keep=False)]

http://stackoverflow.com/q/48306122
has comment: http://stackoverflow.com/comment/83599020
has comment: http://stackoverflow.com/comment/83599089
has comment: http://stackoverflow.com/comment/83601317
has comment: http://stackoverflow.com/comment/83597337
has title: How to flattening of the code into a list comprehension?
tagged with: python
tagged with: list-comprehension
type: AnsweredQuestion
has body: I have this piece of code: for aaa_binary in groups(sources, a): if len(dodane_pary)!=count: g.add_nodes_from (aaa_binary) t1 = (aaa_binary[0],aaa_binary[1]) t2 = (aaa_binary[1],aaa_binary[2]) t3 = (aaa_binary[2],aaa_binary[3]) added_now = [] for edge in (t1,t2,t3): if not g.has_edge(*edge): g.add_edge(*edge) added_now.append(edge) dodane_pary.append(aaa_binary) for j in range(len(dodane_pary)): if nx.shortest_path(g, aaa_binary[0], aaa_binary[3])!=aaa_binary or nx.shortest_path(g, dodane_pary[j][0], dodane_pary[j][3])!=dodane_pary[j]: for edge in added_now: g.remove_edge(*edge) dodane_pary.remove(aaa_binary) break else: break Because of this, I probably will not be able to use multiprocessing in my program, so I would like to first test the speed of the code after flattening to comprehension as a list. How to do it best? Is it better to flatten with pieces? Just for example, for for/if pairs? Or maybe bigger pieces?
score: 0
has comment: http://stackoverflow.com/comment/83597468
has comment: http://stackoverflow.com/comment/83597445
answer count: 1
has answer: http://stackoverflow.com/a/48306200
accepted answer: http://stackoverflow.com/a/48306200
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/48194578
answers question: http://stackoverflow.com/q/48192342
has body: SAME padding means the size of output feature-maps are the same as the input feature-maps (under the assumption of stride=1). For instance, if the input is Nin is of size 28×28, then in the output you expect to get Nout feature maps each of size 28×28 as well. On the other hand, VALID padding means the size of the output feature-maps is reduced. For instance, if the input is Nin is of size 28x28, stride=1 and filter size is 3x3, then the output Nout feature-maps would be each of [{(28-3)/1}+1 = 26] 26x26. To deduce the output the formula is: {(size of Input - size of Filter)/stride} + 1 hence from the above formula, you can see that the size of the output feature-map is inversely proportional to the stride (Higher the stride value, smaller will be the output feature map)
score: 2
type: Answer
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/134308179
type: AnswerComment
has text: well, if you have a method returning booleans, I don't see any reason to use assertEqual
comment on: http://stackoverflow.com/a/48216491
type: Comment
score: 0

http://stackoverflow.com/comment/83564042
score: 0
has text: @StefanPochmann: No strong reason; the `tuple` approach is likely faster (Python caches and reuses small tuples, saving a little allocator overhead, and it allocates in a single block, not one for the object header and one for the elements, reducing memory fragmentation), but the difference is so trivial that's it likely to be lost in the noise; if you prefer the look of a one-element `list`, more power to ya. I just tend to default to `tuple` without thinking about it when `tuple` is legal and mutability is not needed.
type: Comment
comment on: http://stackoverflow.com/a/48287850
type: AnswerComment

http://stackoverflow.com/comment/83456437
type: AnswerComment
comment on: http://stackoverflow.com/a/48236843
score: 0
type: Comment
has text: Yes @Ken, totally should have done that. Added in now.

http://stackoverflow.com/q/48270260
type: Question
type: UnansweredQuestion
score: -2
has body: I have the following code in Python 3.6.0. I am a newbie and have been trying to get this code to work. I don't know how to get python to recognize (and reject) if the user enters the same username with capitals letters; below is the code. I would appreciate if you can show me how, please avoid comprehensions, just show me the full length code: (since "albert" is entered in new_user, I want the program to reject the user name since it is in the current_user in title letters. current_user = ["John","Peter","sam","Albert"] new_user = ["albert"] for name in new_user: if name.lower() in current_user: print ("Sorry Username is taken, please enter a new username") else: print ("Username accepted")
tagged with: python
tagged with: lowercase
tagged with: comparison
tagged with: list
downvote count: 3
has answer: http://stackoverflow.com/a/48270417
upvote count: 1
has title: How to compare usernames in python (comparing lists with title case objects)?
answer count: 1
favorite count: 0

http://stackoverflow.com/a/48194396
has body: Try the following one. Use this code for nodes with specific names: def removeOverride(): nuke.toNode("Remove1")['operation'].setValue('keep') nuke.toNode("Remove1")['channels'].setValue('rgb') nuke.addOnUserCreate(removeOverride(), nodeClass='Remove') # use UpperCamelCasing for any class name ('Blur','Read','Remove') Also for any subsequent nodes created, use this code: def removeOverride(): for node in nuke.allNodes(): if node.Class() == "Remove": node["operation"].setValue("keep") node["channels"].setValue("rgb") removeOverride() # OR nuke.addOnUserCreate(removeOverride(), nodeClass='Remove') And the last configuration using nuke.selectedNodes() and nuke.thisNode() methods is suitable for selected nodes in the DAG: def removeOverride(): thisNode = nuke.thisNode() rootDAG = nuke.root() with rootDAG: allNodesSelected = nuke.selectedNodes() try: allNodesSelected.remove(thisNode) except: pass for node in allNodesSelected: node["operation"].setValue("keep") node["channels"].setValue("rgb") return allNodesSelected nuke.addOnUserCreate(removeOverride(), nodeClass='Remove')
answers question: http://stackoverflow.com/q/48181666
type: Answer
accepted answer of: http://stackoverflow.com/q/48181666
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83375893
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83376034

http://stackoverflow.com/q/48244926
downvote count: 0
has title: Unexpected Output When Appending Objects to an Array
favorite count: 0
tagged with: object
type: Question
has comment: http://stackoverflow.com/comment/83472530
has body: In a program I am writing, I'm trying to append an object to a list, make a small change to that object, and then append the second version of the object to that list. The code below is not the one in which I encountered this error originally, but it shows the same problem. class A(object): def __init__(self): self.val = 0 def __str__(self): return str(self.val) a = A() b = [] for i in range(10): b.append(a) a.val += 1 for a in b: print(a) This is the expected output: 0 1 2 3 4 5 6 7 8 9 This is the actual output: 10 10 10 10 10 10 10 10 10 10
accepted answer: http://stackoverflow.com/a/48244978
tagged with: python
has answer: http://stackoverflow.com/a/48244978
possible better answer: http://stackoverflow.com/a/48244983
score: 2
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48244983
answer count: 2

http://stackoverflow.com/comment/83583158
has text: Glad to hear it! Spacy is a great library. Just be careful with 2.0.0+, as there are still some kinks being worked out. The Github issues are a good place to check: https://github.com/explosion/spaCy/issues
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48296863
score: 0

http://stackoverflow.com/comment/83452876
type: Comment
type: QuestionComment
has text: Well in order to dedupe a stream of strings, you would have to add them to a set as you see them. Otherwise you can't answer the question "have I seen this string before?".
score: 1
comment on: http://stackoverflow.com/q/48234658

http://stackoverflow.com/comment/83608780
has text: I just used sample_csv.Amount.str.extract(r'(\$?(?:\d[ ,.]?)+%?)(?=\s|$)') to pull out any regex matches from the Amount column
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48311191
type: Comment

http://stackoverflow.com/a/48180027
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48179874
downvote count: 0
has body: l = [5,5,1,2,2,3,4] def unique_list(l): se = set(l) # get all the unique elements of list lis = list(se) # convert set to list lis.sort(key=l.index) # preserve order of original list return lis print(unique_list(l))
score: 1

http://stackoverflow.com/comment/83487002
type: Comment
type: QuestionComment
score: 0
has text: did you run collectstatic ?
comment on: http://stackoverflow.com/q/48248072

http://stackoverflow.com/a/48191824
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48191375
has comment: http://stackoverflow.com/comment/83364678
has body: You can create a function to draw a single fry, then call that function multiple times: def draw_fry(canvas, x,y): canvas.create_polygon(x, y, x+10, y+150, x+20, y+150, x+10, y-20, fill="yellow", outline="black") for x in range(150, 260, 10): draw_fry(canvas, x, 100)
downvote count: 0

http://stackoverflow.com/a/57932654
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48205495
has body: Although other answer suggests to run both flask servers with different --port arguments, I wanted to share another issue to consider: Clear the browser cache Did you clear cache memory before running the second script? There are times when browser has previous data of the URL (including first port) still stored. So it will display old data (from first script and port) instead of fetching new data (from second script and port). You can clear the cache memory and then run the second script, access in browser and see it fetches the data correctly from the second app's URL.
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/102343803

http://stackoverflow.com/q/48290863
has body: I have a pandas dataframe that looks like: import pandas as pd df= pd.DataFrame({'Date':['2016-12-31','2018-12-31','2017-06-30','2019-06-30',],'Business':['FRC','FICC','FRC','FICC']\ ,'Amount':[10,100,20,200]}) df Amount Business Date 0 10 FRC 2016-12-31 1 100 FICC 2018-12-31 2 20 FRC 2017-06-30 3 200 FICC 2019-06-30 I wanted to use the re-index and interpolate functions to get an output such as : import pandas as pd df= pd.DataFrame({'Date':['2016-12-31','2018-12-31','2017-06-30','2019-06-30','2017-03-31','2019-03-31'],'Business':['FRC','FICC','FRC','FICC','FRC','FICC']\ ,'Amount':[10,100,20,200,15,150]}) df Amount Business Date 0 10 FRC 2016-12-31 1 100 FICC 2018-12-31 2 20 FRC 2017-06-30 3 200 FICC 2019-06-30 4 15 FRC 2017-03-31 5 150 FICC 2019-03-31 In essence, I need to divide the dataframe into two clusters and use the interpolate function on each cluster separately.So, the FRC cluster will have an interpolation of 15 and the FICC cluster an interpolation of 150
has title: Reindex and Interpolate on complex Pandas dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/83567511
has comment: http://stackoverflow.com/comment/83567424
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48291285
tagged with: pandas
has answer: http://stackoverflow.com/a/48291285
answer count: 1
has comment: http://stackoverflow.com/comment/83567435
type: Question

http://stackoverflow.com/q/48302947
has body: I try to get number of rows, columns and nonzeros values after presolve. I know about getAttr(GRB.Attr.NumVars), getAttr(GRB.Attr.NumConstrs)...but they give the statics before presolve. Can any one help me. Thanks
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48479898
tagged with: gurobi
has answer: http://stackoverflow.com/a/48479898
tagged with: python
tagged with: attributes
has title: Python Gurobi, report of statistics presolve
type: Question
score: 0
answer count: 1

http://stackoverflow.com/q/48214152
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83410223
has comment: http://stackoverflow.com/comment/83410247
has comment: http://stackoverflow.com/comment/83410331
possible better answer: http://stackoverflow.com/a/48214251
has comment: http://stackoverflow.com/comment/83410134
type: Question
tagged with: python-3.x
has title: ValueError when iterating through simple list
has comment: http://stackoverflow.com/comment/83410092
has body: I am trying (as a newb Pythoneer) to translate an old homework assignment from Java to Python. I am getting a TypeError when I try to iterate through a list. It is claiming that I am not using an integer value for my index, but I can't see how I am not. I've probably included too much code, but just in case the error isn't where I think it is (TypeError is on very last line): def power(x, y): if isinstance(y, int): solution = x if y == 0: return 1 else: for i in range(1,y): solution = solution*x return solution else: raise TypeError("Power: Non-Integer power argument") def factorial(x): if isinstance(x, int) and x &gt;= 0: if x == 1 or x == 0: return 1 else: solution = int(x) while x &gt; 1: solution = solution*(x-1) x -= 1 return solution else: raise TypeError("Factorial: argument must be a positive integer") def abs(x): if x &lt; 0: x = -x return x # Calculates the coefficients of the # Taylor series of Sin(x). # center argument must be 0, pi/4, pi, or 3pi/2 def coef_calc(center): coef = [1]*32 i = int(0) c_temp = 1 # temporary holding place for calculated coefficient if center in [0, PI/4, PI, 3*PI/2]: # Mclauren Series (center = 0) if center == 0: while c_temp &gt; 1.0e-31: c_temp = power(-1, i)/factorial(2*i + 1) coef[i] = c_temp i += 1 else: raise ValueError("Argument not in [0, pi/4, pi, 3pi/2]") return coef # CONSTANTS PI = 3.1415926535897932 SQRT_TWO = 1.41421356237309504880 if __name__ == "__main__": print(power(4,2)) print(factorial(4)) print(abs(-0)) coef = coef_calc(0) for x in coef: print(coef[x] + "\n")
has comment: http://stackoverflow.com/comment/83410065
tagged with: python
has answer: http://stackoverflow.com/a/48214251
has answer: http://stackoverflow.com/a/48214360
accepted answer: http://stackoverflow.com/a/48214360
has comment: http://stackoverflow.com/comment/83410373

http://stackoverflow.com/comment/83361718
comment on: http://stackoverflow.com/q/48190726
has text: Your goal doesn't seem like a good idea. Just like you write files with a csv writer, you read files with a csv reader-- otherwise your code is going to break when you suddenly have your split character in a cell.
type: Comment
type: QuestionComment
score: 4

http://stackoverflow.com/comment/83522924
score: 1
type: Comment
has text: I have a problem with that answer - it assumes that the keys are strings with a cretain pattern. There are more general solutions.
type: AnswerComment
comment on: http://stackoverflow.com/a/48269733

http://stackoverflow.com/a/53568193
upvote count: 3
answers question: http://stackoverflow.com/q/48241820
downvote count: 0
type: Answer
has body: For Flask's app.config, load the second set of variables after the first. Flask's below example references two different access methods, but it should work for similar successive uploads as well. Most applications need more than one configuration. There should be at least separate configurations for the production server and the one used during development. The easiest way to handle this is to use a default configuration that is always loaded and part of the version control, and a separate configuration that overrides the values as necessary as mentioned in the example above: app = Flask(__name__) app.config.from_object('yourapplication.default_settings') app.config.from_envvar('YOURAPPLICATION_SETTINGS') For a more explicit overwrite, take a look at using flask app.config.update after you load your config from your existing config file. update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None. app.config.from_envvar('DEFAULT_CONFIG_FILE') app.config.update('OVERRIDING_CONFIG_FILE') http://flask.pocoo.org/docs/1.0/config/
score: 3

http://stackoverflow.com/comment/83485059
type: QuestionComment
has text: why are there 3 " in the string - thats unbalanced - me eyes huuuuuurt
comment on: http://stackoverflow.com/q/48251280
score: 0
type: Comment

http://stackoverflow.com/comment/113504826
has text: Simply, you could add a `hostname` field in your compose file so that django will consume the hostname in a correct way. E.g. `hostname: yourserver.com`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48251925
score: 0

http://stackoverflow.com/q/48218076
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48218250
favorite count: 0
has comment: http://stackoverflow.com/comment/83418257
type: Question
has comment: http://stackoverflow.com/comment/83418312
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/1373164
has comment: http://stackoverflow.com/comment/83418390
tagged with: python
has body: I'm trying to read a bunch of csvs into pandas using a for loop. I want the table names to be the last bit of the full file path before the extension. For example, ACS_BV0002_2016_Age.csv would be Age I am doing this so I can create dictionaries with the table name as a key and the column names and data types as values, which I can then use in psycogpg2 to create all of my tables in postgresql in one fell swoop. This seems to get the name i want: path = r"C:\Data\Waste_Intervention\Census_Tables\Cleaned" fList = os.listdir(path) for doc in fList: csv = "{}\\{}".format(path, doc) name = doc.split("_")[-1][:-4] pd.read_csv(csv) Is there a way I can use the output of name become the variable name for the dataframe read in by pd.read_csv?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83418398
score: 0
duplicate of: http://stackoverflow.com/q/1373164
has title: How can I use a string to set a variable name for my DataFrame?
has comment: http://stackoverflow.com/comment/83418344
tagged with: pandas
has comment: http://stackoverflow.com/comment/83418281
answer count: 1
accepted answer: http://stackoverflow.com/a/48218250
has comment: http://stackoverflow.com/comment/83418431

http://stackoverflow.com/a/48197121
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48196885
has body: It is hard to know for sure but have you checked that all of the required dependencies for your project are either in the same folder as the created executable or (at least) in your path? The other alternative that I am aware of (and use) is cx_Freeze. This particular exe builder has cross platform support. cx_Freeze will attempt to automatically find all dependent python modules and include them in the final build. I imagine that the other two options work in the same manner. Packages that cannot be automatically located and binary dependencies (eg dlls, sos) must be explicitly specified in the build configuration scripts. One method I have for debugging for missing dependencies is to manually copy the suspected missing dependency into the same folder as the .exe to see if it fixes the issue. If it does then I will specify it in the build configuration script. See https://cx-freeze.readthedocs.io/en/latest/distutils.html for cx_Freeze documentation, in particular section titled build_exe. Here is a good example of a non-trival setup.py for cx_Freeze: http://www.pythonexample.com/code/cx_freeze-setup/

http://stackoverflow.com/comment/95290456
type: AnswerComment
has text: where did you do this?
comment on: http://stackoverflow.com/a/48179971
type: Comment
score: 0

http://stackoverflow.com/q/48194230
downvote count: 1
has answer: http://stackoverflow.com/a/48194804
has comment: http://stackoverflow.com/comment/83370091
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83369342
has comment: http://stackoverflow.com/comment/83370051
has comment: http://stackoverflow.com/comment/83369181
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python
has title: How to extract info in the title from div in beautifulsoup?
has comment: http://stackoverflow.com/comment/83369222
linked to: http://stackoverflow.com/q/43005780
tagged with: beautifulsoup
score: 0
upvote count: 1
has body: I am trying to extract just the rating from the html posted in the screenshot. It is embedded in title under div. This code below returns "None" HTML: from bs4 import BeautifulSoup html_soup = BeautifulSoup(response.text, 'html.parser') type(html_soup) rest_container = html_soup.find_all('div', class_ = 'i-stars i-stars--regular-5 rating-large') first_rest=rest_container[0] print (first_rest.text)
has comment: http://stackoverflow.com/comment/83369316
answer count: 1

http://stackoverflow.com/comment/118876644
has text: For negative values, does "greater" mean larger in magnitude or smaller in magnitude? Conventionally, for negative values, greater should mean smaller in magnitude, but is that the case here?
type: AnswerComment
comment on: http://stackoverflow.com/a/48246255
score: 2
type: Comment

http://stackoverflow.com/q/48204515
has answer: http://stackoverflow.com/a/48204579
accepted answer: http://stackoverflow.com/a/48204579
tagged with: python
has title: Change column details in pandas
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
has body: I have a pandas dataframe as follows. mydata = xxx yyy zzz nnn ddd mmm 0 0 10 5 5 5 5 1 0 9 2 3 4 4 2 1 8 8 7 9 0 Now, I want to change the values in the column xxx in a way, if it contains 0 add n else if 1 add y. So, output should look as follows. mydata = xxx yyy zzz nnn ddd mmm 0 n 10 5 5 5 5 1 n 9 2 3 4 4 2 y 8 8 7 9 0 Is it possible to do such data changes in pandas? Or are there any python library I can use instead?
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/48305487
has comment: http://stackoverflow.com/comment/83597929
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/16685384
has title: Find position of instance of class in a list
has comment: http://stackoverflow.com/comment/83598481
tagged with: python
accepted answer: http://stackoverflow.com/a/48305542
tagged with: class
has answer: http://stackoverflow.com/a/48305542
type: AnsweredQuestion
tagged with: list
has body: Given a class, say class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart I would like to find the position in a list of an instance of this class. For instance, given list = [1, 2, 3, Complex(1, 1)] how can I find the position of Complex(1, 1)? I tried list.index(Complex(1, 1)), but the object created from the second call to Complex is not the same as the first, so this results in a ValueError exception being raised. How could I do this? More generally, how could I find the position in a list of any instances of Complex (e.g. for list = [1, Complex(1, 1), 2, Complex(2, 2)] to return 1 and 3)?
has comment: http://stackoverflow.com/comment/83598206
score: 1
linked to: http://stackoverflow.com/q/16685384
has comment: http://stackoverflow.com/comment/83596076
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/84023229
score: 0
type: AnswerComment
has text: Thanks for the hardwork! I've performed similar tinkering and find the same results. Upvoting for your thorough efforts!
comment on: http://stackoverflow.com/a/48231603
type: Comment

http://stackoverflow.com/q/48266106
tagged with: python
tagged with: amazon-web-services
has body: My apologies for basic question. I am completely new to AWS as well as Python. I am trying to do sample code given in https://boto3.readthedocs.io/en/latest/guide/migrations3.html#accessing-a-bucket but facing a error. import botocore import boto3 s3 = boto3.resource('s3') bucket = s3.Bucket('bucketname') exists = True try: s3.meta.client.head_bucket(Bucket='bucketname') except botocore.exceptions.ClientError as e: # If a client error is thrown, then check that it was a 404 error. # If it was a 404 error, then the bucket does not exist. error_code = int(e.response['Error']['Code']) if error_code == 404: exists = False Error in logs is "errorMessage": "Handler 'lambda_handler' missing on module 'lambda_function'"
has answer: http://stackoverflow.com/a/53948320
has title: Missing handler error in AWS Lambda
type: AnsweredQuestion
answer count: 3
possible better answer: http://stackoverflow.com/a/64139792
has comment: http://stackoverflow.com/comment/83524681
upvote count: 26
has answer: http://stackoverflow.com/a/64139792
linked to: http://stackoverflow.com/q/40741822
favorite count: 0
tagged with: aws-lambda
type: Question
has comment: http://stackoverflow.com/comment/83515347
accepted answer: http://stackoverflow.com/a/48266238
score: 26
has answer: http://stackoverflow.com/a/48266238
downvote count: 0

http://stackoverflow.com/comment/83338146
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48178993
has text: Don't think so for that particular question because this question's code not contain `raw_input`.
score: 1

http://stackoverflow.com/comment/83511411
has text: Second line, try `parser = argparse.ArgumentParser(epilog='\tExample: \r\npython ' + sys.argv[0])` instead of `parser = argparse.ArgumentParser(epilog='\tExample: \r\npython ' + sys.argv[0] + ")`
score: 0
comment on: http://stackoverflow.com/q/48264081
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48212564
answers question: http://stackoverflow.com/q/48212428
type: AcceptedAnswer
has body: Use this, which convert dataframe to boolean for rating equals to zero then to a numpy ndarray and use np.sum which defaults to axis=None summing the entire array: df.eq(0).values.sum() Output 3
accepted answer of: http://stackoverflow.com/q/48212428
type: Answer
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/83492748
type: Comment
type: QuestionComment
has text: The server is free to decide what origins to accept or reject - in this case it doesn't like the origin of your client. It would require server configuration modification to change this. I was mistaken that websockets used CORS - they don't use the specific CORS protocol, but the server receives the origin and is free to act upon it.
score: 0
comment on: http://stackoverflow.com/q/48254749

http://stackoverflow.com/a/48231599
has comment: http://stackoverflow.com/comment/83446719
has comment: http://stackoverflow.com/comment/83446095
has comment: http://stackoverflow.com/comment/83447424
has comment: http://stackoverflow.com/comment/83446653
score: 0
has comment: http://stackoverflow.com/comment/83446355
has comment: http://stackoverflow.com/comment/83446601
has comment: http://stackoverflow.com/comment/83445749
has comment: http://stackoverflow.com/comment/83446635
has comment: http://stackoverflow.com/comment/83446360
has comment: http://stackoverflow.com/comment/83445405
has comment: http://stackoverflow.com/comment/83445466
has comment: http://stackoverflow.com/comment/83446047
has comment: http://stackoverflow.com/comment/83446752
has comment: http://stackoverflow.com/comment/83446609
has comment: http://stackoverflow.com/comment/83446556
has comment: http://stackoverflow.com/comment/83445729
has comment: http://stackoverflow.com/comment/83446236
answers question: http://stackoverflow.com/q/48231441
type: Answer
has comment: http://stackoverflow.com/comment/83446083
has comment: http://stackoverflow.com/comment/83446575
has comment: http://stackoverflow.com/comment/83445891
has comment: http://stackoverflow.com/comment/83446770
has comment: http://stackoverflow.com/comment/83446827
has comment: http://stackoverflow.com/comment/83445835
has body: It's not advisable to use root without password. In some databases you are forced to set it if you want to connect as root. You can set any password: dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html Also, 8080 might be the port of your web server, not the mySQL one, try with 3306 port which is the default one for mySQL. You can open my.cnf file located in the /Applications/XAMPP/xamppfiles/etc/ directory to chech in which port is your database listening. Also check that the mySQL daemon is running. In mac os X go to /Applications/XAMPP/XAMPP Control in Finder and check that Apache and MySQL are running. If your MySQL server isn't starting, you may need to set the permissions for it using Terminal with this command: chmod -R 777 /Applications/XAMPP/xamppfiles/var To check that your Articles database exists: mysql -u root -p USE Articles; If it's not created; mysql -u root -p CREATE DATABASE Articles; And connect this way: #!/usr/bin/python import MySQLdb connection = MySQLdb.connect(host="localhost", user="root", passwd="your pwd", db="Articles")

http://stackoverflow.com/a/48328762
answers question: http://stackoverflow.com/q/48328601
type: Answer
has body: df'start','end' = pd.DataFrame(df.Date.str.split('to ').tolist()) You'll have to split the date column on to
score: 0

http://stackoverflow.com/q/48175666
has comment: http://stackoverflow.com/comment/83333751
tagged with: pandas
has body: Im trying to deploy a pandas data frame to a URL and get the return from some fields in new columns in the same data frame.The aim is to loop through each row. The data frame looks like this : name state postcode VIC NSW ACT NT coles VIC 2501 Y N N N woolworth NSW 3409 N Y N N big w ACT 3201 N N Y N target NT 1089 N N N Y I want the name of my columns per row to be deployed and the results in new columns as the example show below. The code below works but I can only make work manually. import urllib.request as req name = '' postcode = '' legalName = '' tradingName = '' NSW = '' SA = '' ACT = '' VIC = '' WA = '' NT = '' QLD = '' TAS = '' authenticationGuid = 'b6aaddd4-8463-4d76-9e24-99530f5df326' #Your GUID should go here #Constructs the URL by inserting the search parameters specified above #GETs the url (using urllib.request.urlopen) conn = req.urlopen('http://abr.business.gov.au/abrxmlsearchRPC/AbrXmlSearch.asmx/' + 'ABRSearchByNameSimpleProtocol?name=' + name + '&amp;postcode=' + postcode + '&amp;legalName=' + legalName + '&amp;tradingName=' + tradingName + '&amp;NSW=' + NSW + '&amp;SA=' + SA + '&amp;ACT=' + ACT + '&amp;VIC=' + VIC + '&amp;WA=' + WA + '&amp;NT=' + NT + '&amp;QLD=' + QLD + '&amp;TAS=' + TAS + '&amp;authenticationGuid=' + authenticationGuid) #XML is returned by the webservice #Put returned xml into variable 'returnedXML' #Output xml string to file 'output.xml' and print to console returnedXML = conn.read() f = open('output.xml', 'wb') f.write(returnedXML) f.close print(returnedXML)
has comment: http://stackoverflow.com/comment/83343838
tagged with: url
tagged with: loops
has title: Loop every row from a pandas data frame to a url using urllib and return XML results in a same file
type: Question
score: 0
answer count: 0
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/48226295
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/83435437
has comment: http://stackoverflow.com/comment/83434213
score: 0
upvote count: 1
tagged with: max
downvote count: 1
answer count: 1
has title: Max Value displayed on matplotlib plot following navigation
has comment: http://stackoverflow.com/comment/83455380
tagged with: plot
favorite count: 0
type: Question
has body: I'm trying to return the maximum data value shown on a plot flowing navigation (e.g. pan or zoom). Currently ax.get_ylim(), returns the max value of the y axis, and not the data displayed. Is this a bug within Matplotlib?
has answer: http://stackoverflow.com/a/72133154
has comment: http://stackoverflow.com/comment/83440506
has comment: http://stackoverflow.com/comment/83434270
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83435923

http://stackoverflow.com/comment/83621419
comment on: http://stackoverflow.com/q/48316527
has text: Do you need the KEY printed in **bold** as all keywords are or in normal text as arguments?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83549806
type: AnswerComment
has text: @AKHILMATHEW what I meant was: have you tried saving this to your database and displaying it on your front ?
comment on: http://stackoverflow.com/a/48281263
type: Comment
score: 0

http://stackoverflow.com/comment/83445197
type: QuestionComment
has text: I'm not sure what the problem with non-stationarity is, but the ar lag polynomial needs to use negtive ar params, `ar=np.append(1., -resid_model.arparams)` (We take it to the left side in the ARMA process equation.)
score: 0
comment on: http://stackoverflow.com/q/48225511
type: Comment

http://stackoverflow.com/q/48247029
has comment: http://stackoverflow.com/comment/83477734
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48247205
type: UnansweredQuestion
has title: Is it possible to read HTML tables into pandas with style tag?
tagged with: python
has comment: http://stackoverflow.com/comment/83476729
score: 3
upvote count: 3
tagged with: pandas
downvote count: 0
has body: I am trying to use pandas read_html function to read the "Official List of the House of Representatives," located here. Using df_list = pd.read_html('http://clerk.house.gov/member_info/olmbr.aspx',header=0,encoding = "UTF-8") house = df_list[0] I do get a nice DataFrame with the representatives name, state, and district. The header is correct and the encoding also. So far so good. However, the problem is the party. There is no column for the party. Instead, the party is denoted by the font (roman or italic). Looking at the HTML source, here's an entry for a democrat: Adams, Alma S. NC 12th and here's an entry for a republican: Anderholt, Robert B. AL 4th Republicans are lacking the tags around their name. How would one go about retrieving this information? Can it be done with pandas or do I need some more sophisticated HTML parsers? If so, which ones?
tagged with: http://stackoverflow.com/tag/html
answer count: 1

http://stackoverflow.com/comment/83484211
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48250610
has text: I put a number next to each of the items in a list starting from 1 onwards, and because lists start from 0 I had to subtract 1 from the user input so that they select the right one. What my code does is turn that code into a blank ("") so that if they want to add something to the list I will make sure that it gets filled. However, my code also allows people to view the list and it ends up like this 'a','','c','d'. Is there any way to make it invisible to the user

http://stackoverflow.com/q/48282462
has comment: http://stackoverflow.com/comment/83548827
answer count: 1
has comment: http://stackoverflow.com/comment/83548887
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: performance
has comment: http://stackoverflow.com/comment/83548569
has comment: http://stackoverflow.com/comment/83548823
has title: How to improve the speed of comparing strings in lists(millions of data)?
has comment: http://stackoverflow.com/comment/83548777
has answer: http://stackoverflow.com/a/48282795
accepted answer: http://stackoverflow.com/a/48282795
tagged with: python
has body: The code that will compare city and sort to file for city in uniqueCity: file = open(city+".txt","a+") for data in salesData: if data[2] == city: file.write(",".join(data).replace(","," ")) file.write("\n") file.close()
has comment: http://stackoverflow.com/comment/83548516
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83548635

http://stackoverflow.com/comment/83620050
comment on: http://stackoverflow.com/a/48313227
type: Comment
has text: Regarding the last point, I have a doubt : Let say you read a pandas dataFrame object with 2 columns `v1,v2` and then you sum these columns to get `sum_v1, sum_v2` Then you would insert this into a CDS one by one. So the first time when you insert `sum_v1` to CDS, it throws this warning that the length is not equal(1,0)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83366985
type: Comment
type: QuestionComment
has text: Python regex (and most regex engines) only returns last match for a group. Why don't you just split on `.` and then do whatever you need.
comment on: http://stackoverflow.com/q/48193148
score: 0

http://stackoverflow.com/comment/83739569
type: Comment
has text: I would restrict `min_samples_leaf` so that there is a minimum number of samples in each leaf, which will be used to compute probabilities (with one sample you get [0, 1] - with e.g. 10 samples you can get [0, 0.1, 0.2, ..., 0.9, 1]). You are going to have to experiment with the settings to find which numbers work best for you and your data.
comment on: http://stackoverflow.com/a/48260611
score: 5
type: AnswerComment

http://stackoverflow.com/comment/83576181
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/48295661
type: Comment
has text: Keras recommends to use [model.save()](https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model). Scikit [recommends joblib](http://scikit-learn.org/stable/modules/model_persistence.html). After tuning the params with RandomizedSearchCV, you can just use `trial_search.best_estimator_` to get your best fitted model and then use keras recommended method on that. Why do you want to save a RandomizedSearhCV object anyways?

http://stackoverflow.com/comment/83334202
score: 0
comment on: http://stackoverflow.com/q/48176564
type: Comment
type: QuestionComment
has text: ectually nothing, I ve got full HTML code like nothing is work

http://stackoverflow.com/a/48302842
has body: You can not change the icon directly. But you can change it if you get access to underlying Qt widgets. import maya.cmds as cmds from maya import OpenMayaUI as omui # Special cases for different Maya versions try: from shiboken2 import wrapInstance except ImportError: from shiboken import wrapInstance try: from PySide2.QtGui import QIcon from PySide2.QtWidgets import QWidget except ImportError: from PySide.QtGui import QIcon, QWidget # Create a window and save its name window = cmds.window(title='GUI') # Show the newly created window cmds.showWindow(window) # Get a pointer and convert it to Qt Widget object qw = omui.MQtUtil.findWindow(window) widget = wrapInstance(long(qw), QWidget) # Create a QIcon object icon = QIcon('/path/to/icon.png') # Assign the icon widget.setWindowIcon(icon)
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48237226

http://stackoverflow.com/q/48258144
favorite count: 0
linked to: http://stackoverflow.com/q/32557920
type: Question
has comment: http://stackoverflow.com/comment/83498766
tagged with: typeerror
duplicate of: http://stackoverflow.com/q/4187185
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48258166
has answer: http://stackoverflow.com/a/48258177
tagged with: python
has title: How could I check if an addition of two variables are same type in Python?
has body: For below program, How could I detect the variable TypeError previously other than truly running it? Does Pylint or pyflake8 has this feature? #!/usr/bin/env python3 # -*- coding: utf-8 -*- A = 1 B = 'b' print(A+B)
answer count: 2
score: 1
linked to: http://stackoverflow.com/q/4187185
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83498778

http://stackoverflow.com/q/48273315
has answer: http://stackoverflow.com/a/48273326
accepted answer: http://stackoverflow.com/a/48273326
upvote count: 3
answer count: 1
downvote count: 0
has title: Pandas skip missing values in map function
favorite count: 0
type: Question
type: AnsweredQuestion
score: 3
has body: Any help on how can I skip missing values in my world field. I thought na_action='ignore' would help, but it doesn't for my case . df['world'] = df['world'].map(lambda x: x.rstrip('L.locoMoco'),na_action='ignore') Thanks
tagged with: pandas
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/48324044
has title: Celery doesn't see tasks when django DEBUG is set to False
tagged with: django
tagged with: celery
has body: I've got a Django application with Celery. Tasks are described in tasks.py files with @shared_task in different apps, each has its own AppConfig and is being installed (added to INSTALLED_APP) correctly. Everything worked fine until I turned DEBUG off. Celery started to fail due to tasks of unregistered type. With the DEBUG variable Celery can see all of my tasks and work correctly. EDIT: My celery.py code is as following: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') app = Celery('APP') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Running manage.py check shows no errors, all config files and logs have correct rights. What can cause such a bug?
type: Question
has comment: http://stackoverflow.com/comment/83633383
type: AnsweredQuestion
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/48489579
answer count: 1
accepted answer: http://stackoverflow.com/a/48489579

http://stackoverflow.com/comment/83370982
comment on: http://stackoverflow.com/q/48194381
type: Comment
type: QuestionComment
has text: @MadPhysicist which input parametre exactly?
score: 0

http://stackoverflow.com/comment/83519787
score: 0
has text: @Martin, I have tried that too, but it did not work.
comment on: http://stackoverflow.com/q/48267879
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83553248
type: Comment
comment on: http://stackoverflow.com/q/48282748
type: QuestionComment
has text: My array of ~50,000 items (in each a & b) Using your answer Divakar: 1.92 ms ± 48.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) Using the other answer: 97.6 ms ± 3.07 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) So 2 orders of magnitude, something to be expected of doing it vectorised. Thank you all for your answers :).
score: 1

http://stackoverflow.com/comment/83494765
has text: @roganjosh I was comparing the test script I have above with the script I am writing and you are correct with one more tab for the mycursor.execute line. The issue with my main Python script was the tab's for the values under the For Loop. They were lined up with the word For in the loop and not inside the loop I should have looked closer at the other For Loops and values I am very new to coding and I did not go to college for software development I am learning on my own by coding and making mistakes I say not bad for picking up Python, postgres, mysql, VB, Java, C++, android in 6 - 8 months
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48253150

http://stackoverflow.com/q/48288763
has comment: http://stackoverflow.com/comment/83562428
has title: Python regex match human names with abbr (dots) in text
tagged with: python
has comment: http://stackoverflow.com/comment/83566083
tagged with: regex
has body: I want to use regex to match patterns in paragraphs like the following: ©2016 Rina Foygel Barber and Emil Y. Sidky. Many optimization problems arising in high-dimensional statistics decompose naturally into a sum of several terms, where the individual terms are relatively simple but the composite objective function can only be optimized with iterative algorithms. In this paper, we are interested in optimization problems of the form F(Kx) + G(x), where K is a fixed linear transformation, while F and G are functions that may be nonconvex and/or nondifferentiable. In particular, if either of the terms are nonconvex, existing alternating minimization techniques may fail to converge; other types of existing approaches may instead be unable to handle nondifferentiability. We propose the mocca (mirrored convex/concave) algorithm, a primal/dual optimization approach that takes a local convex approximation to each term at every iteration. Inspired by optimization problems arising in computed tomography (CT) imaging, this algorithm can handle a range of nonconvex composite optimization problems, and offers theoretical guarantees for convergence when the overall problem is approximately convex (that is, any concavity in one term is balanced out by convexity in the other term). Empirical results show fast convergence for several structured signal recovery problems. So that the first line with human names, year, and copyright (©2016 Rina Foygel Barber and Emil Y. Sidky.) can be removed. The only I can come up now was to use ^© ?[0-9][0-9][0-9][0-9].+\.. However, this can hardly match things like the above paragraph due to the . in human names. Any suggestions? Thanks!
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48289327
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48289327
type: Question
has comment: http://stackoverflow.com/comment/83563395

http://stackoverflow.com/comment/83594867
type: Comment
type: QuestionComment
has text: @binjip Sorry I forgot tu write it. I did but before the `with Session...`
score: 0
comment on: http://stackoverflow.com/q/48303854

http://stackoverflow.com/q/48294224
type: AnsweredQuestion
score: 0
tagged with: pandas
has body: Using LDAP a dataset has been pulled from Active Directory. The date looks like "20180111120926.0Z" and it has been loaded into pandas DataFrame. How do I convert it to a normal date?
has comment: http://stackoverflow.com/comment/83573373
tagged with: python
has answer: http://stackoverflow.com/a/48294327
type: Question
has title: convert LDAP date into normal human date?
answer count: 1
accepted answer: http://stackoverflow.com/a/48294327
has comment: http://stackoverflow.com/comment/83573702

http://stackoverflow.com/comment/83669033
has text: Well, I did not find a basic documentation of the `Poly` command. So, if someone is missing the basics, everything that follows can only be very complicated. If you search the web for "sympy solve inequality", you end up here: http://docs.sympy.org/latest/modules/solvers/inequalities.html, with no remark that one should better just use solveset (which is also much more comfortable)
type: Comment
comment on: http://stackoverflow.com/a/48284736
type: AnswerComment
score: 1

http://stackoverflow.com/comment/83421479
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48219927
has text: Did you try `import test01`? Or am I missing something?

http://stackoverflow.com/q/48310832
has comment: http://stackoverflow.com/comment/83607673
has title: Creating a list of regex matches from a data frame in Python and then counting the number of matches
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/83607654
has answer: http://stackoverflow.com/a/48311000
has comment: http://stackoverflow.com/comment/83607595
answer count: 2
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
tagged with: dataframe
favorite count: 0
type: Question
has body: I'm trying to -match the number of times a dollar/cent/percent appears in a column in a data frame -create a function that lists all of these matches -create a function that count the number of matches I'm able to successfully use regex to find the matches, but I'm unable to get a list to appear and count them. I tried using str.extract() to list out all of the matches and str.contains().sum() to count the number of matches. However, I can't get these to work at the same time and I'm not sure if this is even the right approach. Here's what I have so far: (?:^|\s)(\$?(?:\d[ ,.]?)+%?)(?=\s|$) This will match any dollar/cent or percent, and accounts for a bunch of different typos that I'm trying to include so the regex string is fine. import re import pandas as pd sample_csv = pd.DataFrame({'SMS_text': ['$1', '214-233-4455'], 'SMS_number': ['1', '1'], 'Amount': ['12.12%', '$10.12'], 'Percent': ['10%', '1']}) sample_csv.Amount.str.extract(r'(\$?(?:\d[ ,.]?)+%?)(?=\s|$)') This will list out the matches from the Amount column. 0 12.12% 1 $10.12 Name: Amount, dtype: object And if I substitute str.extract() with sample_csv.Amount.str.contains(r'(\$?(?:\d[ ,.]?)+%?)(?=\s|$)').sum() it will tell me how many matches there are (i.e. 2) but again, I can't get them to work at the same time. Is this the right approach or am I setting this up wrong? Seems like maybe a findall() or maybe an re.compile() might work better, but I'm not sure how to get these to work properly. My desired output from above would be something like: regex_number_matches = ['12.12%', '$10.12'] regex_number_matches_count = 2
has answer: http://stackoverflow.com/a/48311191
type: UnansweredQuestion

http://stackoverflow.com/comment/83645882
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48330016
has text: explain yourself better, I do not understand what you want, it would be very helpful if you endorse an image indicating what you want.
type: Comment

http://stackoverflow.com/comment/83634728
type: Comment
has text: From what package?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48323141

http://stackoverflow.com/q/48323226
has title: How to get specific column key from data frame given a particular element?
has answer: http://stackoverflow.com/a/48323329
has body: Consider the data frame c1 c2 c3 0 a 3 4 2 1 b 1 2 7 say I want to know which column in row 1 has the element 7. how will I achieve it? I am trying to achieve it using pandas.
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83631984
answer count: 2
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48323627
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48323329
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/48323627
tagged with: python

http://stackoverflow.com/q/48182882
has comment: http://stackoverflow.com/comment/83349845
possible better answer: http://stackoverflow.com/a/48183326
tagged with: pandas-groupby
downvote count: 0
has comment: http://stackoverflow.com/comment/83346468
tagged with: pandas
has comment: http://stackoverflow.com/comment/83345618
has comment: http://stackoverflow.com/comment/83348388
tagged with: group-by
has comment: http://stackoverflow.com/comment/83346450
has comment: http://stackoverflow.com/comment/83349786
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/83349552
has comment: http://stackoverflow.com/comment/83346595
has answer: http://stackoverflow.com/a/48183529
accepted answer: http://stackoverflow.com/a/48183529
has comment: http://stackoverflow.com/comment/83347031
has comment: http://stackoverflow.com/comment/83346085
has body: I'm designing a function similar to the GatherBy in Mathematica. I thought it could be easily done by dressing up groupby function in Pandas. This function will group the list by certain given characteristic function. Setup time1 = pd.date_range(start=datetime.datetime(2015, 1, 30), end=datetime.datetime(2015, 2, 5)) datedat = np.array([time1, 0.1 * numpy.arange(7), 0.2 * numpy.arange(7)]).T print(datedat) array([[Timestamp('2015-01-30 00:00:00', freq='D'), 0.0, 0.0], [Timestamp('2015-01-31 00:00:00', freq='D'), 0.1, 0.2], [Timestamp('2015-02-01 00:00:00', freq='D'), 0.2, 0.4], [Timestamp('2015-02-02 00:00:00', freq='D'), 0.3, 0.6], [Timestamp('2015-02-03 00:00:00', freq='D'), 0.4, 0.8], [Timestamp('2015-02-04 00:00:00', freq='D'), 0.5, 1.0], [Timestamp('2015-02-05 00:00:00', freq='D'), 0.6, 1.2]], dtype=object) Suppose I want to group it by year and month —— you see there are data for January and February. So I design a characteristic function: gatherf = lambda x: ((x[0].year)*1000+x[0].month) For every time-data records, this gatherf would calculate a value for groupby to distinguish time. Objective my final object is to develop a function gather_by, by which gather_by(datedat, gatherf) Should generate this: array([[[Timestamp('2015-01-30 00:00:00', freq='D'), 0.0, 0.0], [Timestamp('2015-01-31 00:00:00', freq='D'), 0.1, 0.2]], [[Timestamp('2015-02-01 00:00:00', freq='D'), 0.2, 0.4], [Timestamp('2015-02-02 00:00:00', freq='D'), 0.3, 0.6], [Timestamp('2015-02-03 00:00:00', freq='D'), 0.4, 0.8], [Timestamp('2015-02-04 00:00:00', freq='D'), 0.5, 1.0], [Timestamp('2015-02-05 00:00:00', freq='D'), 0.6, 1.2]]], dtype=object) My Effort In general cases, the datedat might have more column than 3. I couldn't group them one by one. So I tried: datedatF2 =pandas.DataFrame({'dat':datedat,'gather_key':numpy.array(list(map(gatherf, datedat)))}) with groupedall=datedatF2['dat'].groupby(datedatF2['gather_key']) but this leads to Data must be 1-dimensional error. what should I do?
has comment: http://stackoverflow.com/comment/83346352
has comment: http://stackoverflow.com/comment/83346732
type: Question
upvote count: 2
has title: Mathematica's GatherBy function using Pandas groupby
has comment: http://stackoverflow.com/comment/83349621
answer count: 2
has answer: http://stackoverflow.com/a/48183326
has comment: http://stackoverflow.com/comment/83346743
has comment: http://stackoverflow.com/comment/83346416
favorite count: 0
has comment: http://stackoverflow.com/comment/83349680
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/83470320
type: QuestionComment
has text: Please post text, not images. In any case, I can't reproduce the problem. I suspected a `from __future__ import unicode_literals` was used above this code, but it didn't cause the error. `struct.unpack` didn't care if its first parameter was Unicode or not. Make a small, **completely** reproducible example that can be cut-and-pasted and tested. You'll probably figure out the problem by trying to do that anyway.
comment on: http://stackoverflow.com/q/48239221
score: 2
type: Comment

http://stackoverflow.com/a/48319987
has comment: http://stackoverflow.com/comment/83625277
type: Answer
has comment: http://stackoverflow.com/comment/83627847
has comment: http://stackoverflow.com/comment/83625384
score: 0
has comment: http://stackoverflow.com/comment/83625363
has comment: http://stackoverflow.com/comment/83625373
answers question: http://stackoverflow.com/q/48319759
has body: Hard to answer without seeing your code. However, you've already implemented the initial components of exception handling. else may not be necessary, but it sounds like a finally clause is a requirement in this situation. Finish the block to ensure the socket is closed: try: # unreliable process except: return '450 Please try again later" else: # successful outcome finallY: socket.close()
has comment: http://stackoverflow.com/comment/83628072
has comment: http://stackoverflow.com/comment/83630779
has comment: http://stackoverflow.com/comment/83625426
has comment: http://stackoverflow.com/comment/83625396
has comment: http://stackoverflow.com/comment/83625422

http://stackoverflow.com/a/48268962
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48268903
has comment: http://stackoverflow.com/comment/83522799
type: Answer
has body: Try this: d = {'message': {'caption_entities': [], 'channel_chat_created': False, 'chat': {'first_name': 'Rodrigo Formighieri', 'id': 446924384, 'type': 'private', 'username': 'rodrigoformi'}, 'date': 1516040454, 'delete_chat_photo': False, 'entities': [{'length': 7, 'offset': 0, 'type': 'bot_command'}], 'from': {'first_name': 'Rodrigo Formighieri', 'id': 446924384, 'is_bot': False, 'language_code': 'pt-BR', 'username': 'rodrigoformi'}, 'group_chat_created': False, 'message_id': 145, 'new_chat_member': None, 'new_chat_members': [], 'new_chat_photo': [], 'photo': [], 'supergroup_chat_created': False, 'text': '/invite'}, 'update_id': 241263441} is_bot = d.get('message').get('from').get('is_bot') print (is_bot) # False
has comment: http://stackoverflow.com/comment/83522085
score: 2

http://stackoverflow.com/comment/83483794
score: 0
type: Comment
has text: Well of course you can implement your own Python too. Bu that seems like it was out of scope of your question.
type: AnswerComment
comment on: http://stackoverflow.com/a/48246704

http://stackoverflow.com/a/48180601
has comment: http://stackoverflow.com/comment/83342371
accepted answer of: http://stackoverflow.com/q/48179891
type: AcceptedAnswer
downvote count: 0
has body: The task you want is not heavy, it is periodic so using a thread is inappropriate, for this task we can use QVariantAnimation. The other part is to create a method that moves to a certain line of text for it we use QTextCursor next to findBlockByLineNumber() of QTextDocument. And for the last one we must start moving to the last initial visible for it we use the cursorForPosition() method through the size of the viewport(). longText = "\n".join(["{}: long text - auto scrolling ".format(i) for i in range(100)]) class AnimationTextEdit(QTextEdit): def __init__(self, *args, **kwargs): QTextEdit.__init__(self, *args, **kwargs) self.animation = QVariantAnimation(self) self.animation.valueChanged.connect(self.move) @pyqtSlot() def startAnimation(self): self.animation.stop() lines_per_second = 2 self.moveToLine(0) p = QPoint(self.viewport().width() - 1, self.viewport().height() - 1) cursor = self.cursorForPosition(p) self.animation.setStartValue(cursor.blockNumber()) self.animation.setEndValue(self.document().blockCount()-1) self.animation.setDuration(self.animation.endValue()*1000/lines_per_second) self.animation.start() @pyqtSlot(QVariant) def move(self, i): cursor = QTextCursor(self.document().findBlockByLineNumber(i)) self.setTextCursor(cursor) class MyApp(QWidget): def __init__(self): super(MyApp, self).__init__() self.setFixedSize(600, 400) self.txt = AnimationTextEdit(self) self.btn = QPushButton("Start", self) self.layout = QHBoxLayout(self) self.layout.addWidget(self.txt) self.layout.addWidget(self.btn) self.txt.append(longText) self.txt.move(0) self.btn.clicked.connect(self.txt.startAnimation) if __name__ == "__main__": app = QApplication(sys.argv) window = MyApp() window.show() sys.exit(app.exec_()) Update: if you want a continuous movement you must use verticalScrollBar(): longText = "\n".join(["{}: long text - auto scrolling ".format(i) for i in range(100)]) class AnimationTextEdit(QTextEdit): def __init__(self, *args, **kwargs): QTextEdit.__init__(self, *args…
answers question: http://stackoverflow.com/q/48179891
has comment: http://stackoverflow.com/comment/83520003
type: Answer
has comment: http://stackoverflow.com/comment/83459002
upvote count: 4
score: 4

http://stackoverflow.com/a/48249452
has comment: http://stackoverflow.com/comment/83520818
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48249159
has comment: http://stackoverflow.com/comment/83519917
score: 2
has body: I would propose to do it like this: mylist = [["tim_tam", 879.3000000000001], ["yummy_tim_tam", 315.0], ["pudding", 298.2], ["chocolate_pudding", 218.4], ["biscuits", 178.20000000000002], ["berry_tim_tam", 171.9], ["tiramusu", 158.4], ["ice_cream", 141.6], ["vanilla_ice_cream", 122.39999999999999]] d = set() # remembers unique keys, first one in wins for i in mylist: shouldAdd = True for key in d: if i[0].find(key) != -1: # if this key is part of any key in the set shouldAdd = False # do not add it if not d or shouldAdd: # empty set or unique: add to set d.add(i[0]) myCleanList = [x for x in mylist if x[0] in d] # clean list to use only keys in set print(myCleanList) Output: [['tim_tam', 879.3000000000001], ['pudding', 298.2], ['biscuits', 178.20000000000002], ['tiramusu', 158.4], ['ice_cream', 141.6]] If the order of things in the list is not important, you could use a dictionary directly - and create a list from the dict. If you need sublists, create them: similarThings = [ [x for x in mylist if x[0].find(y) != -1] for y in d] print(similarThings) Output: [ [['tim_tam', 879.3000000000001], ['yummy_tim_tam', 315.0], ['berry_tim_tam', 171.9]], 'tiramusu', 158.4, [['ice_cream', 141.6], ['vanilla_ice_cream', 122.39999999999999]], [['pudding', 298.2], ['chocolate_pudding', 218.4]], 'biscuits', 178.20000000000002 ] As @joaquin pointed out in the comment, I am missing the creategarbageterms() functions that groups tiramusu and biscuits with pudding to fit the question 100% - my answer is advocating "do not modify lists in interations, use appropriate set or dict filter it to the groups. Unique keys here are keys that are not parts of later mentioned keys.

http://stackoverflow.com/q/48320175
type: Question
has body: Creating graphs using the the matplotlib 3d polycollection (https://matplotlib.org/examples/mplot3d/polys3d_demo.html). I have changed the x axis range however unlike with 2d graphs the data outside of the axis range is still visible. Is there a way change this without altering the data? My graph: my code: fig = plt.figure() axes = fig.gca(projection='3d') palette_1 = sns.color_palette("husl", (num_colours)) poly = PolyCollection(verts, edgecolors = 'black', facecolors = palette_1) poly.set_alpha(0.7) axes.add_collection3d(poly, zs = z_set, zdir = 'y') x_min = float(5) x_max = float(25) axes.set_xlim3d(x_min, x_max) axes.set_ylim3d(10, 60) axes.set_zlabel('Intensity (%)') axes.set_zlim3d(0, 100)
score: 0
linked to: http://stackoverflow.com/q/37563526
tagged with: matplotlib
tagged with: python
has title: x axis alteration for matplotlib 3d polycollection
answer count: 0
has comment: http://stackoverflow.com/comment/83633040
has comment: http://stackoverflow.com/comment/83627519
has comment: http://stackoverflow.com/comment/83625743
type: UnansweredQuestion

http://stackoverflow.com/comment/83465879
type: Comment
type: AnswerComment
has text: I copy pasted the dictionary that I am using [here](https://justpaste.it/1fnn2). Please try using this as your dictionary, hopefully, you will see the same problem as me.
score: 0
comment on: http://stackoverflow.com/a/48240500

http://stackoverflow.com/q/48224674
tagged with: read-the-docs
tagged with: windows
has answer: http://stackoverflow.com/a/48228584
downvote count: 0
answer count: 1
has body: I have a small app project on github which runs on Windows and requires pythonnet. My requirement.txt contains: beautifulsoup4==4.6 pythonnet==2.3 Now I thought I would build a documentation for it and put it on readthedocs.org. After pushing my documentation to github, importing my project on readthedocs.org, I tried to build the documentation but this operation failed with: Collecting pythonnet==2.3 (from -r /home/docs/checkouts/readthedocs.org/user_builds/trelloradar/checkouts/latest/requirements.txt (line 2)) Using cached pythonnet-2.3.0.tar.gz Building wheels for collected packages: pythonnet Running setup.py bdist_wheel for pythonnet: started Running setup.py bdist_wheel for pythonnet: finished with status 'error' Complete output from command /home/docs/checkouts/readthedocs.org/user_builds/trelloradar/envs/latest/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-iU2ADR/pythonnet/setup.py'; f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/tmpnPH_1rpip-wheel- --python-tag cp27: running bdist_wheel running build running build_ext /bin/sh: 1: mono: not found Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/tmp/pip-build-iU2ADR/pythonnet/setup.py", line 405, in &lt;module&gt; zip_safe=False, ... File "/usr/lib/python2.7/subprocess.py", line 541, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command 'mono tools/nuget/nuget.exe update -self' returned non-zero exit status 127 I understand that the build fails because it is trying to install .Net material, namely pythonnet, on a Unix environment, but I just want to build the docs with Sphinx! I have disabled the venv option: Install your project inside a virtualenv using setup.py install But how do I tell readthedocs' build process to ignore my requirement.txt?
favorite count: 0
type: Question
score: 5
tagged with: pythonnet
upvote count: 5
has title: How can I get readthedocs.org build to ignore my requirement.txt?
tagged with: python
tagged with: requirements.txt
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48228584

http://stackoverflow.com/q/48330086
linked to: http://stackoverflow.com/q/10865116
has title: Issue with button command on Tkinter
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83645963
has body: Code from tkinter import * class Thing: var = {} def item(self): self.root = Tk() # Settings of main window things = [] # Array which contains items with different values for thing in things: # 1* self.var[f'b{thing}'] = Button(self.root, text='Test',command = lambda: self.remove(thing)) self.var[f'b{thing}'].pack() def remove(self, thing=None): print(thing) # 2* Thing().item() Question When I press for the first time any button, the class remove print the correct value, when I try to press another button, the class 'remove' print another time the first value instead of second. I'm thinking that the issue is in buttons command. I appreciate every kind of help, thanks in advance.
has answer: http://stackoverflow.com/a/48330139
tagged with: python
score: -1
tagged with: lambda
has comment: http://stackoverflow.com/comment/83645926
tagged with: class
type: AnsweredQuestion
upvote count: 0
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/48330139

http://stackoverflow.com/comment/83547749
type: QuestionComment
comment on: http://stackoverflow.com/q/48281925
score: 0
type: Comment
has text: and what is the expected output?

http://stackoverflow.com/comment/83585620
score: 1
type: QuestionComment
has text: I don't believe the question is a duplicate of that specific Q&A, though I'd guess there is a better one out there...
type: Comment
comment on: http://stackoverflow.com/q/48300501

http://stackoverflow.com/comment/83452037
has text: i dont think it does and i think thats where the main problem lies, but the problem with that is that i dont know how to make it exit the mainloop? Because i think the issue is that when from the menu it plays zy_mainloop() it just continues where it was which is at the gameover screen
comment on: http://stackoverflow.com/a/48226345
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/48215222
downvote count: 0
has comment: http://stackoverflow.com/comment/83414089
has comment: http://stackoverflow.com/comment/83412623
tagged with: web-scraping
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83412326
favorite count: 0
has title: Web scraping with python's request module requires submit button
type: Question
has comment: http://stackoverflow.com/comment/83412519
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83414379
tagged with: python
has comment: http://stackoverflow.com/comment/83413502
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/83413770
has comment: http://stackoverflow.com/comment/83414117
has body: I'm trying to web scrape my grades off of this website. I have this which enters the login info (I think): import requests def main(): login = {'username':'USERNAME', 'password':'PASSWORD'} url = 'https://parent-portland.cascadetech.org/portland/Login_Parent_PXP.aspx?regenerateSessionId=True' r = requests.post(url, login) r.submit() print(r.text) main() It looks like you have to press a button. &lt;input name="Submit1" id="Submit1" value="Login" cssclass="btn" text="Login" onclick="this.disabled=true;this.form.submit();" type="submit"&gt; However, I just learned this today and I have no idea how to do this with the requests module.
has comment: http://stackoverflow.com/comment/83413733
answer count: 0

http://stackoverflow.com/q/48216974
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83432612
has answer: http://stackoverflow.com/a/48283709
accepted answer: http://stackoverflow.com/a/48283709
answer count: 3
has comment: http://stackoverflow.com/comment/83432508
has comment: http://stackoverflow.com/comment/83432479
has comment: http://stackoverflow.com/comment/83426500
has answer: http://stackoverflow.com/a/48292825
has body: The curve is: import numpy as np import scipy.stats as sp from scipy.optimize import curve_fit from lmfit import minimize, Parameters, Parameter, report_fit# import xlwings as xw import os import pandas as pd I tried running a simply curve fit from scipy: This returns Out[156]: (array([ 1., 1.]), array([[ inf, inf], [ inf, inf]])) Ok, so I thought I need to start bounding my parameters, which is what solver does. I used lmfit to do this: params = Parameters() params.add I tried to nudge python to the right direction by changing the starting parameters: or using curvefit:
downvote count: 1
has comment: http://stackoverflow.com/comment/83431754
tagged with: excel
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48226927
has comment: http://stackoverflow.com/comment/83432830
has comment: http://stackoverflow.com/comment/83432698
upvote count: 5
has title: Curve fit - function failing
has answer: http://stackoverflow.com/a/48226927
linked to: http://stackoverflow.com/q/14854339
has comment: http://stackoverflow.com/comment/83432971
tagged with: curve-fitting
tagged with: python
score: 4
linked to: http://stackoverflow.com/q/35903506
has comment: http://stackoverflow.com/comment/83432501
has comment: http://stackoverflow.com/comment/83571522
has comment: http://stackoverflow.com/comment/83432230
has comment: http://stackoverflow.com/comment/83551658

http://stackoverflow.com/comment/83557886
has text: Why are you using python2.7? Will not be maintained [past 2020](https://pythonclock.org/).
comment on: http://stackoverflow.com/q/48286609
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83473507
type: QuestionComment
comment on: http://stackoverflow.com/q/48245128
score: 1
has text: Do you necessarily want to modify the list you pass in in place?
type: Comment

http://stackoverflow.com/comment/83636828
comment on: http://stackoverflow.com/a/48196801
type: Comment
has text: I have taken more time to reflect on this and think that populating 'totals_before' with the value of the 'oil' column where Date == BeforeDate is the way to get this into production fastest. In the example above, Well_1 would forward fill the value of 10, Well_2 would forward fill the value of 800 if it were under the 'Oil' column and so on. I'm unsure of how to filter in that regard when you are grouping by WellName.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48302932
has comment: http://stackoverflow.com/comment/83590649
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83591536
has comment: http://stackoverflow.com/comment/83590992
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/83590853
has comment: http://stackoverflow.com/comment/83590748
has comment: http://stackoverflow.com/comment/83592274
has title: How to reconcile itertools.product with multiprocessing?
has comment: http://stackoverflow.com/comment/83591974
tagged with: python-itertools
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83591091
tagged with: python
has body: I have the code shared at https://codereview.stackexchange.com/q/185129/157474. And I'm trying to use multiprocessing. I used such a remodeling: count=1 def foo(i): global count dobre2=[] if tuple(reversed(i)) &gt;= tuple(i): a = ['v{}'.format(x%2) for x in i] # the rest of the code return dodane_pary And: if __name__ == '__main__': pool = mul.Pool(4) result = pool.map(foo, itertools.product(tuple(range(2)), repeat=4)) pool.close() pool.join() print (result) Instead: count=1 dobre2=[] for i in itertools.product(tuple(range(2)), repeat=4): if tuple(reversed(i)) &gt;= tuple(i): a = ['v{}'.format(x%2) for x in i] # the rest of the code Expected output: [[0, 2, 4, 6], [0, 2, 4, 1], [0, 2, 3, 8], [0, 2, 3, 5], [2, 3, 8, 7], [6, 1, 3, 8], [2, 3, 5, 9], [11, 0, 2, 3], [11, 4, 1, 5], [7, 1, 5, 9]] Unfortunately, I do not receive the expected exit, but the list in this form: [[[0, 2, 4, 6]], [[0, 2, 4, 6], [0, 2, 4, 1]], [[0, 2, 1, 4]], [[0, 2, 4, 6], [0, 2, 4, 1], [0, 2, 3, 5]], [[0, 2, 1, 4]], [[0, 2, 1, 4], [2, 1, 4, 3]], [[0, 2, 4, 6], [0, 2, 4, 1], [0, 2, 3, 5], [0, 7, 9, 8]], [[0, 2, 1, 4], [2, 1, 4, 3], [0, 5, 7, 3]], [[0, 2, 1, 4], [2, 1, 4, 3], [0, 5, 7, 3]], [[0, 2, 1, 4], [2, 1, 4, 3], [0, 5, 7, 3], [5, 0, 2, 1]], [[0, 2, 1, 4], [2, 1, 4, 3], [0, 5, 7, 3], [5, 0, 2, 1]], [[0, 2, 1, 4], [2, 1, 4, 3], [0, 5, 7, 3], [5, 0, 2, 1], [1, 4, 3, 7]], [[0, 2, 1, 4], [2, 1, 4, 3], [0, 5, 7, 3], [5, 0, 2, 1], [1, 4, 3, 7]], [[0, 2, 1, 4], [2, 1, 4, 3], [0, 5, 7, 3], [5, 0, 2, 1], [1, 4, 3, 7]], [[0, 2, 1, 4], [2, 1, 4, 3], [0, 5, 7, 3], [5, 0, 2, 1], [1, 4, 3, 7]], [[0, 2, 1, 4], [2, 1, 4, 3], [0, 5, 7, 3], [5, 0, 2, 1], [1, 4, 3, 7], [3, 7, 5, 9]]] In addition, every time I start the program, I get some changed results as if the processes were randomly assigned. What am I doing wrong? How to synchronize it well?
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83592016
has comment: http://stackoverflow.com/comment/83591354
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/83603767
score: 0
type: Comment
has text: Why are you passing `date=datetime.timedelta(days=7)` to the new `Calendar` object? A `timedelta` is not a date.
type: QuestionComment
comment on: http://stackoverflow.com/q/48308933

ctypes
tags question: http://stackoverflow.com/q/48177254
tags question: http://stackoverflow.com/q/48308845
tags question: http://stackoverflow.com/q/48287040
tags question: http://stackoverflow.com/q/48204483
tags question: http://stackoverflow.com/q/48320638
tag name: ctypes
type: Tag
tags question: http://stackoverflow.com/q/48255196
tags question: http://stackoverflow.com/q/48184882

http://stackoverflow.com/q/48189835
downvote count: 0
accepted answer: http://stackoverflow.com/a/48189908
upvote count: 1
has comment: http://stackoverflow.com/comment/83359715
has answer: http://stackoverflow.com/a/48189908
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48189923
has body: I am looking at US census data: population State County Alabama Jefferson County 658466 Mobile County 412992 Madison County 334811 Alaska Anchorage Municipality 291826 Fairbanks North Star Borough 97581 Matanuska-Susitna Borough 88995 Final output should sum up the population for each state: State SumOfPopulation Alabama 1406269 Alaska 478402 My attempts with groupby yielded in below error df.groupby('State')['population'].agg('sum') KeyError: 'STNAME' What the appropriate approach would look like?
has title: Group By and SUM column
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/48189923
type: AnsweredQuestion
answer count: 2
score: 1

http://stackoverflow.com/comment/83685511
type: Comment
comment on: http://stackoverflow.com/a/48330492
has text: This is AMAZING! I cannot thank you enough. Not only did this solve my problem, but I learned a lot about how to navigate BS4 objects as well. I altered the code to now give me the most recent 15 games (most recent ones are at the bottom unfortunately, not the top), and everything works awesome now. I'm working with some debugging now where if a game is cancelled, it throws an error, so I'm making some exceptions for that. Anyways, thank you so much once again. This gave me a breakthrough in my project and gave me so much motivation to continue. Cheers and have a great one :)
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83495361
type: AnswerComment
has text: pq do not have pop function
comment on: http://stackoverflow.com/a/48256279
type: Comment
score: 0

http://stackoverflow.com/comment/83504258
has text: I am trying to use cv2.contourArea(cnt) to find the area of each contour and then exclude the ones below a certain value. By doing this, if he finds a circle in number 6 it will make all the image white, not only that specified contour.
comment on: http://stackoverflow.com/q/48259724
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48276477
tagged with: lxml
score: 1
has body: How do you remove a comment like this using lxml without loosing the value Apple iPhone 5s (Space Grey, 16 GB) &lt;h1 class="_3eAQiD" data-reactid="144"&gt; &lt;!-- react-text: 145 --&gt; Apple iPhone 5s (Space Grey, 16 GB) &lt;!-- /react-text --&gt; &lt;/h1&gt;
linked to: http://stackoverflow.com/q/18313818
downvote count: 1
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
has comment: http://stackoverflow.com/comment/94037260
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/10436695
duplicate of: http://stackoverflow.com/q/18313818
answer count: 1
accepted answer: http://stackoverflow.com/a/48276514
tagged with: python
has comment: http://stackoverflow.com/comment/83549916
has answer: http://stackoverflow.com/a/48276514
type: AnsweredQuestion
has title: How to remove comments from HTML LXML

http://stackoverflow.com/comment/83599798
score: 0
has text: Yes! The code above gets me the os cursor position, but, it returns the X and Y of the screen. Not of any particular window.
type: QuestionComment
comment on: http://stackoverflow.com/q/48306887
type: Comment

http://stackoverflow.com/q/48286251
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/48290463
has comment: http://stackoverflow.com/comment/83564357
favorite count: 0
has comment: http://stackoverflow.com/comment/83561302
has body: I just added some music to my pygame game but I think the code is so messy that nothing is in the right place. As a result of this addition, I'm now getting this error: Traceback (most recent call last): File "C:\Users\1234\AppData\Local\Programs\Python\Python36-32\My First game ERROR.py", line 31, in for event in pygame.event.get(): pygame.error: video system not initialized Here is the code that I have written: import pygame, sys pygame.mixer.init(44100, -16,2,2048) class Game(object): def main(self, screen): import time pygame.mixer.music.load('The Tonight Show Star Wars The Bee Gees Stayin Alive Shortened.mp3') pygame.mixer.music.play(-1, 0.0) #class Player(pygame.sprite.Sprite): # def __init__(self, *groups): # super(Player, self.__init__(*groups) #self.image = pygame.image.load('Sprite-01.png') # self.rect = pygame.rect.Rect((320, 240), self.image.get_size()) #def update(self): # key = pygame image = pygame.image.load('Sprite-01.png') clock = pygame.time.Clock() # initialize variables image_x = 0 image_y = 0 while 1: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.quit(): pygame.quit() if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: pygame.quit() image_x += 0 key = pygame.key.get_pressed() if key[pygame.K_LEFT]: image_x -= 10 if key[pygame.K_RIGHT]: image_x += 10 if key[pygame.K_UP]: image_y -= 10 if key[pygame.K_DOWN]: image_y += 10 screen.fill((200, 200, 200)) screen.blit(image, (image_x, image_y)) pygame.display.flip() pygame.mixer.music.stop(52) if __name__ == '__main__': pygame.init() screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption('St.Patrick game') Game().main(screen)
tagged with: python
has answer: http://stackoverflow.com/a/48290463
tagged with: pygame
has answer: http://stackoverflow.com/a/48287618
possible better answer: http://stackoverflow.com/a/48287618
has comment: http://stackoverflow.com/comment/83565587
type: AnsweredQuestion
answer count: 2
has title: Windows/Python pygame.error: video system not initialized after adding Mp3 file
score: 1
upvote count: 1

http://stackoverflow.com/comment/83615032
score: 0
comment on: http://stackoverflow.com/q/48314387
type: Comment
type: QuestionComment
has text: @Pattu: Are these just properties for you to personally use while querying the database in an interactive shell? Or will you be utilizing these properties in code?

http://stackoverflow.com/a/48243123
has comment: http://stackoverflow.com/comment/84438207
has comment: http://stackoverflow.com/comment/83605395
type: Answer
accepted answer of: http://stackoverflow.com/q/48187981
has comment: http://stackoverflow.com/comment/83582465
downvote count: 0
upvote count: 1
score: 1
has body: Running your code gave me some "Invalid Operation Error: 1282" messages for the glReadPixels call. Instead, here is a simple demo I just wrote that shows how to obtain the color and the depth buffer from OpenGL for a rendered triangle. What I do here is bind an FBO (framebuffer object) to the screen with the desired texture attachments (for receiving the color and depth data). I then read out the data from the GPU using glGetTexImage. Using textures might not be the fastest approach, but this is pretty simple and should work nicely. Let me know if anything in this is unclear and I will elaborate on it. from OpenGL.GL import * from OpenGL.GLUT import * import numpy as np import sys def draw_scene(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glBegin(GL_TRIANGLES) glColor3f(1, 0, 0) glVertex3f(-1, -1, 0) glColor3f(0, 1, 0) glVertex3f(0, 1, 0) glColor3f(0, 0, 1) glVertex3f(1, -1, 0) glEnd() def draw_texture(): global color_texture glColor3f(1, 1, 1) glBindTexture(GL_TEXTURE_2D, color_texture) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glBegin(GL_QUADS) glTexCoord2f(0, 0) glVertex3f(-1, -1, 0) glTexCoord2f(0, 1) glVertex3f(-1, 1, 0) glTexCoord2f(1, 1) glVertex3f(1, 1, 0) glTexCoord2f(1, 0) glVertex3f(1, -1, 0) glEnd() glBindTexture(GL_TEXTURE_2D, 0) def update_display(): global fbo, color_texture, depth_texture #Render the scene to an offscreen FBO glBindFramebuffer(GL_FRAMEBUFFER, fbo) draw_scene() glBindFramebuffer(GL_FRAMEBUFFER, 0) #Then render the results of the color texture attached to the FBO to the screen draw_texture() #Obtain the color data in a numpy array glBindTexture(GL_TEXTURE_2D, color_texture) color_str = glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE) glBindTexture(GL_TEXTURE_2D, 0) color_data = np.fromstring(color_str, dtype=np.uint8) #Obtain the depth data in a numpy array glBindTexture(GL_TEXTURE_2D, depth_texture) depth_str = glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_FLOAT) glBindTexture(GL_TEXTURE_2D, 0) de…
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48187981
has comment: http://stackoverflow.com/comment/84442771

http://stackoverflow.com/a/48281355
has body: See built-in function input: If the prompt argument is present, it is written to standard output without a trailing newline. You gave an argument (delay_print("\nGET UP? Y/N: ")) to it (as prompt). So, the interpreter first evaluates the argument. At this time, the program does the write, flush and sleep. Then it returns None (implied when running to the end of a function). That was then provided as the prompt of input(). Your code works like this one: temp = delay_print("\nGET UP? Y/N: ") # assert temp is None GetUp = input(temp) # Same as input(None) So, that is the mistake. The correct should be: delay_print("\nGET UP? Y/N: ") GetUp = input()
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48281034

http://stackoverflow.com/q/48279319
has comment: http://stackoverflow.com/comment/83572970
downvote count: 2
accepted answer: http://stackoverflow.com/a/48305849
tagged with: reshape
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83573153
tagged with: pandas
upvote count: 3
score: 1
has answer: http://stackoverflow.com/a/48305849
has comment: http://stackoverflow.com/comment/83572398
possible better answer: http://stackoverflow.com/a/48307654
favorite count: 0
type: Question
has body: I have a MultiIndex pandas dataframe that looks like this: I want the different quarters as rows instead of hierarchial columns i.e. a long format instead of this wide one. Something like this (output need not be a multindex): How can I do this in Pandas? Edit: Sample input file as requested: rbi_credits_data.xlsx Sample Data(Pandas): cols = pd.MultiIndex(levels=[['Center_Details', '2017-18:Q2', '2017-18:Q1'], ['State', 'District', 'Center', 'Offices', 'Deposit', 'Credit']], labels=[[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 3, 4, 5, 3, 4, 5]]) data = [['JAMMU &amp; KASHMIR', 'KUPWARA', 'Drug Mulla (CT)', '3', '500', '600', '4', '500', '600'], ['JAMMU &amp; KASHMIR', 'LEH LADAKH', 'Chuglamsar (CT)', '3', '500', '600', '4', '500', '600'], ['PUNJAB', 'PATHANKOT', 'Mamun (CT)', '3', '500', '600', '4', '500', '600'], ['PUNJAB', 'GURDASPUR', 'TIBRI', '3', '500', '600', '4', '500', '600']] df = pd.DataFrame(data=data, columns=cols)
answer count: 2
has title: Pivoting MultiIndex Data
has answer: http://stackoverflow.com/a/48307654

http://stackoverflow.com/comment/83416326
type: Comment
has text: @HannahSawyer Many ways you can share a `csv` - if the `csv` file is considerably "small" in size you can copy & paste the csv text contents directly into the question here, or share a link to it on a resource-sharing site like [sharecsv.com](http://www.sharecsv.com/), [gist.github.com](https://gist.github.com/), or something like [www.pastebin.com](http://pastebin.com)
type: QuestionComment
comment on: http://stackoverflow.com/q/48214911
score: 0

http://stackoverflow.com/q/48302090
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48302543
tagged with: apache-spark
answer count: 1
downvote count: 0
has title: How to aggregate over '1 hour' windows cumulatively within a day in PySpark
favorite count: 0
type: Question
tagged with: apache-spark-sql
score: 5
has body: I have a Spark DataFrame like the one below: +---------+--------------------------+ |group_id |event_time | +---------+--------------------------+ |XXXX |2017-10-25 14:47:02.717013| |XXXX |2017-10-25 14:47:25.444979| |XXXX |2017-10-25 14:49:32.21353 | |YYYY |2017-10-25 14:50:38.321134| |YYYY |2017-10-25 14:51:12.028447| |ZZZZ |2017-10-25 14:51:24.810688| |YYYY |2017-10-25 14:37:34.241097| |ZZZZ |2017-10-25 14:37:24.427836| |XXXX |2017-10-25 14:37:24.620864| |YYYY |2017-10-25 14:37:24.964614| +---------+--------------------------+ I want to calculate the rolling count of events per hour within a day per group_id. So, for the datetime 25-10 14:00 and for a group_id, I want to calculate the count of events for that group_id from 25-10 00:00 till 25-10 14:00. Doing something like below: df.groupBy('group_id', window('event_time', '1 hour').alias('model_window')) \ .agg(dfcount(lit(1)).alias('values')) calculates the count of events per hour, but not cumulatively during each day. Any ideas? EDIT: The expected output would be something like: +---------+---------------------------------------------+-------+ |group_id |model_window |values | +---------+---------------------------------------------+-------+ |XXXX |[2017-10-25 00:00:00.0,2017-10-25 01:00:00.0]| 10 | |XXXX |[2017-10-25 00:00:00.0,2017-10-25 02:00:00.0]| 17 | |XXXX |[2017-10-25 00:00:00.0,2017-10-25 03:00:00.0]| 22 | |YYYY |[2017-10-25 00:00:00.0,2017-10-25 01:00:00.0]| 0 | |YYYY |[2017-10-25 00:00:00.0,2017-10-25 02:00:00.0]| 1 | |YYYY |[2017-10-25 00:00:00.0,2017-10-25 03:00:00.0]| 9 | +---------+---------------------------------------------+-------+
upvote count: 5
tagged with: pyspark
tagged with: python
accepted answer: http://stackoverflow.com/a/48302543

http://stackoverflow.com/q/48183917
tagged with: python
has answer: http://stackoverflow.com/a/48184137
answer count: 2
tagged with: subprocess
has body: I have this code: pprocess = subprocess.Popen('PROGRAM', stdout=subprocess.PIPE) while True: output = pprocess.stdout.readline() print 'output = ', output But the output is not being printed using the python code, but instead it is being printed on the console and it appears to be printed directly from the process. Does anyone came across this issue?
type: UnansweredQuestion
has title: Python Subprocess Empty Output
has comment: http://stackoverflow.com/comment/83347554
tagged with: process
has comment: http://stackoverflow.com/comment/83347511
type: Question
has comment: http://stackoverflow.com/comment/83347792
has answer: http://stackoverflow.com/a/48185098
score: 0
has comment: http://stackoverflow.com/comment/83353175

http://stackoverflow.com/q/48246460
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48246501
score: 0
possible better answer: http://stackoverflow.com/a/48246501
has comment: http://stackoverflow.com/comment/83475610
tagged with: scikit-image
has answer: http://stackoverflow.com/a/48246479
has comment: http://stackoverflow.com/comment/83475670
type: Question
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/48246479
has body: I recently found this part of code: filteredImage = image &gt; filters.threshold_otsu(image) In most languages image &gt; filters.threshold_otsu(image) would return true or false. In this case filteredImage is ndarray. So what exactly happens in this code?
has title: Python what does > sign

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

http://stackoverflow.com/comment/83574881
score: 0
type: Comment
type: QuestionComment
has text: @hpaulj I just looked at some introduction to `pickle` and i see your point. But does it increase the loading speed (which is why I wanted to use hdf5)? Currently my program reads a bunch of txt files everytime it runs. Each file contains a table that will be loaded into a numpy array.
comment on: http://stackoverflow.com/q/48294013

http://stackoverflow.com/a/69281051
type: Answer
answers question: http://stackoverflow.com/q/48205495
has body: I have very simple solution for this problem just add this below line in your code app.run(port=3000) simply assume that your first application is working using 5000 port and you try to execute another flask app it may using the same port which is 5000 so that's why you may face these problem so just simply add this line of code in which you can change your port number to execute the application on another port. example: if __name__ == '__main__': app.run(port=3000) Note: instead of port 3000 you can enter any of your choice
upvote count: 3
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/123790891

http://stackoverflow.com/q/48208387
has comment: http://stackoverflow.com/comment/83398207
has comment: http://stackoverflow.com/comment/83397650
score: 10
tagged with: python
has comment: http://stackoverflow.com/comment/83398676
upvote count: 11
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/83398058
has body: To start multiprocess with for loop. import os from multiprocessing import Process def run_proc(name): print('child process %s (%s) running ...' %(name,os.getpid())) if __name__ == '__main__': print('parent process %s.' %os.getppid()) for i in range(5): p = Process(target=run_proc,args=(str(i),)) print('process will start'+str(i)) p.start() p.join() print('process is end') I got the result. parent process 6497. process will start process will start child process 0 (6984) running ... process will start process will start process will start child process 2 (6986) running ... child process 1 (6985) running ... child process 3 (6987) running ... child process 4 (6988) running ... process is end Why the subprocess created early execute later? Why can't get the following outcome? parent process 6497. process will start process will start child process 0 (6984) running ... process will start process will start process will start child process 1 (6986) running ... child process 2 (6985) running ... child process 3 (6987) running ... child process 4 (6988) running ... process is end What Jean-François Fabre says is about how to create the following result: parent process 6497. process will start child process 0 (9639) running ... process will start child process 1 (9640) running ... process will start child process 2 (9641) running ... process will start child process 3 (9643) running ... process will start child process 4 (9644) running ... process is end I can get it just to change p.join in for loop such as below: import os from multiprocessing import Process def run_proc(name): print('child process %s (%s) running ...' %(name,os.getpid())) if __name__ == '__main__': print('parent process %s.' %os.getppid()) for i in range(5): p = Process(target=run_proc,args=(str(i),)) print('process will start'+str(i)) p.start() p.join() print('process is end') What I want to know is why my code result in the following output parent process 6497. process will start process will start ch…
answer count: 1
has title: The order of running subprocess in multiprocess module
downvote count: 1
accepted answer: http://stackoverflow.com/a/48208523
favorite count: 0
has comment: http://stackoverflow.com/comment/83398891
has answer: http://stackoverflow.com/a/48208523
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/27282538

http://stackoverflow.com/a/49701542
has comment: http://stackoverflow.com/comment/126126629
type: Answer
has body: If you want to access folder you specified using Anaconda Prompt, try typing cd C:\Users\u354590 cd means Change Directory.
has comment: http://stackoverflow.com/comment/94639816
downvote count: 2
has comment: http://stackoverflow.com/comment/102687035
score: 11
upvote count: 13
answers question: http://stackoverflow.com/q/48304305

http://stackoverflow.com/a/48328144
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48327371
type: Answer
has comment: http://stackoverflow.com/comment/83642184
answers question: http://stackoverflow.com/q/48327371
upvote count: 2
has body: Is this what you are looking for: outer={'a':{'b':[1,2,3], 'c':[4,5,6]}, 'd':{'e':[7,8,9], 'f':[10,11,12]}} while outer: outer_key, inner = outer.popitem() while inner: inner_key, inner_value = inner.popitem()
type: AcceptedAnswer
score: 2

http://stackoverflow.com/q/48261673
type: Question
score: 2
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
tagged with: indexing
upvote count: 3
has body: I wanted to create an index of all the files and folders that i have in an enterprise cloud so i could then do the backup of it and store the index into a txt file and after i will compare the two last backups ( the txt files ) to check which files/folders changed names. I have tried this code, but it is limited to the times of for loops that i insert into the code and i wanted to know if i could do it in a way of been almost unlimited since i never know if someone will add folders to any sub-folder: for f in next(os.walk(path))[1]: folder=('{}' + ". " + f).format(a) print(folder,file=open(filename, "a")) path1=path+f for f in next(os.walk(path1))[2]: files = (" " + f) print(files,file=open(filename, "a")) b=1 for f in next(os.walk(path1))[1]: folder=(" " + '{}' + "." + '{}' + ". " + f).format(a,b) print(folder,file=open(filename, "a")) path2=path1+("\\")+f for f in next(os.walk(path2))[2]: files = (" " + f) print(files,file=open(filename, "a")) c=1 for f in next(os.walk(path2))[1]: folder=(" " + '{}' + "." + '{}' + "." + '{}' + ". " + f).format(a,b,c) print(folder,file=open(filename, "a")) path3=path2+("\\")+f for f in next(os.walk(path3))[2]: files = (" " + f) print(files,file=open(filename, "a")) d=1 for f in next(os.walk(path3))[1]: folder=(" " + '{}' + "." + '{}' + "." + '{}' + "." + '{}' + ". " + f).format(a,b,c,d) print(folder,file=open(filename, "a")) path4=path3+("\\")+f for f in next(os.walk(path4))[2]: files = (" " + f) print(files,file=open(filename, "a")) e=1 for f in next(os.walk(path4))[1]: folder=(" " + '{}' + "." + '{}' + "." + '{}' + "." + '{}' + "." + '{}' + ". " + f).format(a,b,c,d,e) print(folder,file=open(filename, "a")) path5=path4+("\\")+f for f in next(os.walk(path5))[2]: files = (" " + f) print(files,file=open(filename, "a")) g=1 for f in next(os.walk(path5))[1]: folder=(" " + '{}' + "." + '{}' + "." + '{}' + "." + '{}' + "." + '{}' + "." + '{}' + ". " + f).format(a,b,c,d,e,g) print(folder,file=open(filename, "a")) path6=path5+("\\")+f for …
has answer: http://stackoverflow.com/a/48261973
has answer: http://stackoverflow.com/a/48262521
downvote count: 1
tagged with: python
has title: Index folders and files in python3
favorite count: 0

http://stackoverflow.com/a/48202812
has comment: http://stackoverflow.com/comment/83414071
upvote count: 0
downvote count: 1
has body: This code will help you: from selenium import webdriver from selenium.webdriver.common.keys import Keys 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() driver.get("https://www.tsa-algerie.com") driver.maximize_window() #To click on Search Icon to open the search box ele=driver.find_element_by_xpath('//div[@class="template-header__search search__open transition"]/img') ele.click() #wait till search text box appear and then enter the desired keyword you want to search WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.NAME, "s"))) elem = driver.find_element_by_name("s") elem.send_keys("Algieria") elem.send_keys(Keys.RETURN) assert "No results found." not in driver.page_source driver.close()
answers question: http://stackoverflow.com/q/48188620
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/83420212

http://stackoverflow.com/q/48281836
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has title: Taming the x-axis labels of a multi-level pandas dataframe maptlotlib .plot() call
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has body: I have pandas dataframe with multi-level row index composed of two datetime values. I plot various slices of the dataframe. (they're slices of the inner level). My problem is that the x-axis labels have too much detail. The label includes both levels of the index, and uses a format string that includes 00:00:00 time. I only need to use the outer level (index[0].values) and I don't care about the time fragment. I highlighted in red the parts I don't want. What's the most-efficient way I could give a different index (that looks like what I want) to the .plot()? Can I do it without messing with the dataframe itself? #create the main dataframe dt = pd.DatetimeIndex(start='2010-1-1', end = '2010-12-31', freq='m') dt2 = pd.DatetimeIndex(start='2011-1-1', end = '2011-1-10', freq='d') mi = pd.MultiIndex.from_product([dt,dt2], names=['assessment_date', 'contract_date']) df = pd.DataFrame(index=mi) df['foo']=7 df.plot(rot=50)
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/48290972
answer count: 1

http://stackoverflow.com/a/64334734
answers question: http://stackoverflow.com/q/48325832
type: Answer
has comment: http://stackoverflow.com/comment/125798660
has body: I couldn't find a fully formed answer to this, so I thought it would be worth posting the workaround that I used: from pptx.oxml.xmlchemy import OxmlElement def SubElement(parent, tagname, **kwargs): element = OxmlElement(tagname) element.attrib.update(kwargs) parent.append(element) return element def manuallySetLegendPosition( chart, x, y, w, h ): ## Inside layout, add manualLayout L = chart.legend._element.get_or_add_layout() mL = L.get_or_add_manualLayout() ## Add xMode and yMode and set vals to edge xM = SubElement(mL, 'c:xMode', val="edge") xY = SubElement(mL, 'c:yMode', val="edge") ## Add x, value is between -1 and 1 as a proportion of the chart width ## point of reference on the legend is its centre, not top left xE = SubElement(mL, 'c:x', val=str(x)) ## Add y, same concept as above yE = SubElement(mL, 'c:y', val=str(y)) ## Add w, legend height as a proportion of chart height wE = SubElement(mL, 'c:w', val=str(w)) ## Add h, same concept as above hE = SubElement(mL, 'c:h', val=str(h))
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/83597133
type: Comment
type: QuestionComment
has text: @larsks call i.g. `parse(content, 'mydrive/home/sample/sample3.html')` and get `home/sample/sample3.html` as the output. Btw, I am adding line on how I load the content.
score: 0
comment on: http://stackoverflow.com/q/48304562

http://stackoverflow.com/comment/83847171
has text: Having more than one `Tk` instance is wrong. This may appear to work, but it may also fail in subtle or spectacular ways.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48328543
type: Comment

http://stackoverflow.com/comment/83633050
type: Comment
has text: It will be good when that `grep` will return first boundary occurrence as `sed -n -e` does by adding `-m 1` and `| head -1`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48310479

http://stackoverflow.com/comment/115928148
type: QuestionComment
comment on: http://stackoverflow.com/q/48199961
score: 0
has text: Does this answer your question? [Pythonic way to combine two lists in an alternating fashion?](https://stackoverflow.com/questions/3678869/pythonic-way-to-combine-two-lists-in-an-alternating-fashion)
type: Comment

http://stackoverflow.com/comment/83488871
type: QuestionComment
comment on: http://stackoverflow.com/q/48253160
has text: Did you just use ASCII to plot a graph? :D
score: 1
type: Comment

http://stackoverflow.com/comment/83539436
has text: @ShubhamGupta its called regex. Try to look at some regex examples
type: QuestionComment
comment on: http://stackoverflow.com/q/48274344
score: 0
type: Comment

http://stackoverflow.com/q/48285002
answer count: 3
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48294578
tagged with: raspbian
has answer: http://stackoverflow.com/a/54748473
type: Question
has answer: http://stackoverflow.com/a/55590782
has comment: http://stackoverflow.com/comment/83554625
has body: I'm trying to install google assistant on a newly set up pi 3 with Raspbian. I got the message "No module named googlesamples.assistant.auth_helpers" so I followed the instructions given in answer to this question: No module named googlesamples.assistant.auth_helpers The first 2 commands appear to complete OK, but the third command gives "google-oauthlib-tool: command not found" My programming skills are too rusty to work out what's going wrong. Python 3.5.3; forgotten how to find the version of SDK, but should be the latest one. Any help greatly appreciated.
tagged with: python
has title: "google-oauthlib-tool: command not found" when trying to install google assistant on raspbian
tagged with: google-assistant-sdk
favorite count: 0
linked to: http://stackoverflow.com/q/45779671
upvote count: 2
score: 2

http://stackoverflow.com/comment/83341405
comment on: http://stackoverflow.com/q/48180718
type: QuestionComment
type: Comment
has text: Check what is being returned for `cols[0]`. That seems to be returning an `int` object instead of a BeautifulSoup object as you expected.
score: 0

http://stackoverflow.com/comment/83499040
score: 0
type: Comment
has text: the one in the comment works. do you want to replace it and let me accept as answer?
type: AnswerComment
comment on: http://stackoverflow.com/a/48258054

http://stackoverflow.com/q/48277599
has answer: http://stackoverflow.com/a/48278291
tagged with: docker
tagged with: proxy
type: AnsweredQuestion
upvote count: 19
accepted answer: http://stackoverflow.com/a/48278456
has answer: http://stackoverflow.com/a/48278479
has answer: http://stackoverflow.com/a/48278456
has answer: http://stackoverflow.com/a/78740102
tagged with: python
has answer: http://stackoverflow.com/a/51652188
has comment: http://stackoverflow.com/comment/83539640
type: Question
possible better answer: http://stackoverflow.com/a/48278479
has comment: http://stackoverflow.com/comment/83539230
has title: Pip inside dockerfile under proxy
answer count: 5
downvote count: 0
has body: I am trying to build a Docker image for elasticsearch-curator, Here is the dockerfile: FROM alpine:3.7 RUN adduser -S curator RUN apk add --update \ python \ python-dev \ py-pip \ build-base \ &amp;&amp; pip install virtualenv \ &amp;&amp; pip install elasticsearch-curator \ &amp;&amp; rm -rf /var/cache/apk/* USER curator ENTRYPOINT [ "/usr/bin/curator"] Thing is I am under a proxy, so I must build my image with: docker build --no-cache --build-arg HTTP_PROXY=http://xx.xx.xx.xx:xx -t elasticsearch-curator:5.4 . But when it wants to get virtualenv, I get: Collecting virtualenv Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fb8259ed350&gt;, 'Connection to pypi.python.org timed out. (connect timeout=15)')': /simple/virtualenv/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError(&lt;pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7fb8259ed210&gt;, 'Connection to pypi.python.org timed out. (connect timeout=15)')': /simple/virtualenv/ I found people solving issue inserting ENV http_proxy http://proxy-chain.xxx.com:911/ ENV https_proxy http://proxy-chain.xxx.com:912/ in the Dockerfile, but it is not possible for me, because my proxy is only valid on my building, so if another person from another place want to build the image, he will need to remove http_proxy env var from Dockerfile. Is there any other way to achieve it? It seems like a very common use case...
tagged with: pip
score: 19
favorite count: 0

http://stackoverflow.com/comment/83585798
comment on: http://stackoverflow.com/q/48299103
score: 0
type: Comment
has text: can you share also your index mapping? GET /<indexname>/_mapping
type: QuestionComment

http://stackoverflow.com/a/68571520
answers question: http://stackoverflow.com/q/48190628
type: Answer
has body: you can specify the figure size directly to produce varied sizes as wanted. fig, axs = plt.subplots(2, 3, figsize=(10, 3), sharex=True, sharey=True, constrained_layout=True) Hope this could help.
score: 0

coding-style
type: Tag
tag name: coding-style
tags question: http://stackoverflow.com/q/48229223

http://stackoverflow.com/comment/83589860
comment on: http://stackoverflow.com/q/48302618
score: 3
has text: Coding your Specs does not fit into SO Q&A format - sorry. Good luck with your coding. If you happen to get a solution you could post it as answer to this non-question. If you have a specific problem, consider studying [how-to-ask](https://stackoverflow.com/help/how-to-ask) and [on topic](https://stackoverflow.com/help/on-topic) , provide code respecting [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and your exception / expectation that do not get met by your code and I am sure SO will help you out.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48232976
tagged with: dictionary
tagged with: key
type: AnsweredQuestion
tagged with: python-2.7
score: 1
has title: How can I store the users' data properly?
answer count: 1
has comment: http://stackoverflow.com/comment/83448456
has answer: http://stackoverflow.com/a/48239234
favorite count: 0
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/48239234
has body: I am restoring data for users' in a nested dictionary as follows: user_dict = {user_name:{product:amount, product:amount}} So, user_name is the user's user_name. The product is the what the user put in the basket(e.g. orange juice), and the amount is the amount of a specific product. So, for instance: user_dict = {"sara" : {"orange juice": 2, "apple juice" : 4}, "ali": {"banana":3}} what I want to do is that when a user buys some stuff and put them in the (user_dict) then logs out, when the same user logs in again, I want to get the user's basket as follows: let's say sara logged in and put some stuff in her basket(user_dict) then logged out, when sara logs in again, I want to make get sara's information from the (user_dict) in a new dictionary(called basket) like this: basket = {"orange juice": 2, "apple juice" : 4} Also, I want to make the basket empty if the user (user_name) who logged in does not have anything in the basket. So, I want to make users' things do not interfere and I do not want to lose any information. I have almost finished my project but this is what I am stuck at, so help me guys, please. Here are my lines of code for this task:(but the code does not work as I want) for key in user_dict.keys(): if user_name == key: key_sto = " " nested_dict = user_dict[user_name] val = a.values() val_in_nested = val[0] key_in_nested = key_sto.join(a) basket[key_in_nested] = val_in_nested elif user_name != key : basket = {}
upvote count: 1
tagged with: python

http://stackoverflow.com/q/48230370
tagged with: selenium-chromedriver
has answer: http://stackoverflow.com/a/70178382
has answer: http://stackoverflow.com/a/50999075
has title: Selenium WebDriverException: Message: unknown error: cannot determine loading status from unknown error: missing or invalid 'entry.level'
answer count: 5
accepted answer: http://stackoverflow.com/a/48230710
tagged with: python
tagged with: google-chrome
score: 4
has answer: http://stackoverflow.com/a/48230710
has answer: http://stackoverflow.com/a/51524541
tagged with: selenium-webdriver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/77465519
has comment: http://stackoverflow.com/comment/83495396
has comment: http://stackoverflow.com/comment/83447796
upvote count: 5
tagged with: selenium
downvote count: 1
has body: I have a script which uses selenium for testing. Now even opening a Google page using driver.get(url) # url = Google homepage url is giving me below error driver.get("https://my.gumtree.com/login") File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 245, in get self.execute(Command.GET, {'url': url}) File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 233, in execute self.error_handler.check_response(response) File "C:\Python34\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: cannot determine loading status from unknown error: missing or invalid 'entry.level' (Session info: chrome=65.0.3315.3) (Driver info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 10.0.16299 x86_64) I have Google chrome version 65, Chromedriver 2.35 and selenium 2.53.1 I tried different version combinations(mentioned in below table) as per solutions mentioned in other similar questions but nothing worked. Selenium Chrome Chromedriver 2.53.0 63 2.33 2.53.1 65(latest) 2.34 3.6.0 2.35(latest) 3.7.0 3.8.0 3.8.1(latest) EDIT 1: JDK version java version "1.8.0_151" Java(TM) SE Runtime Environment (build 1.8.0_151-b12) Java HotSpot(TM) 64-Bit Server VM (build 25.151-b12, mixed mode)
possible better answer: http://stackoverflow.com/a/50999075
favorite count: 0
has comment: http://stackoverflow.com/comment/83452573
type: Question

http://stackoverflow.com/comment/83330808
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48175476
has text: You should start by properly indenting your code.
type: Comment

http://stackoverflow.com/comment/83591892
comment on: http://stackoverflow.com/q/48303580
score: 1
type: Comment
type: QuestionComment
has text: Carefully read your last if statement. You might also want to consider using an elif and else

http://stackoverflow.com/comment/83357623
score: 0
type: Comment
has text: I will ask a different question when the timer between questions will be off. Thanks a lot for your answer. :)
type: AnswerComment
comment on: http://stackoverflow.com/a/48188908

http://stackoverflow.com/q/48286900
answer count: 1
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83562701
has title: Create spline plot from text
has comment: http://stackoverflow.com/comment/83560593
favorite count: 0
type: AnsweredQuestion
score: 1
has body: y coordinates system from text to plot a splined text, my first idea was to use opencv to draw the text then get the coordinates from the pixels. here is my code: import numpy as np import cv2 from matplotlib import pyplot as plt # Create a black image img = np.zeros((600, 800, 3), np.uint8) # Write some Text font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX fontScale = 1 fontColor = (255, 255, 255) lineType = 1 text = 'Hello World \n' \ 'I\'m a Robot \n' \ 'my name is "The Terminator 2"' y0, dy = 30, 30 for i, textLine in enumerate(text.split('\n')): y = y0 + i * dy cv2.putText(img, textLine, (30, y), font, fontScale, fontColor, lineType) # Display the image cv2.imshow("img", img) # Plot pixels pixels = np.where(img == 255) plt.scatter(pixels[1], pixels[0]) plt.show() Right now I have the pixels coordinates, on inverted position, but seems to be unsorted so I can't create a spline with it. Is there any other way to do this better?
type: Question
has answer: http://stackoverflow.com/a/48287988
accepted answer: http://stackoverflow.com/a/48287988
downvote count: 0

http://stackoverflow.com/comment/83425683
has text: You're passing a mutable object into the recursion, where it is mutated.
score: 2
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48222139

selenium
tags question: http://stackoverflow.com/q/48280643
tags question: http://stackoverflow.com/q/48278071
tags question: http://stackoverflow.com/q/48316017
tags question: http://stackoverflow.com/q/48220599
tags question: http://stackoverflow.com/q/48198863
tags question: http://stackoverflow.com/q/48276226
tags question: http://stackoverflow.com/q/48319723
tags question: http://stackoverflow.com/q/48309776
tags question: http://stackoverflow.com/q/48293590
tags question: http://stackoverflow.com/q/48325521
tags question: http://stackoverflow.com/q/48257870
tags question: http://stackoverflow.com/q/48216563
tags question: http://stackoverflow.com/q/48236271
tags question: http://stackoverflow.com/q/48215892
tags question: http://stackoverflow.com/q/48192999
tags question: http://stackoverflow.com/q/48300303
tags question: http://stackoverflow.com/q/48246345
tags question: http://stackoverflow.com/q/48281999
tags question: http://stackoverflow.com/q/48307531
tags question: http://stackoverflow.com/q/48206402
tags question: http://stackoverflow.com/q/48317163
tags question: http://stackoverflow.com/q/48280411
tags question: http://stackoverflow.com/q/48216114
tags question: http://stackoverflow.com/q/48306284
tags question: http://stackoverflow.com/q/48235768
tags question: http://stackoverflow.com/q/48289959
tags question: http://stackoverflow.com/q/48203832
tags question: http://stackoverflow.com/q/48209959
tags question: http://stackoverflow.com/q/48178619
tags question: http://stackoverflow.com/q/48202882
tags question: http://stackoverflow.com/q/48179088
tags question: http://stackoverflow.com/q/48322719
tags question: http://stackoverflow.com/q/48313111
tags question: http://stackoverflow.com/q/48272798
tags question: http://stackoverflow.com/q/48195796
tags question: http://stackoverflow.com/q/48268516
tags question: http://stackoverflow.com/q/48209231
tags question: http://stackoverflow.com/q/48199960
tags question: http://stackoverflow.com/q/48188978
tags question: http://stackoverflow.com/q/48315438
tags question: http://stackoverflow.com/q/48188060
tags question: http://stackoverflow.com/q/48267633
tags question: http://stackoverflow.com/q/48286382
tags question: http://stackoverflow.com/q/48201944
tags question: http://stackoverflow.com/q/48239842
tags question: http://stackoverflow.com/q/48303200
tags question: http://stackoverflow.com/q/48207469
tags question: http://stackoverflow.com/q/48202263
type: Tag
tags question: http://stackoverflow.com/q/48188620
tags question: http://stackoverflow.com/q/48313388
tags question: http://stackoverflow.com/q/48317624
tags question: http://stackoverflow.com/q/48248028
tags question: http://stackoverflow.com/q/48224350
tag name: selenium
tags question: http://stackoverflow.com/q/48288376
tags question: http://stackoverflow.com/q/48284024
tags question: http://stackoverflow.com/q/48313021
tags question: http://stackoverflow.com/q/48180075
tags question: http://stackoverflow.com/q/48218781
tags question: http://stackoverflow.com/q/48257080
tags question: http://stackoverflow.com/q/48259782
tags question: http://stackoverflow.com/q/48253733
tags question: http://stackoverflow.com/q/48230370
tags question: http://stackoverflow.com/q/48256870
tags question: http://stackoverflow.com/q/48251621
tags question: http://stackoverflow.com/q/48249705
tags question: http://stackoverflow.com/q/48204998
tags question: http://stackoverflow.com/q/48183664
tags question: http://stackoverflow.com/q/48179010
tags question: http://stackoverflow.com/q/48213750
tags question: http://stackoverflow.com/q/48253703
tags question: http://stackoverflow.com/q/48270721
tags question: http://stackoverflow.com/q/48277136

http://stackoverflow.com/q/48284215
type: AnsweredQuestion
tagged with: for-loop
downvote count: 2
upvote count: 1
linked to: http://stackoverflow.com/q/22122623
tagged with: loops
has title: How to make a loop that goes from a given index and circles back to that index
possible better answer: http://stackoverflow.com/a/48284331
accepted answer: http://stackoverflow.com/a/48284255
has answer: http://stackoverflow.com/a/48284372
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/22122623
has answer: http://stackoverflow.com/a/48284331
has body: Title may be confusing but I don't know how to express myself any better. What I have is a list that looks something like this: myList = ['a', 'b', 'c', 'd', 'e', 'f'] what I want to do is a for loop that, for example, starts at index 3, so 'd' and then goes to the end but at the end of the list insted of finishing goes back to the beginning, goes through 'a','b','c' and then finishes at 'd'. I tried doing it like this with a while loop: index = 3 while index != 2: if index == len(a): index = 0 else: pass print(a[index]) index += 1 This sorta worked but it will never print out 'c' but if I put 3 as index the loop will never even start. Is there a more elegant solution to do something like this?
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83552389
has answer: http://stackoverflow.com/a/48284665
has answer: http://stackoverflow.com/a/48284255
answer count: 4

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

http://stackoverflow.com/comment/83565349
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48286115
has text: @birdoptera Only the last row was written because the indentation is incorrect (ironic considering our exchange on your original question). The last line should be indented so that the output is written _inside_ the `for` loop. Indentation is important in python!

http://stackoverflow.com/comment/83386891
score: 0
type: Comment
has text: Thanks for noticing, that's just a copy paste mistake - i edited question
comment on: http://stackoverflow.com/a/48202770
type: AnswerComment

http://stackoverflow.com/comment/83398063
type: Comment
comment on: http://stackoverflow.com/q/48208507
type: QuestionComment
score: 0
has text: If you can't follow the documentation for msgpack, I am 100% certain that trying to use it to hack a marginally faster version of deepcopy is absolutely the wrong thing. Write the simplest most straightforward code you can, and worry about perfomance later.

http://stackoverflow.com/q/48195226
has comment: http://stackoverflow.com/comment/83371776
has body: I have a DataFrame with a few empty columns and I want to do an interpolation on each line to fill them. Here is an example: 3 12 18 24 36 120 180 360 2018-01-03 00:00:00 1.3913 1.8034 NaN 1.9313 2.0149 2.4471 NaN 2.7855 2018-01-04 00:00:00 1.3964 1.8007 NaN 1.9515 2.037 2.4525 NaN 2.7863 2018-01-05 00:00:00 1.3936 1.7927 NaN 1.9599 2.0596 2.4763 NaN 2.8105 2018-01-08 00:00:00 1.4063 1.7797 NaN 1.9579 2.057 2.48 NaN 2.8113 2018-01-09 00:00:00 1.4322 1.777 NaN 1.9641 2.071 2.5384 NaN 2.8824 When I use interpolate method with axis=1 I am getting the same DataFrame back, with no interpolation whatsoever. I've tried looping through all the lines and changing the interpolation method as well, but I still get no interpolation back. Any guesses on what this may be? Here is an exemple code: ExampleDF.iloc[-1] Out[42]: 3 1.4322 12 1.777 18 NaN 24 1.9641 36 2.071 120 2.5384 180 NaN 360 2.8824 test.iloc[-1].interpolate(method='cubic') Out[43]: 3 1.4322 12 1.777 18 NaN 24 1.9641 36 2.071 120 2.5384 180 NaN 360 2.8824
has title: Pandas - interpolation on the lines
tagged with: interpolation
has answer: http://stackoverflow.com/a/48199075
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/83371362
answer count: 1
has comment: http://stackoverflow.com/comment/83372045
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83371503
tagged with: python
has comment: http://stackoverflow.com/comment/83372017

http://stackoverflow.com/a/48292495
type: AcceptedAnswer
downvote count: 0
has body: I was able to replicate the problem and I solved it with this: def employee(request): """The home page""" profile = EmployeeProfile.objects.get(owner=request.user) teams_weekly_master_schedule = TeamsWeeklyMasterSchedule.objects.get(team = profile.team) context = { 'profile': profile, 'teams_weekly_master_schedule': teams_weekly_master_schedule, } return render(request, 'test.html', context) The first problem was that on line 3, you used filter to retrieve one EmployeeProfile object. Using filter returns a queryset, which can't be accessed as an object. When you use GET, you can use profile.team which returns the team you want.
type: Answer
accepted answer of: http://stackoverflow.com/q/48291939
has comment: http://stackoverflow.com/comment/83570843
has comment: http://stackoverflow.com/comment/83570671
has comment: http://stackoverflow.com/comment/83570890
answers question: http://stackoverflow.com/q/48291939
score: 2
upvote count: 2

http://stackoverflow.com/q/48175990
has comment: http://stackoverflow.com/comment/83331873
tagged with: python-imaging-library
has body: I'm trying to make a chromakey program in Python. My test program is supposed to determine green colors in an image. If it finds green, it sets a certain value to True. The test image is a 4x4 image with no transparency. import PIL from PIL import Image green_num = False testpic = Image.open("test.png") width, height = testpic.size pix = testpic.load() def coloradd(): global colorlist colorlist = 0 if green_value/(2/3) &lt; red_value or blue_value: colorlist += 1 def colorscan(): current_x = 0 current_y = 0 while current_y &lt;= height: global red_value, green_value, blue_value red_value, green_value, blue_value, transparency = pix[current_x, current_y] coloradd() current_x += 1 if current_x &lt; width: current_y += 1 colorscan() print(colorlist) So far, I've continually run into this error. Traceback (most recent call last): File "C:/Users/shawnmcgp/PycharmProjects/untitled/chromakey.py", line 29, in &lt;module&gt; colorscan() File "C:/Users/shawnmcgp/PycharmProjects/untitled/chromakey.py", line 22, in colorscan red_value, green_value, blue_value, transparency = pix[current_x, current_y] IndexError: image index out of range
type: UnansweredQuestion
has title: PIL IndexError: image index out of range
tagged with: python
has comment: http://stackoverflow.com/comment/83331979
has comment: http://stackoverflow.com/comment/83331819
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83332220
type: Question

http://stackoverflow.com/a/48266884
upvote count: 1
has comment: http://stackoverflow.com/comment/83517718
has comment: http://stackoverflow.com/comment/83517921
has comment: http://stackoverflow.com/comment/83517987
has comment: http://stackoverflow.com/comment/83631478
accepted answer of: http://stackoverflow.com/q/48266197
has comment: http://stackoverflow.com/comment/83517937
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/83608341
has comment: http://stackoverflow.com/comment/83517850
answers question: http://stackoverflow.com/q/48266197
has body: IIUC, I think you want something like this. However, I don't quite understand your column naming in your results. df_out = df.rename_axis('colnum',1).set_index(['col1','col2','col3','col4','col5'])\ .stack()\ .groupby(['col1','col5','colnum','col2','col3'])\ .apply(lambda x: pd.Series(x.values.tolist())).unstack([0,1,2])\ .reset_index(level=-1, drop=True) df_out.columns = df_out.columns.map('{0[0]}_{0[1]}_{0[2]}'.format) Print df[1] where col2 = 1 df_out.loc[[1]].dropna(1).reset_index() Output: col2 col3 1_0_col6 1_0_col7 101_1_col6 101_1_col7 201_2_col6 201_2_col7 301_3_col6 301_3_col7 0 1 2015-01-15 273.2 2.8 275.9 3.2 343.0 7.9 235.0 7.2 Print df[2] where col2 = 2 df_out.loc[[2]].dropna(1).reset_index() Output: col2 col3 2_0_col6 2_0_col7 102_1_col6 102_1_col7 202_2_col6 202_2_col7 302_3_col6 302_3_col7 0 2 2015-01-15 273.2 2.8 275.9 3.2 343.0 7.9 235.0 7.2 Print df[2] where col2 = 3 df_out.loc[[3]].dropna(1).reset_index() Output: col2 col3 3_0_col6 3_0_col7 103_1_col6 103_1_col7 203_2_col6 203_2_col7 303_3_col6 303_3_col7 0 3 2015-01-15 273.2 2.8 275.9 3.2 343.0 7.9 235.0 7.2
has comment: http://stackoverflow.com/comment/83601384
has comment: http://stackoverflow.com/comment/83643695
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83519097
downvote count: 0
has comment: http://stackoverflow.com/comment/83519125

http://stackoverflow.com/comment/83526684
score: 0
type: Comment
type: AnswerComment
has text: Glad I could help. Please accept the answer as correct.
comment on: http://stackoverflow.com/a/48230121

class
tags question: http://stackoverflow.com/q/48267100
tags question: http://stackoverflow.com/q/48328951
tags question: http://stackoverflow.com/q/48217583
tags question: http://stackoverflow.com/q/48305487
tags question: http://stackoverflow.com/q/48217075
tags question: http://stackoverflow.com/q/48249890
type: Tag
tags question: http://stackoverflow.com/q/48312372
tags question: http://stackoverflow.com/q/48240905
tags question: http://stackoverflow.com/q/48245089
tags question: http://stackoverflow.com/q/48238599
tags question: http://stackoverflow.com/q/48302139
tags question: http://stackoverflow.com/q/48198381
tags question: http://stackoverflow.com/q/48330086
tags question: http://stackoverflow.com/q/48257623
tags question: http://stackoverflow.com/q/48233947
tag name: class
tags question: http://stackoverflow.com/q/48268643
tags question: http://stackoverflow.com/q/48293503
tags question: http://stackoverflow.com/q/48243652
tags question: http://stackoverflow.com/q/48235913
tags question: http://stackoverflow.com/q/48294919
tags question: http://stackoverflow.com/q/48247674
tags question: http://stackoverflow.com/q/48215072
tags question: http://stackoverflow.com/q/48325019
tags question: http://stackoverflow.com/q/48216856
tags question: http://stackoverflow.com/q/48231573
tags question: http://stackoverflow.com/q/48279419
tags question: http://stackoverflow.com/q/48289923
tags question: http://stackoverflow.com/q/48261274
tags question: http://stackoverflow.com/q/48257280
tags question: http://stackoverflow.com/q/48208839

http://stackoverflow.com/a/58281925
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/102929826
has comment: http://stackoverflow.com/comment/102932784
score: 6
upvote count: 6
has body: Recently the 'args' option was added to solve_ivp, see here: https://github.com/scipy/scipy/issues/8352#issuecomment-535689344
answers question: http://stackoverflow.com/q/48245765

pip
tags question: http://stackoverflow.com/q/48329888
tags question: http://stackoverflow.com/q/48318443
tags question: http://stackoverflow.com/q/48183160
tags question: http://stackoverflow.com/q/48210938
tags question: http://stackoverflow.com/q/48206900
tags question: http://stackoverflow.com/q/48194257
tags question: http://stackoverflow.com/q/48227278
tags question: http://stackoverflow.com/q/48298170
tags question: http://stackoverflow.com/q/48271294
tags question: http://stackoverflow.com/q/48254484
tags question: http://stackoverflow.com/q/48272960
tags question: http://stackoverflow.com/q/48259271
tags question: http://stackoverflow.com/q/48213358
tags question: http://stackoverflow.com/q/48216669
tags question: http://stackoverflow.com/q/48241169
tags question: http://stackoverflow.com/q/48311645
tags question: http://stackoverflow.com/q/48217036
tags question: http://stackoverflow.com/q/48299528
tags question: http://stackoverflow.com/q/48329778
tags question: http://stackoverflow.com/q/48302295
tags question: http://stackoverflow.com/q/48176420
tags question: http://stackoverflow.com/q/48322679
tags question: http://stackoverflow.com/q/48268646
tags question: http://stackoverflow.com/q/48277599
tags question: http://stackoverflow.com/q/48291546
type: Tag
tags question: http://stackoverflow.com/q/48243510
tags question: http://stackoverflow.com/q/48185439
tags question: http://stackoverflow.com/q/48201821
tags question: http://stackoverflow.com/q/48304300
tags question: http://stackoverflow.com/q/48275475
tags question: http://stackoverflow.com/q/48191933
tags question: http://stackoverflow.com/q/48249425
tags question: http://stackoverflow.com/q/48241888
tags question: http://stackoverflow.com/q/48206013
tags question: http://stackoverflow.com/q/48283503
tags question: http://stackoverflow.com/q/48306212
tags question: http://stackoverflow.com/q/48205006
tags question: http://stackoverflow.com/q/48243737
tag name: pip
tags question: http://stackoverflow.com/q/48293384
tags question: http://stackoverflow.com/q/48269756
tags question: http://stackoverflow.com/q/48217233
tags question: http://stackoverflow.com/q/48180251
tags question: http://stackoverflow.com/q/48325992
tags question: http://stackoverflow.com/q/48186639
tags question: http://stackoverflow.com/q/48304875
tags question: http://stackoverflow.com/q/48256306
tags question: http://stackoverflow.com/q/48176265
tags question: http://stackoverflow.com/q/48193204
tags question: http://stackoverflow.com/q/48301318
tags question: http://stackoverflow.com/q/48191319
tags question: http://stackoverflow.com/q/48269046
tags question: http://stackoverflow.com/q/48198453

http://stackoverflow.com/q/48226104
has title: How can I get the original URL from an archive.is short link using python?
has comment: http://stackoverflow.com/comment/83434999
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48227329
tagged with: url
tagged with: web-services
linked to: http://stackoverflow.com/q/74219538
favorite count: 0
has answer: http://stackoverflow.com/a/78041092
tagged with: short-url
type: Question
type: UnansweredQuestion
tagged with: python
has body: I would like to write a function which takes an archive.is (or archive.fo, archive.li, or archive.today) link as input and gives the URL of the original site as output. For example, if the input was 'http://archive.is/9mIro', then I would want the output to be 'http://www.dailytelegraph.com.au/news/nsw/australian-army-bans-male-recruits-to-get-female-numbers-up/news-story/69ee9dc1d4f8836e9cca7ca2e3e5680a'. How can I do this in python?
upvote count: 2
score: 2

http://stackoverflow.com/q/48297096
has answer: http://stackoverflow.com/a/48297355
upvote count: 4
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83579367
answer count: 1
has body: I am using boto3 to connect to AWS-SES for sending mails. Instead of access key, I want to use IAM role to connect. sts_client = boto3.client('sts') assumedRoleObject = sts_client.assume_role( RoleArn="arn:aws:iam::824214895785:role/my_role_s3", RoleSessionName="AssumeRoleSession1" ) credentials = assumedRoleObject['Credentials'] s3_resource = boto3.resource( 's3', aws_access_key_id = credentials['AccessKeyId'], aws_secret_access_key = credentials['SecretAccessKey'], aws_session_token = credentials['SessionToken'], ) But this is giving me an error - botocore.exceptions.NoCredentialsError: Unable to locate credentials There is no credentials file on my machine as I do not want to use access key. And the machine has all the permissions for accessing SES. Is there any other setting I need to do? Traceback - Traceback (most recent call last): File "/opt/python/run/venv/lib/python3.4/site-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/opt/python/run/venv/lib/python3.4/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/opt/python/run/venv/lib/python3.4/site-packages/flask_restplus/api.py", line 313, in wrapper resp = resource(*args, **kwargs) File "/opt/python/run/venv/lib/python3.4/site-packages/flask/views.py", line 84, in view return self.dispatch_request(*args, **kwargs) File "/opt/python/run/venv/lib/python3.4/site-packages/flask_restplus/resource.py", line 44, in dispatch_request resp = meth(*args, **kwargs) File "/opt/python/current/app/api/endpoints/task_comms_item.py", line 94, in post case_mail_obj.send_mail(final_mail_data) File "/opt/python/current/app/tools/mails/create_mail.py", line 88, in send_mail super(CreateMail, self).send_mail() File "/opt/python/current/app/tools/mails/base.py", line 37, in send_mail self.mail_obj.send(self.mail_format) File "/opt/python/current/app/lib/mail.py", line 154, in send ReplyToAddresses=self.mail_dict…
downvote count: 1
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/83578975
tagged with: python
tagged with: boto3
tagged with: amazon-ses
linked to: http://stackoverflow.com/q/5971312
has title: Connecting to Amazon SES using IAM role and boto3
has comment: http://stackoverflow.com/comment/83579137
has comment: http://stackoverflow.com/comment/83579273

http://stackoverflow.com/a/48216790
score: 0
accepted answer of: http://stackoverflow.com/q/48216505
type: Answer
type: AcceptedAnswer
has body: As pointed out in the comments, it is very difficult to create an aggregate function for multiplication in SQLite. However, you can work around it by using itertools.groupby to perform the combination and multiplication operations and then create a new table. This answer utilizes a context manager and property decorators to create a clean class call: import sqlite3 import itertools class UpdateTable: def __init__(self, *args): self.__dict__ = dict(zip(['table', 'filename'], args)) self.new_table = None @property def newtable(self): return self.new_table @newtable.setter def newtable(self, new_table_name): self.new_table = new_table_name def __enter__(self): data = map(lambda (a, b, c):[b, float(c)], list(sqlite3.connect(self.filename).cursor().execute('SELECT * FROM {}'.format(self.table)))) self.new_data = [(a, reduce(lambda x, y:x[-1]*y[-1], list(b))) for a, b in itertools.groupby(sorted(data, key=lambda x:x[0]), key=lambda x:x[0])] return self def __exit__(self): conn = sqlite3.connect(self.filename) conn.execute('CREATE TABLE {} (A text, B float)'.format(self.new_table)) conn.executemany('INSERT INTO {} VALUES (?, ?)'.format(self.new_table), self.new_data) conn.commit() conn.close() with UpdateTable('table', 'db_file.db') as t: t.newtable = 'table2' Python3 requires functools for reduce and is not compatible with lambda tuple unpacking. Python3 version: import functools import sqlite3 import itertools class UpdateTable: def __init__(self, *args): self.__dict__ = dict(zip(['table', 'filename'], args)) self.new_table = None @property def newtable(self): return self.new_table @newtable.setter def newtable(self, new_table_name): self.new_table = new_table_name def __enter__(self): data = map(lambda x:[x[1], float(x[-1])], list(sqlite3.connect(self.filename).cursor().execute('SELECT * FROM {}'.format(self.table)))) self.new_data = [(a, functools.reduce(lambda x, y:x[-1]*y[-1], list(b))) for a, b in itertools.groupby(sorted(data, key=lambda x:x[0]), key=lambda x:x[0])…
answers question: http://stackoverflow.com/q/48216505

http://stackoverflow.com/a/48330991
score: 0
answers question: http://stackoverflow.com/q/48330581
has body: to the keys in the dictionary is assigned the identifier name in the for loop, the key is the string before the : in a dictionary favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } friends = ['phil','sarah'] for name in favorite_languages.keys(): print(name.title()) if name in friends: print(" hi " +name.title() + ", i see your favorite language is " + favorite_languages[name].title() + "!") so the for-loop iterates through any key in the dictionary and prints its value with the title() method in addition the if-statement determines if the key ( = name ) is existent in the list friends, if this is true it executes the linked code, if it is false it doesn't the exact output is Sarah hi Sarah, i see your favorite language is C! Edward Jen Phil hi Phil, i see your favorite language is Python! for-loop greps key 'Sarah', if-statement checks if it is in list friends : is true so print for-loop greps key 'Edward', if-statement checks if it is in list friends : is false so no print for-loop greps key 'Jen', if-statement checks if it is in list friends : is false so no print for-loop greps key 'Phil', if-statement checks if it is in list friends : is true so print in the dictionary the value that is associated with a key is accessed with [key].title(), in this case [name].title() because name is used as identifier for the keys
type: Answer

http://stackoverflow.com/comment/83529196
type: Comment
comment on: http://stackoverflow.com/q/48272705
type: QuestionComment
has text: Why not just remove the `\n`?
score: 3

http://stackoverflow.com/comment/83389117
comment on: http://stackoverflow.com/q/48203834
has text: No i want to be printed what the user inputs
type: Comment
score: 0
type: QuestionComment

cython
tags question: http://stackoverflow.com/q/48258260
tags question: http://stackoverflow.com/q/48179088
tags question: http://stackoverflow.com/q/48330471
tags question: http://stackoverflow.com/q/48197797
tags question: http://stackoverflow.com/q/48294406
tags question: http://stackoverflow.com/q/48263108
tags question: http://stackoverflow.com/q/48272969
tags question: http://stackoverflow.com/q/48184882
tags question: http://stackoverflow.com/q/48219170
type: Tag
tags question: http://stackoverflow.com/q/48329771
tags question: http://stackoverflow.com/q/48232857
tags question: http://stackoverflow.com/q/48232319
tags question: http://stackoverflow.com/q/48217604
tag name: cython
tags question: http://stackoverflow.com/q/48320410

http://stackoverflow.com/a/48296201
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48294561
accepted answer of: http://stackoverflow.com/q/48294561
type: Answer
has body: The documentation states: You can create custom styles and use them by calling style.use with the path or URL to the style sheet. Alternatively, if you add your .mplstyle file to mpl_configdir/stylelib, you can reuse your custom style sheet with a call to style.use(). So, yes, it is possible.

http://stackoverflow.com/q/48299129
has answer: http://stackoverflow.com/a/48419671
tagged with: python
has body: Question in the title. Using the remote python API of v-rep, I am able to get images and control motor properties of robots, but I cannot find any way to get the coordinates of a path object that was made with the path planning functionality in v-rep. I would like to get them as an array in my external python script. I have found that there is no remote API functions dedicated to path objects, but there might be a more generic function that could be used for this.
has title: How can I get coordinates of a path through the remote API of v-rep?
score: 0
answer count: 2
tagged with: motion-planning
tagged with: robotics
type: UnansweredQuestion
tagged with: simulator
type: Question
has answer: http://stackoverflow.com/a/73822364

http://stackoverflow.com/a/48317219
has body: You can use zip() function, just replace izip with zip, and the code should work.
answers question: http://stackoverflow.com/q/48317072
type: Answer
score: 0

http://stackoverflow.com/comment/83353788
has text: Like the error said, you gave a bucket name that is not valid. Bucket names must be up to 255 characters long and can only have English letters, numbers, periods, hyphens and underscores. I assume that `'bucketname'` and `'xxxxxx'` are placeholders for the actual value that you are passing, so I can't tell what's wrong with it, but if you are printing the names of your buckets you should be able to use any in that list.
type: QuestionComment
comment on: http://stackoverflow.com/q/48187021
score: 2
type: Comment

http://stackoverflow.com/a/48191044
answers question: http://stackoverflow.com/q/48190993
type: AcceptedAnswer
downvote count: 0
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48190993
has body: But why is not the usual formatting syntax used? You can use it. Just specify the keyword argument style='{' when you configure logging. They did not change it to the default, in order to keep backwards compat (the logging module predates str.format style formatting) what does the s after the parentheses mean? "s" means use plain string representation. Compare "d" for digits. This is printf style syntax. What effect has -8s? Align left, pad to 8 width &gt;&gt;&gt; '%(foo)-8s' % {'foo': 'hello'} 'hello ' Is it possible to have custom values in there (e.g. an ID which identifies what type of element was currently handled), or does this have to be in the message? Yes, but don't bother trying to get stdlib logging to do this stuff. Go directly to structlog.
type: Answer

http://stackoverflow.com/a/48294752
downvote count: 0
has comment: http://stackoverflow.com/comment/83575103
answers question: http://stackoverflow.com/q/48294729
has comment: http://stackoverflow.com/comment/83574471
has comment: http://stackoverflow.com/comment/83615028
has comment: http://stackoverflow.com/comment/83616100
type: Answer
has comment: http://stackoverflow.com/comment/83575044
has comment: http://stackoverflow.com/comment/83575021
has comment: http://stackoverflow.com/comment/83575081
has comment: http://stackoverflow.com/comment/83574510
score: 2
has body: If want check ? values only in all columns: df1 = df.loc[:, (df.astype(str) == '?').any()] More general if want check all possible substrings ? in all columns: df2 = df.loc[:, df.apply(lambda x: x.astype(str).str.contains('\?')).any()] EDIT: df = pd.DataFrame({'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,'?',2,3], 'D':['?',3,5,7,1,0], 'E':[5,3,6,9,2,'?'], 'F':list('aaabbb')}) print (df) A B C D E F 0 a 4 7 ? 5 a 1 b 5 8 3 3 a 2 c 4 9 5 6 a 3 d 5 ? 7 9 b 4 e 5 2 1 2 b 5 f 4 3 0 ? b You can create boolean DataFrame first and then check any True per rows and per columns for filtering: mask = df.apply(lambda x: x.astype(str).str.contains('\?')) df2 = df.loc[mask.any(axis=1), mask.any()] print (df2) C D E 0 7 ? 5 3 ? 7 9 5 3 0 ? Detail: print (mask) A B C D E F 0 False False False True False False 1 False False False False False False 2 False False False False False False 3 False False True False False False 4 False False False False False False 5 False False False False True False print (mask.any(axis=1)) 0 True 1 False 2 False 3 True 4 False 5 True dtype: bool print (mask.any()) A False B False C True D True E True F False dtype: bool
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48294729
type: AcceptedAnswer

http://stackoverflow.com/a/48286345
type: Answer
accepted answer of: http://stackoverflow.com/q/48284349
answers question: http://stackoverflow.com/q/48284349
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: aiohttp version 2.3 has a subtle bug: it doesn't inform about improper sub application initialization order. Sub-application logically is frozen after registering in parent, adding new routes to it is an error. Not released yet aiohttp 3.0 raises explicit exception on app.add_subapp() call, see corresponding issue and pull request for more details. To fix your snippet reorder route registering calls: from aiohttp import web async def handler(request): return web.Response(text="OK") subsubapp = web.Application() subsubapp.router.add_get('/page2/', handler) subapp = web.Application() subapp.router.add_get('/page1/', handler) subapp.add_subapp('/sub/', subsubapp) app = web.Application() app.add_subapp('/wt/', subapp) web.run_app(app, host='127.0.0.1', port=8080) After this fetching http://127.0.0.1:8080/wt/sub/page2/ resources returns 200 OK.

http://stackoverflow.com/q/48278619
has comment: http://stackoverflow.com/comment/83542037
possible better answer: http://stackoverflow.com/a/48278870
type: Question
has answer: http://stackoverflow.com/a/48278870
has answer: http://stackoverflow.com/a/48278783
has title: python call to popen.communicate gives no output
tagged with: python
has comment: http://stackoverflow.com/comment/83544977
type: AnsweredQuestion
score: 0
answer count: 2
has body: I have a class function declared as def catFunc(self,filename): print "catFunc",filename process = subprocess.Popen(['cat',/root/scratch.php], stdout=subprocess.PIPE, shell=True) out, err = process.communicate() print (out) print (err) and called like this fn = '/root/scratch.php' self.catFunc(fn) But I see no output and cannot figure out why Any help greatly appreciated
accepted answer: http://stackoverflow.com/a/48278783

http://stackoverflow.com/a/48243939
has body: you can do : split(df$Stage) The value will be split into a list. HTH
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48243028

http://stackoverflow.com/comment/83535829
comment on: http://stackoverflow.com/a/48270713
type: Comment
type: AnswerComment
has text: Please consider closing the thread since your original question is answered.
score: 1

http://stackoverflow.com/comment/83622817
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48297357
score: 0
has text: As I understood this command pip install pysnmp-mibs just install certain compiled snmp mibs into xxx.py so it is easier to create for example snmp traps variables (you don't need to write whole OID number in call,just write name of mib: name of variable) ...and that is why i want to add some more enterprise mib to my .py dir.

http://stackoverflow.com/q/48310058
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/83615585
tagged with: scikit-learn
has body: I have a model with a categorical factor. I encode it as One Hot Encoding using pandas.get_dummies. The categorical factor has many levels that are uncommon, though. were I to re-encode the new data using pandas.get_dummies the new columns might be 'off' because that new level won't appear in the new data. I was thinking about doing the following: dummies_df = pd.get_dummies(list_of_all_possible_levels) dummies_df[:] = 0 dummies_df.drop(dummies_df.index[1:], inplace=True) # If there are 10 levels this becomes a 10x10 Dataframe. I only need # one 'empty' row and drop everything after the first. # Let's say the DataFrame looks like this: df['categorical_factor', 'numeric_factor', 'other_numeric_factor'] # I want to do something where I flag the column of the feature as 1 # and append the one-row dummies_df to each row of df for cat in df.categorical_factor: dummies_df[cat] = 1 df['numeric_factor', 'other_numeric_factor'] + dummies_df I'm just confused to whether I should be looping though the rows like this, or there's a better 'cartesian product'-type answer. If this were R I would just do cbind(df, dummies_df) since R knows to recycle the values of dummies_df. Or maybe I should use pandas.get_dummies on the new data and join-in the missing levels as new columns like this: new_dat['missing_level_1'] = [0 for _ in new_dat.index] new_dat['missing_level_2'] = [0 for _ in new_dat.index] Edit: Sample Data levels=['level_1', 'level_2', 'level_3'] A = [0,1,2] B = [3,4,5] df = pd.DataFrame({'levels': levels, 'A': A, 'B': B}) df = df.drop('levels', axis=1).join(pd.get_dummies(df.levels)) new_levels=['level_1', 'level_2', 'level_2'] new_A = [5,6,7] new_B = [8,9,7] new_df = pd.DataFrame({'levels': new_levels, 'A': new_A, 'B': new_B}) new_df = new_df.drop('levels', axis=1).join(pd.get_dummies(new_df.levels)) df is now +---------+---+---+---------+---------+---------+ | (index) | A | B | level_1 | level_2 | level_3 | +---------+---+---+---------+---------+---------+ | 0 | 0 | 3 |…
has comment: http://stackoverflow.com/comment/83607486
accepted answer: http://stackoverflow.com/a/48315465
has comment: http://stackoverflow.com/comment/83605966
has title: One Hot Encoding of uncommon feature levels in Python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48315465
tagged with: pandas
has comment: http://stackoverflow.com/comment/83607638
tagged with: python
type: Question
tagged with: one-hot-encoding
answer count: 1
has comment: http://stackoverflow.com/comment/83606875

http://stackoverflow.com/comment/83614447
score: 0
type: AnswerComment
has text: What if I want to do the same but for the summary tab? Trying to use what you've written to do it myself but super confusing!
comment on: http://stackoverflow.com/a/48287489
type: Comment

http://stackoverflow.com/a/48280824
upvote count: 3
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48203397
score: 3
has body: Here are my two cents on this. According to documentation, epoll is available only on Linux 2.5.44 and newer. With code: import os if os.uname()[0] != 'Linux' or os.uname()[2] &lt; '2.5.44': #use select else: #use epoll Better yet, I reckon that the above could be turned into a nice decorator, to be used wherever you want in your program, that returns the correct function depending on the underlying os.

http://stackoverflow.com/q/48178984
accepted answer: http://stackoverflow.com/a/48190738
downvote count: 0
has answer: http://stackoverflow.com/a/48190738
has answer: http://stackoverflow.com/a/48179091
tagged with: python
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48179091
has title: How do you make the game end when the main player collides with an image (obstacle)?
tagged with: pygame
has body: import math import random import pygame from pygame.locals import * import sys def events(): for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() pygame.init() W = 700 H = 400 updater = pygame.time.Clock() display = pygame.display.set_mode((700, 400)) pygame.display.set_caption("Skating_Game") x = y = 0 surface = pygame.image.load("man2.png") pygame.display.set_icon(surface) class player: def __init__(self, velocity, maxJumpRange): self.velocity = velocity self.maxJumpRange = maxJumpRange def setLocation(self, x, y): self.x = x self.y = y self.xVelocity = 0 self.jumping = False self.jumpCounter = 0 self.falling = True def keys(self): k = pygame.key.get_pressed() if k[K_LEFT]: self.xVelocity = -self.velocity elif k[K_RIGHT]: self.xVelocity = self.velocity else: self.xVelocity = 0 if k[K_SPACE] and not self.jumping and not self.falling: self.jumping = True self.jumpCounter = 0 def move(self): self.x += self.xVelocity if self.jumping: self.y -= self.velocity self.jumpCounter += 1 if self.jumpCounter == self.maxJumpRange: self.jumping = False self.falling = True elif self.falling: if self.y &lt;= H - 60 and self.y + self.velocity &gt;= H - 60: self.y = H - 60 self.falling = False else: self.y += self.velocity def draw(self): display = pygame.display.get_surface() character = pygame.image.load("man3.png").convert_alpha() display.blit(character, (self.x, self.y - 100)) #pygame.draw.circle(display, (255, 255, 255), (self.x, self.y - 25), 25, 0) def do(self): self.keys() self.move() self.draw() P = player(3, 50) P.setLocation(350, 0) BLACK = ( 0, 0, 0) g=0 font = pygame.font.SysFont("Plump", 30) obstacle = pygame.image.load("obstacle.png").convert_alpha() background = pygame.image.load("Road.png").convert() x = 0 while True: events() rel_x = x % background.get_rect().width display.blit(background, (rel_x - background.get_rect().width,0)) if rel_x &lt; 700: display.blit(background, (rel_x, 0)) x…
favorite count: 0
type: Question
answer count: 2
upvote count: 2

http://stackoverflow.com/a/48219354
has comment: http://stackoverflow.com/comment/83420876
has comment: http://stackoverflow.com/comment/83421112
type: Answer
has comment: http://stackoverflow.com/comment/83420951
score: -1
answers question: http://stackoverflow.com/q/48219085
upvote count: 0
has comment: http://stackoverflow.com/comment/83421042
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83420759
downvote count: 1
accepted answer of: http://stackoverflow.com/q/48219085
has body: You can select element in an iterative object (such as D in your code) simply by choosing its index. Such as: for i in range(period): print D[i] But in your code, rtn_daily and sig_daily are not in the same shape, I assume that you want to add sig_daily multiply by D[i] in each position of rtn. so try this: # -*- coding:utf-8 -*- import numpy as np period = 63 # can be edited to an input() command for variable periods. Mrgn_dec = .10 # decimal value of 10%, can be manipulated to produce a 10% increase/decrease rtn_annual = np.repeat(np.arange(0.00,0.15,0.05), 31) # creates an array ??? not sure if helpful sig_annual = np.repeat(np.arange(0.01,0.31,0.01), 3) #use .31 as python doesnt include the upper range value. #functions for variables of daily return and risk. rtn_daily = (float(1)/252)*rtn_annual sig_daily = (1/(np.sqrt(252)))*sig_annual D=np.random.normal(size=period) # unsure of range to use for standard distribution print D for i in range(period): r=(rtn_daily[i]+sig_daily[i]*D[i]) print r Last of all, if you are using python2, the division method is for integer, so that means 1/252 will give you zero as result. a = 1/252 &gt;-- 0 to solve this you may try to make it float: rtn_daily = (float(1)/252)*rtn_annual

http://stackoverflow.com/comment/83439495
comment on: http://stackoverflow.com/a/48228231
type: Comment
score: 0
type: AnswerComment
has text: @Dmitri see previous comment & addition to answer

http://stackoverflow.com/comment/83353338
comment on: http://stackoverflow.com/a/48186358
score: 0
type: AnswerComment
has text: Ok! Thank you very much!
type: Comment

http://stackoverflow.com/a/48220426
has body: Python's grammar is LL(1), meaning that it only looks ahead one symbol when parsing. [(v1, v2) for v1 in myList1 for v2 in myList2] Here, the parser sees something like this. [ # An opening bracket; must be some kind of list [( # Okay, so a list containing some value in parentheses [(v1 [(v1, [(v1, v2 [(v1, v2) [(v1, v2) for # Alright, list comprehension However, without the parentheses, it has to make a decision earlier on. [v1, v2 for v1 in myList1 for v2 in myList2] [ # List-ish thing [v1 # List containing a value; alright [v1, # List containing at least two values [v1, v2 # Here's the second value [v1, v2 for # Wait, what? A parser which backtracks tends to be notoriously slow, so LL(1) parsers do not backtrack. Thus, the ambiguous syntax is forbidden.
answers question: http://stackoverflow.com/q/48220279
type: Answer
has comment: http://stackoverflow.com/comment/107945537
score: 12
downvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48220279
upvote count: 14

http://stackoverflow.com/a/48281028
answers question: http://stackoverflow.com/q/48276227
upvote count: 2
downvote count: 0
type: Answer
score: 2
has body: I know what I did wrong: My matrices are declared as 64-bit floats in python (64-bit machine) and I used float pointers in my OpenCL code seems to cause the problem. Changing float to double in the OpenCL code fixes the problem :)

http://stackoverflow.com/comment/83638204
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48326179
score: 0
has text: The MB I was writing was "fluffy", and just for ease of reading moreso than accuracy, the bytes figure is there for anyone needing the exact size. Re: checksum, I certainly could do that, but with this amount of files, on a not-so-fast FTP server, and s3 which isn't super fast for this stuff, that would take a serious amount of time. And I have manually checked a few of these files with difference, and there hasn't been a single difference I've found between them yet - hence my confusion.

http://stackoverflow.com/comment/83692495
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48259602
has text: Thanks a lot! That's exactly what I want. BTW, match_template from skimage.feature can also solve this with a normalized xcorr matrix as output

http://stackoverflow.com/a/48223850
type: Answer
accepted answer of: http://stackoverflow.com/q/48223587
answers question: http://stackoverflow.com/q/48223587
has body: You got your nesting mixed up. The following works: {name: {col: int(value) for col, value in zip(grades_list[0][1:], row)} for name, *row in grades_list[1:]} The for name, *row in ... loop takes each row, and extracts just the first value into name, the remainder into row (the * tells Python to take the remainder). This lets you then use the row together with the column names from the first row to create the nested dictionaries. It is often easier to see what a comprehension does by using regular loops. Your code does this: grade_dicts = {} for y in grades_lists[0][1:]: for x in grades_lists[1:]: for z in x[1:]: grade_dicts[x[0]] = {y:z} That's way too many loops, and you end up setting a value for x[0] several times; len(x[1:]) times in fact. Only the last {y: z} dictionary remains. My version does this: grade_dicts = {} for name, *row in grades_list[1:]: inner = {} for col, value in zip(grades_list[0][1:], row): inner[col] = int(value) grade_dicts[name] = inner That's just two loops, where the inner produces a separate dictionary for each column. I used zip() to pair up the labels and the values.
type: AcceptedAnswer
score: 5
upvote count: 5
downvote count: 0

http://stackoverflow.com/comment/83432875
comment on: http://stackoverflow.com/a/48225556
has text: After the operation, rev_id is not a column again. How to convert the result to three columns
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48184995
type: UnansweredQuestion
tagged with: windows
tagged with: python
tagged with: requirements.txt
score: 2
tagged with: python-2.7
linked to: http://stackoverflow.com/q/36377777
has title: Install requirements.txt with pip for Python 2 on Windows
has answer: http://stackoverflow.com/a/48190443
downvote count: 0
has body: I am trying to install remote environment like on remote server using requirements.txt. So first I went to Server went to virtualenv by source bin/activate and typed: pip freeze &gt; requirements.txt then on my Windows machine I run: pip2 install -r requirements.txt I have currently Python27 on Server and Windos machine. This is output on my Windows 8: Collecting Cap1xxx==0.1.3 (from -r requirements.txt (line 1)) Using cached Cap1xxx-0.1.3.tar.gz Collecting ExplorerHAT==0.4.2 (from -r requirements.txt (line 2)) Using cached ExplorerHAT-0.4.2.tar.gz Collecting Flask==0.10.1 (from -r requirements.txt (line 3)) Using cached Flask-0.10.1.tar.gz Collecting Jinja2==2.7.3 (from -r requirements.txt (line 4)) Using cached Jinja2-2.7.3.tar.gz Collecting MarkupSafe==0.23 (from -r requirements.txt (line 5)) Using cached MarkupSafe-0.23.tar.gz Collecting Pillow==2.6.1 (from -r requirements.txt (line 6)) Using cached Pillow-2.6.1-cp27-none-win32.whl Collecting ................. and so on Collecting urllib3==1.9.1 (from -r requirements.txt (line 43)) Using cached urllib3-1.9.1-py2-none-any.whl Requirement already satisfied: virtualenv==15.1.0 in c:\python27\lib\site-packages (from -r requirements.txt (line 44)) Collecting wheel==0.24.0 (from -r requirements.txt (line 45)) Using cached wheel-0.24.0-py2.py3-none-any.whl Collecting wsgiref==0.1.2 (from -r requirements.txt (line 46)) Using cached wsgiref-0.1.2.zip Collecting RPi.GPIO (from Cap1xxx==0.1.3-&gt;-r requirements.txt (line 1)) Using cached RPi.GPIO-0.6.3.tar.gz Collecting PyOpenSSL (from ndg-httpsclient==0.3.2-&gt;-r requirements.txt (line 22)) Collecting and everything is fine ............................. And then there is a traceback: Running setup.py install for RPi.GPIO ... error Complete output from command c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\3c8a~1\\appdata\\local\\temp\\pip-build-tvvec2\\RPi.GPIO\\setup.py';f= getattr(tokenize, 'open', open)(__file__);code=f.read().replace(…
has answer: http://stackoverflow.com/a/48234788
has comment: http://stackoverflow.com/comment/135754132
has comment: http://stackoverflow.com/comment/83360798
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83350459
answer count: 2
upvote count: 2

http://stackoverflow.com/comment/102911477
has text: I ended up finding exactly what you put here, using `pandas` was just impossible, it was much much slower and I was forced to utilize `numpy`. The time savings are non-trivial with very little code change.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/58254844

http://stackoverflow.com/comment/83474671
comment on: http://stackoverflow.com/q/48245973
score: 1
type: QuestionComment
has text: Find this one : http://liftoff.github.io/pyminifier/
type: Comment

http://stackoverflow.com/comment/83474207
comment on: http://stackoverflow.com/a/48245226
score: 0
type: AnswerComment
type: Comment
has text: I literally ran your code as you provided it and this is what came out. That tells me your input differs from mine.

http://stackoverflow.com/a/48370737
has comment: http://stackoverflow.com/comment/83793558
has comment: http://stackoverflow.com/comment/83764373
has comment: http://stackoverflow.com/comment/83795018
downvote count: 0
has comment: http://stackoverflow.com/comment/83795492
score: 16
upvote count: 16
has comment: http://stackoverflow.com/comment/83759617
has comment: http://stackoverflow.com/comment/83780519
has body: By default, celery will reset handers on celery.task logger, you could disable this behavior with worker_hijack_root_logger option. Or, you could reconfigure this logger in after_setup_task_logger signal, even dont let celery config the loggers with setup_logging signal: from celery.signals import setup_logging @setup_logging.connect() def config_loggers(*args, **kwargs): from logging.config import dictConfig dictConfig(app.config['LOGGING_CONFIG'])
has comment: http://stackoverflow.com/comment/83792740
answers question: http://stackoverflow.com/q/48289809
has comment: http://stackoverflow.com/comment/83795065
type: Answer

http://stackoverflow.com/q/48215956
tagged with: menu
tagged with: statusbar
type: AnsweredQuestion
score: 0
has title: Change default field in a multi field statusbar in wxpython (to display menuitem help text)
has body: In wxpython when we create a multi field statusbar, the first field is being used by default, to display the help texts of mouse hovered menu items. for example in the code below: import wx class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title='Multi field status bar.') panel = wx.Panel(self) self.statusbar = self.CreateStatusBar(2) self.menubar = wx.MenuBar() self.menuitem = wx.Menu() self.SetMenuBar(self.menubar) if True: # Utilitie IDs: self.ID_new_utilitie = wx.NewId() self.ID_delete_utilitie = wx.NewId() if True: # Menu items: self.menuitem.Append(self.ID_new_utilitie, "&amp;New", "Create New Utilitie.") self.menuitem.Append(self.ID_delete_utilitie, "&amp;Delete", "Delete Selected Utilitie.") self.menubar.Append(self.menuitem, '&amp;Actions') if True: # Utilitie Actions: wx.EVT_MENU(self, self.ID_new_utilitie, self.Create_New_Utilitie) wx.EVT_MENU(self, self.ID_delete_utilitie, self.Delete_Selected_Utilitie) self.Show() def Create_New_Utilitie(self, event): pass def Delete_Selected_Utilitie(self, event): pass if __name__ == '__main__': app = wx.App(False) frame = MainFrame() app.MainLoop() Whenever we hover over a menu item, the help text gets displayed automatically in the 1st field (by default). An image illustrating my question while running the example above. Please note that I am not asking how to SetStatusText the 2nd field with help texts but how to change the default field for displaying them. Thanks.
answer count: 1
tagged with: wxpython
type: Question
has answer: http://stackoverflow.com/a/48255199
accepted answer: http://stackoverflow.com/a/48255199
tagged with: python

http://stackoverflow.com/comment/83498818
type: AnswerComment
has text: Thank you - this does achieve the expected result. However, as I explain in a Clarification above, it does not exactly address the problem I am trying to solve (sorting on field 2, as opposed to sorting on the last field). My apologies for the confusion!
comment on: http://stackoverflow.com/a/48250903
type: Comment
score: 0

http://stackoverflow.com/a/48183588
answers question: http://stackoverflow.com/q/48183174
has comment: http://stackoverflow.com/comment/83354023
has comment: http://stackoverflow.com/comment/83347293
has comment: http://stackoverflow.com/comment/83347532
has comment: http://stackoverflow.com/comment/83347618
has comment: http://stackoverflow.com/comment/83354699
type: Answer
has comment: http://stackoverflow.com/comment/83354552
has comment: http://stackoverflow.com/comment/83347761
has comment: http://stackoverflow.com/comment/83353459
has comment: http://stackoverflow.com/comment/83352810
has comment: http://stackoverflow.com/comment/83350619
has comment: http://stackoverflow.com/comment/83354838
has comment: http://stackoverflow.com/comment/83349724
downvote count: 0
has comment: http://stackoverflow.com/comment/83349476
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/48183174
has comment: http://stackoverflow.com/comment/83350009
type: AcceptedAnswer
has body: In your case, something like this should do the job: acc['parent'] = np.full(pop_size, False, dtype=bool) o = 0 while o &lt; pop_size: b = 0 while b &lt; n_rw: acc.loc[o,'parent'] = ((rw[b] &gt; acc['left'][o]) &amp; (rw[b] &lt;= acc['right'][o])) Now you are writing into the DataFrame and actually changing the values that were previously initiated. if acc.loc[o,'parent'] == True: break else: b = b+1 o = o+1 print acc However, I'm not sure what your code is doing.
has comment: http://stackoverflow.com/comment/83353436
has comment: http://stackoverflow.com/comment/83348431
has comment: http://stackoverflow.com/comment/83353568
has comment: http://stackoverflow.com/comment/83353630

http://stackoverflow.com/comment/83451444
type: AnswerComment
comment on: http://stackoverflow.com/a/48234349
has text: For a small array such as `a = np.array([4,2,9,1,3])`, using `itertools.permutations` is faster, but as the length of the input increases, your code eventually wins.
score: 0
type: Comment

http://stackoverflow.com/comment/83606767
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48310216
has text: I don't think that is possible. Why don't you create a function that recalculates the column and call it after every update?

ethereum
type: Tag
tags question: http://stackoverflow.com/q/48330955
tags question: http://stackoverflow.com/q/48181275
tags question: http://stackoverflow.com/q/48259293
tag name: ethereum

http://stackoverflow.com/q/48264692
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
tagged with: pandas
answer count: 1
has body: I am having a problem with adding a dictionary which contains lists into a pandas data-frame. My data looks like this: a = {'id':[0,1,2,3,4,5,6], 'value':[354,324,211,78,644,198,342]} When you add a dictionary to a pandas dataframe, it adds the elements of each list to a row in the dataframe, like this: test1 = pd.DataFrame(a) But then, when I try to append a dictionary (the same dictionary in this case), each column then contains a list. test1 = test1.append(a, ignore_index = True) I have tried to find out why this is the case. Any help? Thanks.
favorite count: 0
has title: Adding Dictionaries with lists to a Pandas DataFrame (pd.DataFrame(dict) vs df.append(dict))
type: Question
has answer: http://stackoverflow.com/a/48265154
accepted answer: http://stackoverflow.com/a/48265154
tagged with: python
tagged with: dictionary

http://stackoverflow.com/a/48252920
type: Answer
answers question: http://stackoverflow.com/q/48252855
score: 0
has body: This can be done quite efficiently using a regular expression match, e.g.: import re re_containsA = re.compile(r'.*a.*') for key, word in worddict.items(): if re_containsA.match(word): print(key) The re.match object can then be used to find the location of the matched text.
has comment: http://stackoverflow.com/comment/83568355

http://stackoverflow.com/a/48318926
upvote count: 1
has comment: http://stackoverflow.com/comment/83652196
answers question: http://stackoverflow.com/q/48318730
has body: You can scrape data from web site using Python, Beautifulsoup library help to clean up the html code and extract. Thare are other libraries also. Even NodeJs alsocan do the same this. Main thing is your logic. Python and Beautifulsoup will gives you data. You have to analysis and save themin db. Beautiful Soup Documentation Other Requests, lxml, Selenium, Scrapy Example from bs4 import BeautifulSoup import requests page = requests.get("http://www.dataforcities.org/") soup = BeautifulSoup(page.content, 'html.parser') all_links = soup.find_all(("a") Like above you can find anything. There are many functions. Tutorial web scraping tutorial python and beautifulsoup Better to check official documentation as well.
type: Answer
has comment: http://stackoverflow.com/comment/83623878
downvote count: 0
score: 1

django
tags question: http://stackoverflow.com/q/48327865
tags question: http://stackoverflow.com/q/48201033
tags question: http://stackoverflow.com/q/48323976
tags question: http://stackoverflow.com/q/48293666
tags question: http://stackoverflow.com/q/48193919
tags question: http://stackoverflow.com/q/48261466
tags question: http://stackoverflow.com/q/48220717
tags question: http://stackoverflow.com/q/48191484
tags question: http://stackoverflow.com/q/48276444
tags question: http://stackoverflow.com/q/48222837
tags question: http://stackoverflow.com/q/48307041
tags question: http://stackoverflow.com/q/48277696
tags question: http://stackoverflow.com/q/48322442
tags question: http://stackoverflow.com/q/48320056
tags question: http://stackoverflow.com/q/48218891
tags question: http://stackoverflow.com/q/48263309
tags question: http://stackoverflow.com/q/48314694
tags question: http://stackoverflow.com/q/48242738
tags question: http://stackoverflow.com/q/48206545
tags question: http://stackoverflow.com/q/48249893
tags question: http://stackoverflow.com/q/48186658
tags question: http://stackoverflow.com/q/48318968
tags question: http://stackoverflow.com/q/48253070
tags question: http://stackoverflow.com/q/48247083
tags question: http://stackoverflow.com/q/48248323
tags question: http://stackoverflow.com/q/48226225
tags question: http://stackoverflow.com/q/48310059
tags question: http://stackoverflow.com/q/48262123
tags question: http://stackoverflow.com/q/48281960
tags question: http://stackoverflow.com/q/48225786
tags question: http://stackoverflow.com/q/48183390
tags question: http://stackoverflow.com/q/48192255
tags question: http://stackoverflow.com/q/48196024
tags question: http://stackoverflow.com/q/48207340
tags question: http://stackoverflow.com/q/48222296
tags question: http://stackoverflow.com/q/48181511
tags question: http://stackoverflow.com/q/48229906
tags question: http://stackoverflow.com/q/48328366
tags question: http://stackoverflow.com/q/48264075
tags question: http://stackoverflow.com/q/48309493
tags question: http://stackoverflow.com/q/48309523
tags question: http://stackoverflow.com/q/48293627
tags question: http://stackoverflow.com/q/48229312
tags question: http://stackoverflow.com/q/48233405
tags question: http://stackoverflow.com/q/48298371
tags question: http://stackoverflow.com/q/48264539
tags question: http://stackoverflow.com/q/48241548
tags question: http://stackoverflow.com/q/48199594
tags question: http://stackoverflow.com/q/48311831
tags question: http://stackoverflow.com/q/48296262
tags question: http://stackoverflow.com/q/48218254
tags question: http://stackoverflow.com/q/48292070
tags question: http://stackoverflow.com/q/48301889
tags question: http://stackoverflow.com/q/48200851
tags question: http://stackoverflow.com/q/48191460
tags question: http://stackoverflow.com/q/48252839
tags question: http://stackoverflow.com/q/48241991
tags question: http://stackoverflow.com/q/48271543
tags question: http://stackoverflow.com/q/48314232
tags question: http://stackoverflow.com/q/48191071
tags question: http://stackoverflow.com/q/48236570
tags question: http://stackoverflow.com/q/48262495
tags question: http://stackoverflow.com/q/48249068
tags question: http://stackoverflow.com/q/48207521
tags question: http://stackoverflow.com/q/48291939
tags question: http://stackoverflow.com/q/48322869
tags question: http://stackoverflow.com/q/48245133
tags question: http://stackoverflow.com/q/48242631
tags question: http://stackoverflow.com/q/48287650
tags question: http://stackoverflow.com/q/48193316
tags question: http://stackoverflow.com/q/48246810
tags question: http://stackoverflow.com/q/48243168
tags question: http://stackoverflow.com/q/48187924
tags question: http://stackoverflow.com/q/48309478
tags question: http://stackoverflow.com/q/48239221
tags question: http://stackoverflow.com/q/48197857
tags question: http://stackoverflow.com/q/48187740
tags question: http://stackoverflow.com/q/48318175
tags question: http://stackoverflow.com/q/48281394
tags question: http://stackoverflow.com/q/48254269

http://stackoverflow.com/q/48253841
tagged with: python
accepted answer: http://stackoverflow.com/a/48253905
type: AnsweredQuestion
score: 0
tagged with: deep-learning
answer count: 1
upvote count: 1
tagged with: keras
downvote count: 1
favorite count: 0
type: Question
has title: How to add new elements to the config object of Keras models?
has body: I'm in trouble with adding new elements to the config object of Keras models. We can get the config object with the following code: config = model.get_config() But, I can not find any methods like model.set_condig(). I'd like to set my own elements to it. Anyone know how to do this ?
has answer: http://stackoverflow.com/a/48253905

http://stackoverflow.com/a/48276166
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/138308251
downvote count: 0
answers question: http://stackoverflow.com/q/48275759
type: Answer
accepted answer of: http://stackoverflow.com/q/48275759
score: 42
upvote count: 42
has body: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known seems to indicate that the elasticsearch client is not able to resolve the hostname. It could possibly be because you include the protocol https:// specified in the host. Change that line to host = 'kbckjsdkcdn.us-east-1.es.amazonaws.com' to see if it works. Also the example comment you have there, seems to indicate that the protocol should not be included in the host variable.
has comment: http://stackoverflow.com/comment/95344511

http://stackoverflow.com/q/48321359
tagged with: list
has comment: http://stackoverflow.com/comment/83648713
downvote count: 0
accepted answer: http://stackoverflow.com/a/48321468
favorite count: 0
has answer: http://stackoverflow.com/a/48324748
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48321468
score: 2
has answer: http://stackoverflow.com/a/48321528
has body: I have a dictionary objects like below: {('look', 'toward'): 1, ('new', 'cage'): 3, ('think', 'surpris'): 0, ('go', 'see'): 1 } What I would like to do is to extract a each words separately in order like 'look', 'toward', 'new', 'cage'....up to end without use values(). How can I extract these words ? Is it better to make a list instead of a dictionary ? It would be really appreciated if it is explained in detail.
upvote count: 2
has comment: http://stackoverflow.com/comment/83627850
answer count: 5
has answer: http://stackoverflow.com/a/48321443
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48321400
has title: Extract keys from a dictionary as a flat list
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48321443

http://stackoverflow.com/comment/83498104
score: 0
comment on: http://stackoverflow.com/a/48257654
type: AnswerComment
has text: This fixes both axes with much simpler code. Thank you! Just one issue: How do I limit the x-axis to single dates? I'm not sure what those in-between dates with 13's are doing there.
type: Comment

http://stackoverflow.com/q/48272012
accepted answer: http://stackoverflow.com/a/48272304
type: Question
tagged with: ffmpeg
tagged with: ffprobe
tagged with: python
has answer: http://stackoverflow.com/a/48272304
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/csv
has body: How can I use FFprobe in python scripts, which also exports the output as csv file? The command I want to perform is: ffprobe -i file_name -show_frames -select_streams v:1 -print_format csv &gt; filename.csv I looked at other posts about similar problem, and changed a little: def probe_file(filename): cmnd = ['ffprobe', '-i',filename, '-show_frames', '-select_streams', 'a', '-print_format', 'csv'] p = subprocess.Popen(cmnd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print filename out, err = p.communicate() print "==========output==========" print out if err: print "========= error =r=======" print err however, I can't seem to have "> filename.csv" working. After analysing the video, I want all the output as csv file, named the same as the file name Does anyone know how I can approach this? Thanks in advance
answer count: 1
has title: Using FFprobe in Python

http://stackoverflow.com/q/48214134
has comment: http://stackoverflow.com/comment/83428733
has answer: http://stackoverflow.com/a/50409232
downvote count: 0
has comment: http://stackoverflow.com/comment/83420738
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: facebook
has body: I cant seem to get it to work guys, after reading similar questions my issue is not due to not specifying key and secret nor is it because i forgot to add '-oauth2' after facebook. please help?? All i see on the browser is Backend not Found. Maybe it is just because my django or python versions are too new?? I use python 3.6 and django 2.0... here is my project's settings.py SECRET_KEY = '<my_secret_key>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main_app', 'django_filters', 'cuentas', 'social_django', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] # python social auth settings SOCIAL_AUTH_FACEBOOK_KEY = '<facebook_app_id>' SOCIAL_AUTH_FACEBOOK_SECRET = '<facebook_app_secret>' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_API_VERSION = '2.11' AUTHENTICATION_BACKENDS = [ 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth…
tagged with: django
tagged with: python
tagged with: python-social-auth
has title: Backend not Found for Facebook
has comment: http://stackoverflow.com/comment/83438973
has answer: http://stackoverflow.com/a/48229067
answer count: 2
has comment: http://stackoverflow.com/comment/83438350
score: 1

http://stackoverflow.com/comment/83497241
has text: What do you want to do with the data? Are you attempting to update some chart or table or perform a calculation with another python function?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48252790
score: 0

http://stackoverflow.com/comment/83558248
has text: How would i then have something like f_x = 3*x+4, without having to manually enter it into each loop? The idea is that f_x will change with each run of the program.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48286520

http://stackoverflow.com/comment/83431884
comment on: http://stackoverflow.com/q/48225021
score: 1
type: Comment
type: QuestionComment
has text: Are you using a fairly barebones python installation? What OS are you on? Could you try installing it using `pip`/`pip3`/`conda` which will all get the dependencies first? Or could you use `apt-get` to install the dependencies then try again, i.e. `sudo apt-get build-dep matplotlib`?

http://stackoverflow.com/comment/83344998
has text: Each of your methods creates and installs a new handler on _every_ invocation. Fix that by not doing it.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48181460
type: QuestionComment

http://stackoverflow.com/a/48188419
has comment: http://stackoverflow.com/comment/83361347
has body: If you are not obliged to create a separate Anaconda environment and your purpose is to change the global version of Anaconda Python, try: conda install python=3.6.4 If the package is missing you could try locally with: conda install --use-local your_file_version.tar.bz2 See the screen below: You can download the packages here Update: For windows users you need to download the packages from here using conda-forge
has comment: http://stackoverflow.com/comment/83357259
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83379501
answers question: http://stackoverflow.com/q/48188307
has comment: http://stackoverflow.com/comment/83356910
has comment: http://stackoverflow.com/comment/83357187
score: 1
upvote count: 1

http://stackoverflow.com/q/48198334
has comment: http://stackoverflow.com/comment/83413938
tagged with: plot
has comment: http://stackoverflow.com/comment/83410184
accepted answer: http://stackoverflow.com/a/48215060
has comment: http://stackoverflow.com/comment/83409880
type: AnsweredQuestion
score: 3
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48215060
has comment: http://stackoverflow.com/comment/83390859
upvote count: 3
tagged with: matplotlib
has title: multiple interactive matplotlib behave differently in python 2.7 vs 3.6
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83409527
has body: I have a python script that loops continuously with user input directing it to get data from a file then plots it using matplotlib. My hope is to have the plots show up and stick around (and continue to be interactive) while the script continues on in the console asking for the next round of user input and plotting. So the user might end up with a few plot windows open in the end that are all functional. I actually have it working in my python 2.7 anaconda build with the following example code that just plots a random dataset each loop. import sys import matplotlib.pyplot as plt import matplotlib import numpy as np print('matplotlib version: '+matplotlib.__version__) version = sys.version_info[0] def plot_data(data): fig = plt.figure(figsize=(6,6)) plt.plot(data) plt.ion() plt.show() plt.pause(0.001) while True: if version &lt; 3: option = raw_input('type (1) to plot next data, (q) to quit\n') else: option = input('type (1) to plot next data, (q) to quit\n') if option == '1': data = np.random.choice(1000,100, replace = False) plot_data(data) elif option == 'q': break Running the code with my python 3.6 build, the plot shows up but is frozen in a non-responding state until I go back to the console and type in q to quit my user input loop. In python 2.7 the plot windows are fully functional through multiple input loops and plot calls. So I'm hoping someone knows what difference here. I'm printing the matplotlib version and it seems like both my 2.7 and 3.6 environments are using the same matplotlib 2.0.2 so maybe it's in the GUI handler?
has comment: http://stackoverflow.com/comment/83410012
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83409735
tagged with: python

http://stackoverflow.com/a/48189386
has comment: http://stackoverflow.com/comment/83363182
has comment: http://stackoverflow.com/comment/83362606
has comment: http://stackoverflow.com/comment/83362272
type: Answer
has comment: http://stackoverflow.com/comment/83365176
accepted answer of: http://stackoverflow.com/q/48180177
has comment: http://stackoverflow.com/comment/83361557
has comment: http://stackoverflow.com/comment/83361410
has comment: http://stackoverflow.com/comment/83361537
has comment: http://stackoverflow.com/comment/83362191
answers question: http://stackoverflow.com/q/48180177
has comment: http://stackoverflow.com/comment/83362050
has comment: http://stackoverflow.com/comment/83361970
type: AcceptedAnswer
has body: Python uses the floating-point features of the hardware it runs on, according to Python documentation. On most common machines today, that is IEEE-754 arithmetic or something near it. That Python documentation is not explicit about rounding mode but mentions in passing that the result of a sample division is the nearest representable value, so presumably Python uses round-to-nearest-ties-to-even mode. (“Round-to-nearest” for short. If two representable values are equally close in binary floating-point, the one with a zero in the low bit of its significand is produced.) In IEEE-754 arithmetic in round-to-nearest mode, the result of a division is the representable value nearest to the exact mathematical value. Since you say the mathematical value of x/y is reasonable, it is in the normal range of representable values (not below it, in the subnormal range, where precision suffers, and not above it, where results are rounded to infinity). In the normal range, results of elementary operations will be accurate within the normal precision of the format. However, since x and y are “very small numbers,” we may be concerned that they are subnormal and have a loss of precision already in them, before division is performed. In the IEEE-754 basic 64-bit binary format, numbers below 2-1022 (about 2.22507•10-308) are subnormal. If x and y are smaller than that, then they have already suffered a loss of precision, and no method can produce a correct quotient from them except by happenstance. Taking the logarithms to calculate the quotient will not help. If the machine you are running on happens not to be using IEEE-754, it is still likely that computing x/y directly will produce a better result than np.exp(np.log(x)-np.log(y)). The former is a single operation computing a basic function in hardware that was likely reasonably designed. The latter is several operations computing complicated functions in software that is difficult to make accurate using common hardware operations. The…
downvote count: 0
has comment: http://stackoverflow.com/comment/83361658
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/83369119
has comment: http://stackoverflow.com/comment/83361907
has comment: http://stackoverflow.com/comment/83362240
has comment: http://stackoverflow.com/comment/83362273

http://stackoverflow.com/comment/83367258
comment on: http://stackoverflow.com/q/48192856
type: Comment
type: QuestionComment
score: 0
has text: *Which* directory did you add to `PYTHONPATH`? How did you do that? WHat exactly is the problem here? Why are you trying to do all this (instead of, say, just installing things into a virtualenv or something)? Testing tools like `tox` will do this for you.

http://stackoverflow.com/comment/83410335
score: 0
comment on: http://stackoverflow.com/q/48213278
type: Comment
type: QuestionComment
has text: You are showing us a color image but Otsu deals with grayscale images. And how the hell do you know that the threshold should be 170 ?

http://stackoverflow.com/comment/129753263
score: 0
type: AnswerComment
has text: @FedericoTaranto The problem here is specific to decision trees. Yet you are right to control overfitting in stochastic gradient descent with the regularization parameter.
type: Comment
comment on: http://stackoverflow.com/a/48260611

http://stackoverflow.com/q/48251925
has answer: http://stackoverflow.com/a/48252510
tagged with: python
has comment: http://stackoverflow.com/comment/83486690
has title: Get server URL in django docker
has comment: http://stackoverflow.com/comment/83486561
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/113504826
favorite count: 0
type: Question
tagged with: docker
has comment: http://stackoverflow.com/comment/83486483
type: AnsweredQuestion
has body: I am running Django project in docker. I have 3 docker container. For Django App For Postgres For Nginx My docker-compose.yml file is as follow version: "3" services: db: restart: always container_name: tts-db image: postgres:9.6 environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=tts expose: - "5432" nginx: image: nginx:latest container_name: tts-nginx ports: - "8000:8000" volumes: - ./nginx/site-enabled:/etc/nginx/conf.d depends_on: - web web: build: . container_name: tts-app environment: - DATABASE=db - DEBUG=False - STATICFILES_STORAGE=whitenoise.storage.CompressedManifestStaticFilesStorage depends_on: - db expose: - "8888" entrypoint: ./entry_point.sh command: gunicorn urdu_tts.wsgi:application -w 2 -b :8888 restart: always In my django app, I need to access host address. I used request.get_host() which works in localhost. When I run this in Docker, I get url like http://web/media/voice/voice.wav. My nginx configuration is as follow. upstream web { ip_hash; server web:8888; } server { location ^/static/ { autoindex on; alias /static/; } location ~ ^/media/?(.*)$ { try_files /media/$1 /mediafiles/$1 =404; } location / { proxy_pass http://web; client_max_body_size 20m; } listen 8000; server_name localhost; } How can I get server url in Docker?
tagged with: docker-compose
accepted answer: http://stackoverflow.com/a/48252510
tagged with: nginx
has comment: http://stackoverflow.com/comment/83486512
score: 1

http://stackoverflow.com/q/48206810
has title: Python printing objects - TypeError: must be str, not Address
type: AnsweredQuestion
answer count: 3
upvote count: 2
score: 2
has answer: http://stackoverflow.com/a/48206968
possible better answer: http://stackoverflow.com/a/48206957
downvote count: 0
has answer: http://stackoverflow.com/a/48206957
accepted answer: http://stackoverflow.com/a/48206902
tagged with: console
favorite count: 0
type: Question
has body: I have Person and Address classes. Each Person holds an Address. Code: class Address: def __init__(self, street, town, city, postcode, country): self.street = street self.town = town self.city = city self.postcode = postcode self.country = country def __str__(self): return ("\t" + "Street: " + self.street + "\n\t" + "Town: " + self.town + "\n\t" + "City: " + self.city + "\n\t" + "Postcode: " + self.postcode + "\n\t" + "Country:" + self.country) class Person: def __init__(self, name, age, phone, address): # instance variables, unique to each Person self.name = name self.age = age self.phone = phone self.address = address def __str__(self): return "Name: " + self.name + "\n" + "Age: " + self.age + "\n" + "Phone: " + self.phone + "\n" + "Address: " + self.address However, when I call print(p) where p is a Person, I get the following exception: File "phone2.7.py", line 30, in __str__ return "Name: " + self.name + "\n" + "Age: " + self.age + "\n" + "Phone: " + self.phone + "\n" + "Address: " + self.address TypeError: must be str, not Address Can anyone pinpoint what the issue is here? Thanks.
has answer: http://stackoverflow.com/a/48206902
tagged with: python

http://stackoverflow.com/a/48289365
answers question: http://stackoverflow.com/q/48289293
score: 3
type: Answer
upvote count: 3
downvote count: 0
has body: I think that you are doing something wrong because: &gt;&gt;&gt; 'HELLO'.lower() 'hello' and &gt;&gt;&gt; test = 'HELLO' &gt;&gt;&gt; print (test).lower() hello &gt;&gt;&gt; print test.lower() hello both works fine in python2.7 In python 3.6 (at least): &gt;&gt;&gt; print (test.lower()) hello &gt;&gt;&gt; print ((test).lower()) hello But you are trying to execute lower method of result of print that is None. &gt;&gt;&gt; print(type(print('hi'))) hi &lt;class 'NoneType'&gt;

http://stackoverflow.com/comment/83465391
comment on: http://stackoverflow.com/q/48241274
score: 0
type: Comment
has text: Also see https://stackoverflow.com/questions/2958684/python-division and the various linked questions there, as well as the questions linked in the duplicate target.
type: QuestionComment

http://stackoverflow.com/comment/83465613
score: 0
has text: @larsks. I have thought about putting the question on RPi, but all the pi does is act as a terminal to control a completely separate chip. RPi wants software problems specific to the Pi, but I have no problems with controlling the chip, especially with Minicom. I am 90% sure that there is a software problem with the Sim900 though, and so it would be a great fit for StackOverflow. If it turns out it isn't a software problem, then I will ask this on a generic hardware site.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48237875

http://stackoverflow.com/comment/83461597
comment on: http://stackoverflow.com/a/48239354
has text: Thank you! It's finally working. But there needed some changes. Type req2.content instead of req2.text, choose 'wb' mode and '*.mid', not '*.midi*'
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48272128
has body: Using matplotlib 2.1 and numpy 1.13 the code from the question works fine as it is. A plausible explanation for why most people are able to run the code without error could be that matplotlib would rely on pandas for the plotting of datetime.time objects. If pandas is not installed or not found, it would hence fail. There is some assumption implicitly in the code, which may cause the problem and error seen. This is that the time alone may not be well represented on a matplotlib axes, which usually would expect datetime (i.e. including date) objects. Introducing some date to the times on the axes might solve the problem. import io u = u"""16,59,55,51 13.8 17,00,17,27 13.7 17,00,39,01 13.6 17,01,01,06 13.4""" import matplotlib.pyplot as plt import matplotlib.dates as mdates import csv from datetime import datetime x = [] y = [] plots = csv.reader(io.StringIO(u), delimiter=' ') for row in plots: hours,minutes,seconds,milliseconds = [int(s) for s in row[0].split(",")] x.append(datetime(2018,1,1,hours,minutes,seconds,milliseconds)) y.append(float(row[1])) plt.plot(x,y, marker='o', label='brightness') plt.gca().invert_yaxis() plt.xlabel('time [UT]') plt.ylabel('brightness [mag, CR]') plt.legend() plt.grid() hours = mdates.SecondLocator(bysecond=[0,30]) t_fmt = mdates.DateFormatter('%H:%M:%S') plt.gca().xaxis.set_major_locator(hours) plt.gca().xaxis.set_major_formatter(t_fmt) plt.show()
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48271838
downvote count: 0
has comment: http://stackoverflow.com/comment/83528226
score: 4
has comment: http://stackoverflow.com/comment/83528608
has comment: http://stackoverflow.com/comment/83528552
has comment: http://stackoverflow.com/comment/83528264
answers question: http://stackoverflow.com/q/48271838
has comment: http://stackoverflow.com/comment/83528689
type: Answer
has comment: http://stackoverflow.com/comment/83528200
has comment: http://stackoverflow.com/comment/83528302
upvote count: 4

http://stackoverflow.com/q/48237282
tagged with: serversocket
has answer: http://stackoverflow.com/a/48238694
answer count: 1
tagged with: raspberry-pi3
has body: my raspberry pi is the server and Im trying to send continuous message from rpi to android while recieving a command from client (android app),i really dont know if this is possible and how to do it is out of my reach and it is not a feedback message.,, i want to wait for the android client to connect, THEN send messages continuously to the client whilst simultaneously handling the ctrCmd messages from the client.i hope you can help me how it is done thank you.. import apptopi from socket import * from time import ctime from nanpy import (ArduinoApi, SerialManager) apptopi.setup() connection = SerialManager() a = ArduinoApi(connection = connection) ctrCmd = ['Up','Down','Left','Right','Stop','Connect'] add = 0 add += 1 a = str(add) //**this is a sample that i want to send continously HOST = '' PORT = 21567 BUFSIZE = 1024 ADDR = (HOST,PORT) tcpSerSock = socket(AF_INET, SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(0) tcpSerSock.send(str.encode(a)) &lt;== i really don't know how to send continuously while True: print 'Waiting for connection' tcpCliSock,addr = tcpSerSock.accept() print '...connected from :', addr try: while True: data = '' data = tcpCliSock.recv(BUFSIZE) if not data: break if data == ctrCmd[0]: apptopi.forw() print 'forward' if data == ctrCmd[1]: apptopi.back() print 'backward' if data == ctrCmd[2]: apptopi.left() print 'leftturn' if data == ctrCmd[3]: apptopi.right() print 'rightturn' if data == ctrCmd[4]: apptopi.stp() print 'stop' except KeyboardInterrupt: apptopi.close() GPIO.cleanup() tcpSerSock.close();
type: Question
has comment: http://stackoverflow.com/comment/83458278
type: UnansweredQuestion
tagged with: sockets
has comment: http://stackoverflow.com/comment/83457117
has comment: http://stackoverflow.com/comment/83457631
tagged with: python
has comment: http://stackoverflow.com/comment/83458024
has title: how to send continuous message from server to client while receiving message from client(using socket.listen and socket.send at the same time
tagged with: python-2.7
score: 0

http://stackoverflow.com/a/52085463
downvote count: 0
answers question: http://stackoverflow.com/q/48178916
score: 13
has comment: http://stackoverflow.com/comment/134309350
has body: import numpy as np import matplotlib.pyplot as plt from skimage import io path = "test.tif" IM = io.imread(path) IM_MAX= np.max(IM, axis=0) plt.imshow(IM_MAX)
type: Answer
upvote count: 13

http://stackoverflow.com/q/48306887
has comment: http://stackoverflow.com/comment/83599888
has title: find x and y location of window pane using python
tagged with: python
has comment: http://stackoverflow.com/comment/83599046
has comment: http://stackoverflow.com/comment/83599798
has comment: http://stackoverflow.com/comment/83599834
has comment: http://stackoverflow.com/comment/83599745
has comment: http://stackoverflow.com/comment/83600530
score: 2
has comment: http://stackoverflow.com/comment/83599943
has comment: http://stackoverflow.com/comment/83600461
answer count: 0
upvote count: 2
tagged with: user-interface
has comment: http://stackoverflow.com/comment/83599708
downvote count: 0
tagged with: win32gui
has comment: http://stackoverflow.com/comment/83599966
has comment: http://stackoverflow.com/comment/83600397
favorite count: 0
has comment: http://stackoverflow.com/comment/83600227
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83600550
has body: I'm trying to find the relative location of the mouse when I click inside of a specific window pane. That is - to be clear, I need to get the X and Y position of a mouse click within a window. I do not need the XY position of the mouse on the screen (as I can already get that). I basically need the location of the window pane of interest. I can calculate the relative XY from there. The code below simulates what I think the proposed solution is. I've tried importing win32gui but it doesn't work in python 64bit. Is there some other way of getting the x and y locations of a window pane from Microsoft? My code I think will look something like this: #### start of code ##### from pynput.mouse import Listener # part I don't know how to do###### X_ofwindow, Y_ofwindow = microsoftwindow(x1,y1) ############################################### def on_click (x,y, button, pressed): x_relative_to_window = x - X_ofwindow y_relative_to_window = y - Y_ofwindow with Listener(on_click=on_click) as listener: listener.join()
has comment: http://stackoverflow.com/comment/83600429

http://stackoverflow.com/comment/83334150
type: Comment
has text: You need to use `yield from` when you use the `@asyncio.coroutine` decorator. `await` is only allowed in `async def`
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48177039

http://stackoverflow.com/q/48189689
upvote count: 1
has answer: http://stackoverflow.com/a/48208427
favorite count: 0
has comment: http://stackoverflow.com/comment/83395859
tagged with: cx-freeze
type: Question
tagged with: dll
accepted answer: http://stackoverflow.com/a/48208427
has title: Python: CX_freeze build failing struct.error in win32verstamp
tagged with: python
tagged with: build
possible better answer: http://stackoverflow.com/a/54831715
type: AnsweredQuestion
has body: I was trying to freeze a python program on my Win10 machine with Python using Anaconda Spyder. This worked previously like 1-2 months ago with this script. Since then, i have changed a lot in the script, so i dont know what is happening and cant track it down myself. This is the output given by cx-freeze: PS C:\Users\Test\Documents\AMS_Jannis\Mk-medA\SimAMR&gt; python setup_CX.py build running build running build_exe creating directory C:\\Users\\Test\\Desktop\\SimAMR-Builds\\Build_20180110_152024 copying C:\ProgramData\Anaconda3\lib\site-packages\cx_Freeze\bases\Console.exe -&gt; C:\\Users\\Test\\Desktop\\SimAMR-Builds\\Build_20180110_152024\\SimAMR.exe copying C:\ProgramData\Anaconda3\api-ms-win-crt-stdio-l1-1-0.dll -&gt; C:\\Users\\Test\\Desktop\\SimAMR-Builds\\Build_20180110_152024\api-ms-win-crt-stdio-l1-1-0.dll copying C:\ProgramData\Anaconda3\python36.dll -&gt; C:\\Users\\Test\\Desktop\\SimAMR-Builds\\Build_20180110_152024\python36.dll copying C:\ProgramData\Anaconda3\VCRUNTIME140.dll -&gt; C:\\Users\\Test\\Desktop\\SimAMR-Builds\\Build_20180110_152024\VCRUNTIME140.dll copying C:\ProgramData\Anaconda3\api-ms-win-crt-math-l1-1-0.dll -&gt; C:\\Users\\Test\\Desktop\\SimAMR-Builds\\Build_20180110_152024\api-ms-win-crt-math-l1-1-0.dll copying C:\ProgramData\Anaconda3\api-ms-win-crt-locale-l1-1-0.dll -&gt; C:\\Users\\Test\\Desktop\\SimAMR-Builds\\Build_20180110_152024\api-ms-win-crt-locale-l1-1-0.dll copying C:\ProgramData\Anaconda3\api-ms-win-crt-string-l1-1-0.dll -&gt; C:\\Users\\Test\\Desktop\\SimAMR-Builds\\Build_20180110_152024\api-ms-win-crt-string-l1-1-0.dll copying C:\ProgramData\Anaconda3\api-ms-win-crt-runtime-l1-1-0.dll -&gt; C:\\Users\\Test\\Desktop\\SimAMR-Builds\\Build_20180110_152024\api-ms-win-crt-runtime-l1-1-0.dll copying C:\ProgramData\Anaconda3\api-ms-win-crt-convert-l1-1-0.dll -&gt; C:\\Users\\Test\\Desktop\\SimAMR-Builds\\Build_20180110_152024\api-ms-win-crt-convert-l1-1-0.dll copying C:\ProgramData\Anaconda3\api-ms-win-crt-time-l1-1-0.dll -&g…
has answer: http://stackoverflow.com/a/54831715
answer count: 2
downvote count: 0
score: 1

http://stackoverflow.com/q/48266273
has title: Modify models field via view doesn't work
has answer: http://stackoverflow.com/a/48266660
accepted answer: http://stackoverflow.com/a/48266660
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83515707
tagged with: models
tagged with: django
tagged with: python
score: -1
has body: In my Django application, I want to subtract 1 "free_places" field in the "Event" model using the "EventDetailView" view where the form is located. Each time the form is OK (when the user subscribes to the event), the "free_places" field should decrease by 1. I do not know why my code does not work. My view: class EventDetailView(DetailView, ModelFormMixin): model = models.Event form_class = forms.RegisterForm context_object_name = 'event' def get_success_url(self): return reverse('events:list') def get_initial(self): return {'event': self.kwargs['pk']} def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): self.object = self.get_object() self.object.free_places - 1 self.object.save() return self.form_valid(form) else: return self.form_invalid(form) Models: class Event(models.Model): title = models.CharField(max_length=500) date = models.DateField() text = models.TextField() image = FilerImageField(null=True, blank=True) flag = models.ForeignKey(Flag) free_places = models.IntegerField() class Meta: ordering = ['-date'] def __str__(self): return self.title @property def slug(self): return slugify(self.title) def get_absolute_url(self): return reverse('events:detail', args=[self.slug, self.id]) def get_model_id(self): return self.id class Register(models.Model): event = models.ForeignKey(Event) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) company = models.CharField(max_length=30, blank=True) street = models.CharField(max_length=50, blank=True) post_code = models.CharField(max_length=30, blank=True) city = models.CharField(max_length=30, blank=True) email = models.EmailField() phone_number = models.IntegerField() def __str__(self): return self.first_name def get_event_name(self): return self.event
tagged with: forms
has comment: http://stackoverflow.com/comment/83516388
has comment: http://stackoverflow.com/comment/83515860
has comment: http://stackoverflow.com/comment/83516192
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/83516023
answer count: 1
downvote count: 1

http://stackoverflow.com/a/48277795
downvote count: 0
has body: brew lets you install multiple formulae, if you separate them by a space. Specify your formulae as a list; formulae = ['ghostscript', 'imagemagik', ...] Now, join those list elements with str.join and pass it to os.system - import os os.system("brew install {}".format(" ".join(formulae))) However, this doesn't help with the pip command. Fortunately for us, pip doesn't need to be called via os.system. Import the module and call pip.main. import pip pip.main(['install', 'sphinx']) This would still mean running two commands, but two is better than four.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48277572
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48277572
score: 1

http://stackoverflow.com/comment/83795492
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48370737
type: AnswerComment
has text: the handler object you created from dict settings has been delete by celery, you have to recreate them. like: `hdr = myapp.utils.classes.logging.SBRotatingFileHandler(...); logger.addHandler(hdr)`

http://stackoverflow.com/q/48175707
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83331149
has answer: http://stackoverflow.com/a/48175972
has title: Assign value of a list into another list while using append or insert method returning None as output
score: 0
answer count: 2
has body: I am a beginner in python. I am trying to assign value of a list into another list while using append or insert method. However, the output is always none. Can you please advise. Below is the piece of code: Input: guest_list = ['AA', 'BB', 'CC', 'DD'] new_guest_list = guest_list.append("XX") print(new_guest_list) Output: None Input: guest_list = ['AA', 'BB', 'CC', 'DD'] new_guest_list = guest_list.insert(0,"XX") print(new_guest_list) Output: None
has comment: http://stackoverflow.com/comment/83331126
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/1682567
has answer: http://stackoverflow.com/a/48176271
has comment: http://stackoverflow.com/comment/83332328

http://stackoverflow.com/a/48310169
has body: Look at your logic: if choice != A or choice != B ... choice can match only one of your hard-coded alternatives; this test must be True for any value of choice. Instead, try something like if choice not in ["Baguette", "Bagel", "Sub", ...]: Better yet, use the list you already have: if choice not in sandwiches:
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48310130
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48310130

http://stackoverflow.com/q/48330657
tagged with: python-2.7
score: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83647305
has comment: http://stackoverflow.com/comment/83670044
has answer: http://stackoverflow.com/a/48330865
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83648677
has title: How do you increase the size(height) of the entry(display) box in tkinter(Python)?
tagged with: python
has body: I have been Coding and I cannot find out how to increase the size(height) of the display box on my calculator. I have tried a lot of things except it gives me an error. Can someone explain what I should do so I can increase the height of the display because right now it is a little too small. So pls help. ( And I am using Windows(10) laptop. ) Here's the (sample)code for my calculator. " from tkinter import * master = Tk() display = Entry(master, width=46, justify='right', bd=0, bg='light grey') master.title("Calculator") class Calculator: def __init__(self): self.var1 = "" self.var2 = "" self.result = 0 self.current = self.result self.operator = 0 def numb_butt(self, index): if self.current is 0: self.var1 = str(self.var1) + str(index) display.delete(first=0, last=END) display.insert(0, string=self.var1) else: self.var2 = str(self.var2) + str(index) display.delete(first=0, last=END) display.insert(0, self.var2) def equate(self): if self.operator is 0: self.result = float(self.var1) + float(self.var2) elif self.operator is 1: self.result = float(self.var1) - float(self.var2) elif self.operator is 2: self.result = float(self.var1) * float(self.var2) display.delete(first=0, last=END) display.insert(0, self.result) self.var1 = self.result def set_op(self, op): self.operator = op display.delete(0, END) if self.current is 0: self.current = 1 else: self.equate() self.var2 = "" def clear(self): self.__init__() display.delete(0, END) calc = Calculator() b0 = Button(master, text="0", command=lambda: calc.numb_butt(0), width=12, height=3) b1 = Button(master, text="1", command=lambda: calc.numb_butt(1), width=12, height=3) b2 = Button(master, text="2", command=lambda: calc.numb_butt(2), width=12, height=3) b3 = Button(master, text="3", command=lambda: calc.numb_butt(3), width=12, height=3) b4 = Button(master, text="4", command=lambda: calc.numb_butt(4), width=12, height=3) b5 = Button(master, text="5", command=lambda: calc.numb_butt(5), width=12, height=3) b6 = Button(master, …
accepted answer: http://stackoverflow.com/a/48330865
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/83584054
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48268453
has text: @MarkSetchell I updated the method of counting and also added another example (a very extreme case)
type: Comment

http://stackoverflow.com/comment/83328900
type: QuestionComment
comment on: http://stackoverflow.com/q/48174601
has text: Are you intending to match your words with the pattern `r'k[a-z]p[a-z]+a'`? What *exactly* are you trying to accomplish? This question is fairly obscure in its expected resolution
score: 1
type: Comment

http://stackoverflow.com/comment/83434944
has text: Thanks for the answer. I play around with the Cifar10 CNN Multi GPU Tensorflow Tutorial: https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10/cifar10_multi_gpu_train. py. If I set the epochs too high, the loss value becomes NaN. Looking for a solution were only one Model is saved.
comment on: http://stackoverflow.com/a/48226173
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/111522978
type: AnswerComment
comment on: http://stackoverflow.com/a/48285359
type: Comment
has text: I tried both of these and I get the error: ```RGBsliders.py", line 21, in update preview['bg'] = hex TypeError: 'NoneType' object does not support item assignment```
score: 0

http://stackoverflow.com/q/48282664
has answer: http://stackoverflow.com/a/48283050
tagged with: python
has body: I am just new in Python and have limited knowledge about Object Oriented Programming. Just want to ask a few things about Object, Methods and Function. I noticed that an Objects have parentheses right after its name like book = Workbook() and some have no parenthesis on it. May I know the difference between the two? Similarly, for methods right after the name of the method b.get_sheet_names() have parentheses. May I know what is the concept behind inclusion of parentheses right after the object name and methods.
type: UnansweredQuestion
type: Question
upvote count: 3
has comment: http://stackoverflow.com/comment/83549130
has answer: http://stackoverflow.com/a/48282772
has title: Purpose of parentheses right after object's and method's name
downvote count: 1
favorite count: 0
score: 2
answer count: 2

http://stackoverflow.com/comment/83594729
comment on: http://stackoverflow.com/q/48304854
type: Comment
type: QuestionComment
has text: The documentation where you link to has four arguments: `items`, `like`, `regex` and `axis`. None of the (if you read the documentation) accepts a function/lambda expression.
score: 0

http://stackoverflow.com/q/48326712
tagged with: grep
score: 1
has body: I have two files file1.txt variable1=string1 with spaces characters variable2=string2 with spaces characters variable3=string3 with spaces characters file2.txt sometext1 textvariable1 sometext2 sometext3 variable2 sometext4 sometextcharactersvariable1 charactersvariable3 sometext5 variable2 .................... I would like the file2.txt with all the variables replaced with the values in file1.txt i tried multiple grep and awk commands,python codes to read each word , compare and replace read file options fgrep -w -o -f "file1.txt" "file2.txt" awk '/PATTERN/{system("cat file1");next}1' file2 but this works for only one variable. I know i have to loop through each word in file2 and compare it with file1 and then replace. But not sure how to. expected output: sometext1 string1 sometext2 sometext3 string2 sometext4 string1 string3 sometext5 string2 ................
tagged with: python
tagged with: unix
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48326924
tagged with: awk
has comment: http://stackoverflow.com/comment/83638757
upvote count: 1
has title: replace variables of a file with reference to values in another file
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48327103
answer count: 3
has answer: http://stackoverflow.com/a/48326919

http://stackoverflow.com/comment/83340030
has text: Can you share your `models.py` with the customer `User` model? Also, your `settings.py`?
comment on: http://stackoverflow.com/q/48178942
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83571074
type: QuestionComment
comment on: http://stackoverflow.com/q/48292943
score: 0
type: Comment
has text: `result` is a string, not a file to be returned. See http://flask.pocoo.org/docs/0.12/api/#flask.send_file

masking
tag name: masking
tags question: http://stackoverflow.com/q/48203008
type: Tag

http://stackoverflow.com/comment/83410165
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48214251
has text: That would just give you `SyntaxError: keyword can't be an expression`

http://stackoverflow.com/q/48214863
downvote count: 0
upvote count: 6
score: 6
type: AnsweredQuestion
has title: Python Replace Whole Values in Dataframe String and Not Substrings
has body: I am trying to replace strings in a dataframe if the whole string equals another string. I do not want to replace substrings. So: If I have df: Index Name Age 0 Joe 8 1 Mary 10 2 Marybeth 11 and I want to replace "Mary" when the whole string matches "Mary" with "Amy" so I get Index Name Age 0 Joe 8 1 Amy 10 2 Marybeth 11 I'm doing the following: df['Name'] = df['Name'].apply(lambda x: x.replace('Mary','Amy')) My understanding from searching around is that the defaults of replace set regex=False and replace should look for the whole value in the dataframe to be "Mary". Instead I'm getting this result: Index Name Age 0 Joe 8 1 Amy 10 2 Amybeth 11 What am I doing wrong?
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/48214887
tagged with: python
tagged with: regex
favorite count: 0
type: Question
tagged with: replace
has answer: http://stackoverflow.com/a/48214898
accepted answer: http://stackoverflow.com/a/48215674
possible better answer: http://stackoverflow.com/a/48214887
has answer: http://stackoverflow.com/a/48215674

http://stackoverflow.com/q/48218386
has answer: http://stackoverflow.com/a/48220326
tagged with: sql
score: 1
has body: I'm an intermediate python developer with quite a bit of experience working with t-sql/mysql in data analytics. I'm trying my hand at some web programming using python to build certain components of the back-end of my site. In one of my applications, instead of querying a database, I've placed some dictionary-based data structures directly in a list in a python file, and I import it into the script that holds the application logic. Important to note that this data is static and around 5k dictionaries at this point. The data itself contains key-value pairs where the values is frequently a list of a tuple, so I find the flexibility of the python data structure to be easier to work with than a traditional RDBMS table. I've scoured the internet and I can't seem to find any reference to developers actually using a .py file to store data for use in their programs, which leads me to believe this method shouldn't be used in a production site. I'm hoping for some clarity around why this might be the case (and potential alternatives) Will my .py solution scale poorly vs a RDBMS solution? Either as the number of users using my application grows or if I choose to support more vehicles in my data set? Is there a nosql solution that might give me the flexible data structure I need if the .py solution doesn't work? Or is a mysql solution still superior in this use case? Thanks!
has answer: http://stackoverflow.com/a/48218512
downvote count: 0
tagged with: mysql
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83420598
has title: Using a python file as a database
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48220326
possible better answer: http://stackoverflow.com/a/48218512

tweepy
tags question: http://stackoverflow.com/q/48219349
tags question: http://stackoverflow.com/q/48253721
type: Tag
tags question: http://stackoverflow.com/q/48324771
tags question: http://stackoverflow.com/q/48275614
tags question: http://stackoverflow.com/q/48241779
tags question: http://stackoverflow.com/q/48176265
tags question: http://stackoverflow.com/q/48244852
tag name: tweepy

http://stackoverflow.com/comment/83554994
has text: What if you have more than two rows that have missing values?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48284040
score: 1

statistics
tags question: http://stackoverflow.com/q/48289643
tags question: http://stackoverflow.com/q/48323926
tags question: http://stackoverflow.com/q/48241158
tags question: http://stackoverflow.com/q/48301809
tags question: http://stackoverflow.com/q/48257144
tags question: http://stackoverflow.com/q/48251823
tag name: statistics
tags question: http://stackoverflow.com/q/48242555
tags question: http://stackoverflow.com/q/48273276
tags question: http://stackoverflow.com/q/48266118
tags question: http://stackoverflow.com/q/48307785
tags question: http://stackoverflow.com/q/48254674
type: Tag

http://stackoverflow.com/a/49525065
has body: Since you probably have GDAL installed, I recommend converting the file to UTF-8 using the CLI: ogr2ogr output.shp input.shp -lco ENCODING=UTF-8 Worked like a charm for me. It's much faster than QGIS and can be used in a cluster environment. I also posted this answer here. Specifying the encoding in geopandas did not work for me.
score: 1
answers question: http://stackoverflow.com/q/48305400
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/83391764
has text: Possible duplicate of [Shuffle groups of sublists in Python](https://stackoverflow.com/questions/35214352/shuffle-groups-of-sublists-in-python)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48205282

http://stackoverflow.com/a/48254988
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83492808
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83492928
answers question: http://stackoverflow.com/q/48254937
has comment: http://stackoverflow.com/comment/83492885
type: Answer
accepted answer of: http://stackoverflow.com/q/48254937
has comment: http://stackoverflow.com/comment/83492939
has body: The error message says: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; struct.error: bad char in struct format This states that format string is wrong. You should try: struct.unpack('ffffffiiii', raw_data) The e format string is for a fairly esoteric 16 bit float, and is unlikely to be what you need. In addition it is not supported on Python 2. Test Code: import struct raw_data = b'\x00P\x03E\x00\x00\xfaD\x00\x00\x00\x00\x00@\xfbD\x00`' \ b'\xfbD\x00@\x03Ed\x00\x00\x00e\x00\x00\x00n\x00\x00\x00o' \ b'\x00\x00\x00' print(struct.unpack('ffffffiiii', raw_data)) Results: (2101.0, 2000.0, 0.0, 2010.0, 2011.0, 2100.0, 100, 101, 110, 111)

http://stackoverflow.com/comment/83594594
score: 0
comment on: http://stackoverflow.com/q/48303854
type: QuestionComment
has text: It seems you didn't define `summaries` in your graph. You have to merge the individual summaries that you created. You can do that with `summaries = tf.summary.merge_all()`. You can place it after the creation of the tree.
type: Comment

http://stackoverflow.com/comment/83449022
comment on: http://stackoverflow.com/a/48228766
has text: Mike probably knows the most about wxPython out of anyone in the world (including Robin Dunn :P (although im sure Robin knows more about the implementation details :P) I would listen to his words of wisdom
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83503550
has text: No, it should contain the *contents of* the JSON file.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48259515

http://stackoverflow.com/a/48330449
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83647470
upvote count: 4
answers question: http://stackoverflow.com/q/48330147
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48330147
has body: Try this out: df=pd.read_csv('zhoop.csv', header=[0,1], index_col=0) Note: in order to index rows you would use df.loc[rownum], not just df[rownum].
score: 4
has comment: http://stackoverflow.com/comment/83647286

http://stackoverflow.com/q/48209764
accepted answer: http://stackoverflow.com/a/48210688
type: Question
has body: first code import inspect members = inspect.getmembers(module) print(members) second code import inspect for a,b in inspect.getmembers(module): print(a) why 'inspect.getmembers(module)' returns entirely different outputs for above cases. consider test = [(1,2),(3,4)] for a,b in test: print(a) which will print 1,3 but this logic is not applicable to inspect.getmembers() why is that someone please explain
has comment: http://stackoverflow.com/comment/83402132
has comment: http://stackoverflow.com/comment/83402282
has title: why inspect.getmember gives different outputs
tagged with: python
has comment: http://stackoverflow.com/comment/83402010
has comment: http://stackoverflow.com/comment/83403608
has answer: http://stackoverflow.com/a/48210688
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83400714
answer count: 1

http://stackoverflow.com/comment/83379453
type: AnswerComment
comment on: http://stackoverflow.com/a/48199014
has text: Not sure why you lost an upvote! Just so everyone else is aware, this is a very good pandas answer.
score: 0
type: Comment

http://stackoverflow.com/a/48243537
accepted answer of: http://stackoverflow.com/q/48243283
answers question: http://stackoverflow.com/q/48243283
type: AcceptedAnswer
has body: You created a str (unicode text) object here: text = "" and then proceed to append UTF-8 encoded bytes: text += status.text.encode('utf-8') In Python 2, "" created a bytestring and that was all fine (albeit that you are then posting UTF-8 bytes to a service that will interpret it all as Latin-1, see the API documentation. To fix this, don't encode the status texts until you are done collecting all the tweets. In addition, tell Watson to expect UTF-8 data. Last but not least, you should really build a list of twitter texts first and concatenate them in one step later on with str.join(), as concatenating strings in a loop takes quadratic time: text = [] for status in statuses: if (status.lang =='en'): #English tweets text.append(status.text) # ... personality_insights = PersonalityInsights(username=pi_username, password=pi_password) pi_result = personality_insights.profile( ' '.join(text).encode('utf8'), content_type='text/plain; charset=utf-8' )
type: Answer
has comment: http://stackoverflow.com/comment/83472676
score: 0

http://stackoverflow.com/a/48291688
has body: It's not that horrible: you've merely reversed your reference usage. Your indices, ref, tell you how to build the sorted list from the original. However, you've used it in the opposite direction: you've applied it to the sorted list, trying to reconstruct the original. You need the inverse mapping. Is that enough to get you to solve your problem?
type: Answer
answers question: http://stackoverflow.com/q/48291444
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83568748
has comment: http://stackoverflow.com/comment/83568937
has comment: http://stackoverflow.com/comment/83569986
has comment: http://stackoverflow.com/comment/83568990

http://stackoverflow.com/a/48278594
score: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48257845
upvote count: 1
has body: This is a common problem with basemap. Even though the data should be cyclic in longitudinal direction, basemap can not deal with that properly. I usually use cdo to first order the data in the way it should be displayed using cdo sellonlatbox,-180,180,-90,90 input.nc output.nc cdo also provides a python wrapper so you can use it directly in your scripts. If you don't want to use cdo, you can use numpy to re-arrange your data, here is a small example: from matplotlib import pyplot as plt import numpy as np from mpl_toolkits import basemap fig,axes = plt.subplots(nrows=3, ncols=1) mp1 = basemap.Basemap(ax = axes[0], projection = 'cyl', lon_0=180, lat_0=0) mp2 = basemap.Basemap(ax = axes[1], projection = 'cyl', lon_0=0, lat_0=0) mp3 = basemap.Basemap(ax = axes[2], projection = 'cyl', lon_0=0, lat_0=0) for mp in mp1, mp2, mp3: mp.drawcoastlines() mp.drawcountries() mp.drawmeridians(np.arange(0,360,30)) mp.drawparallels(np.arange(-90,90,30)) ##some data: lons = np.arange(0,360) lats = np.arange(-90,91) lons,lats = np.meshgrid(lons,lats) data = np.sin(2*np.pi*lons/360)+np.sin(np.pi*lats/180) ##first plot mp1.pcolormesh(lons,lats,data) ##second plot mp2.pcolormesh(lons,lats,data) ##third plot (with longitudes re-ordered) lons = lons%180-180*(lons//180) ##re-computing lons to be from -180 to 180 lon_order = np.argsort(lons, axis = 1) ##computing new order of lons lat_order = np.argsort(lats, axis = 0) ## ... and lats (maybe unnecessary) mp3.pcolormesh(lons[lat_order,lon_order],lats, data[lat_order,lon_order]) plt.show() The result looks like this, where the first plot displays the data in the original format, the second one tries to center the data on lon_0=0 without re-ordering and the third one does the re-ordering. Hope this helps.

http://stackoverflow.com/comment/83554367
type: Comment
comment on: http://stackoverflow.com/a/48282738
type: AnswerComment
has text: Yes, it is possible, if very large data and not really huge RAM get weird errors sometimes ;)
score: 0

http://stackoverflow.com/q/48285286
has comment: http://stackoverflow.com/comment/83555595
has comment: http://stackoverflow.com/comment/83555181
tagged with: matplotlib
has body: I briefly report my situation: I'm running simulations in python and I plot a chart during data processing iteration. The problem are: The dynamic plot I made, works well, but after some(500 more or less) iterations, it starts to go slowly, taking more than the pause time I decided for each iteration. So I need to close the figure window to make it again fast, but after 200 iterations, it becomes again slowly and so on... Since I run simulation with over 40000 iterations, improvements may arrive to reduce almost 1 min my simulation's time. Here there the code I'm talking about: uxs =[] uxP =[] i=0 for z in Ti: # Unscendet Kalman Filter operations i+=1 ukf.predict(dt, fx_args=(Te[floor(i/4.)],u)) ukf.update(z) uxs.append(ukf.x.copy()) uxP.append(ukf.P.copy()) # Create Temporary Version of uxs and uxP, in this way I can use them as a numpy array uxsTemp = np.array(uxs) uxPTemp = np.array(uxP) # Dynamic graph plt.figure("Live Temperature") ax = plt.gca() t = np.arange(0,uxsTemp[:,0].size,1) # Create a timeline with step 1, longer as the current data number plt.plot(t, Ti[0:uxsTemp[:,0].size], 'ro', label='External measures (Ti(t))') plt.plot(t, uxsTemp[:,0],'b', label='Estimated (Ti(t))') if(i%50==0): print("mod:"+str(i%50) +"\nP:"+str(ukf.P[0,0])) circle1 = plt.Circle((uxsTemp[:,0].size, ukf.x[0]), sqrt(ukf.P[0,0]), color='g', fill=True) ax.add_artist(circle1) ax.plot((uxsTemp[:,0].size, ukf.x[0]),'ys', color='black') # I put a yellow point on current point plt.xlim(uxsTemp[:,0].size - 10,uxsTemp[:,0].size + 5) plt.ylim(-5,40) plt.show(block=False) pause(0.00000001) I hope someone have a possible solutions. Since when I close the figure window, it then re-opens and go faste, I guess something like clear variables may help me. But I don't know how to deal with it. PS: another problem is the following line that does not work, I think because it is overlapped by red points of the other data: ax.plot((uxsTemp[:,0].size, ukf.x[0]),'ys', color='black') # I put a yellow poin…
tagged with: python-3.x
tagged with: charts
type: Question
score: 0
has comment: http://stackoverflow.com/comment/83555443
answer count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83555310
tagged with: plot
has title: Python: improve code efficency, focus on plot part usign matplotlib.pyplot

http://stackoverflow.com/a/51331862
type: Answer
has body: You need to add one more open close parenthesis at front. from keras.layers import Multiply att_mull = Multiply()([dense_all, dense_att])
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/48309322
upvote count: 5

tensorflow
tags question: http://stackoverflow.com/q/48272580
tags question: http://stackoverflow.com/q/48316020
tags question: http://stackoverflow.com/q/48231457
tags question: http://stackoverflow.com/q/48303166
tags question: http://stackoverflow.com/q/48212694
type: Tag
tags question: http://stackoverflow.com/q/48236521
tags question: http://stackoverflow.com/q/48211346
tags question: http://stackoverflow.com/q/48212068
tags question: http://stackoverflow.com/q/48298682
tags question: http://stackoverflow.com/q/48286968
tags question: http://stackoverflow.com/q/48266862
tags question: http://stackoverflow.com/q/48201725
tags question: http://stackoverflow.com/q/48175456
tags question: http://stackoverflow.com/q/48225494
tags question: http://stackoverflow.com/q/48239431
tags question: http://stackoverflow.com/q/48234032
tags question: http://stackoverflow.com/q/48236144
tags question: http://stackoverflow.com/q/48272497
tags question: http://stackoverflow.com/q/48206320
tags question: http://stackoverflow.com/q/48225315
tags question: http://stackoverflow.com/q/48323677
tags question: http://stackoverflow.com/q/48192089
tags question: http://stackoverflow.com/q/48175190
tags question: http://stackoverflow.com/q/48212629
tags question: http://stackoverflow.com/q/48246631
tags question: http://stackoverflow.com/q/48177832
tags question: http://stackoverflow.com/q/48329150
tags question: http://stackoverflow.com/q/48185719
tags question: http://stackoverflow.com/q/48211085
tags question: http://stackoverflow.com/q/48270557
tags question: http://stackoverflow.com/q/48222542
tags question: http://stackoverflow.com/q/48213526
tags question: http://stackoverflow.com/q/48205733
tags question: http://stackoverflow.com/q/48191886
tags question: http://stackoverflow.com/q/48174704
tags question: http://stackoverflow.com/q/48179905
tags question: http://stackoverflow.com/q/48276174
tags question: http://stackoverflow.com/q/48285212
tags question: http://stackoverflow.com/q/48192342
tags question: http://stackoverflow.com/q/48251568
tags question: http://stackoverflow.com/q/48298389
tags question: http://stackoverflow.com/q/48242547
tags question: http://stackoverflow.com/q/48197871
tags question: http://stackoverflow.com/q/48221692
tags question: http://stackoverflow.com/q/48246740
tags question: http://stackoverflow.com/q/48264676
tags question: http://stackoverflow.com/q/48281206
tags question: http://stackoverflow.com/q/48208866
tags question: http://stackoverflow.com/q/48211805
tags question: http://stackoverflow.com/q/48255267
tags question: http://stackoverflow.com/q/48189994
tags question: http://stackoverflow.com/q/48230031
tags question: http://stackoverflow.com/q/48216772
tags question: http://stackoverflow.com/q/48230786
tags question: http://stackoverflow.com/q/48322542
tags question: http://stackoverflow.com/q/48309346
tags question: http://stackoverflow.com/q/48276192
tags question: http://stackoverflow.com/q/48283090
tags question: http://stackoverflow.com/q/48235239
tags question: http://stackoverflow.com/q/48215159
tags question: http://stackoverflow.com/q/48218618
tags question: http://stackoverflow.com/q/48219121
tags question: http://stackoverflow.com/q/48324072
tags question: http://stackoverflow.com/q/48215969
tags question: http://stackoverflow.com/q/48298787
tags question: http://stackoverflow.com/q/48179257
tags question: http://stackoverflow.com/q/48287815
tags question: http://stackoverflow.com/q/48260912
tags question: http://stackoverflow.com/q/48303354
tags question: http://stackoverflow.com/q/48196672
tags question: http://stackoverflow.com/q/48324949
tags question: http://stackoverflow.com/q/48268918
tags question: http://stackoverflow.com/q/48216067
tags question: http://stackoverflow.com/q/48176348
tags question: http://stackoverflow.com/q/48219522
tags question: http://stackoverflow.com/q/48198770
tags question: http://stackoverflow.com/q/48219296
tags question: http://stackoverflow.com/q/48243178
tags question: http://stackoverflow.com/q/48325147

http://stackoverflow.com/comment/83379928
score: 0
type: Comment
type: AnswerComment
has text: A `continue` at the end of the loop does not make any sense.
comment on: http://stackoverflow.com/a/48199276

http://stackoverflow.com/comment/83568554
has text: @juanpa.arrivillaga I agree, but I only said time-efficiency, not time-*complexity*.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48291711
type: QuestionComment

http://stackoverflow.com/comment/83347883
score: 0
comment on: http://stackoverflow.com/a/48184005
has text: thanks you your comment but i already did that, no idea to get second table.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48240578
has comment: http://stackoverflow.com/comment/83517107
type: Answer
answers question: http://stackoverflow.com/q/48235045
upvote count: 2
score: 2
has body: The value is being set correctly. Your problem is that at the time pytest_configure hooks are being called, the ini file values and the command line args are already parsed, so adding to the ini values will not bring anything - they won't be read again anymore. In particular, the testpaths value from ini file is already processed and stored in config.args. So we can overwrite config.args instead: @pytest.hookimpl() def pytest_configure(config): suite = config.getoption('--suite') if suite == 'a': config.args = ['tests/a'] elif suite == 'b': config.args = ['tests/b'] Edit An example of accessing the config in your tests (via pytestconfig fixture): def test_spam(pytestconfig): print(pytestconfig.getini('testpaths')) print(pytestconfig.args) suite_testpaths = set(pytestconfig.args) - set(pytestconfig.getini('testpaths')) print('testpaths that were added via suite arg', suite_testpaths)
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83523030
accepted answer of: http://stackoverflow.com/q/48235045

http://stackoverflow.com/q/48252757
downvote count: 0
accepted answer: http://stackoverflow.com/a/48252768
has answer: http://stackoverflow.com/a/48252768
favorite count: 0
type: Question
has title: Pandas dataframe. Eliminating rows matching certain conditions in a column
upvote count: 1
tagged with: dataframe
tagged with: python
has body: I have the following table: Days Age Sex 5 39 F NaN 54 M 4 26 M 1 42 M 4 29 M I want to count separately mean value of days for men and women, but taking only those rows where I have 3 days or more. (Eliminating all the missing values and everything that is &lt;3 in column "Days") I was thinking of something like: df.groupby("Sex")["Days"].mean().where().... where column[0] >= 3 But have problems with "where" condition What will be the best command to do it? Thank you.
type: AnsweredQuestion
tagged with: pandas-groupby
tagged with: pandas
score: 1
answer count: 1

http://stackoverflow.com/a/48217098
answers question: http://stackoverflow.com/q/48216748
has body: You are deleting elements from lists while iterating over them. This is not allowed because you are decreasing the length of the lists and at the same time try to access list elements at indices that are no longer valid. Thus the IndexError you get. See this question Remove items from a list while iterating for a way around. You should fix your code and ask a new question with a minimal correct working example for your other issue, if it isn't fixed by this fix.
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48216748
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83392126
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48205474
has text: Thanks for the suggestion, but I feel that using [tuples.sort(key=lambda x: x[-1])] would work just as well.
type: Comment

http://stackoverflow.com/a/48259585
score: 2
has body: To scroll to the end of the page of a (not so long) infinity scroll through Default Chrome Browser and Headless Chrome Browser you can use the following code block : from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException options = Options() options.add_argument("--headless") options.add_argument("start-maximized") options.add_argument("disable-infobars") options.add_argument("--disable-extensions") options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe') driver.get('http://www.website.com') while (driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")): try: WebDriverWait(driver, 50).until(EC.visibility_of_element_located((By.XPATH, "//div[@itemprop='itemListElement']" ))) # do your other actions within the Viewport except TimeoutException: break print("Reached to the bottom of the page")
upvote count: 2
answers question: http://stackoverflow.com/q/48257870
downvote count: 0
has comment: http://stackoverflow.com/comment/83513065
type: Answer
has comment: http://stackoverflow.com/comment/128897309
has comment: http://stackoverflow.com/comment/83511555
has comment: http://stackoverflow.com/comment/83511947
has comment: http://stackoverflow.com/comment/83511494
has comment: http://stackoverflow.com/comment/83512320

http://stackoverflow.com/comment/83373690
comment on: http://stackoverflow.com/q/48196275
type: QuestionComment
has text: no, in this case the order doesn't matter!
score: 0
type: Comment

http://stackoverflow.com/q/48276429
answer count: 1
tagged with: image-processing
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83541198
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50874988
tagged with: python
has comment: http://stackoverflow.com/comment/83541446
has comment: http://stackoverflow.com/comment/83540198
has comment: http://stackoverflow.com/comment/83538985
tagged with: c++
score: 0
has comment: http://stackoverflow.com/comment/83538367
has title: Block normalization of histogram of oriented gradient
has body: I am a beginner in image processing. I have some questions regarding HOG. https://www.learnopencv.com/histogram-of-oriented-gradients/ From this website, it mentioned that each element inside the HOG descriptor will be divided by the sum of all elements in a block. However, how to do block normalization if overlapping the blocks? I do not understand because some elements in the vector will be elements of more than one blocks. Picture of block normalization For example, if we have a histogram [v11 v12 v13 v14...v19] ,[v21 v22 v23 v24...v29], [v31 v32 v33 v34 v35...v39] and [v41 v42 v43 v44..v49] in the red block, we can normalize the first element of the first vector like this: v11/(v11+v12+...+v21+v22+v23+..+v31+v32+...+v41+v42...+v49) However, how can I normalize the vectors in the red block and yellow block? Thank you very much.

http://stackoverflow.com/comment/83553383
score: 0
has text: @StevenRumbalski here list(itertools.permutations(range(1, 5), 2)) gives [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)] i need also numbers like (1,1),(2,2),(3,3),(4,4). Is there a way to do that?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48284094

http://stackoverflow.com/a/48298198
answers question: http://stackoverflow.com/q/48297136
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48297136
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83581244
has body: Create a method that returns the default value, def get_default_balance_alert_threshold(): return AppParameters.load().DEFAULT_BALANCE_ALERT_THRESHOLD then use that method as your default. class Convive(models.Model): balance_alert_threshold = models.IntegerField( default=get_default_balance_alert_threshold, blank=True, null=True, )
type: Answer

http://stackoverflow.com/comment/83412889
score: 0
type: QuestionComment
has text: Aha, it's there in the guide. `client_secrets.json`. Look inside that file and there should be an email address.
type: Comment
comment on: http://stackoverflow.com/q/48215243

http://stackoverflow.com/q/48217284
type: Question
tagged with: python
tagged with: pygame
has title: After playing my game once, if i select it again from the main menu it instantly cuts to the game over screen (pygame)
has comment: http://stackoverflow.com/comment/83416693
has comment: http://stackoverflow.com/comment/83416631
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83434546
score: 0
tagged with: function
has body: Basically whenever i select my game from the main menu it will play, but then if i go back to the main menu and select it again, it just shows the game over screen, and wont play again. In the code below its about the zy_mainloop() part of the main_menu that doesnt run after the first time. I'd really appreciate some help with this def main_menu(): WIDTH = 1280 HEIGHT = 800 screen = pygame.display.set_mode((WIDTH, HEIGHT)) main_menu = True while main_menu: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_1: WIDTH = 480 HEIGHT = 600 pygame.display.set_mode((WIDTH, HEIGHT)) g.new() g.show_go_screen() main_menu = False if event.key == pygame.K_2: zy_mainloop() main_menu = False screen.blit(mainmenu_img, mainmenu_rect) pygame.display.flip() def start_screen(): WIDTH = 1280 HEIGHT = 800 screen = pygame.display.set_mode((WIDTH, HEIGHT)) start_screen = True while start_screen: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_x: main_menu() start_screen = False screen.blit(startscreen_img, startscreen_rect) pygame.display.flip() def game_over_noscore(): WIDTH = 1280 HEIGHT = 800 screen = pygame.display.set_mode((WIDTH, HEIGHT)) screen.blit(gameovernoscore_img, noscore_rect) pygame.display.flip() gameover_screen = True while gameover_screen: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_x: main_menu() gameover_screen = False def zy_mainloop(): WIDTH = 480 HEIGHT = 600 screen = pygame.display.set_mode((WIDTH, HEIGHT)) zy_running = True while zy_running: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: zy_running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE and zyplayer.shotsfired &lt;= 1: zyplayer.shoot() # Update zy_all_sprites.update() # …
has comment: http://stackoverflow.com/comment/83416599
answer count: 1
accepted answer: http://stackoverflow.com/a/48226345
has comment: http://stackoverflow.com/comment/83416732
has answer: http://stackoverflow.com/a/48226345

http://stackoverflow.com/comment/83592654
has text: Post the whole tensorflow graph definition
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48303854
score: 1

http://stackoverflow.com/a/48218363
has comment: http://stackoverflow.com/comment/83418875
downvote count: 0
has body: You should set the handler to python_file_name.function_name. So in your case it should be twilio_test.lambda_handler. From the documentation: ... You specify the function name in the Python code to be used as the handler when you create a Lambda function. For instructions to create a Lambda function using the console, see Create a Simple Lambda Function. In this example, the handler is hello_python.my_handler (file-name.function-name) ...
accepted answer of: http://stackoverflow.com/q/48218263
has comment: http://stackoverflow.com/comment/83418857
has comment: http://stackoverflow.com/comment/83418764
type: Answer
has comment: http://stackoverflow.com/comment/83418729
answers question: http://stackoverflow.com/q/48218263
score: 2
upvote count: 2
type: AcceptedAnswer

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

http://stackoverflow.com/q/48234499
has comment: http://stackoverflow.com/comment/83451777
answer count: 4
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48234725
has title: Is there syntactic sugar for a function that accepts a tuple?
has comment: http://stackoverflow.com/comment/83451654
downvote count: 0
has body: Suppose I have a function that takes two arguments and performs some calculation on them: def add(a, b): return a + b I want to call this function through a multiprocessing library which can only handle functions with a single argument. So, I change the function to take its argument as a single tuple instead: def add2(ab): a, b = ab return a + b However, this seems clunky to me. The variables essentially need to be defined (and documented) twice. If I were using a lambda function, I could just write the following and it will accept the tuple properly: add3 = lambda (a, b): a + b Unfortunately, my function is not trivial enough to implement as a lambda function. Is there any sort of syntactic sugar feature in python that would allow me to write a named function that accepts a tuple but treats each component of that tuple as a separate named argument? My attempts to search for solutions to this have mostly turned up references to the *args operator, but that does not apply here because I do not control the site where the function is called. Here is an example of how the function is being called. Note that it is called via the multiprocessing library so I cannot pass more than one argument: import multiprocessing pool = multiprocessing.Pool(processes=4) for result in pool.imap_unordered(add, [(1,2),(3,4)]): print(result) Answers for either python 2.7 or 3.x are welcome.
possible better answer: http://stackoverflow.com/a/48234725
favorite count: 0
has answer: http://stackoverflow.com/a/48234525
type: Question
has comment: http://stackoverflow.com/comment/83451662
upvote count: 2
accepted answer: http://stackoverflow.com/a/48234794
tagged with: python
has comment: http://stackoverflow.com/comment/83451625
has answer: http://stackoverflow.com/a/48235400
has answer: http://stackoverflow.com/a/48234794

http://stackoverflow.com/comment/83517504
score: 0
comment on: http://stackoverflow.com/q/48266118
type: Comment
type: QuestionComment
has text: numpy is a third-party module. I've added that for you.

http://stackoverflow.com/comment/83647761
comment on: http://stackoverflow.com/q/48330855
score: 0
type: Comment
has text: @CharlesDuffy: File "<string>", line 1 import sys, json;\nfor img in json.load(sys.stdin)['Images']:\n\tprint img['ImageId'] ^ SyntaxError: unexpected character after line continuation character
type: QuestionComment

http://stackoverflow.com/comment/127874488
comment on: http://stackoverflow.com/a/48304953
has text: Option 1 is a neat trick.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/83331941
comment on: http://stackoverflow.com/q/48176067
type: QuestionComment
has text: It may be helpful to add more diagnostic information to your `except` block. In particular, rather than just printing "Couldn't find file", print the exception object and the stack trace, so you can be completely sure exactly which line is causing the problem. If you're thinking "I'm pretty confident that my code only crashes with FileNotFoundError, so I don't need any of that extra stuff", then you should be doing `except FileNotFoundError:` instead of just `except:`. Then when a non-FileNotFoundError occurs once in a blue moon, the unhandled crash will give you all the information you need.
score: 5
type: Comment

http://stackoverflow.com/comment/83372805
comment on: http://stackoverflow.com/q/48195857
score: 1
type: Comment
type: QuestionComment
has text: Also, there is an answer to your question, but it would be giving you what you want, not what you need (the two are different). It would be good to start with how these dataframes are created.

http://stackoverflow.com/a/48219970
answers question: http://stackoverflow.com/q/48209005
score: 0
type: Answer
has body: You're right to say that it would be great to extract that code outside of the view function. Personally I really like the way Cornice did this for REST APIs: https://cornice.readthedocs.io/en/latest/validation.html For example, from the link above: from cornice import Service foo = Service(name='foo', path='/foo') def has_paid(request, **kwargs): if not 'X-Verified' in request.headers: request.errors.add('header', 'X-Verified', 'You need to provide a token') @foo.get(validators=has_paid) def get_value(request): """Returns the value. """ return 'Hello' I work on an app where there are both Cornice endpoints and regular views declared with @view_config, so I wrote a decorator that can be used to wrap Colander schema classes (https://docs.pylonsproject.org/projects/colander/en/latest/). The decorator looks like this: from collections import defaultdict from pyramid.renderers import render_to_response import colander from translationstring import TranslationString class PreValidator: def __init__(self, schema_class, renderer, on_invalid=None, extra_vars=None): self.schema_class = schema_class self.renderer = renderer self.on_invalid = on_invalid self.extra_vars = extra_vars def __call__(self, wrapped): def wrapper(context, request): schema = self.schema_class().bind(request=request) try: values = schema.deserialize(request.POST.mixed()) request.validated = values return wrapped(context, request) except colander.Invalid as e: if hasattr(self.on_invalid, '__call__'): self.on_invalid(request) errors = dict([(c.node.name, c.messages()) for c in e.children]) general_errors = e.messages() if len(general_errors) &gt; 0: errors['_general'] = general_errors for _, msgs in errors.items(): for i, msg in enumerate(msgs): if type(msg) == TranslationString: msgs[i] = request.localizer.translate(msg) for_renderer = dict( values=defaultdict(lambda: '', request.POST.items()), errors=errors, ) if hasattr(self.extra_vars, '__call__'): self.extra_vars(request, for_renderer) return render_…

http://stackoverflow.com/q/48243905
accepted answer: http://stackoverflow.com/a/48244041
tagged with: lxml
answer count: 1
score: 1
downvote count: 1
favorite count: 0
type: Question
upvote count: 2
has title: python - Get EVERY div class and div id from website
has answer: http://stackoverflow.com/a/48244041
tagged with: python
has comment: http://stackoverflow.com/comment/83470373
has body: So there were some attempts, but i cannot find a way to get the name and content of every div class div id Im using lxml and beautysoup in my project, but i simply cant seem to find a way to find div's that are unknown to me. Can someone show me a method or any tips how to do this? Thanks in advance.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83470307

http://stackoverflow.com/comment/83551701
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48276340
has text: It might be worth quickly looking at memoryview slices too. I doubt they'd be any different in speed but it's possible that they might be naturally gil-free. (That said, I doubt it's as important to release the gil as OP things)
score: 1

http://stackoverflow.com/q/48328255
has comment: http://stackoverflow.com/comment/83657434
tagged with: singly-linked-list
score: 0
tagged with: linked-list
has body: I wanted to create a singly linked list with two values a node as practice after having successfully done it with one value per node, though I have no idea how exactly to approach this. I've tried to convert the code for a generic linked list to one with two values a node, though it hasn't come close at all. I'd really appreciate any help with this. The problem itself: When I try to use the getTitle() method, it returns the error: "AttributeError: 'LinkedList' object has no attribute 'title'". The way I've tried to assign the values to a node was by simply having an extra value parameter, though looking at the error, it's probably resulted in nothing being assigned to the node. These are my codes. Generic singly linked list: class Node: def __init__(self, newData=None, nextNode=None, position=0): self.data = newData self.next = nextNode self.position = position def getData(self): return self.data def setData(self,newData): self.data = newData def getNext(self): return self.next def setNext(self,newNode): self.next = newNode def setFirst(self, newNode): self.head = newNode class LinkedList: def __init__(self): self.head = None self.tail = None self.size = 0 def getSize(self): return self.size def printAll(self): if self.head == None: print("List is empty") return current = self.head while current != None: print(current.data) current = current.next def searchForNode(self, data): if self.head == None: print("List is empty") return current = self.head while current: if current.getData() == data: return True else: current = current.getNext() return False def locateNode(self, data): if self.head == None: print("List is empty") return current = self.head position = 0 while current: if current.getData() == data: return position else: current = current.getNext() position+=1 return False def deleteNode(self, data): if self.head == None: print("List is empty") return current = self.head if current.getData() == data: self.head = current.getNext() else: while current.getNext() !…
has comment: http://stackoverflow.com/comment/83642154
has title: How do I assign two or more values to a single node in a singly linked list in python?
tagged with: nodes
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83643352
has comment: http://stackoverflow.com/comment/83642547
has comment: http://stackoverflow.com/comment/83643858
has comment: http://stackoverflow.com/comment/83642118
tagged with: python
tagged with: data-structures

http://stackoverflow.com/comment/83370652
comment on: http://stackoverflow.com/q/48194775
type: Comment
type: QuestionComment
score: 0
has text: updated the original post.

http://stackoverflow.com/a/48234646
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48234450
answers question: http://stackoverflow.com/q/48234450
type: Answer
score: 2
upvote count: 2
has body: Amazingly, support for ANSI escape sequences in the Windows console was only added in Windows 10 Version 1511: http://www.nivot.org/blog/post/2016/02/04/Windows-10-TH2-(v1511)-Console-Host-Enhancements They will not work in older versions of Windows, unless you use a terminal emulator which supports them, like ConEmu: https://conemu.github.io/
has comment: http://stackoverflow.com/comment/83452544
downvote count: 0

http://stackoverflow.com/comment/83586450
score: 0
type: Comment
has text: Can you explain the logic behind the reversals? Also I think this fails for something like `mylist = [['xxx', 879], ['xxx', 200]]`
type: AnswerComment
comment on: http://stackoverflow.com/a/48300546

http://stackoverflow.com/q/48267018
upvote count: 5
linked to: http://stackoverflow.com/q/20428636
has body: I have a 4 column DataFrame Subject_id Subject Time Score Subject_1 Math Day 1 Subject_1 Math Night 2 Subject_1 Music Day 3 Subject_1 Music Night 4 Subject_2 Math Day 5 Subject_2 Math Night 6 Subject_2 Music Day 7 Subject_2 Music Night 8 I want to group this columns hierarchically and convert them into a dictionary as follows: result = { 'Subject_1': { 'Math': { 'Day': 1, 'Night': 2 }, 'Music': { 'Day': 3, 'Night': 4 } } 'Subject_2': { 'Math': { 'Day': 5, 'Night': 6 }, 'Music': { 'Day': 7, 'Night': 8 } } } I managed to use pivot with one column less and get the desired result df.pivot('Subject_id', 'Subject', 'Score').to_dict('index') But if I try one more column (one level deeper dictionary) df.pivot('Subject_id', 'Subject', 'Time', 'Score').to_dict('index') I get the error: TypeError: pivot() takes at most 4 arguments (5 given) I have similarly tried using groupby with a lambda function with 3 columns: df.groupby('Subject_id') .apply(lambda x: dict(zip(x['Subject'],x['Score']))) .to_dict() But I cannot get the desired result with 4 columns. Is there a way I can give an arbitrary number of columns and convert them into a hierarchical dictionary? Like grouping by several fields in a specific order of hierarchy.
downvote count: 0
linked to: http://stackoverflow.com/q/19189274
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/48267240
tagged with: dictionary
type: AnsweredQuestion
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48268879
has answer: http://stackoverflow.com/a/48268879
has title: Pandas dataframe to hierarchical dictionary
favorite count: 0
type: Question
score: 5
accepted answer: http://stackoverflow.com/a/48267240

http://stackoverflow.com/q/48317726
tagged with: python
accepted answer: http://stackoverflow.com/a/48318047
type: AnsweredQuestion
has title: Pandas - duplicate rows based on values
answer count: 2
tagged with: pandas
downvote count: 0
tagged with: duplicates
possible better answer: http://stackoverflow.com/a/48318460
score: 1
has answer: http://stackoverflow.com/a/48318460
favorite count: 0
type: Question
has body: I have a dataframe, where I want to duplicate rows N times, where N is a value in another row. For example, if this is my dataframe: Company WEEK_DAYS SEPTEMBER 15 SEPTEMBER 22 SEPTEMBER 29 value 0 google MON-FRI 0 0 5 0.5 1 google TUE 3 2 0 0.7 so, the columns I want to replicate based on their value are SEPTEMBER 15, SEPTEMBER 22, and SEPTEMBER 29, and the value should be value. So the final output should be something like that: Company WEEK_DAYS WEEK value 0 google MON-FRI SEPTEMBER 29 0.5 1 google MON-FRI SEPTEMBER 29 0.5 2 google MON-FRI SEPTEMBER 29 0.5 3 google MON-FRI SEPTEMBER 29 0.5 4 google MON-FRI SEPTEMBER 29 0.5 5 google TUE SEPTEMBER 15 0.7 6 google TUE SEPTEMBER 15 0.7 7 google TUE SEPTEMBER 15 0.7 8 google TUE SEPTEMBER 22 0.7 9 google TUE SEPTEMBER 22 0.7 I tried using stack and pivot - but I didn't manage to get the desired output. Any help will be appreciated!
has answer: http://stackoverflow.com/a/48318047
tagged with: pivot
upvote count: 1

http://stackoverflow.com/comment/83568516
comment on: http://stackoverflow.com/q/48272785
type: Comment
type: QuestionComment
score: 0
has text: It sounds like a class homework, doesn't it?

http://stackoverflow.com/q/48305646
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/48305716
has answer: http://stackoverflow.com/a/48305736
has answer: http://stackoverflow.com/a/48305716
has answer: http://stackoverflow.com/a/48305720
has body: When I just press enter for raw_input("select: ") question, I get all dictionary keys. Why I get it? and How can I avoid this problem? dict={"tony":1,"jack":2,"apple":3} search = raw_input("select: ") number = 1 for i in dict.keys(): if search in i: print number, i number +=1
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48306376
type: Question
has title: Why I get all dictionary keys when raw_input is empty
answer count: 5
has answer: http://stackoverflow.com/a/48305750
has comment: http://stackoverflow.com/comment/83596424
tagged with: python
possible better answer: http://stackoverflow.com/a/48305720

http://stackoverflow.com/comment/83599926
type: QuestionComment
comment on: http://stackoverflow.com/q/48307183
type: Comment
has text: Sorry there was a typo. I've fixed it now
score: 0

http://stackoverflow.com/q/48225652
has answer: http://stackoverflow.com/a/48225709
tagged with: pandas
score: 1
upvote count: 3
tagged with: dataframe
favorite count: 0
type: Question
has body: I cannot understand the meaning of 25% and max of dataframe.describe() I tried to look for it but didn't get any hint whatsoever. I tried on different datasets, 25% isn't always an integer so it cannot be the number of values less than 25% of the max value. What does 25% and max signify?
has comment: http://stackoverflow.com/comment/83432868
downvote count: 2
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48225709
has title: Pandas describe() method
type: AnsweredQuestion

http://stackoverflow.com/q/48317641
has title: SQL like summarize reports using Python Pandas
answer count: 3
has body: I often produce in R single statement summarize reports using dplyr as the following: a &lt;- group_by(data,x) b &lt;- summarise(a, # count distinct y where value is not missing y_distinct = n_distinct(y[is.na(y) == F]), # count distinct z where value is not missing z_distinct = n_distinct(z[is.na(z) == F]), # count total number of values total = n(), # count y where value not missing y_not_missing = length(y[is.na(y) == F]), # count y where value is missing y_missing = length(y[is.na(y) == T])) which is similar to the way I would produce it in SQL: select count(distinct(case when y is not null then y end)) as y_distinct, count(distinct(case when z is not null then z end)) as z_distinct, count(1) as total, count(case when y is not null then 1 end) as y_not_missing, count(case when z is not null then 1 end) as y_missing from data group by x however, I'm (Python newbie and) not able to find the Panda's equivalent, and got lost in the documentation. I'm able to produce each aggregation using a different groupby -> agg statements, but need help to produce the report in a single data frame (preferably using a single statement).
tagged with: pandas
has comment: http://stackoverflow.com/comment/83620858
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48317888
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48317809
has answer: http://stackoverflow.com/a/48317770
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/a/48253131
type: Answer
has body: It depends on your usages. Basically, MongoDB is suitable for JSON document so, you will be able to insert your Python object "directly". If you want/need to use MySQL, you will probably need to perform some transformations before inserting. Check this post for more information: Inserting JSON into MySQL using Python
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48252967

http://stackoverflow.com/comment/83544195
comment on: http://stackoverflow.com/q/48273815
score: 0
has text: @charlietfl How to do with that? do you mean in Nginx?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48274138
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83531856
score: 0
has body: We are supposed to make a dealer and a player function for blackjack and then combine them into another function. I don't really know how to go about doing that. We also need to include the amount of times the player has won out of the number of games played. import random def play_hand_player(): total=0 player_is_bust=False ace_was_thrown=False more='y' while (more!='n') and not(player_is_bust): card=random.choice([1,2,3,4,5,6,7,8,9,10,10,10,10]) total=total+card if (card==1): #runs if the card is equal to one ace_was_thrown=True print("Ace\t ",end='') else: print(card,"\t",end='') if (total&gt;21): #runs if the card total is over 21 player_is_bust=True if not (player_is_bust): print("New total: ",end="") if (ace_was_thrown) and (total+10&lt;22): print(total,"or",total+10,end="") else: print(total,end="") more=input("\tAnother Card? ") if (player_is_bust): print("Bust") if (more=="n"): if (ace_was_thrown==True)and(total+10&lt;17)and(total+10&gt;22): print("\tFinal Total: ",total+10) else: print("\tFinal Total: ",total) print("") def play_hand_dealer(): total = 0 dealer_is_under = True dealer_is_bust = False ace_was_thrown = False while (dealer_is_under): card=random.choice([1,2,3,4,5,6,7,8,9,10,10,10,10]) total = total + card if (card == 1): ace_was_thrown = True print ("Ace ", end = "") else: print (card," ", end = "") if (total&gt;16): dealer_is_under = False if (total&gt;21): dealer_is_bust = True if (ace_was_thrown) and (total + 10 &gt; 16) and (total + 10 &lt; 22): dealer_is_under = False total = total + 10 if (dealer_is_bust): print (" Bust") else: print (" Total:", total) print ("Instructions: Press Enter Key to play another game, 'q' to quit.\n") def blackjack(): gamesWon = 0 totalHandsPlayed = 0 player = play_hand_player() dealer = play_hand_dealer() if player &gt; dealer: gamesWon += 1 print ("PLAYER WINS, ") else: print ("DEALER WINS. ")
has title: Python Blackjack - combining two functions
linked to: http://stackoverflow.com/q/20309456
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/83531964
tagged with: blackjack
answer count: 0
tagged with: function

http://stackoverflow.com/comment/83533397
comment on: http://stackoverflow.com/a/48274948
type: Comment
has text: I keep getting nothing in my doctest when I do it this way.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83541972
has text: Indeed, see [mcve]. We need a reproducible example (just invent some data) to see in how far the approach from the question fails.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48275425

http://stackoverflow.com/q/48241595
tagged with: freeze
has body: I made a program to send email with attachment. While the program is loading the files to be attached, the gui stops responding and Windows changes the window status to 'not responding', but when it has finished loading the files everything is back working. I wonder if there is a way to prevent Windows from changing the state, thanks in advance. Code: def send_mail(self, send_to, files=[]): msg = MIMEMultipart() msg['From'] = self.programData['name'] msg['To'] = '' msg['Date'] = formatdate(localtime = True) msg['Subject'] = self.programData['name'] txt = self.programData['emailText'] text = txt msg.attach(MIMEText(text)) for path in files: part = MIMEBase('application', "octet-stream") with open(path, 'rb') as file: part.set_payload(file.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(path))) msg.attach(part) smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.starttls() smtp.login('user','passw') smtp.sendmail('sender', send_to, msg.as_string()) smtp.quit()
has comment: http://stackoverflow.com/comment/83465921
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83466263
has comment: http://stackoverflow.com/comment/83466164
type: Question
tagged with: smtplib
has comment: http://stackoverflow.com/comment/83466548
tagged with: windows
has title: Issue with smtplib Python 3.6
tagged with: python

http://stackoverflow.com/comment/83450243
has text: There's no way you could be getting that first file from your code.
type: QuestionComment
comment on: http://stackoverflow.com/q/48233433
score: 0
type: Comment

http://stackoverflow.com/a/48217274
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48217172
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: If I understand correctly what you want is actually a Problem queryset and not a ProblemVote queryset? If so you should use the Problem model and the double underscore notation in filter to get what you want. Something like: all_problems = Problem.objects.filter(stage='PV', vote__user=user) accepted_problems = Problem.objects.filter(stage='PV', vote__user=user, vote__status='AC') rejected_problems = Problem.objects.filter(stage='PV', vote__user=user, vote__status='R') Making sure to change the vote in the filter calls to whatever the foreign key accessor actually is in your model (the related_name attribute on the foreign key field). EDIT: Changed the filter calls due to the way Django processes queries on foreign key fields as described here
accepted answer of: http://stackoverflow.com/q/48217172

http://stackoverflow.com/a/48270441
answers question: http://stackoverflow.com/q/48269844
accepted answer of: http://stackoverflow.com/q/48269844
type: Answer
score: 7
type: AcceptedAnswer
downvote count: 0
upvote count: 7
has body: By using replace df1.Name.replace(df2.set_index('Name1').Name2.to_dict()) Out[437]: 0 Alexs 1 Maria 2 Maria 3 Pandas 4 Coalas Name: Name, dtype: object

http://stackoverflow.com/q/48229580
score: 1
has title: Frames not stacking with pack()
answer count: 1
tagged with: user-interface
has answer: http://stackoverflow.com/a/48229970
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/7546050
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
has body: I am trying to create a program in which the user navigates through the screens with "Next" and "Previous" buttons. Editing the code from the selected answer here I have produced the following code: import Tkinter as tk import tkFont as tkfont def cancel(): root.destroy() def disable_event(): pass #Set the parent (main/root) window root = tk.Tk() root.title("Some title") root.geometry('700x500') #Width x Height root.resizable(0, 0) #Make root unresizable and force the use of "Cancel" button root.protocol("WM_DELETE_WINDOW", disable_event) class InstallerApp(tk.Tk): def __init__(self, *args, **kwargs): self.title_font = tkfont.Font(family='Helvetica', size=18) container = tk.Frame(root) container.pack(side="top", fill="both", expand=True) self.frames = {} for F in (Intro, FirstPage): page_name = F.__name__ frame = F(parent=container, controller=self) self.frames[page_name] = frame self.show_frame("Intro") def show_frame(self, page_name): frame = self.frames[page_name] frame.tkraise() class Intro(tk.Frame): def __init__(self, parent, controller): Intro = tk.Frame.__init__(self, parent) self.controller = controller leftFrame = tk.Frame(Intro, height=500, width=250, bg="#000000") leftFrame.pack(side="left") middleFrame = tk.Frame(Intro, height=500, width=5) middleFrame.pack(side="left") rightFrame = tk.Frame(Intro, height=500, width=450, bg="#FFFFFF") buttonFrame = tk.Frame(Intro, height=35, width=450, bg="#FFFFFF") nextButton = tk.Button(buttonFrame, width=10, text="Next &gt;", command=lambda: controller.show_frame("FirstPage")).grid(row=0, column=0) div3 = tk.Frame(buttonFrame, bg="#FFFFFF", width=10).grid(row=0, column=1) cancelButton = tk.Button(buttonFrame, text="Cancel", width=10, command=cancel).grid(row=0,column=2) buttonFrame.pack_propagate(False) buttonFrame.pack(side="bottom") #Other child widgets to rightFrame managed by pack rightFrame.pack_propagate(False) rightFrame.pack_forget() rightFrame.pack(side="right") class FirstPage(tk.Frame): #the same code with…
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/48229970

http://stackoverflow.com/a/48257300
answers question: http://stackoverflow.com/q/48240369
type: Answer
has body: Following are the functions which i've used to achieve the desired output: def isnan(value): try: return math.isnan(float(value)) except: return False def compare(p_loc,*args): fs = 0 fns = 0 fnan1 = 0 fnan2 = 0 fd1=0 fd2=0 if isnan(p_loc): return 'doubt' for k,v in enumerate(args): if v != p_loc: fs = 1 for k,v in enumerate(args): if v == p_loc: fns = 1 for k,v in enumerate(args): if isnan(v): fnan1 = 1 for k,v in enumerate(args): if isnan(v): fnan2 = 1 for k,v in enumerate(args): if v == p_loc: fd1 = 1 for k,v in enumerate(args): if v != p_loc: fd2 = 1 if fs ==0: return 'same' if fnan1 == 1: return 'doubt' elif (fd1 == 1 and fd2 == 1) and (fnan2 == 0): return 'doubt' elif fns == 0: return 'not same' def compare_locality(p,p_loc,s0,s0_loc,s1,s1_loc,s2,s2_loc): loc = [] if not isnan(s0) : loc.append(s0_loc) if not isnan(s1) : loc.append(s1_loc) if not isnan(s2) : loc.append(s2_loc) if len(loc) == 0: return '' else: return compare(p_loc,*loc) Following line invokes the above function and creates a new column: data['comp_loc'] = data.apply(lambda x: compare_locality(x['pri'],x['pri_loc'],x['s0'],x['s0_loc'],x['s1'],x['s1_loc'],x['s2'],x['s2_loc']),axis=1)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48240369
score: 0

http://stackoverflow.com/comment/83564114
type: QuestionComment
has text: What do you mean with logged in? Are you executing this program multiply times?
comment on: http://stackoverflow.com/q/48289552
type: Comment
score: 0

http://stackoverflow.com/comment/83564369
comment on: http://stackoverflow.com/a/48289546
has text: Of course, I could append `Y` to `X` and then call `pdist`, but this would be quite wasteful since I only need 1/4 of the results.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48198763
accepted answer of: http://stackoverflow.com/q/48198153
has body: Depends on how you want it presented. But here is one way: pd.concat([ df.pct_change().shift(-1), df.pct_change(2).shift(-2) ], axis=1, keys=['Shift1', 'Shift2']) Shift1 Shift2 ColA ColA Date 2018-01-03 01:30:00 -0.001711 0.001038 2018-01-03 01:45:00 0.002754 -0.000904 2018-01-03 02:00:00 -0.003648 0.000415 2018-01-03 02:15:00 0.004078 0.014519 2018-01-03 02:30:00 0.010399 0.009797 2018-01-03 02:45:00 -0.000597 0.009835 2018-01-03 03:00:00 0.010438 NaN 2018-01-03 03:15:00 NaN NaN
answers question: http://stackoverflow.com/q/48198153
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/98772520
upvote count: 3
has comment: http://stackoverflow.com/comment/98772286
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48308308
type: Answer
score: 4
answers question: http://stackoverflow.com/q/48308240
upvote count: 4
downvote count: 0
has body: import numpy as np x = np.array([[12, 35, 12, 26], [35, 35, 12, 26]]) (x == 35) + 0 array([[0, 1, 0, 0], [1, 1, 0, 0]])
has comment: http://stackoverflow.com/comment/83602410

http://stackoverflow.com/a/48181470
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48180676
score: 1
upvote count: 1
type: AcceptedAnswer
has body: For the command using PIPE , you need to redirect the output of one command to the input of other subprocess Popen class. Below example should work for you from subprocess import Popen import shlex input="lsof -ti:9938,9955,9910,9988" command=shlex.split(input) #will split the command in list format p1 = Popen(command, stdout=PIPE) p2 = Popen(["xargs", "kill"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2.communicate()[0] For detailed information you can refer here https://docs.python.org/2/library/subprocess.html
answers question: http://stackoverflow.com/q/48180676

http://stackoverflow.com/q/48288163
tagged with: metaclass
has body: I want to create a configuration class with cascading feature. What do I mean by this? let say we have a configuration class like this class BaseConfig(metaclass=ConfigMeta, ...): def getattr(): return 'default values provided by the metaclass' class Config(BaseConfig): class Embedding(BaseConfig, size=200): class WordEmbedding(Embedding): size = 300 when I use this in code I will access the configuration as follows, def function(Config, blah, blah): word_embedding_size = Config.Embedding.Word.size char_embedding_size = Config.Embedding.Char.size The last line access a property which does not exist in Embedding class 'Char'. That should invoke getattr() which should return 200 in this case. I am not familiar with metaclasses enough to make a good judgement, but I gues I need to define the __new__() of the metaclass. does this approach makes sense or is there a better way to do it? EDIT: class Config(BaseConfig): class Embedding(BaseConfig, size=200): class WordEmbedding(Embedding): size = 300 class Log(BaseConfig, level=logging.DEBUG): class PREPROCESS(Log): level = logging.INFO #When I use log = logging.getLogger(level=Config.Log.Model.level) #level should be INFO
downvote count: 0
upvote count: 1
score: 1
has title: How to use python metaclass for the following scenario?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48288364
has comment: http://stackoverflow.com/comment/83561472
tagged with: python
possible better answer: http://stackoverflow.com/a/48288364
accepted answer: http://stackoverflow.com/a/48307836
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48307836
answer count: 2

http://stackoverflow.com/comment/83525770
type: QuestionComment
has text: There is no "sequence generator". You have a *generator expression* without parentheses, which are required *with the exception* of when you pass it as a single argument. You can use `(str(e) for e in blank)` as a valid generator expression.
type: Comment
comment on: http://stackoverflow.com/q/48254972
score: 0

http://stackoverflow.com/comment/83507937
score: 0
type: Comment
type: QuestionComment
has text: @georgexsh: that's true. I tried the second answer of the topic you pointed and it solved my problem.
comment on: http://stackoverflow.com/q/48257387

http://stackoverflow.com/a/48286115
has comment: http://stackoverflow.com/comment/83556963
has comment: http://stackoverflow.com/comment/83560986
answers question: http://stackoverflow.com/q/48285413
type: Answer
has body: The problem is that only some of the values in the CSV are float, but for the rest the conversion will fail. You can try: with open('metaanalysis_data.csv', 'rb') as f_input, open('metaanalysis_datas.csv', 'wb') as f_output: csv_input = csv.reader(f_input, quotechar="'") csv_output = csv.writer(f_output) csv_output.writerow(next(csv_input)) for row in csv_input: for i, elem in enumerate(row): try: row[i] = '{:.3f}'.format(float(elem)) except ValueError: pass csv_output.writerow(row) That way, when the conversion fails it will raise a ValueError exception and the element row[i] will remain what it was.
score: 1
has comment: http://stackoverflow.com/comment/83565349
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83529312
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48272389
has text: @PM2Ring data added, adding more code, etc...

http://stackoverflow.com/a/48176006
has comment: http://stackoverflow.com/comment/83331906
has body: You need to convert guess to a string for the print statements to work, try writing + str(guess) instead of + guess.
answers question: http://stackoverflow.com/q/48175967
type: Answer
has comment: http://stackoverflow.com/comment/83331980
has comment: http://stackoverflow.com/comment/83332245
score: 0

http://stackoverflow.com/comment/83614789
type: Comment
comment on: http://stackoverflow.com/a/48309092
has text: So Ive compiled the code and all i'm getting is a date entry box with the drop down unactionable . Am i missing something here ? is there a bug in python 3.4.0 ?? not sure what the prob is :(
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83592918
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48303782
type: AnswerComment
has text: @cricket_007 it will work and give [''] as asked in question that we have to remove the str1 nowhere mentioned that how many time it should occur.

http://stackoverflow.com/q/48174383
has title: OMPython + SLURM decreasing performance by adding cores
score: 0
has comment: http://stackoverflow.com/comment/83341855
answer count: 0
tagged with: openmodelica
type: Question
tagged with: openmp
tagged with: slurm
tagged with: performance
has comment: http://stackoverflow.com/comment/83356753
has body: Note This question can be considered a followup of a previous problem. Background I need to run a blocks simulation. I've used OMEdit to create the system and I call omc to run the simulation using OMPython with zmq for messaging. The simulation works fine but now I need to move it to a server to simulate the system for long times. Since the server is shared among a team of people, it uses slurm to queue the jobs. The server has 32 cores but they asked me to use only 8 while I tune my script and then 24 when I want to run my final simulation. I've configured slurm to call my script in the following manner: #!/bin/bash # #SBATCH --job-name=simulation_Test_ADC2_pipe_4096s #SBATCH --output=simulation_Test_ADC2_pipe_4096s.txt # #SBATCH --ntasks=1 #SBATCH --cpus-per-task=8 #SBATCH --time=10:00 #SBATCH --mem-per-cpu=10000 source activate /home/jabozzo/conda_envs/py27 #which python OMP_NUM_THREADS=8 python ./Test_ADC2_pipe_4096s.py Since I can't limit the number of cores the simulation uses with just --cpus-per-task, I've to also use OMP_NUM_THREADS (See previous question for more details). The simulations run fine and restrict themselves to the number of assigned cores. Problem The simulation speed does not increase with added cores. It actually decreases, by a large factor. Here are some measurements I've made: constant_time = 39s | samples | cpus | total_time | var_time (total-constant_time) | 10 1 1m 03s 24s 10 4 1m 20s 41s 10 8 1m 31s 52s 10 16 1m 42s 63s Samples Is a simulation parameter and proportional to the simulation length, so all simulations are the same. Cpus is the value of OMP_NUM_THREADS and --cpus-per-task total_time is the time the python script runs. var_time is the actual simulation time, a constant of 39s is subtracted from total_time since it's related to compilation time. I've not a clue why this is happening. Can this be disk-related? Update 1: Measurements I've tested all combination of linear and non-linear solvers and none of them benefit from p…
linked to: http://stackoverflow.com/q/48119762
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83406471

http://stackoverflow.com/q/48326627
has title: Plotting pandas groupby output using matplotlib subplots
tagged with: python
accepted answer: http://stackoverflow.com/a/48334651
type: AnsweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: plot
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48334651
has body: I have a dataframe,df2 which has 6 rows and 1591 columns 0.0.0 10.1.21 1.5.12 3.7.8 3.5.8 1.7.8 ... June 1 1 4 0 0 4 July 0 0 0 0 0 0 August 54 0 9 0 5 0 September 22 0 6 0 0 1 October 0 9 5 1 4 0 I want to plot multiple of 3 columns in each panel in a figure as a stacked bar. that is column: 0.0.0 to 1.5.12 to be plotted in a separate panel and column:3.7.8 to 1.7.8 in another panel. Here is the code: df= df2 df['key1'] = 0 df.key1.loc[:, ['0.0.0', '10.1.21', '1.5.12']].values = 1 df.key1.loc[:,['3.7.8', '3.5.8', '1.7.8']].values = 2 df.key1.loc[:,['4.4.3', '2.2.0', '2.8.0']].values = 3 # Plot in Three Panels distinct_keys = df['key1'].unique() fig, axes = pyplot.subplots(len(distinct_keys), 1, sharex=True, figsize= (3,5)) #{df_subset groups the rows with the same key in other to plot them in the same panel} for i, key in enumerate(distinct_keys): df_subset =df[df['key1']==key] # plot axes[i] = df_subset.plot(kind='bar', stacked=True) pyplot.legend(bbox_to_anchor=(1.04,1), loc="upper right") pyplot.subplots_adjust(right=0.7) pyplot.tight_layout(rect=[0,0,0.75,1]) pyplot.savefig("output.png", bbox_inches="tight") but i get :IndexingError: Too many indexers
tagged with: pandas
score: 1
tagged with: group-by
tagged with: matplotlib

http://stackoverflow.com/a/48274123
upvote count: 1
answers question: http://stackoverflow.com/q/48274065
score: 1
type: Answer
has body: Use the keyword continue. While in a loop whenever the keyword continue is called, it makes the loop to iterate over it leaving the code below unprocessed. ids = list(set(df['user_id'])) for k in ids: if k == 'the_element_you_dont_want': continue #Skips the code below when its called #Other code code block #processing = df.user_id.eq(ids-{k}????)
downvote count: 0

http://stackoverflow.com/comment/83543242
has text: Your regex fails because it *requires* the last `uk` to end with a `.` as well. Since you're not interested in what comes before and after, the anchors are not necessary; you can use `(?<=//)(([^./]+\.)+[^/]+)`. ([live on **regex101**](https://regex101.com/r/AsuaXr/1))
comment on: http://stackoverflow.com/q/48279740
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83490738
comment on: http://stackoverflow.com/q/48254034
type: QuestionComment
score: 0
has text: "It is not working" may be an accurate description but we need some more information that that.
type: Comment

http://stackoverflow.com/comment/83408556
score: 0
comment on: http://stackoverflow.com/q/48209092
type: Comment
has text: @Jean-FrançoisFabre any idea how I can handle that? Thanks :)
type: QuestionComment

http://stackoverflow.com/q/48330428
has comment: http://stackoverflow.com/comment/83647368
has comment: http://stackoverflow.com/comment/83647631
downvote count: 0
has comment: http://stackoverflow.com/comment/83646890
has comment: http://stackoverflow.com/comment/83647530
answer count: 1
has title: Amazon Python 2.7 Lambda: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so"
has answer: http://stackoverflow.com/a/48331544
tagged with: amazon-web-services
tagged with: aws-lambda
linked to: http://stackoverflow.com/q/46937833
favorite count: 0
type: Question
tagged with: oracle-database
tagged with: python
accepted answer: http://stackoverflow.com/a/48331544
has body: This article was the closest to what I experienced: Connecting to Oracle RDS using AWS Lambda using Python. However, after following all of the steps, I am unable to get a successful result. Steps on ami-aa5ebdd2 in us-west-2: sudo yum -y install gcc mkdir oracle_connect source oracle_connect/bin/activate virtualenv oracle_connect pip install cx_Oracle wget https://github.com/bumpx/oracle-instantclient/raw/master/instantclient-basic-linux.x64-12.2.0.1.0.zip mv instantclient_12_2/* oracle_connect/lib/ cd oracle_connect vi test.py # insert python code here cp /lib64/libaio.so.1.0.1 lib ln -s ./lib/libclntsh.so.12.1 ./lib/libclntsh.so ln -s ./lib/libaio.so.1.0.1 ./lib/libaio.so.1 ln -s ./lib/libaio.so.1.0.1 ./libaio.so.1.0.1 ln -s ./lib/libaio.so.1.0.1 ./libaio.so.1.0.1 cd lib/python2.7/site-packages/ zip -r ~/oracle_connect.zip * .* cd ~/oracle_connect/lib64/python2.7/site-packages/ zip -r ~/oracle_connect.zip * .* cd ~/oracle_connect zip --symlinks -r9 ~/oracle_connect.zip lib/* zip ~/oracle_connect.zip test.py The test code is just a cx_Oracle.connect(connection_string) within a lambda handler. Any advice? I tried to give as much detail as possible. When I try to run this locally, it won't work until I setup: export LD_LIBRARY_PATH=/home/ec2-user/oracle_connect/lib So I setup the environmental variable on the lambda as: LD_LIBRARY_PATH: /var/task/lib
score: 2
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/q/48268130
has body: In CodeSkulptor (online Python coding page) I wrote a simple code, with a time delay. So simple: import time time.sleep(5) print("random string") When I press run, I got an error message: Line 2: AttributeError: '&lt;invalid type&gt;' object has no attribute 'sleep' Any ideas what is wrong? Or how can I fix it?
has comment: http://stackoverflow.com/comment/83519547
has title: CodeSkulptor time delay: no attribute 'sleep'
score: 0
tagged with: codeskulptor
has answer: http://stackoverflow.com/a/48280101
tagged with: python
has answer: http://stackoverflow.com/a/48268218
type: Question
answer count: 2
tagged with: time
type: UnansweredQuestion
tagged with: delay

http://stackoverflow.com/q/48236959
tagged with: epoch
has comment: http://stackoverflow.com/comment/83456549
tagged with: python
linked to: http://stackoverflow.com/q/11743019
tagged with: timestamp
type: AnsweredQuestion
has body: Am seeing strange issue when converting data time to epoch format between the languages Python and Ruby. I noticed huge difference in seconds on the same server. In Python 3.6.2: &gt;&gt;&gt; datetime.datetime.utcnow() datetime.datetime(2018, 1, 13, 4, 25, 19, 204056) &gt;&gt;&gt; int(datetime.datetime.utcnow().strftime("%s")) 1515839122 &gt;&gt;&gt; In Ruby 1.8.7: irb(main):038:0&gt; Time.now.utc =&gt; Sat Jan 13 04:25:18 UTC 2018 irb(main):039:0&gt; Time.now.utc.to_i =&gt; 1515817520 irb(main):040:0&gt; Am worrying if am using wrong method in any the mentioned languages or looking way to fix this to get the same epoch seconds in both the languages. Since my application is developed to work using both the languages and the epoch time will be shared between those languages. I believe it doesn't matter about the languages version, since the timestamp is same for irrespective of languages.
duplicate of: http://stackoverflow.com/q/11743019
upvote count: 3
downvote count: 2
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/83461033
accepted answer: http://stackoverflow.com/a/48237097
favorite count: 0
type: Question
has title: epoch timestamp difference between Ruby and Python
tagged with: ruby
has answer: http://stackoverflow.com/a/48237097
has comment: http://stackoverflow.com/comment/83456587

http://stackoverflow.com/q/48284453
tagged with: python
has title: multicolor line on matplotlib
tagged with: plot
favorite count: 0
accepted answer: http://stackoverflow.com/a/48285078
type: AnsweredQuestion
tagged with: colors
has answer: http://stackoverflow.com/a/48285078
tagged with: matplotlib
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/83554009
has comment: http://stackoverflow.com/comment/83554479
type: Question
has body: Is it possible to have something similar to edgecolor and facecolor for plt.plot()? I need to plot a curve with a different colored boundary around it for e.g. a segment of the line would look like ||| with the outer lines in a different color and the inner line in a different color. Can this be done using a single plot command rather than plotting three plots?
linked to: http://stackoverflow.com/q/42165631
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48292298
tagged with: python
tagged with: kivy
has body: I set up a Screen in a Kivy ScreenManager (myScreen is just a class that inherits Screen) class firstScreen(myScreen): def __init__(self,**kwargs): super(firstScreen, self).__init__(**kwargs) self.name = "first" self.add_widget(Button(on_release = switchScreens("second"))) I also set up a second screen: class secondScreen(myScreen): def __init__(self,**kwargs): super(secondScreen, self).__init__(**kwargs) self.name = "second" I then set up my ScreenManager: sm = ScreenManager() sm.add_widget(firstScreen()) sm.add_widget(secondScreen()) And here is the code for switchScreens: def switchScreens(next): sm.current = next When I run sm, I get the following error: kivy.uix.screenmanager.ScreenManagerException: No Screen with name "second". This seems wrong to me, since I added the secondScreen() to sm, with a name of "second". How can I get the Button on firstScreen to correctly send the app to secondScreen?
downvote count: 0
type: AnsweredQuestion
score: 1
upvote count: 1
answer count: 1
has title: Kivy Error: No Screen with Name
favorite count: 0
type: Question
tagged with: kivy-language
has answer: http://stackoverflow.com/a/48359502
accepted answer: http://stackoverflow.com/a/48359502

http://stackoverflow.com/a/48176570
type: Answer
score: 0
has body: I've always been told not to update a file I'm reading/comparing. When I'm doing something like comparing csv files like this I like to build a new list of file contents then check to see if the desired row or value is in the new list. In your case I would; Create a new list containing the csv file values your looking at Define the string your looking for Check that the desired string is in the 25th element of the new list If it is append the 25th element with your desired string. Write a new updated csv file with the list you built/appended This is what I came up with using a single file and a predefined keyword to find. For your case, just add the file you want to get your keyword from, then set the keyword to be the [0] element in that list/file Hope this helps import csv import os csv_file = os.path.join(os.path.join(os.environ['USERPROFILE']),'Dir', 'file.csv') updated_csv_file_path = os.path.join(os.path.join(os.environ['USERPROFILE']),'Dir', 'updated_file.csv') with open(csv_file, 'r') as rawcsv, open(updated_csv_file_path, 'w', newline='') as csv_out_file: reader = csv.reader(rawcsv) writer = csv.writer(csv_out_file) desired_file1_string = 'Greg' update_string = 'OK' file2_contents = [] # adds all of rows (lists) found in the csv file to a new list for us to update for item in reader: file2_contents.append(item) print('Inital value of the 25th element: \n {}'.format(file2_contents[25])) # if the desired string is in the 25th element of the list, appends ';OK' to the end of that list if desired_file1_string in file2_contents[25]: file2_contents[25].append(update_string) print('Post append value of the 25th element: \n{}'.format(file2_contents[25])) # writes a new csv file with the contents of file2_contents list writer = csv.writer(csv_out_file) for line in file2_contents: writer.writerow(line) The results Inital value of the 25th element: ['Greg', 'Unruh', '', 'some_words', 'some more words'] Post append value of the 25th element: ['Greg', 'Unruh', '', 'some…
answers question: http://stackoverflow.com/q/48175322

multithreading
tags question: http://stackoverflow.com/q/48262966
tags question: http://stackoverflow.com/q/48197248
tags question: http://stackoverflow.com/q/48277521
tags question: http://stackoverflow.com/q/48263704
tags question: http://stackoverflow.com/q/48243418
tags question: http://stackoverflow.com/q/48266472
tags question: http://stackoverflow.com/q/48293224
tags question: http://stackoverflow.com/q/48229766
type: Tag
tags question: http://stackoverflow.com/q/48253740
tags question: http://stackoverflow.com/q/48181950
tags question: http://stackoverflow.com/q/48211914
tags question: http://stackoverflow.com/q/48200675
tags question: http://stackoverflow.com/q/48195549
tags question: http://stackoverflow.com/q/48193130
tags question: http://stackoverflow.com/q/48185746
tags question: http://stackoverflow.com/q/48257221
tags question: http://stackoverflow.com/q/48319966
tags question: http://stackoverflow.com/q/48256374
tags question: http://stackoverflow.com/q/48314325
tags question: http://stackoverflow.com/q/48227104
tags question: http://stackoverflow.com/q/48240345
tags question: http://stackoverflow.com/q/48195453
tags question: http://stackoverflow.com/q/48295296
tags question: http://stackoverflow.com/q/48195845
tags question: http://stackoverflow.com/q/48309112
tags question: http://stackoverflow.com/q/48325908
tags question: http://stackoverflow.com/q/48210685
tags question: http://stackoverflow.com/q/48313984
tags question: http://stackoverflow.com/q/48198215
tags question: http://stackoverflow.com/q/48226597
tags question: http://stackoverflow.com/q/48260173
tags question: http://stackoverflow.com/q/48177299
tags question: http://stackoverflow.com/q/48296986
tags question: http://stackoverflow.com/q/48206439
tags question: http://stackoverflow.com/q/48283746
tags question: http://stackoverflow.com/q/48252631
tags question: http://stackoverflow.com/q/48245748
tag name: multithreading
tags question: http://stackoverflow.com/q/48251987
tags question: http://stackoverflow.com/q/48268789
tags question: http://stackoverflow.com/q/48180414
tags question: http://stackoverflow.com/q/48276616

http://stackoverflow.com/q/48260503
has title: How to initialize parent class, when child class uses super keyword in python
tagged with: multiple-inheritance
has body: I tried running these few lines of Python code involving super &amp; MRO. The line class Child(Add, Sub, Mul, Sqroot, Div): is deciding the First line of the output i.e. currently Inside add class. Please help me with the concept, because if I changed that line to class Child(Sqroot, Add, Sub, Mul, Div):, the first line of the output changed to Inside sqroot class class Sqroot(object): def __init__(self): print 'Inside sqroot class' def sqroot(self, num): print 'The square root of the number is ',num**0.5 class Add(object): def __init__(self): print 'Inside add class' def add(self, num1, num2): print 'The sum is :', num1+num2 class Sub(object): def __init__(self): print 'Inside subtraction class' def sub(self, num1, num2): print 'The subtraction is :', num1-num2 class Mul(object): def __init__(self): print 'Inside multiplication class' def mul(self, num1, num2): print 'The multiplication is :', num1*num2 class Div(object): def __init__(self): print 'Inside division class' def div(self, num1, num2): print 'The division is :', num1/num2 class Child(Add, Sub, Mul,Sqroot, Div): def __init__(self): super(Child, self).__init__() ob = Child() ob.sqroot(9) ob.add(6,4) ob.sub(3,5) ob.mul(6,4) ob.div(6,4) OUTPUT:- Inside add class The square root of the number is 3.0 The sum is : 10 The subtraction is : -2 The multiplication is : 24 The division is : 1
has answer: http://stackoverflow.com/a/48260892
linked to: http://stackoverflow.com/q/3277367
tagged with: initialization
type: Question
tagged with: python
type: UnansweredQuestion
tagged with: parent-child
answer count: 1
has comment: http://stackoverflow.com/comment/83504045
tagged with: super
score: 0

http://stackoverflow.com/comment/83506225
comment on: http://stackoverflow.com/a/48261497
has text: Ok. So what is your platform?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83502333
type: AnswerComment
comment on: http://stackoverflow.com/a/48252615
has text: Ok solved. Re-assuming: I save the `__builtins__.raw_input` function in `original_raw_input`, then I ovveride it with the lambda function: `__builtins__.raw_input = lambda _: fake_input()`. The function `fake_input()` uses the `pop` function on a list of values. Then I reset the `__builtins__.raw_input`. Python is really fascinating.
type: Comment
score: 0

http://stackoverflow.com/a/48306185
type: Answer
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48274851
accepted answer of: http://stackoverflow.com/q/48274851
has body: Here is an example that will illustrate what's going on. Let's consider what happens when you call reduce on a list with some function f: reduce(f, [a,b,c]) = f(f(a,b),c) If we take your example, f = lambda u, v: u[1] + v[1], then the above expression breaks down into: reduce(f, [a,b,c]) = f(f(a,b),c) = f(a[1]+b[1],c) But a[1] + b[1] is an integer so there is no __getitem__ method, hence your error. In general, the better approach (as shown below) is to use map() to first extract the data in the format that you want, and then apply reduceByKey(). A MCVE with your data element = sc.parallelize( [ ('A', ('toto' , 10)), ('A', ('titi' , 30)), ('5', ('tata', 10)), ('A', ('toto', 10)) ] ) You can almost get your desired output with a more sophisticated reduce function: def add_tuple_values(a, b): try: u = a[1] except: u = a try: v = b[1] except: v = b return u + v print(element.reduceByKey(add_tuple_values).collect()) Except that this results in: [('A', 50), ('5', ('tata', 10))] Why? Because there's only one value for the key '5', so there is nothing to reduce. For these reasons, it's best to first call map. To get your desired output, you could do: &gt;&gt;&gt; print(element.map(lambda x: (x[0], x[1][1])).reduceByKey(lambda u, v: u+v).collect()) [('A', 50), ('5', 10)] Update 1 Here's one more approach: You could create tuples in your reduce function, and then call map to extract the value you want. (Essentially reverse the order of map and reduce.) print( element.reduceByKey(lambda u, v: (0,u[1]+v[1])) .map(lambda x: (x[0], x[1][1])) .collect() ) [('A', 50), ('5', 10)] Notes Had there been at least 2 records for each key, using add_tuple_values() would have given you the correct output.
type: AcceptedAnswer

http://stackoverflow.com/comment/83478076
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48247657
has text: I said to add it to your question please.

http://stackoverflow.com/comment/83558070
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48286413
has text: df = policy_yr policy_month policy_no. Premium.

http://stackoverflow.com/a/48198192
has comment: http://stackoverflow.com/comment/94619375
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48190355
has comment: http://stackoverflow.com/comment/83388209
has body: Not sure what command you're running but usually you can press SPACE when you see the --More-- prompt. For example: import pexpect, sys child = pexpect.spawn('more /etc/services') child.logfile_read = sys.stdout patterns = ['--More--', pexpect.EOF] while True: ret = child.expect(patterns) if ret == 0: child.send(' ') elif ret == 1: break
answers question: http://stackoverflow.com/q/48190355
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/94613129
has comment: http://stackoverflow.com/comment/94608172

http://stackoverflow.com/comment/83575074
has text: But I want to just when user access the home page API, then I record it. whether the middleware can realize this case?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48295154
score: 0

http://stackoverflow.com/q/48295401
type: Question
upvote count: 2
tagged with: python
has body: I want to freeze a single convolutional layer in my model and I did it by passing traninable=False parameter in the convolution layer similar to Dense layer Dense(32, trainable=False) from keras.layers import Dense, Dropout, Activation, Flatten from keras.models import Sequential from keras.layers.normalization import BatchNormalization from keras.layers import Conv2D,MaxPooling2D,ZeroPadding2D,GlobalAveragePooling2D model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=(28,28,1))) model.add(BatchNormalization(axis=-1)) model.add(Activation('relu')) model.add(Conv2D(32, (3, 3))) model.add(BatchNormalization(axis=-1)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Conv2D(64,(3, 3),trainable=False)) #freezed layer model.add(BatchNormalization(axis=-1)) model.add(Activation('relu')) model.add(Conv2D(64, (3, 3))) model.add(BatchNormalization(axis=-1)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Flatten()) # Fully connected layer model.add(Dense(512)) model.add(BatchNormalization()) model.add(Activation('relu')) model.add(Dropout(0.2)) model.add(Dense(10)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) The model seems to compile without any error but when I checked keras docs the Conv2D dosen't seems to have a parameter named trainable. Is my way of freezing convolutional layer valid and what is happening here?
has title: What is the right way to freeze a convoloutional layer in keras
type: AnsweredQuestion
tagged with: keras-layer
score: 2
accepted answer: http://stackoverflow.com/a/48295796
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48295796
tagged with: keras
favorite count: 0

http://stackoverflow.com/q/48250981
tagged with: minimum
has title: How to delete the lowest number in an array, and if there's several minimum numbers, delete the first
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/48251184
accepted answer: http://stackoverflow.com/a/48251184
tagged with: python
has answer: http://stackoverflow.com/a/48251154
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48251216
answer count: 3
upvote count: 5
possible better answer: http://stackoverflow.com/a/48251154
favorite count: 0
type: Question
tagged with: numpy
has body: I'm trying to make a script, where the input is an array with random numbers. I try to delete the lowest number in the array which is no problem. But if there are several occurrences of this number in the array, how do I make sure that it is only the first occurrence of this number that gets deleted? Let's say we have the following array: a = np.array([2,6,2,1,6,1,9]) Here the lowest number is 1, but since it occurs two times, I only want to remove the first occurence so i get the following array as a result: a = np.array([2,6,2,6,1,9])
tagged with: python-3.x
score: 5

http://stackoverflow.com/comment/83887386
comment on: http://stackoverflow.com/q/48265583
type: Comment
score: 0
type: QuestionComment
has text: hmm, this sounds overly complicated. I tried the solution you advertised as ideal solution. If it works on your side then why don't you post the complete working solution? like I said I am still looking for a working solution for the stated problem - not a different broken one. Besides I can not add my solution as a comment. But you could post a complete solution as an answer.

http://stackoverflow.com/comment/83460255
type: AnswerComment
score: 0
has text: Thanks very much - that's a useful approach!
comment on: http://stackoverflow.com/a/48229206
type: Comment

http://stackoverflow.com/comment/83468784
score: 1
type: Comment
type: AnswerComment
has text: Yes, it can even parse the thousand separators, I was really amazed when `int('100_000')` worked (Python 3.6).
comment on: http://stackoverflow.com/a/48242971

http://stackoverflow.com/comment/83470349
comment on: http://stackoverflow.com/a/48243476
has text: You are awesome @Spence Wetjen!!!! Your solution is what I was expecting. Just one thing: is it possible to kick out that blank sheet from the workbook. Thanks a trillion.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48248016
score: 2
has comment: http://stackoverflow.com/comment/83480149
has body: If you directly convert this color image to gray and threshold it, then you will get this. It's not suitable for threshold the two A: But if you split the channels in BGR, you will get this: Clearly, threshold the B channel will work. #!/usr/bin/python3 # 2018.01.14 16:31:39 CST # 2018.01.14 16:50:45 CST import cv2 img = cv2.imread("img12.png") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) b,g,r = cv2.split(img) th, threshed1 = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU) th, threshed2 = cv2.threshold(b, 100, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU) cv2.imwrite("threshed_gray.png", threshed1) cv2.imwrite("threshed_blue.png", threshed2)
answers question: http://stackoverflow.com/q/48247857
has comment: http://stackoverflow.com/comment/83479547
has comment: http://stackoverflow.com/comment/83479468
has comment: http://stackoverflow.com/comment/83479607
upvote count: 2
has comment: http://stackoverflow.com/comment/83480379
has comment: http://stackoverflow.com/comment/83480720
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83481352
has comment: http://stackoverflow.com/comment/83486657

http://stackoverflow.com/a/48267053
has body: I think it returns an error because Keras is checking the shapes of your inputs. However lists (what you are feeding) don't have a shape attribute. Try passing them as arrays: import numpy as np model_.fit(np.asarray(X), np.asarray([None]*2), epochs=50, batch_size=32)
has comment: http://stackoverflow.com/comment/83518437
has comment: http://stackoverflow.com/comment/83517953
score: 0
answers question: http://stackoverflow.com/q/48266778
has comment: http://stackoverflow.com/comment/83517247
has comment: http://stackoverflow.com/comment/83517677
has comment: http://stackoverflow.com/comment/83517480
has comment: http://stackoverflow.com/comment/83518308
has comment: http://stackoverflow.com/comment/83518074
type: Answer

http://stackoverflow.com/a/48321506
type: Answer
answers question: http://stackoverflow.com/q/48321363
has body: Dunno whether this qualifies as more pythonic or not, but it handles it as HTML data. from lxml import html content = ' RTO / Registration office : Yadgiri ' HtmlData = html.fromstring(content) ListData = HtmlData.xpath(‘//text()’) And to get the last element: ListData[-1]
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83628092
accepted answer of: http://stackoverflow.com/q/48321363

http://stackoverflow.com/comment/83629529
score: 0
comment on: http://stackoverflow.com/a/48315969
type: Comment
type: AnswerComment
has text: ./hacking/test-module -m delete_sdb_domain.py -a "sdb_domain_name=zzz" is working I think and got some RAW OUTPUT and INVALID OUTPUT FORMAT

http://stackoverflow.com/q/48284593
accepted answer: http://stackoverflow.com/a/48284719
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83553205
answer count: 3
has answer: http://stackoverflow.com/a/48284719
has comment: http://stackoverflow.com/comment/83553646
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83553368
has answer: http://stackoverflow.com/a/48285001
has body: NEW: Since I am here in line 30 it is now telling me clock is not defined I've been writing some code for a game I'm making for homework and it was working until I added some code for music and then suddenly the indent levels were off. Here is the code: image_x = 0 image_y = 0 while 1: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: return if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: return Please ask if you need to see the entire program if need be. Here's the entire thing, maybye this will help: # This just imports all the Pygame modules import pygame class Game(object): def main(self, screen): clock = pygame.time.Clock() #soundObj = pygame,mixer.Sound('The Tonight Show Star Wars The Bee Gees Stayin Alive Shortened.mp3') #soundObj.play() #import time #time.sleep(52) #class Player(pygame.sprite.Sprite): # def __init__(self, *groups): # super(Player, self.__init__(*groups) #self.image = pygame.image.load('Sprite-01.png') # self.rect = pygame.rect.Rect((320, 240), self.image.get_size()) #def update(self): # key = pygame image = pygame.image.load('Sprite-01.png') # initialize variables image_x = 0 image_y = 0 while 1: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: return if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: return image_x += 0 key = pygame.key.get_pressed() if key[pygame.K_LEFT]: image_x -= 10 if key[pygame.K_RIGHT]: image_x += 10 if key[pygame.K_UP]: image_y -= 10 if key[pygame.K_DOWN]: image_y += 10 screen.fill((200, 200, 200)) screen.blit(image, (image_x, image_y)) pygame.display.flip() if __name__ == '__main__': pygame.init() screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption('St.Patrick game') Game().main(screen)
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48284712
has comment: http://stackoverflow.com/comment/83553238
has answer: http://stackoverflow.com/a/48284712
has comment: http://stackoverflow.com/comment/83553206
has comment: http://stackoverflow.com/comment/83553336
tagged with: python
tagged with: pygame
has title: Pyagame 'Return' outside function: Clock Is not defined
has comment: http://stackoverflow.com/comment/83554026

http://stackoverflow.com/a/48393773
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48246083
score: 9
has body: pytrends returns pandas.DataFrame objects, and there are a number of ways to go about indexing and selecting data. Let's take this following bit of code, for example: kw_list = ['apples', 'oranges', 'bananas'] interest_over_time_df = pytrend.interest_over_time() If you run print(interest_over_time_df) you will see something like this: apples oranges bananas isPartial date 2017-10-23 77 15 43 False 2017-10-24 77 15 46 False 2017-10-25 78 14 41 False 2017-10-26 78 14 43 False 2017-10-27 81 17 42 False 2017-10-28 91 17 39 False ... You'll see an index column date on the left, as well as the four data columns apples, oranges, bananas, and isPartial. You can ignore isPartial for now: that field lets you know if the data point is complete for that particular date. At this point you can select data by column, by columns + index, etc.: &gt;&gt;&gt; interest_over_time_df['apples'] date 2017-10-23 77 2017-10-24 77 2017-10-25 78 2017-10-26 78 2017-10-27 81 &gt;&gt;&gt; interest_over_time_df['apples']['2017-10-26'] 78 &gt;&gt;&gt; interest_over_time_df.iloc[4] # Give me row 4 apples 81 oranges 17 bananas 42 isPartial False Name: 2017-10-27 00:00:00, dtype: object &gt;&gt;&gt; interest_over_time_df.iloc[4, 0] # Give me row 4, value 0 81 You may be interested in pandas.DataFrame.loc, which selects rows by label, as opposed to pandas.DataFrame.iloc, which selects rows by integer: &gt;&gt;&gt; interest_over_time_df.loc['2017-10-26'] apples 78 oranges 14 bananas 43 isPartial False Name: 2017-10-26 00:00:00, dtype: object &gt;&gt;&gt; interest_over_time_df.loc['2017-10-26', 'apples'] 78 Hope that helps.
upvote count: 9

http://stackoverflow.com/a/48236207
answers question: http://stackoverflow.com/q/48235938
has comment: http://stackoverflow.com/comment/83455439
type: Answer
has comment: http://stackoverflow.com/comment/83455371
score: 1
has body: Like you said, the problem is that lists are mutable. The solution, then, is that you must make a copy of array instead of mutating the original. It should look something like this: (Edit: changed to reflect grovina's comment that a shallow copy is sufficient) newArray = [] def permutations(array): if array in newArray: return for i in range(len(array)): array_copy = list(array) # or array[:] or copy.copy(array); they all create copies array_copy[0], array_copy[i] = array_copy[i], array_copy[0] newArray.append(array_copy) permutations(array_copy) return newArray Since you're modifying newArray (which is mutable since it's a list), it's also not necessary to return it at the end of the function, but that's up to you.
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83571180
has text: Possible duplicate of [How to do relative imports in Python?](https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python)
score: 0
comment on: http://stackoverflow.com/q/48292196
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48191295
downvote count: 0
has comment: http://stackoverflow.com/comment/83366743
has body: How is it possible to extract the n-th digit of a number in Sagemath? We have to compute the 13787th digit from pi + e in Sagemath. My approach was the following: sage: xi = e + pi ....: var1 = xi.n(digits=13786+1) ....: var2 = xi.n(digits=13787+1) ....: var3 = ((var2-var1) * 10^13787).trunc() ....: var3 0 Which gave me 0 back, however it should be 9.
favorite count: 0
type: Question
tagged with: math
tagged with: python
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/48193364
tagged with: sage
has title: Extract the n-th digit of a number in Sagemath
upvote count: 2
has answer: http://stackoverflow.com/a/48193364
answer count: 1

http://stackoverflow.com/a/48192069
has body: I think you need pd.Timedelta or dt.days: records['old'] = abs(today - pd.to_datetime(records['date'])) &gt; pd.Timedelta(180, unit='d') Or: records['old'] = abs(today - pd.to_datetime(records['date'])).dt.days &gt; 180 Sample: rng = pd.date_range('2017-12-30', periods=10) records = pd.DataFrame({'date': rng, 'a': range(10)}) today = pd.datetime.now() records['old'] = abs(today - pd.to_datetime(records['date'])) &gt; pd.Timedelta(5, unit='d') print (records) a date old 0 0 2017-12-30 True 1 1 2017-12-31 True 2 2 2018-01-01 True 3 3 2018-01-02 True 4 4 2018-01-03 True 5 5 2018-01-04 True 6 6 2018-01-05 True 7 7 2018-01-06 False 8 8 2018-01-07 False 9 9 2018-01-08 False
accepted answer of: http://stackoverflow.com/q/48192039
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48192039
score: 1
type: Answer

http://stackoverflow.com/q/48195979
tagged with: word-embedding
tagged with: python
type: AnsweredQuestion
score: 0
has title: Tensorflow, compare an indexed value in a tensor with an integer for if condition
answer count: 1
has body: I am using TensorFlow to do a customized embedding training similar to continuous bag of words (CBOW) model. However, unlike 'CBOW', which has a fixed length sliding window, my sliding window can be considered as flexible. Here is the problem: Let's say, the embedding is word embedding. For word t, I have a tensor showing indexes of its context words: [-1, 1, 2, -1]. The maximum window size is 4, so the length of the vector is 4. But sometimes I do not have 4 context words for a word, so I use '-1' to mean 'no word in this position', and other integers are the index of a word. I also have an 'embedding' tensor, which is the embeddings for all the words. What I am trying to do is to get the average embedding for the context words in order to represent the context. For example, if the context words are [-1, 1, 2, -1], I would get (1 * (embedding for word 1) + 2 * (embedding for word 2) ) / 2. I just need to neglect all the -1. So in my code, I try to loop through the context word tensor to compare each value with -1 and use an if condition to control if I would add the embedding of this context word. I tried different ways for this, but always get 'TypeError: Using a tf.Tensor as a Python bool is not allowed.' Is there a way to solve this problem? Or even better, is there a better representation of positions with no words so I can compute more efficiently (Tried to use NaN but also get a lot of troubles...)? Thanks a lot for the help and hopefully I have a clear description of the problem.
linked to: http://stackoverflow.com/q/33633370
upvote count: 1
downvote count: 1
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/48216791
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48216791

http://stackoverflow.com/comment/83647305
has text: The buttons are resizing perfectly what is the problem?
score: 0
comment on: http://stackoverflow.com/q/48330657
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48206064
accepted answer of: http://stackoverflow.com/q/48205972
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48205972
has comment: http://stackoverflow.com/comment/83402184
type: Answer
has comment: http://stackoverflow.com/comment/83395756
has body: This would be the correct list comprehension: [[float(c) for c in row] for row in data] Please note that I have changed int(...) to float(...) to handle the floating numbers in your input. This gives as output: [[1.0, -160.0], [2.0, -3000.0], [4.0, -2.0], [5.0, 0.27]] As per your comment, if you have letters in your list, you can also add an if statement to your list comprehension: [[float(c) if c.lstrip('-').isdigit() else c for c in row] for row in data ]
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83401960
downvote count: 0

http://stackoverflow.com/q/48311628
has answer: http://stackoverflow.com/a/48311954
tagged with: python
has comment: http://stackoverflow.com/comment/83609213
has body: I have a list of dictionaries: [ { '_item_id1':'0002', '_ticket_quantity1':1, '_showtime_id':5635775 }, { '_item_id2':'0001', '_ticket_quantity2':1, '_showtime_id':5635775 } ] I want to do json.dumps() in this format: data = json.dumps({ 'ticketTypes': [{ 'showtimeId': showtime_id, 'id': item_id1, 'quantity': ticket_quantity1 }, { 'showtimeId': showtime_id, 'id': item_id2, 'quantity': ticket_quantity2 }] })
tagged with: python-2.7
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/83609166
has comment: http://stackoverflow.com/comment/83609115
tagged with: http://stackoverflow.com/tag/json
downvote count: 3
has comment: http://stackoverflow.com/comment/83609219
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83611194
has comment: http://stackoverflow.com/comment/83609121
has answer: http://stackoverflow.com/a/48312062
has title: json.dump() in a custom format?
type: UnansweredQuestion
score: -3

http://stackoverflow.com/comment/83614454
type: AnswerComment
type: Comment
has text: if you want to check the value each time the click is trigerred, then you need to do it by ajax, which needs to be called on every click
score: 0
comment on: http://stackoverflow.com/a/48314203

http://stackoverflow.com/comment/83359081
type: Comment
type: QuestionComment
has text: Since you are not using the dictionary value, why not use a `set`?
score: 2
comment on: http://stackoverflow.com/q/48189414

http://stackoverflow.com/q/48189278
has answer: http://stackoverflow.com/a/48189643
has comment: http://stackoverflow.com/comment/83358547
has comment: http://stackoverflow.com/comment/83359348
type: Question
upvote count: 4
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83359561
has body: I have an ASCII file that is essentially a grid of 16-bit signed integers; the file size on disk is approximately 300MB. I do not need to read the file into memory, but do need to store its contents as a single container (of containers), so for initial testing on memory use I tried list and tuples as inner containers with the outer container always as a list via list comprehension: with open(file, 'r') as f: for _ in range(6): t = next(f) # skipping some header lines # Method 1 grid = [line.strip().split() for line in f] # produces a 3.3GB container # Method 2 (on another run) grid = [tuple(line.strip().split()) for line in f] # produces a 3.7GB container After discussing use of the grid amongst the team, I need to keep it as a list of lists up until a certain point at which time I will then convert it to a list of tuples for program execution. What I am curious about is how a 300MB file can have its lines stored in a container of containers and have its overall size be 10x the original raw file size. Does each container really occupy that much memory space for holding a single line each?
has comment: http://stackoverflow.com/comment/83358598
has comment: http://stackoverflow.com/comment/83358841
has comment: http://stackoverflow.com/comment/83358565
has comment: http://stackoverflow.com/comment/83359439
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83358894
has comment: http://stackoverflow.com/comment/83358986
tagged with: python
has comment: http://stackoverflow.com/comment/83358943
has comment: http://stackoverflow.com/comment/83359240
score: 4
has comment: http://stackoverflow.com/comment/83359292
has comment: http://stackoverflow.com/comment/83358458
favorite count: 0
linked to: http://stackoverflow.com/q/519633
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48189643
has comment: http://stackoverflow.com/comment/83359005
has comment: http://stackoverflow.com/comment/83358755
has title: Storing file in lists uses 10x memory as file size

http://stackoverflow.com/q/48266801
has answer: http://stackoverflow.com/a/48267777
tagged with: pyqt
answer count: 1
has title: How to get value by clicking on the qslider?
type: Question
has comment: http://stackoverflow.com/comment/83518094
type: UnansweredQuestion
has body: So i am using Pyqt for creating GUI program using Python programming language. And i am trying to get the value of Qslider when clicking it, but i don't understand how... self.slide.mouseDoubleClickEvent= lambda event: self.slideclicked() This is how i declare the method when the slide is clicked, and this is the method : def slideclicked(self): print(self.slide.value()) I am hoping to get the value where the mouse clicked, but instead i am just getting current value of the Qslider.
tagged with: python
tagged with: qslider
score: 0

http://stackoverflow.com/q/48270122
has body: For a long time I can not find the right way. I always get a mistake. I have already tried all the paths listed below. os.path.abspath sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(".")))) sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.insert(0, os.path.dirname(os.path.abspath('.'))) sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0, os.path.abspath('..')) Here is the ReadTheDocs error output Running Sphinx v1.6.5 making output directory... Traceback (most recent call last): File "/home/docs/checkouts/readthedocs.org/user_builds/kh-taskbuster/envs/latest/local/lib/python2.7/site-packages/sphinx/cmdline.py", line 305, in main opts.warningiserror, opts.tags, opts.verbosity, opts.jobs) File "/home/docs/checkouts/readthedocs.org/user_builds/kh-taskbuster/envs/latest/local/lib/python2.7/site-packages/sphinx/application.py", line 168, in __init__ confoverrides or {}, self.tags) File "/home/docs/checkouts/readthedocs.org/user_builds/kh-taskbuster/envs/latest/local/lib/python2.7/site-packages/sphinx/config.py", line 150, in __init__ execfile_(filename, config) File "/home/docs/checkouts/readthedocs.org/user_builds/kh-taskbuster/envs/latest/local/lib/python2.7/site-packages/sphinx/util/pycompat.py", line 150, in execfile_ exec_(code, _globals) File "/home/docs/checkouts/readthedocs.org/user_builds/kh-taskbuster/envs/latest/local/lib/python2.7/site-packages/six.py", line 709, in exec_ exec("""exec _code_ in _globs_, _locs_""") File "&lt;string&gt;", line 1, in &lt;module&gt; File "conf.py", line 23, in &lt;module&gt; from django.conf import settings ImportError: No module named django.conf Exception occurred: File "conf.py", line 23, in &lt;module&gt; from django.conf import settings ImportError: No module named django.conf Here is my conf.py line 1-19 only comments import os import sys sys.path.insert(0, os.path.abspath('.')) from django.conf import settings settings.configure() Here is my project three
type: AnsweredQuestion
score: 0
tagged with: read-the-docs
has answer: http://stackoverflow.com/a/49240460
type: Question
has title: Read The Docs ImportError
answer count: 1
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/49240460

http://stackoverflow.com/a/48216491
has comment: http://stackoverflow.com/comment/134308179
has comment: http://stackoverflow.com/comment/134833203
answers question: http://stackoverflow.com/q/48216473
score: 26
type: Answer
upvote count: 26
has body: Always use assertEqual(), as it customizes failure output. The method delegates to various helper methods to show you how, for example, two strings or two lists differ when the assertion fails, provided the type of both arguments match and have a type-specific helper method registered. assertTrue() can only tell you about the assertion failing, not show you why. From the assertEqual() documentation: In addition, if first and second are the exact same type and one of list, tuple, dict, set, frozenset or str or any type that a subclass registers with addTypeEqualityFunc() the type-specific equality function will be called in order to generate a more useful default error message (see also the list of type-specific methods). Only use assertTrue() if there is no more specific assertion available.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48216473
downvote count: 0

http://stackoverflow.com/q/48310132
upvote count: 7
has comment: http://stackoverflow.com/comment/83608856
tagged with: unicode
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83620480
has comment: http://stackoverflow.com/comment/83606152
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
score: 6
tagged with: python
has comment: http://stackoverflow.com/comment/83610979
downvote count: 1
has body: I am trying to query and display utf-8 encoded characters in a gui built on tkinter and thus tcl. However, I have found that tkinter cannot display 4-byte characters i.e. unicode codepoints greater than U+FFFF. Why is this the case? What limitations would implementing non-BMP characters have for tcl? I can't query non-BMP characters through my gui, but if they come up in a result I can copy/paste the character and see the character/codepoint through unicode-table.com despite my system not displaying it. So, it seems that the character is being displayed as codepoint U+FFFD but stored in the view with the correct codepoint. I am running a Python 3.6.4 script on Windows 7. Update: Here is the error I get for some context where the 4-byte unicode codepoint is out of range of BMP characters and can't be handled by Tcl File "Project/userInterface.py", line 569, in populate_tree iids.append(self.detailtree.insert('', 'end', values=entry)) File "C:\Program Files (x86)\Python36-32\Lib\tkinter\ttk.py", line 1343, in insert res = self.tk.call(self._w, "insert", parent, index, *opts) _tkinter.TclError: character U+1f624 is above the range (U+0000-U+FFFF) allowed by Tcl I handle this by using regular expressions to substitute out of range unicode characters with the replacement character. for item in entries: #handles unicode characters that are greator than 3 bytes as tkinter/tcl cannot handle/display them entry = list(item) for i, col in enumerate(entry): if col and isinstance(col, str): re_pattern = re.compile(u'[^\u0000-\uD7FF\uE000-\uFFFF]', re.UNICODE) filtered_string = re_pattern.sub(u'\uFFFD', col) #replaces \u1000 and greater with the unknow character if filtered_string != col: entry[i] = filtered_string entry = tuple(entry) iids.append(self.detailtree.insert('', 'end', values=entry))
has comment: http://stackoverflow.com/comment/83608871
has title: Why does tcl/tkinter only support BMP characters?
tagged with: tcl
tagged with: windows
has comment: http://stackoverflow.com/comment/83607608

http://stackoverflow.com/q/48237188
type: UnansweredQuestion
has title: Django URLs randomly shows ImproperlyConfigured
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83457121
has comment: http://stackoverflow.com/comment/83457000
has body: I sometimes receive an ImproperlyConfigured "The included URLconf 'app_name.urls' does not appear to have any patterns in it." on my website. When I revisit the URL that caused the error, it works fine. The error shows that "patterns" is a module in these cases. Most of the time it properly loads my URLs. Does anyone spot a problem with my URLs? This is a strange issue that occurs on both the root URL (/) and the details page (####/details). I've never seen an error for my other URLs, but they don't receive much traffic. I haven't been able to reproduce the error, but I receive it several times a day. I'm using Python 3.5.2 with Django 2.0. The codebase was original written with Django 1.6 I believe. I recently migrated to 2.0 and that is when I noticed the issue. I modified django/urls/resolvers.py to log the 'patterns' variable and most of the time I receive this list: [&lt;URLResolver &lt;URLPattern list&gt; (admin:admin) 'admin/'&gt;, &lt;URLPattern '&lt;int:pk&gt;/details' [name='details']&gt;, &lt;URLPattern 'check/' [name='check']&gt;, &lt;URLPattern 'logout/' [name='logout']&gt;, &lt;URLPattern 'search/' [name='search']&gt;, &lt;URLPattern 'features/' [name='features']&gt;, &lt;URLPattern 'terms-of-service/' [name='terms']&gt;, &lt;URLPattern 'privacy-policy/' [name='privacy']&gt;, &lt;URLPattern '' [name='index']&gt;] urls.py from django.urls import path, re_path from django.contrib import admin from app_name import views from app_name.result_view import SubmissionDetailView handler404 = 'app_name.views.not_found_view' urlpatterns = [ path('admin/', admin.site.urls), path('&lt;int:pk&gt;/details', SubmissionDetailView.as_view(), name='details'), path('check/', views.check, name='check'), path('logout/', views.logout_view, name='logout'), path('search/', views.search, name='search'), path('features/', views.features, name='features'), path('terms-of-service/', views.terms, name='terms'), path('privacy-policy/', views.privacy, name='privacy'), path('', views.…
score: 1
has comment: http://stackoverflow.com/comment/83456967
has answer: http://stackoverflow.com/a/68554729
answer count: 1
downvote count: 0
tagged with: django-urls
upvote count: 1
has comment: http://stackoverflow.com/comment/83457016
favorite count: 0
type: Question

http://stackoverflow.com/comment/83521976
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48264553
type: QuestionComment
has text: One would need to see a [mcve] of the issue to help here. Without such example, this question is not useful.

http://stackoverflow.com/a/48247281
score: -1
upvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48246777
has body: first terminating the program when it reaches end of file. open the file using open() fp=open("sample.txt","r") read the lines using for loop for l in fp: print the lines fp=open("sample.txt","r") for l in fp: print (l,end='') if you are working with python2.7 fp=open("sample.txt","r") for l in fp: print l Now we can use exception handling to terminate the input when crtl+D is pressed in stdin.here i am specifying the sample program try: str1=raw_input("Enter the String :") print "Given String :",str1 except: print "User typed ctrl+d"
downvote count: 1

http://stackoverflow.com/a/48193327
has body: Use a negative lookbehind to check that href=" doesn't precede your URL (second line): (?x) # verbose (?&lt;!href=\") #don't match already inside hrefs (https?|ftp|gopher) # make sure we find a resource type :// # ...needs to be followed by colon-slash-slash ((?:\w+[:.]?){2,}) # at least two domain groups, e.g. (gnosis.)(cx) fixed capture group* (/?| # could be just the domain name (maybe w/ slash) [^ \n\r\"]+ # or stuff then space, newline, tab, quote [\w\/]) # resource name ends in alphanumeric or slash (?=[\s\.,&gt;)'\"\]]) # assert: followed by white or clause ending https://regex101.com/r/EpcMKw/2/
score: 1
answers question: http://stackoverflow.com/q/48193118
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/83480206
comment on: http://stackoverflow.com/q/48248821
type: Comment
score: 0
has text: @Zero Yup, it is.
type: QuestionComment

http://stackoverflow.com/comment/83576486
score: 0
comment on: http://stackoverflow.com/q/48295949
type: Comment
type: QuestionComment
has text: So, have you configured `PYTHONPATH` ?

http://stackoverflow.com/comment/83489919
has text: a list or a dictionary
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48252682

http://stackoverflow.com/q/48178286
tagged with: signal-processing
type: Question
has answer: http://stackoverflow.com/a/59432148
possible better answer: http://stackoverflow.com/a/59432148
tagged with: python
tagged with: computer-vision
has answer: http://stackoverflow.com/a/48178398
has body: I am looking for a way to get the indices of the local maxima of a tensor using TensorFlow exclusively. tl;dr I am not a data scientist. I don't know much about the theory behind much of computer vision, but I am trying to build a computer vision app using TensorFlow. I plan on saving my model and calling it as a service using TF Serving, so I can't depend on external libraries such as numpy, scipy, etc. What I want to accomplish is algorithmically the same as scipy's signal.argrelextrema, but in a way that can be saved with my model and rerun. Other algorithms for this have been shown here, but none execute within TensorFlow. Can anyone point me in the right direction?
type: AnsweredQuestion
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/4624970
has answer: http://stackoverflow.com/a/48200591
accepted answer: http://stackoverflow.com/a/48200591
has title: Finding local maxima with TensorFlow
tagged with: data-science
tagged with: tensorflow

http://stackoverflow.com/comment/83469233
score: 0
type: AnswerComment
has text: It will really be cool if the names of the 2 dataframes could be named asides df2,df3. when I change it to other names, it doesn't work. Any idea?
type: Comment
comment on: http://stackoverflow.com/a/48214096

http://stackoverflow.com/comment/83631861
comment on: http://stackoverflow.com/a/48254324
type: Comment
type: AnswerComment
has text: That should be `DS.blit(resume_button['active_surface'], resume_button['rect'])` and `DS.blit(quit_button['active_surface'], quit_button['rect'])`.
score: 0

http://stackoverflow.com/q/48219790
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/48222163
tagged with: python
has comment: http://stackoverflow.com/comment/83424002
has title: Escape Characters That Do Not Move Cursor
has answer: http://stackoverflow.com/a/48222163
tagged with: escaping
type: AnsweredQuestion
score: 0
has body: I have a function that prints out text one character at a time. The function waits .01 seconds before printing out the next character, which give it a nice flowing feel to it. I also have it pause slightly longer for characters such as periods, commas, basically anything that would cause a break in speech if the sentence were being spoken out loud. I am trying to write an intro to my game, and I would like it to pause for 5 seconds at the end of each paragraph. My first thought was to use '\n', but that turned out disastrous due to some formatting issues (any time enter was used in the block of text it would wait 5 seconds). I tried using '\r' and '\v', but I didn't like how it moved the cursor (either at the beginning of the line, or in the middle of nowhere). I was wondering if there was an escape character that I could use that didn't move the cursor, and also didn't print anything? If not, could I make my own? Here is the code used for printing the text: def slowText(text, length): for c in text: sys.stdout.write( '%s' % c ) sys.stdout.flush() if c == '.' or c == '!' or c == '?' or c == ';' or c == ':': time.sleep(.5) elif c == ',': time.sleep(.2) elif c == '\r': time.sleep(5) else: time.sleep(length) print "\n" Thanks for the help!

http://stackoverflow.com/comment/83330787
comment on: http://stackoverflow.com/a/48175530
score: 0
has text: You are wonderful my friend. This worked beautifully. Thank you for the explanation. Much appreciated!
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48197709
type: UnansweredQuestion
tagged with: airflow
tagged with: python
has body: I'm mostly brand new to airflow. I have a two step process: Get all files that match a criteria Uncompress the files The files are half a gig compressed, and 2 - 3 gig when uncompressed. I can easily have 20+ files to process at a time, which means uncompressing all of them can run longer than just about any reasonable timeout I could use XCom to get the results of step 1, but what I'd like to do is something like this: def processFiles (reqDir, gvcfDir, matchSuffix): theFiles = getFiles (reqDir, gvcfDir, matchSuffix) for filePair in theFiles: task = PythonOperator (task_id = "Uncompress_" + os.path.basename (theFile), python_callable = expandFile, op_kwargs = {'theFile': theFile}, dag = dag) task.set_upstream (runThis) The problem is that "runThis" is the PythonOperator that called processFiles, so it has to be declared after processFiles. Is there any way to make this work? Is this the reason that XCom exists, and I should dump this approach and go with XCom?
has title: Want to create airflow tasks that are downstream of the current task
score: 1
has answer: http://stackoverflow.com/a/48254444
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/83444626
type: AnswerComment
comment on: http://stackoverflow.com/a/48230029
has text: What about putting `fun = Foo().fun` in the module?
score: 1
type: Comment

http://stackoverflow.com/a/48245516
downvote count: 0
type: AcceptedAnswer
has body: As Paul Panzer said, x @ A @ y is most readable and works as expected (requires Python 3.5+ and NumPy 1.10+). SciPy uses dot for matrix multiplication too, in their own examples on sparse matrices page. So you can use dot consistently like x.dot(A.dot(y)) or A.dot(y).dot(x) although the latter is harder to read because x is out of place. The only reason you can't use x.dot(A).dot(y) is that NumPy does not understand sparse matrices, so the dot method of x is unsuitable for multiplication by a sparse matrix. Although SciPy sparse matrices interpret x * A and A * y as matrix multiplication, I prefer to never use that option, because of the risk of wrong operation if A changes to a dense matrix for some reason. It doesn't look like this usage of * is promoted in SciPy documentation; all examples use dot.
has comment: http://stackoverflow.com/comment/83495617
accepted answer of: http://stackoverflow.com/q/48243928
has comment: http://stackoverflow.com/comment/83496159
answers question: http://stackoverflow.com/q/48243928
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/83495841
has comment: http://stackoverflow.com/comment/83495935

http://stackoverflow.com/a/49398021
type: Answer
has body: The above answer is not entirely true... There's another way! Took me forever to figure out :( Step 1: If you are/were using them, make sure that all traces of WhiteNoise and django_heroku are removed: from imports, INSTALLED_APPS, virtual environment, etc. Step 2: STATIC_URL = '/static/' STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "path/to/other/static/dir"), ] The key for me was using the proper storage engine which is set by STATICFILES_STORAGE. You don't need to set STATIC_ROOT because the root will be generated for you by the engine. More on that in the warning section here: https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-STATIC_ROOT DEBUG = False ALLOWED_HOSTS = ['127.0.0.1'] Then finally $ python manage.py collectstatic $ python manage.py runserver If this doesn't help, don't forget logging: With DEBUG=False, how can I log django exceptions to a log file This kind of helped: https://docs.djangoproject.com/en/1.11/howto/static-files/
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48276444

http://stackoverflow.com/q/48232932
upvote count: 2
score: 1
has title: Best way to find the maximum sum of multiple arrays given constraints on index
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48233304
has body: Say I have 3 sorted arrays each of length 4, and I want to choose an index from each array such that the sum of the indexes are equal to 4. How would I find the maximum possible sum without testing all possible choices? For instance I have the following arrays 1 : [0,0,0,8] 2 : [1,4,5,6] 3 : [1,5,5,5] Then the solution would be 3,0,1. Because 3 + 0 + 1 = 4 and 8 + 1 + 5 is the maximum combination where the sum of the indexes are 4. I need a solution that can be generalized to n arrays of size m where the sum of the indexes could equal anything. For instance, it could be asked that this be solved with 1000 arrays all of size 1000 where the sum of the index is 2000. If there is a python package somewhere that does this please let me know.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83448960
tagged with: python
tagged with: optimization
tagged with: pandas

c++
tags question: http://stackoverflow.com/q/48285915
tags question: http://stackoverflow.com/q/48254937
tags question: http://stackoverflow.com/q/48232857
tags question: http://stackoverflow.com/q/48265489
tags question: http://stackoverflow.com/q/48242102
tags question: http://stackoverflow.com/q/48276429
tags question: http://stackoverflow.com/q/48263108
tags question: http://stackoverflow.com/q/48308764
tags question: http://stackoverflow.com/q/48275591
tags question: http://stackoverflow.com/q/48197797
tags question: http://stackoverflow.com/q/48255243
type: Tag
tags question: http://stackoverflow.com/q/48265569
tags question: http://stackoverflow.com/q/48321513
tags question: http://stackoverflow.com/q/48212123
tags question: http://stackoverflow.com/q/48244332
tags question: http://stackoverflow.com/q/48265088
tags question: http://stackoverflow.com/q/48268550
tags question: http://stackoverflow.com/q/48199784
tags question: http://stackoverflow.com/q/48193130
tags question: http://stackoverflow.com/q/48215649
tag name: c++
tags question: http://stackoverflow.com/q/48327567
tags question: http://stackoverflow.com/q/48329092
tags question: http://stackoverflow.com/q/48191350

http://stackoverflow.com/q/48233692
type: AnsweredQuestion
score: 0
has body: I'm making a stock prices predict model, I got a 1 year historical prices as a "database". As I runned the code I got a list index out of range, tried using a row and column selection but it didn't work def get_data(IndFut): with open('IndFut.csv','r') as csvfile: csvFileReader = csv.reader(csvfile) next(csvFileReader) for row in csvFileReader: dates.append(int(row[0].split('/')[0])) prices.append(float(row[1])) Here is the data Day Close Open High Low Volume 11/01/2018 79830 78590 79845 78555 10/01/2018 78638 78850 79025 78510 57030 09/01/2018 79242 79750 79925 79100 67500 08/01/2018 79829 79730 79915 79055 57270 And the following error appears: prices.append(float(row[1])) IndexError: list index out of range How do I procced?
tagged with: python
tagged with: stock
has comment: http://stackoverflow.com/comment/83449999
type: Question
tagged with: model
has comment: http://stackoverflow.com/comment/83450024
has answer: http://stackoverflow.com/a/48234086
possible better answer: http://stackoverflow.com/a/48234086
answer count: 2
has comment: http://stackoverflow.com/comment/83450180
has comment: http://stackoverflow.com/comment/83450082
has answer: http://stackoverflow.com/a/48233889
accepted answer: http://stackoverflow.com/a/48233889
has comment: http://stackoverflow.com/comment/83450606
has comment: http://stackoverflow.com/comment/83449862
has title: Index out of range python stock analysis
has comment: http://stackoverflow.com/comment/83450471
has comment: http://stackoverflow.com/comment/83449988

http://stackoverflow.com/comment/83595701
type: AnswerComment
comment on: http://stackoverflow.com/a/48305091
has text: I am not agree with you, there are some function that are very general. Some filter as Gauss or Sobel and simple thresholding functions are easy to migrate with different parameters.
type: Comment
score: 0

http://stackoverflow.com/q/48246346
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: Can't run App Engine locally with BigQuery
tagged with: google-app-engine
tagged with: python
has body: When I import BigQuery: from google.cloud import bigquery I get the following error: Traceback (most recent call last): File "/Users/manuelgodoy/Projects/Klein/src/application/storage/bigquery_models.py", line 6, in &lt;module&gt; from google.cloud import bigquery File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/google/cloud/bigquery/__init__.py", line 32, in &lt;module&gt; __version__ = get_distribution('google-cloud-bigquery').version File "/Users/manuelgodoy/Projects/google-cloud-sdk/platform/google_appengine/lib/setuptools-0.6c11/pkg_resources.py", line 311, in get_distribution if isinstance(dist,Requirement): dist = get_provider(dist) File "/Users/manuelgodoy/Projects/google-cloud-sdk/platform/google_appengine/lib/setuptools-0.6c11/pkg_resources.py", line 197, in get_provider return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0] File "/Users/manuelgodoy/Projects/google-cloud-sdk/platform/google_appengine/lib/setuptools-0.6c11/pkg_resources.py", line 666, in require needed = self.resolve(parse_requirements(requirements)) File "/Users/manuelgodoy/Projects/google-cloud-sdk/platform/google_appengine/lib/setuptools-0.6c11/pkg_resources.py", line 565, in resolve raise DistributionNotFound(req) # XXX put more info here DistributionNotFound: google-cloud-bigquery Does any one know how to solve this problem? I installed the library exactly as Google documentation suggests: pip install --upgrade google-cloud-bigquery
tagged with: google-bigquery
has comment: http://stackoverflow.com/comment/83478337
answer count: 0

http://stackoverflow.com/a/48315254
upvote count: 6
has comment: http://stackoverflow.com/comment/83615974
answers question: http://stackoverflow.com/q/48314971
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/104740652
type: Answer
has body: I'm going to borrow from a recent answer of mine. This technique is a general purpose strategy for updating a dataframe in place: df.update( df.loc[df['conlumn_a'] == 'apple', 'conlumn_b'] .replace(r'^11$', 'XXX', regex=True) ) df conlumn_a conlumn_b 0 apple 123 1 banana 11 2 apple XXX 3 orange 33 Note that all I did was remove the inplace=True and instead wrapped it in the pd.DataFrame.update method.
has comment: http://stackoverflow.com/comment/83615945

http://stackoverflow.com/comment/83721683
score: 0
type: AnswerComment
has text: First look at this photo, https://imgur.com/a/w6ya1 . These are the outcomes if you type or enter cow1 when the code is finished running. [333, 3.0, 334, 7.0, 333, 11.0, 334, 15.0, 333, 10.0, 334, 5.0, 333, 9.0, 334, 13.0, 333, 17.0, 334, 3.0, 333, 7.0, 334, 11.0, 333, 15.0, 334, 10.0]
comment on: http://stackoverflow.com/a/48315596
type: Comment

http://stackoverflow.com/comment/83480137
type: Comment
has text: Both answers are perfect, which to accept :-(
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48248836

http://stackoverflow.com/a/48273584
type: Answer
has comment: http://stackoverflow.com/comment/83571754
has body: You can try this. df2['Updated']=np.where((df2.Class=='B')&amp;(df2.Flag=='Y'),'N',np.where((df2.Class=='R')&amp;(df2.Flag=='N'),'Y',df2.Flag)) df1.Flag=df1['Tracking_Nbr'].map(df2.set_index('Tracking_Nbr').Updated) df1 Out[594]: Tracking_Nbr Flag 0 770310517324 N 1 787757679168 N 2 770320639804 N 3 787819140020 N 4 787806525476 N 5 787817272220 Y 6 787787101424 Y
accepted answer of: http://stackoverflow.com/q/48273391
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48273391
upvote count: 1
has comment: http://stackoverflow.com/comment/83571674
score: 1

http://stackoverflow.com/comment/83560344
has text: I have a .txt file along with my transfer.py file in the same directory. I need the .txt file to get some output from the transfer.py file. Do u think I need to schedule the .txt file as well like I did to the .py file? or the command as I mentioned above needs to be changed for this? @BenjaminW
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48287185
score: 0

http://stackoverflow.com/a/48242016
accepted answer of: http://stackoverflow.com/q/48241909
has body: Generic case : Keeping largest or smallest n elements along an axis Basically two steps would be involved : Get those n indices to be kept along the specified axis with np.argparition. Initialize a zeros array and use those earlier obtained indices with advanced-indexing to select from the input array as well as assign into the zeros array. Let's try to solve for a generic problem that works to select n elements along the specified axis and also be able to keep largest n as well as smallest n elements. The implementation would look like this - def keep(ar, n, axis=-1, order='largest'): axis = np.core.multiarray.normalize_axis_index(axis, ar.ndim) slice_l = [slice(None, None, None)]*ar.ndim if order=='largest': slice_l[axis] = slice(-n,None,None) idx = np.argpartition(ar, kth=-n, axis=axis)[slice_l] elif order=='smallest': slice_l[axis] = slice(None,n,None) idx = np.argpartition(ar, kth=n, axis=axis)[slice_l] else: raise Exception('Invalid order value') grid = np.ogrid[tuple(map(slice, ar.shape))] grid[axis] = idx out = np.zeros_like(ar) out[grid] = ar[grid] return out Sample runs Input array : In [208]: np.random.seed(0) ...: I = np.random.randint(11,99,(2,2,6)) In [209]: I Out[209]: array([[[55, 58, 75, 78, 78, 20], [94, 32, 47, 98, 81, 23]], [[69, 76, 50, 98, 57, 92], [48, 36, 88, 83, 20, 31]]]) Keep largest 2 elements along last axis : In [210]: keep(I, n=2, axis=-1, order='largest') Out[210]: array([[[ 0, 0, 0, 78, 78, 0], [94, 0, 0, 98, 0, 0]], [[ 0, 0, 0, 98, 0, 92], [ 0, 0, 88, 83, 0, 0]]]) Keep largest 1 element along first axis : In [211]: keep(I, n=1, axis=1, order='largest') Out[211]: array([[[ 0, 58, 75, 0, 0, 0], [94, 0, 0, 98, 81, 23]], [[69, 76, 0, 98, 57, 92], [ 0, 0, 88, 0, 0, 0]]]) Keep smallest 2 elements along last axis : In [212]: keep(I, n=2, axis=-1, order='smallest') Out[212]: array([[[55, 0, 0, 0, 0, 20], [ 0, 32, 0, 0, 0, 23]], [[ 0, 0, 50, 0, 57, 0], [ 0, 0, 0, 0, 20, 31]]])
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48241909
has comment: http://stackoverflow.com/comment/83466552
has comment: http://stackoverflow.com/comment/83466624
has comment: http://stackoverflow.com/comment/83466575
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83466612
upvote count: 1

http://stackoverflow.com/q/48326721
answer count: 2
tagged with: mocking
type: UnansweredQuestion
has title: Python Mock class import error
tagged with: elasticsearch
tagged with: python
has answer: http://stackoverflow.com/a/53872577
score: 0
has body: I'm trying to mock elasticsearch.Elasticsearch.indices.exists function in my Python test case, but I'm getting the following import error. However, mock just elasticsearch.Elasticsearch was working fine. @ddt class TestElasticSearchConnector(unittest.TestCase): @patch('elasticsearch.Elasticsearch.indices.exists') @patch('connectors.elastic_search_connector.ElasticSearchConnector._get_local_conn') def test_check_index(self, mock_es, _get_local_conn): mock_es = Mock() mock_es._index_exists = False mock_es.indices.exists.return_value = True mock_es.create.return_value = {'result': 'created'} Getting the mock import error here ====================================================================== ERROR: test_check_index (tests.base.TestESConnector) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1197, in _dot_lookup return getattr(thing, comp) AttributeError: type object 'Elasticsearch' has no attribute 'indices' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1297, in patched arg = patching.__enter__() File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1353, in __enter__ self.target = self.getter() File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1523, in &lt;lambda&gt; getter = lambda: _importer(target) File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1210, in _importer thing = _dot_lookup(thing, comp, import_path) File "/Users/user/.virtualenvs/my-prjlib/python3.6/site-packages/mock/mock.py", line 1199, in _dot_lookup __import__(import_path) ModuleNotFoundError: No module named 'elasticsearch.Elasticsearch' ---------------------------------------------------------------------- Ran 1 te…
type: Question
has answer: http://stackoverflow.com/a/55473751

http://stackoverflow.com/a/48323185
has body: It's not the Flask.route function that receives the decorated function, but the one called decorator. That's how you can give the routing rules to the decorator with an extra function call. If you look closely, you will see that your example of "a typical decorator" is broken in multiple places, thus is a wrong example to compare with. After fixing the compilation errors it gives the following runtime error: def decorator(func): def wrapper(): x = func() return x return wrapper @decorator() def balabala(): pass ... TypeError: decorator() missing 1 required positional argument: 'func' This is because you call it without an argument. A decorator defined this way is not meant to be used with parentheses, the right way would be: @decorator # no brackets here def balabala(): pass
answers question: http://stackoverflow.com/q/48322982
score: 0
type: Answer

http://stackoverflow.com/q/48208222
has answer: http://stackoverflow.com/a/48209153
favorite count: 0
type: Question
has title: setting axis scale in matplotlib contour plot
has comment: http://stackoverflow.com/comment/83406298
has comment: http://stackoverflow.com/comment/83397426
tagged with: contour
has body: I'm generating a contour plot in matplotlib based on output from an FEM program which gives nodal coordinates and their corresponding state parameters as follows: x = [x1,x2,x3,...,xn] y = [y1,y2,y3,...,yn] z = [z1,z2,z3,...,zn] Where z is a list. The contour plot is generated as follows import matplotlib.pyplot as plt import numpy as np import matplotlib.mlab as ml #paste data extraction routine here to generate list for x, y and z xi = np.linspace(min(x),max(x),len(x)) yi = np.linspace(min(y), max(y), len(y)) zi = ml.griddata(x,y,z,xi,yi, interp = 'linear') plt.figure() contourplot = plt.contourf(xi,yi,zi, cmap=plt.cm.bone, origin='lower') cbar = plt.colorbar(contourplot) plt.axis('equal') plt.show() The contour plot I'm getting depends on the second to last line plt.axis('equal') If I include the line I get this: If I don't include the line I get this: The figure depicts deformation in a soil layer and I'd like to make sure that it plots to scale, and that I can control the resulting size of the image. The first figure is to scale (i.e the axes are in the same scale) but its not taking up the entire figure as can be seen. The second figure is not to scale, but it takes up the whole figure. I'd like to make sure that I get a proper to-scale image. Can I control the axes in this manner? Thanks
tagged with: python
tagged with: plot
type: AnsweredQuestion
score: 0
tagged with: matplotlib
answer count: 1
accepted answer: http://stackoverflow.com/a/48209153
upvote count: 1
has comment: http://stackoverflow.com/comment/83398158
downvote count: 1

http://stackoverflow.com/comment/83597563
score: 0
has text: @Nae something like this is not working w = Label(master, addPic()) w.pack() mainloop()
type: Comment
comment on: http://stackoverflow.com/q/48306087
type: QuestionComment

http://stackoverflow.com/comment/83466552
comment on: http://stackoverflow.com/a/48242016
has text: Thanks for this. The "all_idx = ..." line in both solutions was the bit I was missing. It seems an odd syntax for me, to build an array out of 3 with commas separating them. It does work - I've just reproduced it. Please could you explain this line a little further?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48247055
linked to: http://stackoverflow.com/q/48113948
has body: This is a follow up on Security Dialogflow fulfillment thread. the answer there explore the req.headers.authorization you will find an authentication variable (concat these three things: Your dialogflow username The character ':' Your dialogflow password and encode it in base64) makes sense but in my python implementation the request headers I get is: Accept: */* Content-Type: application/json; charset=UTF-8 Content-Length: 571 Host: xxxxxxxx User-Agent: Apache-HttpClient/4.5.4 (Java/1.8.0_151) Accept-Encoding: gzip,deflate X-Forwarded-Proto: https X-Forwarded-For: xx.xxxx.xx..xx PS: I tried both V1 and V2 not sure how to take care of authorization
downvote count: 0
upvote count: 1
tagged with: basic-authentication
tagged with: python
type: AnsweredQuestion
has title: Security Dialogflow fulfillment request headers
has answer: http://stackoverflow.com/a/49776816
accepted answer: http://stackoverflow.com/a/49776816
score: 1
answer count: 1
tagged with: dialogflow-es
favorite count: 0
type: Question

http://stackoverflow.com/comment/83341667
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48180690
type: QuestionComment
has text: i'm trying to paste full error but its not posting @sid2491

http://stackoverflow.com/a/59000722
type: Answer
score: 9
downvote count: 0
type: AcceptedAnswer
has body: One year and 10 months later, I got the response by myself: use BERT embeddings in PyTorch: Phrases: I adapted PyTorch extract_features.py at https://github.com/ethanjperez/pytorch-pretrained-BERT/blob/master/examples/extract_features.py class Main: def main(self,input_file,output_file): self.input_file=input_file self.output_file=output_file self.bert_model='bert-base-multilingual-uncased' self.do_lower_case=True self.layers="-1" self.max_seq_length=128 self.batch_size=32 self.local_rank=-1 self.no_cuda=False if self.local_rank == -1 or self.no_cuda: device = torch.device("cuda" if torch.cuda.is_available() and not self.no_cuda else "cpu") n_gpu = torch.cuda.device_count() else: device = torch.device("cuda", self.local_rank) n_gpu = 1 # Initializes the distributed backend which will take care of sychronizing nodes/GPUs torch.distributed.init_process_group(backend='nccl') logger.info("device: {} n_gpu: {} distributed training: {}".format(device, n_gpu, bool(self.local_rank != -1))) layer_indexes = [int(x) for x in self.layers.split(",")] tokenizer = BertTokenizer.from_pretrained(self.bert_model, do_lower_case=self.do_lower_case) examples = read_examples(self.input_file) features = convert_examples_to_features( examples=examples, seq_length=self.max_seq_length, tokenizer=tokenizer) unique_id_to_feature = {} for feature in features: unique_id_to_feature[feature.unique_id] = feature model = BertModel.from_pretrained(self.bert_model) model.to(device) if self.local_rank != -1: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[self.local_rank], output_device=self.local_rank) elif n_gpu &gt; 1: model = torch.nn.DataParallel(model) all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long) all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long) eval_data = TensorDataset(all_input_ids, all_input_mask, all_example_index) if self.local_ran…
answers question: http://stackoverflow.com/q/48225845
upvote count: 9
accepted answer of: http://stackoverflow.com/q/48225845

http://stackoverflow.com/a/48199416
downvote count: 0
answers question: http://stackoverflow.com/q/48197987
type: Answer
has comment: http://stackoverflow.com/comment/83397668
accepted answer of: http://stackoverflow.com/q/48197987
has body: You need to instead do something like this: url = "https://coinmarketcap.com/currencies/CRYPTO/historical-data/? start=20171124&amp;end=20171130" response = urllib2.urlopen(url.replace('CRYPTO', crypto['id'])) …or to make more explicit what’s happening: url = "https://coinmarketcap.com/currencies/CRYPTO/historical-data/? start=20171124&amp;end=20171130" newurl = url.replace('CRYPTO', crypto['id']) response = urllib2.urlopen(newurl) …because as your code is now, your url.replace('CRYPTO', crypto['id']) on its own doesn’t change anything; instead it just creates a new string but never does anything with that new string. Your code’s not changing the url string, because that’s not how string.replace(…) works — and not how Python strings work. So what’s happening with your current code is that the CRYPTO substring in the URL isn’t being replaced before you call urllib2.urlopen(…) on it. Thus the results you get are from this URL: https://coinmarketcap.com/currencies/CRYPTO/historical-data/?start=20171124&amp;end=20171130
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/48234928
has comment: http://stackoverflow.com/comment/83452740
has comment: http://stackoverflow.com/comment/83452838
type: Answer
has body: sum(i[2] for i in a) Should solve that. Output: 783.289 # based on first 2 iteration given For mean(), you'll need to convert the generator back to a list first: numpy.mean([i[2] for i in a])
score: 0
answers question: http://stackoverflow.com/q/48234889

http://stackoverflow.com/q/48195079
score: 0
has body: I'm scraping a webpage that does not load any XHR request and all the content are in the page. But when i try to scrape the page with scrapy shell or spiders, i get some variables instead of text. For example look at this page: https://lastsecond.ir/tours/24588-%D8%AA%D9%88%D8%B1-%D9%85%D8%B4%D9%87%D8%AF-22-%D8%AF%DB%8C-96-%D8%A7%D8%B2-%D8%A7%D8%B5%D9%81%D9%87%D8%A7%D9%86 I try this code with scrapy shell : response.css("table a h3 img").extract() The response should be this, like it is in the html response: &lt;img src="https://lastsecond.ir/site/images/placeholder/hotel.svg" alt="Mehr Reza hotel" class="hotelpic"&gt; But i get this : ['&lt;img :src="hotel.imageUrl" class="hotelpic" :alt="hotel.name"&gt;'] And i can't scrape it.
answer count: 1
tagged with: web-scraping
tagged with: scrapy
downvote count: 1
favorite count: 0
has title: getting variables instead of text while scraping
type: Question
has answer: http://stackoverflow.com/a/48200970
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/a/48253696
has comment: http://stackoverflow.com/comment/83490374
type: Answer
has comment: http://stackoverflow.com/comment/83490547
has body: I'm not completely clear on what you are trying to accomplish. If you are trying to insert the entire list into one "cell" in the database, you'll need to convert the list to a string representation: import pickle varlist=["easy","hard","medium"] cursor_one.execute("insert into data (list) values(%s)", pickle.dumps(varlist)) conn.commit() If however, you are trying to put each entry in the list into its own row in the database, you will need to iterate through the list inserting a row for each entry: varlist=["easy","hard","medium"] for var in varlist: cursor_one.execute("insert into data (list) values(%s)", var) conn.commit()
score: 0
has comment: http://stackoverflow.com/comment/83490688
answers question: http://stackoverflow.com/q/48253264
has comment: http://stackoverflow.com/comment/83490002

http://stackoverflow.com/comment/83413697
has text: @MoinuddinQuadri What about the minus sign?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48215857

http://stackoverflow.com/q/48238411
favorite count: 0
score: 3
tagged with: matplotlib
tagged with: python
has body: I am trying to update plot every iteration. I got a great answer here and shown below: self.point, = plt.plot([],[], 'o', color='green') self.line, = plt.plot([],[], ls="-", color='red', lw=2) plt.show(block=False) self.plot_pose() def plot_pose(self): self.point.set_data(self.pose[0], self.pose[1]) self.line.set_data([self.pose[0], self.pose[0] - 0.5*np.cos(self.pose[2])], [self.pose[1], self.pose[1] + 0.5*np.sin(self.pose[2])]) plt.pause(0.0001) Unfortunately, when I run this on jupyter notebook, it doesn't update the plot, even with the %matplotlib inline. Any suggestions on how to get this to work on jupyter-notebook?
tagged with: jupyter-notebook
type: Question
linked to: http://stackoverflow.com/q/47040324
has comment: http://stackoverflow.com/comment/83463267
linked to: http://stackoverflow.com/q/35532498
linked to: http://stackoverflow.com/q/43663613
has title: how to run plt.draw/plt.pause function on jupyter-notebook to update plots
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 0
duplicate of: http://stackoverflow.com/q/43663613

http://stackoverflow.com/comment/83559979
score: 0
type: QuestionComment
has text: or just prediction = {}
type: Comment
comment on: http://stackoverflow.com/q/48287289

http://stackoverflow.com/q/48263087
tagged with: pandas
upvote count: 2
downvote count: 0
answer count: 1
has body: I would like to loop through a pandas dataframe's columns using a for loop to count the value based on the list given. My_list =[ 'apple', 'orange', 'grapes' ] I can do it with value_count() functions as given below to calculate frequency df['Fruits']. value_count() but I want to calculate using the for loop to iterate over dataframe to get count and average of the list given. My_list =[ 'apple', 'orange', 'grapes' ] Df: Fruits value apple 10 apple 20 orange 2 grapes 5 grapes 10 grapes 3 My output should be like this. Fruits count average apple 2 15 orange 1 2 grapes 3 6
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48263201
has answer: http://stackoverflow.com/a/48263201
tagged with: python
has title: How to loop through the pandas dataframe columns using for loop to count the value based on the list given
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/83451060
score: 2
comment on: http://stackoverflow.com/q/48234251
has text: Change `yield from data` to `return iter(data)`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83630529
comment on: http://stackoverflow.com/q/48322722
has text: What did you try till now?
type: Comment
score: 4
type: QuestionComment

http://stackoverflow.com/q/48205282
has comment: http://stackoverflow.com/comment/83391859
accepted answer: http://stackoverflow.com/a/48205329
upvote count: 1
has answer: http://stackoverflow.com/a/48205329
downvote count: 1
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48205430
score: 0
tagged with: list
answer count: 3
has comment: http://stackoverflow.com/comment/83394910
has answer: http://stackoverflow.com/a/48205430
has comment: http://stackoverflow.com/comment/83391636
tagged with: python
has body: I have a list of lists in python: l = [ [1,2,3], [4,5,6], [7,8,9] ] and I want to shuffle each sublist. How can I achieve this? Note, that the order of the sublists should be preserved while their content is shuffled. This is different from previous questions, such as this question, where the order is shuffled and the content preserved. I have tried the following: import random x = [ [1,2,3], [4,5,6], [7,8,9] ] random.shuffle(x) # This shuffles the order of the sublists, # not the sublists themselves. x = [ random.shuffle(sublist) for sublist in x ] # This returns None # for each sublist. print(x)
has answer: http://stackoverflow.com/a/48206199
favorite count: 0
linked to: http://stackoverflow.com/q/35214352
type: Question
has comment: http://stackoverflow.com/comment/83391694
has title: Python shuffle content of sublists of a list
tagged with: random
tagged with: nested-lists
tagged with: shuffle
has comment: http://stackoverflow.com/comment/83391764
has comment: http://stackoverflow.com/comment/83393062

http://stackoverflow.com/comment/83488026
has text: @Gixxerrider could you copy/paste the line with the error so that we see in which line and which file the error occurs.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48245528

http://stackoverflow.com/q/48266990
has body: Good afternoon, I want to change the green lines in splines here: So, I wrote this : import numpy as np import math as m import matplotlib.pyplot as plt from scipy import interpolate x=np.array([-1.51680376, -5.59528478, 3.02763056, 3.99336847, 1.16267044,2.76931318, -0.07837944, 2.16852768, -1.81093278, 1.82262034,-5.47060927, 1.49435114, -7.97536149, 1.05175547, -4.12788774,0.31526786, -4.4241668 ]) y=np.array([45,45,41.1314913,41,40.25582197,40,39.33855863,39, 38.45406219,38,37.69804062,37,37,36,36,35,35]) tck = interpolate.splrep(x, y) xnew = np.arange(min(x),max(x), 200) ynew = interpolate.splev(xnew, tck) plt.plot(x,y,'g',xnew,ynew) plt.show() I have a problem in this line: f48=interpolate.splrep(x,y) Python says there is an error on input data but I don't understand why... Thank you for help :)
answer count: 1
has answer: http://stackoverflow.com/a/48272861
type: Question
has title: Interpolation with interpolate.splrep
tagged with: python
type: UnansweredQuestion
tagged with: scipy
tagged with: interpolation
score: 0

ubuntu-16.04
tags question: http://stackoverflow.com/q/48290671
tag name: ubuntu-16.04
tags question: http://stackoverflow.com/q/48188284
tags question: http://stackoverflow.com/q/48239355
tags question: http://stackoverflow.com/q/48317314
type: Tag

postgresql-9.1
tags question: http://stackoverflow.com/q/48253150
tag name: postgresql-9.1
type: Tag

http://stackoverflow.com/comment/83496914
comment on: http://stackoverflow.com/q/48218869
type: QuestionComment
has text: Looking at your gist, I assume this means the problem is something with the alembic bulk_insert () statement. I used this, because I was adding the data as part of an alembic migration, and had the alembic table reference at hand. I'll see if I can rewrite it to use SqlAlchemy insert()s, and see if that works.
score: 0
type: Comment

http://stackoverflow.com/a/76954774
has body: Python was trying to access a pickle file that was on my OneDrive, and I was not logged into OneDrive. I logged in and the problem went away.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48288120

http://stackoverflow.com/comment/83336514
has text: Awesome, this works. I will search more about module level function, thank you
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48178100
type: Comment

http://stackoverflow.com/q/48267058
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/88690508
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83527986
has title: Using np.view() with changes to structured arrays in numpy 1.14
has answer: http://stackoverflow.com/a/48269334
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83517988
has comment: http://stackoverflow.com/comment/83528744
downvote count: 0
linked to: http://stackoverflow.com/q/5957380
tagged with: python
score: 7
answer count: 1
upvote count: 7
has body: I have a numpy structured array with a mixed dtype (i.e., floats, ints, and strings). I want to select some of the columns of the array (all of which contain only floats) and then get the sum, by column, of the rows, as a standard numpy array. The initial array takes a form comparable to: some_data = np.array([('foo', 3.5, 2.15), ('bar', 2.8, 5.3), ('baz', 1.2, 3.7)], dtype=[('col1', '&lt;U20'), ('A', '&lt;f8'), ('B', '&lt;f8')]) For this example, I'd like to take the sum of columns A and B, yielding np.array([7.5, 11.15]). With numpy ≤1.13, I could do that as follows: get_cols = ['A', 'B'] desired_sum = np.sum(some_data[get_cols].view(('&lt;f8', len(get_cols))), axis=0) With the release of numpy 1.14, this method now fails with ValueError: Changing the dtype to a subarray type is only supported if the total itemsize is unchanged, which is a result of the changes made in numpy 1.14 to the handling of structured arrays. (User bbengfort commented about the FutureWarning given about this change in this answer.) In light of these changes to structured arrays, how can I obtain the desired sum from the structured array subset?
has comment: http://stackoverflow.com/comment/88580969

http://stackoverflow.com/comment/83630078
type: QuestionComment
has text: @PM2Ring pyqt for the GUI
comment on: http://stackoverflow.com/q/48322332
score: 0
type: Comment

regression
tags question: http://stackoverflow.com/q/48223192
tags question: http://stackoverflow.com/q/48290623
tags question: http://stackoverflow.com/q/48276192
tag name: regression
tags question: http://stackoverflow.com/q/48196672
tags question: http://stackoverflow.com/q/48251943
tags question: http://stackoverflow.com/q/48177707
type: Tag
tags question: http://stackoverflow.com/q/48263163
tags question: http://stackoverflow.com/q/48235420
tags question: http://stackoverflow.com/q/48188865
tags question: http://stackoverflow.com/q/48257144

http://stackoverflow.com/a/48246614
accepted answer of: http://stackoverflow.com/q/48246496
type: AcceptedAnswer
has body: Very simple: Your code is not calling any function, but just building them and leaving them alone. Just add main() right before print("completed") so the code calls that function. Note 1: Why are you reading the text file over and over again inside the loop, and why opening it manually? Auto-close it by the: with open(word_file, "r") as f: Words = f.read().splitlines() code before gen(). Note 2: What is seed doing? You defined it but haven't used it anywhere. Note 3: Please check your indentation before posting a question.
type: Answer
answers question: http://stackoverflow.com/q/48246496
score: 0

http://stackoverflow.com/q/48183231
type: Question
upvote count: 0
linked to: http://stackoverflow.com/q/42459939
type: UnansweredQuestion
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83347226
tagged with: scikit-learn
tagged with: python
has body: I entered the following code: import sklearn import sklearn as sk import sklearn.preprocessing as skl from sklearn.preprocessing import Imputer from sk.preprocessing import Imputer from skl import Imputer The part which reads; from sklearn.preprocessing import Imputer gets executed normally. However, when I run from sk.preprocessing import Imputer, I get the following error: from sk.preprocessing import Imputer Traceback (most recent call last):` File "&lt;ipython-input-84-fc12144914d1&gt;", line 1, in &lt;module&gt;` from sk.preprocessing import Imputer` ModuleNotFoundError: No module named 'sk'` And from skl import Imputer yields the following: from skl import Imputer` Traceback (most recent call last):` File "&lt;ipython-input-85-1e925587d122&gt;", line 1, in &lt;module&gt;` from skl import Imputer` ModuleNotFoundError: No module named 'skl'` Why am I not able to create a shortcut for the Library?
favorite count: 0
has answer: http://stackoverflow.com/a/48183361
score: -1
has title: Not able to create shortcut for sklearn
has comment: http://stackoverflow.com/comment/83347431

http://stackoverflow.com/comment/83333570
score: 0
has text: you're right, i can just raise the original exception.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48176618

http://stackoverflow.com/comment/83504147
type: AnswerComment
comment on: http://stackoverflow.com/a/48260074
has text: Yeah i've done the list by myself :) this is the one: types = ["A320","A520","B550H","B2710","G388","G389","G390","G800","G870","G900","G901","G903","G930", "G935","G950","G955","I9295","N950","R360","R365","R600","R720","R732","R760","R770","S7710"]
score: 0
type: Comment

http://stackoverflow.com/comment/83382543
has text: ... and when you want them handled. But pls not with a blank `except`, specify what you error you intend to catch.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48200761
score: 0

http://stackoverflow.com/a/48310418
type: Answer
has comment: http://stackoverflow.com/comment/83607289
has comment: http://stackoverflow.com/comment/83607075
has comment: http://stackoverflow.com/comment/83611113
answers question: http://stackoverflow.com/q/48307183
has comment: http://stackoverflow.com/comment/83609444
score: 0
has comment: http://stackoverflow.com/comment/83608975
has comment: http://stackoverflow.com/comment/83609960
has body: Your algorithm (once the if/for mixup is fixed) still doesn't work because subtraction is not commutative. The algorithm only effectively checks x,y pairs where x comes later in the array than y. That's OK when it's testing x+y = target, since it doesn't matter which order the two values are in. But for x-y = target, the order does matter, since x - y is not the same thing as y - x. A fix for this would be to check each number in the array to see if it could be either x or y with the other value being one of the earlier values from arr. There needs to be a different check for each, so you probably need two if statements inside the loop: seen = set() for n in arr: if n-target in seen: x = n y = n-target return [x,y] if n+target in seen: x = n+target y = n return [x,y] seen.add(x) Note that I renamed the loop variable to n, since it could be either x or y depending on how the math worked out. It's not strictly necessary to use x and y variables in the bodies of the if statements, you could do those computations directly in the return statement. I also dropped the unneeded enumerate call, since the single-loop versions of the code don't use i at all.
has comment: http://stackoverflow.com/comment/83611423

http://stackoverflow.com/comment/83357259
comment on: http://stackoverflow.com/a/48188419
type: Comment
score: 0
type: AnswerComment
has text: It seems that it does not have windows version available

http://stackoverflow.com/q/48323850
tagged with: function
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/48324071
has title: Iterating over a list of strings for operations in Python
accepted answer: http://stackoverflow.com/a/48324071
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: loops
tagged with: string
favorite count: 0
tagged with: python-3.x
has body: I'm trying to do a rather simple loop in Python 3.6.1 that involves a list of strings. Essentially, I have a dataframe that looks like this: X_out Y_out Z_in X_in Y_in Z_in Year 1969 4 3 4 4 3 3 1970 2 0 1 3 2 2 1971 3 1 1 0 1 2 1972 2 0 0 3 1 0 and I'd like to find the net change of X, Y, and Z, making them new columns in this dataframe. In its simplest form, this could be df['x_net'] = df['x_in'] - df['x_out'] df['y_net'] = df['y_in'] - df['y_out'] df['z_net'] = df['z_in'] - df['z_out'] but in actuality, there are about fifteen columns that need to be created in this way. Since it'll be a bear, I figure it's best to put in a function, or at least a loop. I made a list of our initial "root" variables, without the suffixes that looks like this: root_vars = ['x', 'y', 'z'] And I think that my code might(?) look something like: for i in root_vars: df['%s_net'] = df['%s_in'] - df['%s_out'] %(root_vars_[i]) but that's definitely not right. Could someone give me a hand on this one please? Thank you so much!
type: Question
upvote count: 2

http://stackoverflow.com/comment/83397297
has text: If `time` might be different and cant be used, why do you include it in your question ?
score: 0
comment on: http://stackoverflow.com/q/48208193
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48234092
has comment: http://stackoverflow.com/comment/83451726
accepted answer: http://stackoverflow.com/a/48234867
has comment: http://stackoverflow.com/comment/83452250
has answer: http://stackoverflow.com/a/48234867
has comment: http://stackoverflow.com/comment/83451628
tagged with: dataframe
tagged with: python
tagged with: namedtuple
has comment: http://stackoverflow.com/comment/83450923
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/83451645
has title: Python - Access one part of a named tuple inside a two-dimensional list
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83451823
has body: In Python, I have row data that I'm trying to set to a pandas data frame. However the cell data is a named tuple so my output data contains: Cell(r=1,c=2,v='value'). All I want is the v from the named tuple. How would I go about setting my dataframe with only the cell value. This is what I use to set the rows to the dataframe: df = pandas.DataFrame(data=cells) Named tuple and example code below: import collections Cell = collections.namedtuple('Cell',['r','c','v']) cells = [[Cell(1,3,5),Cell(6,233,22)],[Cell(6,88,22),Cell(6454,2344443,34)]] Desired result: 5 22 22 34
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83451525

http://stackoverflow.com/comment/83491454
has text: Wherever you find the old DLL. But it might be possible that your Python has the SQLite compiled into its own executable.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48251032
type: QuestionComment

http://stackoverflow.com/a/48254358
answers question: http://stackoverflow.com/q/48253823
upvote count: 6
has comment: http://stackoverflow.com/comment/83502939
has body: The marked solution might solve the problem. However, in my opinion it doesn't really add more functionality than you can already achieve. If you truly want to make Pyglet into a class, you actually gotta inherit something, or make use of the possibility of programming in a OOP way i recon. Here's my two cents: import pyglet from pyglet.gl import * from collections import OrderedDict from time import time key = pyglet.window.key class main(pyglet.window.Window): def __init__ (self, width=1024, height=576, caption="Pokémon Life and Death: Esploratori del proprio Destino", fps=True, *args, **kwargs): super(main, self).__init__(width, height, *args, **kwargs) platform = pyglet.window.get_platform() display = platform.get_default_display() screen = display.get_default_screen() self.xDisplay = int(screen.width / 2 - self.width / 2) self.yDisplay = int(screen.height / 2 - self.height / 2) self.set_location(self.xDisplay, self.yDisplay) self.sprites = OrderedDict() if fps: self.sprites['fps_label'] = pyglet.text.Label('0 fps', x=10, y=10) self.last_update = time() self.fps_count = 0 self.keys = OrderedDict() self.mouse_x = 0 self.mouse_y = 0 self.alive = 1 def on_draw(self): self.render() def on_close(self): self.alive = 0 def on_mouse_motion(self, x, y, dx, dy): self.mouse_x = x self.mouse_y = y def on_mouse_release(self, x, y, button, modifiers): print('Released mouse at {}x{}'.format(x, y)) def on_mouse_press(self, x, y, button, modifiers): if button == 1: print('Pressed mouse at {}x{}'.format(x, y)) def on_mouse_drag(self, x, y, dx, dy, button, modifiers): self.drag = True print('Dragging mouse at {}x{}'.format(x, y)) def on_key_release(self, symbol, modifiers): try: del self.keys[symbol] except: pass def on_key_press(self, symbol, modifiers): if symbol == key.ESCAPE: # [ESC] self.alive = 0 self.keys[symbol] = True def pre_render(self): pass def render(self): self.clear() # FPS stuff (if you want to) self.fps_count += 1 if time() - self.last_update &gt; 1: # 1 sec pass…
downvote count: 0
type: Answer
score: 6

http://stackoverflow.com/comment/83539212
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48265569
score: 0
has text: My code is similar to yours. You should show the values for `destUpLeftX, destUpLeftY, width, height, srcUpLeftX, srcUpLeftY`

http://stackoverflow.com/comment/83564816
has text: Lev-san thank you for your comments !! I will learn English more to be able to find out duplicate post. this time i couldn't find it..... Again, Thank you very much!!
comment on: http://stackoverflow.com/q/48271675
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83610606
type: Comment
comment on: http://stackoverflow.com/a/48296179
type: AnswerComment
has text: If I create a new django project with pycharm, pycharm will work perfectly, but if I open the project I copied from my computer there will be a django not found prompt, I think it is a configuration error, how can I solve
score: 1

http://stackoverflow.com/comment/83618670
score: 0
type: Comment
has text: You can add `.rename(columns={0:'zero', 1:'one'})`
type: AnswerComment
comment on: http://stackoverflow.com/a/48316452

http://stackoverflow.com/a/48270730
type: Answer
accepted answer of: http://stackoverflow.com/q/48267483
has comment: http://stackoverflow.com/comment/83525273
has comment: http://stackoverflow.com/comment/83525515
upvote count: 2
has body: strftime is going to return an object by default. The other two columns whose dtypes are timedelta are that way because you said to fill the blanks with pd.NaT. Use np.NaN instead like this: df[nt].applymap(lambda x : x.strftime('%I:%M:%S %p') if pd.notnull(x) else np.NaN) df[nt].applymap(lambda x : x.strftime('%I:%M:%S %p') if pd.notnull(x) else np.NaN).dtypes
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48267483
score: 2

http://stackoverflow.com/a/48324930
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48323556
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48323556
type: Answer
has body: Your image isn't P2 (ASCII greyscale), it is P5 (Binary Greyscale). If you want to convert it to P2, you can use ImageMagick which is installed on most Linux distort and is available for macOS and Windows. convert YourP5Image.pgm -compress none ActualP2Image.pgm Or, find the Python way of reading binary NetPBM images. It is 16-bit, by the way.

http://stackoverflow.com/q/48295381
has body: I have list: print (L) [('bar', 'one'), ('bar', 'two'), ('baz', 'one'), ('baz', 'two'), ('foo', 'one'), ('qux', 'one'), ('qux', 'two'), ('oof', 'two'), ('oof', 'one'), ('oof', 'three')] I want grouping by first element in tuples and filter all tuples which contains one and two as second element. So need filter out ('oof', 'two') and ('foo', 'one') because only one element for foo and 3 elements for oof. Expected output - for each first element bar, baz second is one and two and length is 2: print(L1) [('bar', 'one'), ('bar', 'two'), ('baz', 'one'), ('baz', 'two'), ('qux', 'one'), ('qux', 'two')] I try: L = [b in ['one','two'] for a,b in L] print (L) [True, True, True, True, True, True, True, True] What is nice/pythonic solution for it?
possible better answer: http://stackoverflow.com/a/48323162
has comment: http://stackoverflow.com/comment/83575432
tagged with: group-by
downvote count: 0
has answer: http://stackoverflow.com/a/48323162
tagged with: python
has comment: http://stackoverflow.com/comment/83575328
has answer: http://stackoverflow.com/a/48357169
type: AnsweredQuestion
score: 3
tagged with: list
has answer: http://stackoverflow.com/a/48295602
upvote count: 3
has title: Filter list of tuples
accepted answer: http://stackoverflow.com/a/48295784
has comment: http://stackoverflow.com/comment/83575374
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/48295784
type: Question
tagged with: tuples
has comment: http://stackoverflow.com/comment/83575439
has comment: http://stackoverflow.com/comment/83575415

http://stackoverflow.com/q/48257226
score: 0
linked to: http://stackoverflow.com/q/29654628
answer count: 0
has title: How to join/connect two list in python?
duplicate of: http://stackoverflow.com/q/29654628
has comment: http://stackoverflow.com/comment/83497098
type: Question
has body: I have two time-data pairs: datedat1 = numpy.array([ pandas.date_range(start=datetime.datetime(2015, 1, 29), periods=5), 0.1 * numpy.arange(5)]).T datedat2 = numpy.array([ pandas.date_range(start=datetime.datetime(2015, 1, 30), periods=7), 100 * numpy.arange(7)]).T I want to connect datedat1 and datedat2 to get one long time-data pair. So I try: (numpy.array([datedat1,datedat2])).flatten() However, the flatten() didn't work. It just returns (numpy.array([datedat1,datedat2])), a nested list. I want to get this array([[Timestamp('2015-01-29 00:00:00', freq='D'), 0.0], [Timestamp('2015-01-30 00:00:00', freq='D'), 0.1], [Timestamp('2015-01-31 00:00:00', freq='D'), 0.2], [Timestamp('2015-02-01 00:00:00', freq='D'), 0.30000000000000004], [Timestamp('2015-02-02 00:00:00', freq='D'), 0.4], [Timestamp('2015-01-30 00:00:00', freq='D'), 0], [Timestamp('2015-01-31 00:00:00', freq='D'), 100], [Timestamp('2015-02-01 00:00:00', freq='D'), 200], [Timestamp('2015-02-02 00:00:00', freq='D'), 300], [Timestamp('2015-02-03 00:00:00', freq='D'), 400], [Timestamp('2015-02-04 00:00:00', freq='D'), 500], [Timestamp('2015-02-05 00:00:00', freq='D'), 600]], dtype=object) What should I do?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83497091
tagged with: python
tagged with: flatten
tagged with: numpy

http://stackoverflow.com/comment/83339007
comment on: http://stackoverflow.com/a/48178127
type: Comment
has text: How would this be modified if I had more than one column that needed to be flattened? For example if there was a `crew` column that was similar to `cast`? I got `d = df.assign(cast=df.cast.apply(pd.io.json.loads),crew=df.crew.apply(pd.io.json.loads)).to_dict('r') ` to work; but I had issues normalizing with `df = pd.io.json.json_normalize(d, meta=['movie_id', 'title'], record_path=['cast','crew'])`
type: AnswerComment
score: 0

http://stackoverflow.com/q/48313409
has body: I'm relatively new to python. I've been trying to learn python through a hands-on approach (I learnt c/c++ through the doing the euler project). Right now I'm learning how to extract data from files. I've gotten the hang of extracting data from simple text files but I'm kinda stuck on xml files. An example of what I was trying to do. I have my call logs backed up on google drive and they're a lot (about 4000) Here is the xml file example &lt;call number="+91234567890" duration="49" date="1483514046018" type="3" presentation="1" readable_date="04-Jan-2017 12:44:06 PM" contact_name="Dad" /&gt; I want to take all the calls to my dad and display them like this number = 234567890 duration = "49" date="04-Jan-2017 12:44:06 PM" duration = "x" date="y" duration = "n" date="z" and so on like that. How do you propose I do that?
answer count: 1
has title: How do I extract specific data from xml using python?
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83612740
has answer: http://stackoverflow.com/a/48313606
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/83612748
score: 0
accepted answer: http://stackoverflow.com/a/48313606

http://stackoverflow.com/q/48242168
tagged with: python
score: -3
tagged with: optimization
tagged with: python-3.x
tagged with: python-2.7
downvote count: 4
has answer: http://stackoverflow.com/a/48242259
has body: Say I take the phrase "Please insert your answer here" and wish to repeat it many times within a program would it be significantly more efficient to print "Please insert your answer here" or to create a variable with that text to do the same function? #First option answer= input("Please insert your answer here ") #second option prepared_question= "Please insert your answer here " answer= input(prepared_question) Assuming this would be repeated many times, would there be a significantly more efficient option? Naturally, from a writer's Perspective, it is much nicer to simply re-use a variable and I question whether it takes more time.
upvote count: 1
type: UnansweredQuestion
answer count: 1
favorite count: 0
has title: Comparative efficiancy with inserting variables to simply adding text
tagged with: performance
type: Question
has comment: http://stackoverflow.com/comment/83466757

http://stackoverflow.com/a/48332344
answers question: http://stackoverflow.com/q/48330458
has body: @Marichyasana is a very good solution. I went a little overboard in answering your question and tested multiple pool sizes. The code is about 114 lines that you can use this as a base to deviate from. I'm testing multiple Pool() sizes of a list of 100,000 samples. I don't think my code is very "Pythonic" and any feedback would be great. I used this example. Results: number of processes: 3; process time is: 00:00:01 length of results list 1000 number of processes: 10; process time is: 00:00:02 length of results list 1000 number of processes: 20; process time is: 00:00:09 length of results list 1000 number of processes: 33; process time is: 00:00:04 length of results list 1000 Code: # from multiprocessing import Queue from multiprocessing import Pool from random import randint from Timer import Timer # custom timer wraper I wrote def create_list_indexes(m_int_list_len): """ this method creates as many evenly spaces segments for the list of data m_int_list_len type: int desc: length of the list of data; number of samples of data returns type: list desc: list of lists; indexes for data list list_return[x][0] -&gt; type: int; low index list_return[x][1] -&gt; type: int; high index """ # segment length int_seg_len = 100 list_return = list() # get number of segments fo the list if m_int_list_len % int_seg_len == 0: int_num_seg = int(m_int_list_len / int_seg_len) bool_zero_mod = True else: int_num_seg = int(m_int_list_len / int_seg_len) + 1 bool_zero_mod = False # create indexes of list for int_i in range(0, int_num_seg): # check for zero mod if ~bool_zero_mod and int_i == int_num_seg - 1: int_low = int_i * int_seg_len int_high = m_int_list_len else: int_low = int_i * int_seg_len int_high = int_low + int_seg_len - 1 list_return.append([int_low, int_high]) return list_return def test_pools(m_tuple_args): """ this method tests the different number of pools on a large list of data m_list_tasks type: list desc: list of tuples m_tuple_args[0] -&gt; type: int; target to search fo…
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83671311
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83663110

http://stackoverflow.com/comment/83379160
comment on: http://stackoverflow.com/q/48198834
has text: `?` is the parameter marker, not `%s`.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/48206925
has body: I'm fairly new to python. Now I wrote a python program that does A) background checks in one thread, and logs the result of it with logging to stdout. And B) also has a Lib.cmd running in a loop to give the program commands. import logging from cmd import Cmd class TPrompt(Cmd): def do_config(self): """prints the current config""" print({'loglevel': 20}) def check(): while True: logger.info('Check') sleep(1) def main(): #start thread for checking t1 = Thread(target=check) t1.setDaemon(True) t1.start() prompt = TPrompt(_conf) prompt.use_rawinput = True prompt.cmdloop('Starting prompt...') the shell output looks like this: prompt&gt; 2018-01-11 13:02:38 - INFO - Check config {'loglevel': 20} prompt&gt; 2018-01-11 13:02:39 - INFO - Check 2018-01-11 13:02:40 - INFO - Check con2018-01-11 13:02:46 - INFO - Check fig *** Unknown syntax: fig What happens is that the current command is separated by the newline in the log and not valid anymore. Using cmd.use_rawinput does not seem to help. Any other thoughts? Is there a way around? Thanks!
tagged with: logging
answer count: 0
type: UnansweredQuestion
score: 1
downvote count: 0
has title: use Lib.cmd to give commands while logging to stdout
tagged with: cmd
upvote count: 1
favorite count: 0
type: Question
tagged with: stdin
tagged with: stdout
tagged with: python

http://stackoverflow.com/comment/83425680
score: 0
has text: The reduce function in your question is incorrect. What are you trying to do here with the crime collection?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48199138

http://stackoverflow.com/q/48232567
tagged with: pandas
has comment: http://stackoverflow.com/comment/83447503
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/48232940
upvote count: 6
has answer: http://stackoverflow.com/a/48232940
has title: How to replace nan values in read_csv?
score: 5
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I'm reading a flat file with read_csv and flat file as some NaN values because of which it is changing the datatype to float instead of integer which I dont want. Is there any way to replace the NaN values with 0 in the read_csv method? I know I can do df.fillna(value=0) but my question is how can I replace these nan values in the read_csv. decop=pd.read_csv("C:\\Users\\mnk044\\Downloads\\amna_decp_part-m-00000", sep="\x01", names=clist)
type: AnsweredQuestion

http://stackoverflow.com/q/48227539
downvote count: 0
score: 1
upvote count: 1
tagged with: wireless
favorite count: 0
type: Question
tagged with: linux
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: python
has title: Wireless Card returns back to managed mode after a couple seconds | Python
has comment: http://stackoverflow.com/comment/83438624
has comment: http://stackoverflow.com/comment/83439540
answer count: 0
tagged with: scapy
has body: I am trying to put my WN722N Wireless Card in Monitor Mode while being in Python environment. I used python-wifi library as well as command-line to put the Wireless card in monitor but after sometime it comes back to its previous state with return of an OSError. This is what i am trying to do: iface = raw_input("Wireless Interface") #wlan1 in my case os.system('ip link set %s down' % iface) os.system('iwconfig %s mode monitor' % iface) os.system('ip link set %s up' % iface) In fact it does work and put my Wireless Card (wlan1) in monitor mode but for not more than 5 to 6 seconds and an error is raised in one of the threads running in the background. The code of thread is: from scapy.all import * from threading import Thread def function(pkt): if pkt.haslayer(Dot11Beacon): &lt;...snipped...&gt; sniff(iface=&lt;monitor mode interface here&gt;, prn=function) Error which raise after 5 to 6 seconds: Exception in thread Thread-3: 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 "python.py", line 113, in depDev p = sendp(pckt, iface=interface) File "/usr/lib/python2.7/dist-packages/scapy/sendrecv.py", line 278, in sendp return __gen_send(conf.L2socket(iface=iface, *args, **kargs), x, inter=inter, loop=loop, count=count, File "/usr/lib/python2.7/dist-packages/scapy/arch/linux.py", line 434, in __init__ _flush_fd(self.ins) File "/usr/lib/python2.7/dist-packages/scapy/arch/linux.py", line 312, in _flush_fd os.read(fd,MTU) OSError: [Errno 100] Network is down I also tried using python-wifi from pythonwifi.iwlibs import Wireless dev = Wireless(iface) dev.setMode("Monitor") But nothing changed

http://stackoverflow.com/comment/83377510
score: 2
type: QuestionComment
has text: I bet that somewhere, you have a variable in scope that is an `int` object called `int = 123` or whatever...
type: Comment
comment on: http://stackoverflow.com/q/48198173

http://stackoverflow.com/comment/83340310
has text: I just finished testing a similar solution that may not be better than what you have here. But I think any solution will need to handle the condition of the first row, row zero, is `True` for the `if row % 300 == 0:`.
comment on: http://stackoverflow.com/a/48180146
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48176934
tagged with: django-rest-framework
favorite count: 0
has body: My model definition looks like this: class MyModel(models.Model): tag_separator = models.CharField(max_length=1, null=True, blank=True) The tag_separator is a single character, and it can be a single space: " ". I need to select null=True in order to get it to work, but when I POST data through my REST API, it saves the tag_separator as an empty string: "tag_separator": "". Is there a simple way to stop Django from assuming that my single space string is an empty string? I am using: Django==1.11 and djangorestframework==3.7.7
type: Question
has answer: http://stackoverflow.com/a/48753168
has answer: http://stackoverflow.com/a/48177139
has title: How do you save a single space (" ") in a field in a django Model?
type: UnansweredQuestion
tagged with: django
tagged with: django-models
tagged with: python
answer count: 2
upvote count: 2
score: 2
downvote count: 0

autograd
tags question: http://stackoverflow.com/q/48242585
tags question: http://stackoverflow.com/q/48274929
type: Tag
tag name: autograd

http://stackoverflow.com/q/48317828
accepted answer: http://stackoverflow.com/a/48328220
tagged with: resize
tagged with: python
tagged with: qtableview
upvote count: 4
score: 4
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: pyqt5
has title: How to proportionally adjust column widths in a QTableView?
has answer: http://stackoverflow.com/a/64288783
possible better answer: http://stackoverflow.com/a/64288783
tagged with: multiple-columns
favorite count: 0
type: Question
has body: I want to proportionally change the column width of all columns in a QTableView widget, so that each column has the same width regardless of the data. For example, if a table has three columns, each column should always have a width of one third of the available horizontal space - and the width should be automatically updated whenever the dialog is resized by the user. So far I've only managed to resize columns to their contents, which is not what I want. Here's the code I've got so far: main.ui <?xml version="1.0" encoding="UTF-8"?> Dialog <x>0</x> <y>0</y> 624 329 0 0 Dialog true QAbstractItemView::SelectRows Populate btnPopulate <resources/> <connections/> test.py #!/usr/bin/env python # -*- coding: utf-8 -*- import sys, os from PyQt5 import uic from PyQt5.QtGui import QStandardItemModel from PyQt5.QtWidgets import QDialog, QApplication, QHeaderView class GUI(QDialog): def __init__(self): super(GUI, self).__init__() dirname = os.path.dirname(os.path.abspath(__file__)) uic.loadUi(os.path.join(dirname,'main.ui'), self) # button self.btnPopulate.clicked.connect(self.populate) # table model self.header = ['col1', 'col2', 'col3'] self.QSModel = QStandardItemModel() self.QSModel.setColumnCount(3) self.QSModel.setHorizontalHeaderLabels(self.header) # table view self.tableView.setModel(self.QSModel) self.tableView.setWordWrap(True) self.tableView.horizontalHeader().setStretchLastSection(False) def populate(self): self.longtext = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla ac tellus nunc. Phasellus imperdiet leo metus, et gravida lacus. Donec metus ligula, elementum at pellentesque pellentesque, suscipit ac nunc.''' row = self.QSModel.rowCount() for x in range(7): self.QSModel.insertRow(row) self.QSModel.setData(self.QSModel.index(row, 0), 'Lorem ipsum') self.QSModel.setData(self.QSModel.index(row, 1), self.longtext) self.QSModel.setData(self.QSModel.index(row, 2), 'Lorem ipsum') self.tableView.resizeColumnsToContents() if __name__ == '__main__': app…
has answer: http://stackoverflow.com/a/48328220

http://stackoverflow.com/comment/83483303
type: AnswerComment
has text: Like several of the proposals above, this shows how to sort on the last field of a string, but not for an arbitrary field. If Madonna is considered to be a first name without a last name, then it would be in the wrong position.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48249587

http://stackoverflow.com/q/48213509
linked to: http://stackoverflow.com/q/23294658
has answer: http://stackoverflow.com/a/48213583
answer count: 5
possible better answer: http://stackoverflow.com/a/48213583
has title: Backtracking in a while loop (python 3.x)
has answer: http://stackoverflow.com/a/48213604
tagged with: python
has comment: http://stackoverflow.com/comment/83408543
has answer: http://stackoverflow.com/a/48213920
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48213634
upvote count: 2
has comment: http://stackoverflow.com/comment/83408718
accepted answer: http://stackoverflow.com/a/48213604
downvote count: 0
has body: I'm reasonably new to Python. I wanted to know if I could use an input and ask a question like 'are you sure?', and if the answer is no to go back to the original input. I've got this so far: variable = input("Make a choice between a, b, c or d. ") while variable not in ("a","b","c","d"): variable = input("Make a correct choice. ") if variable == "a": do things if variable == "b": do other things etc etc I want to ask, after they have typed in their choice, are you sure about your choice? If they say yes, that's fine, carry on, but if they say 'no' I want to be able to go to the same input without typing the whole thing out again. Is there any way to do that?
has answer: http://stackoverflow.com/a/48213597
favorite count: 0
type: Question
tagged with: while-loop

http://stackoverflow.com/comment/83334530
score: 0
has text: use pandas to_excel function.. https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html
comment on: http://stackoverflow.com/q/48177174
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83603397
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. StackOverflow is not a coding or tutorial service.
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48308910
type: Comment

http://stackoverflow.com/q/48242371
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83468074
type: Question
has answer: http://stackoverflow.com/a/48242535
has answer: http://stackoverflow.com/a/48245047
has title: Python help needed cant seem to solve this
tagged with: python
has comment: http://stackoverflow.com/comment/83468899
score: 0
answer count: 2
has body: I'm suppose to write a code to give me the output of a value between 0 and 86400 and the current time in the 24 hour clock. However I am getting stuck when it comes to writing the formulas for the 24 hour clock and the print function. Here's the code I have written so far. total_time = float('70000') hours = int(total_time / 3600.0) minutes = int((total_time - (hours * 3600.0)) / 60.0) seconds = int(((total_time) - (hours * 3600) - (minutes * 60))) print("Enter a value between 0 and 86400", total_time) print("The current time is",hours.minutes.seconds)

http://stackoverflow.com/a/48242033
has comment: http://stackoverflow.com/comment/83489790
score: 2
has comment: http://stackoverflow.com/comment/83468126
has comment: http://stackoverflow.com/comment/84297001
answers question: http://stackoverflow.com/q/48241838
downvote count: 0
has comment: http://stackoverflow.com/comment/83466820
upvote count: 2
has comment: http://stackoverflow.com/comment/83470800
has comment: http://stackoverflow.com/comment/83466669
type: Answer
has body: Yes, you can upload the package to S3. There is a limit for that as well. It's 250 MB currently. https://docs.aws.amazon.com/lambda/latest/dg/limits.html Here's a simple command to do that. aws lambda update-function-code --function-name FuncName --zip-file fileb://path/to/zip/file --region us-west-2

http://stackoverflow.com/comment/83495997
type: QuestionComment
comment on: http://stackoverflow.com/q/48256619
has text: @JohnGordon That works for this, but turns up false positives for a lot of other random cases.
score: 1
type: Comment

http://stackoverflow.com/q/48231934
tagged with: python
has title: Django form missing fields
has body: I'm trying to get a simple form working. Oddly, other forms I wrote in this app are working fine, but this one wont show the fields. Can anyone tell me what I'm missing? Here are the files views.py: def newnote(request, record_id): if request.method == 'POST': form = NoteForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/tracker/all/') else: form = NoteForm() return render(request, 'tracker/noteform.html', {'form': form}) models.py class Note(models.Model): record = models.ForeignKey(Record, on_delete=models.CASCADE) note_text = models.CharField('Notes', max_length=2000) note_date = models.DateField('Date Entered') forms.py class NoteForm(forms.Form): class Meta: model = Note fields = ['note_text', 'note_date' ] template (noteform.html) &lt;form action="/tracker/newnote/" method="post"&gt; &lt;div id="fields"&gt; {% csrf_token %} {{ form }} &lt;input type="submit" value="Submit" /&gt; &lt;/div&gt; &lt;/form&gt; One other note, I have commented out the div id called "fields", to rule out CSS as the issue.
has comment: http://stackoverflow.com/comment/83446284
type: AnsweredQuestion
score: 0
tagged with: forms
accepted answer: http://stackoverflow.com/a/48231973
has answer: http://stackoverflow.com/a/48231973
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/83446224
tagged with: django

http://stackoverflow.com/comment/85426325
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48314533
has text: Excellent, yes I was wondering if these modules had a summary function like there is in R
type: Comment

http://stackoverflow.com/comment/83647857
has text: that depens where the other devices are located. are the in the same netwokr or on the internet? If they are on the same network you can just do the change i describe otherwise it becomes more difficult.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48330687
score: 0

http://stackoverflow.com/q/48254034
score: -2
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/48264086
accepted answer: http://stackoverflow.com/a/48264086
tagged with: python
has comment: http://stackoverflow.com/comment/83490676
possible better answer: http://stackoverflow.com/a/48254103
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83490658
has comment: http://stackoverflow.com/comment/83490649
answer count: 2
has comment: http://stackoverflow.com/comment/83490767
has title: how to find and replace in csv using python
downvote count: 3
has body: I have csv file with 900 rows and 11 columns. It contains approximately 4000 links which I want to replace with 4000 links (I have another csv file which contains both links in column 1 and 2). I am trying to automate it (find and replace) using python Here is my code but it is not working. Actually I am not getting any error but program run continuously without giving any results. I run it for 2. 3 hours and helplessly killed it. import csv def replace_all(text, dic): for i, j in dic.iteritems(): text = text.replace(i, j) return text with open('file_that_find_replace_data.csv', mode='r') as infile: reader = csv.reader(infile) d = {rows[0]:rows[1] for rows in reader} f = open('main_file.csv','r') filedata = f.read() for row in filedata: newdata = replace_all(filedata, d) f = open('main_file.csv','w') f.write(newdata) f.close() print ('done')
upvote count: 1
has comment: http://stackoverflow.com/comment/83490738
has answer: http://stackoverflow.com/a/48254103
has comment: http://stackoverflow.com/comment/83492567
favorite count: 0
type: Question
tagged with: file-read

http://stackoverflow.com/comment/83542742
score: 0
has text: what is the datatype of `unix` value?
type: QuestionComment
comment on: http://stackoverflow.com/q/48279582
type: Comment

http://stackoverflow.com/a/48201175
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48200911
has body: The anatomy of an ndarray in NumPy looks like this red cube below: (source: Physics Dept, Cornell Uni) Once you leave the 2D space and enter 3D or higher dimensional spaces, the concept of rows and columns doesn't make much sense anymore. But still you can intuitively understand 3D arrays. For instance, considering your example: In [41]: b Out[41]: array([[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [10, 11, 12]]]) In [42]: b.shape Out[42]: (2, 2, 3) Here the shape of b is (2, 2, 3). You can think about it like, we've two (2x3) matrices stacked to form a 3D array. To access the first matrix you index into the array b like b[0] and to access the second matrix, you index into the array b like b[1]. # gives you the 2D array (i.e. matrix) at position `0` In [43]: b[0] Out[43]: array([[1, 2, 3], [4, 5, 6]]) # gives you the 2D array (i.e. matrix) at position 1 In [44]: b[1] Out[44]: array([[ 7, 8, 9], [10, 11, 12]]) However, if you enter 4D space or higher, it will be very hard to make any sense out of the arrays itself since we humans have hard time visualizing 4D and more dimensions. So, one would rather just consider the ndarray.shape attribute and work with it. More information about how we build higher dimensional arrays using (nested) lists: For 1D arrays, the array constructor needs a sequence (tuple, list, etc) but conventionally list is used. In [51]: oneD = np.array([1, 2, 3,]) In [52]: oneD.shape Out[52]: (3,) For 2D arrays, it's list of lists but can also be tuple of lists or tuple of tuples etc: In [53]: twoD = np.array([[1, 2, 3], [4, 5, 6]]) In [54]: twoD.shape Out[54]: (2, 3) For 3D arrays, it's list of lists of lists: In [55]: threeD = np.array([[[1, 2, 3], [2, 3, 4]], [[5, 6, 7], [6, 7, 8]]]) In [56]: threeD.shape Out[56]: (2, 2, 3) P.S. Internally, the ndarray is stored in a memory block as shown in the below picture. (source: Enthought)
score: 31
has comment: http://stackoverflow.com/comment/83383585
answers question: http://stackoverflow.com/q/48200911
type: Answer
upvote count: 31
downvote count: 0
has comment: http://stackoverflow.com/comment/83383900
has comment: http://stackoverflow.com/comment/83385474

http://stackoverflow.com/comment/83494511
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48255660
has text: Every time you call `aiohttp.request`, you are creating a new connector and a new session which should be created only once inside a whole process. Have a look at how to use it correctly: https://docs.aiohttp.org/en/stable/client.html
score: 6

http://stackoverflow.com/a/48223832
upvote count: 2
downvote count: 0
has body: What you are after is called color quantization. Several algorihtms have been designed, such as the Median Cut or the Popularity algorithm. They allow you to build an "optimal" color table with the desired number of entries. These methods were popular in the times of expensive graphics cards, but have lost fame since the generalization of true color. Complementarily to color quantization, one often uses color dithering, a method that restores some of the smoothness of color gradients and avoids banding effects. https://nl.mathworks.com/help/images/reduce-the-number-of-colors-in-an-image.html?requestedDomain=true
score: 2
answers question: http://stackoverflow.com/q/48222977
type: Answer

http://stackoverflow.com/a/60443862
type: Answer
score: 1
has body: Another way to do this would be to use the -m venv command that comes built-in with Python 3.6 and above. Check Python version python --version Create venv and install requirements python -m venv venv source venv/bin/activate pip install -r requirements.txt Try running the wagtail command after the installation is complete.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48261062

http://stackoverflow.com/comment/83436631
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48227451
has text: There's something going wrong with the parentheses around `sum`…

http://stackoverflow.com/comment/83624698
comment on: http://stackoverflow.com/q/48319325
score: 0
has text: Yes Pedro. The source is the dictionary defined in the own code... So it looks like there's no fix for this?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48245142
score: 2
upvote count: 2
has body: Let's start with some general tricks: Check if the n-th element is too big for the list before iterating. If you also keep a "counter" that stores the number of zeros, you could even check if nth &gt;= len(the_list) - number_of_zeros (not sure if &gt;= is correct here, it seems like the example uses 1-based indices so I could be off-by-one). That way you save time whenever too big values are used. Use more efficient functions. So instead of input you could use sys.stdin.readline (note that it will include the trailing newline). And, even though it's probably not useful in this context, the built-in bisect module would be better than the binary_search function you created. You could also use for _ in itertools.repeat(None, q) instead of for i in range(q), that's a bit faster and you don't need that index. Then you can use some more specialized facts about the problem to improve the code: You only store zeros and ones, so you can use if j to check for ones and if not j to check for zeros. These will be a bit faster than manual comparisons especially in when you do that in a loop. Every time you look for the nth 1, you could create a temporary dictionary (or a list) that contains the encountered ns + index. Then re-use that dict for subsequent queries (dict-lookup and list-random-access is O(1) while your search is O(n)). You could even expand it if you have subsequent queries without change in-between. However if a change happens you either need to discard that dictionary (or list) or update it. A few nitpicks: The variable names are not very descriptive, you could use for index, item in enumerate(arr): instead of i and j. You use a list, so arr is a misleading variable name. You have two i variables. But don't get me wrong. It's a very good attempt and the fact that you use enumerate instead of a range is great and shows that you already write pythonic code.
downvote count: 0
answers question: http://stackoverflow.com/q/48244991
type: Answer

http://stackoverflow.com/q/48275038
tagged with: opencv
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83542595
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83533852
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48277603
has body: Update: It works fine now. Original: question from the exercise in the link: http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_trackbar/py_trackbar.html#trackbar I want to create a Paint application with adjustable colors and brush radius using trackbars. But when I run my code for some seconds, my python.exe shut down, it seems that there is a memory access violation but I don't know why. Thanks for your help! import cv2 import numpy as np draw = False def nothing(x): pass # use mouse to draw lines def draw_line(event,x,y,flags,param): global draw if event == cv2.EVENT_LBUTTONDOWN: draw = True elif event == cv2.EVENT_MOUSEMOVE: if draw == True: cv2.circle(img, (x,y),t,(b,g,r),-1) elif event == cv2.EVENT_LBUTTONUP: draw = False else: pass # get current positions of five trackbars def get_tar(): global r,g,b,s,t r = cv2.getTrackbarPos('R','image') g = cv2.getTrackbarPos('G','image') b = cv2.getTrackbarPos('B','image') s = cv2.getTrackbarPos(switch,'image') t = cv2.getTrackbarPos('T','image') # Create a black image, a window img = np.zeros((300,512,3),np.uint8) img[:] = 255 cv2.namedWindow('image') # create trackbars for color and thickness change cv2.createTrackbar('R','image',0,255,nothing) cv2.createTrackbar('G','image',0,255,nothing) cv2.createTrackbar('B','image',0,255,nothing) cv2.createTrackbar('T','image',0,20,nothing) # create switch for ON/OFF and reset functionality switch = '0 : OFF \n1 : ON' cv2.createTrackbar(switch, 'image',0,1,nothing) while(1): cv2.imshow('image',img) k = cv2.waitKey(100) &amp; 0xFF if k == 27: break # get current positions of five trackbars get_tar() if s == 0: img[:] = 255 draw = False else: cv2.setMouseCallback('image', draw_line) cv2.destroyAllWindows() and the error is: Process finished with exit code -1073741819 (0xC0000005) and then my python.exe shut down
has title: About the exercise in 'OpenCV-Python Tutorials - Trackbar as the Color Palette'
tagged with: python
has comment: http://stackoverflow.com/comment/83538570
tagged with: image
has answer: http://stackoverflow.com/a/55215460

anaconda
tags question: http://stackoverflow.com/q/48271869
tags question: http://stackoverflow.com/q/48200784
tags question: http://stackoverflow.com/q/48235426
type: Tag
tags question: http://stackoverflow.com/q/48311645
tags question: http://stackoverflow.com/q/48295348
tags question: http://stackoverflow.com/q/48226958
tags question: http://stackoverflow.com/q/48176087
tags question: http://stackoverflow.com/q/48234119
tags question: http://stackoverflow.com/q/48198844
tag name: anaconda
tags question: http://stackoverflow.com/q/48231593
tags question: http://stackoverflow.com/q/48282596
tags question: http://stackoverflow.com/q/48195422
tags question: http://stackoverflow.com/q/48269125
tags question: http://stackoverflow.com/q/48323378
tags question: http://stackoverflow.com/q/48191933
tags question: http://stackoverflow.com/q/48205276
tags question: http://stackoverflow.com/q/48230953
tags question: http://stackoverflow.com/q/48331023
tags question: http://stackoverflow.com/q/48188307
tags question: http://stackoverflow.com/q/48213190
tags question: http://stackoverflow.com/q/48245368
tags question: http://stackoverflow.com/q/48257321
tags question: http://stackoverflow.com/q/48195735
tags question: http://stackoverflow.com/q/48236584
tags question: http://stackoverflow.com/q/48308077
tags question: http://stackoverflow.com/q/48304305
tags question: http://stackoverflow.com/q/48273967
tags question: http://stackoverflow.com/q/48211174

http://stackoverflow.com/comment/83626426
type: Comment
type: QuestionComment
has text: Ok i will do it .
score: 0
comment on: http://stackoverflow.com/q/48265555

http://stackoverflow.com/q/48196672
upvote count: 1
tagged with: regression
answer count: 1
accepted answer: http://stackoverflow.com/a/48196716
tagged with: machine-learning
tagged with: tensorflow
favorite count: 0
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48196716
tagged with: python
has body: I'm a beginner in machine learning (ML) and can't figure out why my regression is incorrect or not plotting correctly. This is what I have currently and most is taken from previous examples of a book which I'm working with. Would be nice if somebody could also explain where the formula for the cost function comes from. import time import csv import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import tensorflow as tf import numpy as np def read_csv(filepath, bucket=7): days_in_year = 365 freq = {} for period in range(0, int(days_in_year / bucket)): freq[period] = 0 with open(filepath, 'r') as csvfile: csvreader = csv.reader(csvfile) csvreader.__next__() for row in csvreader: if row[0] == '': continue t = time.strptime(row[0], "%m/%d/%Y") if t.tm_year == 2014 and t.tm_yday &lt; (days_in_year-1): freq[int(t.tm_yday / bucket)] += 1 print("finished reading input") return freq freq = read_csv("311_data.csv") x_dataset = list(freq.keys()) y_dataset = list(freq.values()) print(x_dataset) print(y_dataset) def normalize(data): y = np.empty(len(data)) count = 0 for x in data: y[count] = (x-min(data))/(max(data)-min(data)) count += 1 return y x_dataset = normalize(x_dataset) y_dataset = normalize(y_dataset) (x_train, x_test, y_train, y_test) = train_test_split(x_dataset, y_dataset, train_size=0.7, test_size=0.3) learning_rate = 0.01 training_epochs = 40 num_coeffs = 9 reg_lambda = 0. X = tf.placeholder(tf.float32) Y = tf.placeholder(tf.float32) def model(X, w): terms = [] for i in range(num_coeffs): term = tf.multiply(w[i], tf.pow(X, i)) terms.append(term) return tf.add_n(terms) w = tf.Variable([0.] * num_coeffs, name="parameters") y_model = model(X, w) cost = tf.div(tf.add(tf.reduce_sum(tf.square(Y-y_model)), tf.multiply(reg_lambda, tf.reduce_sum(tf.square(w)))), 2*x_train.size) train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) sess = tf.Session() init = tf.global_variables_initializer() sess.run(init) for reg_lambda in…
type: Question
downvote count: 0
has title: Result for Regression not correct

http://stackoverflow.com/q/48276011
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/48802007
upvote count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48290990
tagged with: python
has title: Rendering a Tree in Python
downvote count: 1
favorite count: 0
tagged with: tree
tagged with: recursion
score: 2
has body: I had dataset like below: A B 1 2 5 3 2 5 3 Below code gives me the following output: def all_paths(table, root): # convert table structure to adjacency list children = {} for node, child in table: if child: children[node] = children.setdefault(node, []) + [child] # generator for iteration over all paths from a certain node def recurse(path): yield path if path[-1] in children: for child in children[path[-1]]: # recursive calls for all child nodes yield from recurse(path + [child]) return recurse([root]) # Sample data in simple list format table = [ [1, 2], [5, 3], [2, 5], [2, 6], [2, 4], [6, 7], ] # Output all paths from node 1 for path in all_paths(table, 1): print(path) Output: [1] [1, 2] [1, 2, 5] [1, 2, 5, 3] [1, 2, 6] [1, 2, 6, 7] [1, 2, 4] But what i want here is to print output in render tree format like below: 1 └── 2 |── 5 | └──3 |── 6 | └──7 └── 4 I know python library Anytree is useful here but I don't know how to implement this code. Any help would be highly appreciated.
tagged with: anytree
type: Question

combinatorics
tags question: http://stackoverflow.com/q/48230296
tag name: combinatorics
tags question: http://stackoverflow.com/q/48291543
type: Tag

http://stackoverflow.com/q/48257889
has comment: http://stackoverflow.com/comment/83498310
type: Question
has body: I want to list out all the unique values in all columns in a Pandas dataframe and store them in another data frame. I have tried this but its appending row wise and I want it column wise. How do I do that? raw_data = {'student_name': ['Miller', 'Miller', 'Ali', 'Miller'], 'test_score': [76, 75,74,76]} df2 = pd.DataFrame(raw_data, columns = ['student_name', 'test_score']) newDF = pd.DataFrame() for column in df2.columns[0:]: dat = df2[column].drop_duplicates() df3 = pd.DataFrame(dat) newDF = newDF.append(df3) print(newDF) Expected Output: student_name test_score Ali 74 Miller 75 76
tagged with: python
answer count: 1
score: 6
upvote count: 6
accepted answer: http://stackoverflow.com/a/48257936
has title: how to get unique values in all columns in pandas data frame
has answer: http://stackoverflow.com/a/48257936
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83498875
favorite count: 0
has comment: http://stackoverflow.com/comment/83498898

http://stackoverflow.com/comment/83476135
has text: I am unclear what you are asking. You are quite free to put as many asserts as you desire into one `test_...` function. What are you trying to do? Keep in mind that the **ONLY** point of the function naming to make it easier to interpret the test report.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48246674

http://stackoverflow.com/a/48230179
has body: You can just map() what you want: &gt;&gt;&gt; num=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e"] &gt;&gt;&gt; list(map(lambda x: num[x], [5, 12])) ['5', 'c']
type: Answer
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48229447

http://stackoverflow.com/a/48247415
answers question: http://stackoverflow.com/q/48246575
score: 0
has body: According to the documentation here dVal is an object. From what I remember of Spyder, only simple builtin variables show up in the variable explorer. You can try using the Object Inspector tab in that same window in order to get some insight into objects. You can also type help(dVal) to see the documentation. You can also type dir(dVal) to see the list of attributes and methods.
type: Answer

http://stackoverflow.com/comment/83617980
comment on: http://stackoverflow.com/q/48279901
type: Comment
has text: @eyllanesc yes I did.
type: QuestionComment
score: 0

http://stackoverflow.com/a/48326324
accepted answer of: http://stackoverflow.com/q/48326171
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48326171
has body: See here an example of this: ^[^=]+|(?&lt;=;)[^=]+ Which finds elements in between ; and =, or the one that starts on the beginning of the input and ends with a =. Output: ['Store Item Number (DPCI)', 'Pop Musical Style', 'Origin', 'Record label']
type: Answer
score: 0

http://stackoverflow.com/q/48227037
accepted answer: http://stackoverflow.com/a/48227221
tagged with: matplotlib
has title: Error on weighted histogram in python
upvote count: 4
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/64262450
answer count: 2
tagged with: weighted
has answer: http://stackoverflow.com/a/48227221
tagged with: histogram
tagged with: python
score: 4
possible better answer: http://stackoverflow.com/a/64262450
has body: I want to calculate the error on a bin height by taking the square root of the sum of the weights squared (sumw2) in that bin (poission error). Is there any way to get the sum of weights (sumw) and/or sumw2 when histogramming data with either matplotlib or numpy (or any other library for that matter)? Let's say I have some data in a numpy array x and some weights w in another numpy array, to get the histogram I would either so n, bins, patches = pyplot.hist(x,weights=w) or n, bins = numpy.histogram(x,weights=w) In both cases I have no clue which entries of w belong to which bin right? Edit: Currently I'm using YODA to do this. The disadvantage from my point of view is that YODA histograms can only be filled with one data point at a time.
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/85650531
has text: Hi; I've been trying to initiate the app but it crashes on startup. My Android phone is quite old but it should be able to run the app. Did you have any complaints so far?
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48298629

http://stackoverflow.com/q/48267322
type: Question
has answer: http://stackoverflow.com/a/48268175
tagged with: pycharm
has body: I build a simple function that control if a password have: I built a simple function that checks if a password contains: at least one uppercase letter, a number, must be at least 8 characters long The function is: import re class Password(): def validate(password): while True: if len(password) &lt; 8: print("False") elif re.search('[0-9]', password) is None: print("False") elif re.search('[A-Z]', password) is None: print("False") else: print("Your password seems fine") break This function is saved in a file called password.py Now I want do a unit test that control each condition: import Password import unittest class TestPassword(unittest.TestCase): def test_password(self): valid = Password.Password() self.assertEqual("asdfA1qw",valid.validate()) if __name__ == '__main__': unittest.main() But I don't know how. How can i set a control for each if?
possible better answer: http://stackoverflow.com/a/48267390
has answer: http://stackoverflow.com/a/48267682
tagged with: python
answer count: 4
tagged with: passwords
type: AnsweredQuestion
has title: Test a function with 3 if by unit test
has comment: http://stackoverflow.com/comment/83517737
score: 0
accepted answer: http://stackoverflow.com/a/48267442
has answer: http://stackoverflow.com/a/48267390
has answer: http://stackoverflow.com/a/48267442
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/83517763

http://stackoverflow.com/comment/83485562
type: AnswerComment
comment on: http://stackoverflow.com/a/48251332
type: Comment
has text: I should have mentioned that "to_split" won't be the same format everytime. Also the "expected_output" variable is needed.
score: 0

http://stackoverflow.com/comment/83334430
type: AnswerComment
has text: You can write whichever content you want.. where is the content coming from? Another file?
comment on: http://stackoverflow.com/a/48175963
score: 0
type: Comment

http://stackoverflow.com/comment/83611821
comment on: http://stackoverflow.com/q/48299103
score: 0
has text: i am facing problem during the ProductKeyword object creation.Even i don't have any data indexed in Elastic database to GET using curl.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83501279
has text: Possible duplicate of [What is the purpose "pip install --user ..."?](https://stackoverflow.com/questions/42988977/what-is-the-purpose-pip-install-user)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48259271
type: QuestionComment

http://stackoverflow.com/comment/83646184
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48329753
has text: Yes, that's ok.
type: Comment

http://stackoverflow.com/comment/83474300
comment on: http://stackoverflow.com/q/48245678
score: 0
has text: it is, but you have to have an api key https://docs.vipparcel.com/#Print Shipping Label
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48242880
has body: I am using Jupyter Notebook on a remote server (using ssh). I am using matplotlib and I want to save coordinates to annotate pictures to draw bounding boxes. I used : collector = [] def onclick(event): global i, collector collector.append((event.xdata, event.ydata)) # Open the annotations file to continue to write target = open('annotation.txt', 'a') # Write picture and coordinates target.write(line) target.write("\n") i += 1 event.canvas.figure.clear() event.canvas.figure.gca().imshow(images[i]) fig = plt.figure(figsize=(5,5)) fig.canvas.mpl_connect('button_press_event', onclick) plt.imshow(images[0]) plt.show() However, I don't why but it seems to not work anymore. Does someone know a solution to save click events on Jupyter Notebook ? Thank you very much in advance.
tagged with: jupyter-notebook
has title: Save click events for Jupyter Notebook
score: 0
has answer: http://stackoverflow.com/a/48244750
answer count: 1
type: Question
tagged with: matplotlib
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83592508
has text: Good catch, let me search for the shortest way to normalize the probabilities
type: Comment
comment on: http://stackoverflow.com/a/48303788
score: 0
type: AnswerComment

http://stackoverflow.com/comment/126922891
type: QuestionComment
comment on: http://stackoverflow.com/q/48177258
score: 0
type: Comment
has text: I’m voting to close this question because it's no longer relevant for me.

feature-detection
type: Tag
tags question: http://stackoverflow.com/q/48331004
tag name: feature-detection
tags question: http://stackoverflow.com/q/48322019

http://stackoverflow.com/q/48245089
type: Question
has comment: http://stackoverflow.com/comment/83472957
has title: Implementing __delattr__ for a user defined class
has comment: http://stackoverflow.com/comment/83472903
tagged with: python
accepted answer: http://stackoverflow.com/a/48245164
has comment: http://stackoverflow.com/comment/83473001
tagged with: class
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48245164
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83472891
upvote count: 2
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/83472910
downvote count: 1
favorite count: 0
has body: Class MyClasse: nom="me" age=24 def __delattr__(self,name) if name=="nom": raise AttributeError( "you are not allowed") else:object.__delattr__(self,name) A=MyClasse() del A.age

http://stackoverflow.com/q/48176531
has answer: http://stackoverflow.com/a/48178550
accepted answer: http://stackoverflow.com/a/48178294
favorite count: 0
has answer: http://stackoverflow.com/a/48178294
score: 9
type: Question
upvote count: 9
tagged with: python-imaging-library
possible better answer: http://stackoverflow.com/a/48178550
tagged with: python
has body: I am developing a tool which retrieves a JPG from an API and processes it. The source of the image cannot be trusted and I want to test if the image is a valid JPG (which is the only image type allowed). I encountered an error with PIL that I am unable to fix. Below is my code: image = StringIO(base64.b64decode(download['file'])) img = Image.open(image) if img.verify(): print 'Valid image' else: print 'Invalid image' However, it seems that img.verify() returns None. I can call other functions on the open image like img.size() which returns the size. I get the following output when I try to debug the code: img = Image.open(image) print img print img.size() print img.verify() [2018-01-09 20:56:43,715: WARNING/Worker-1] &lt;PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=2577x1715 at 0x7F16E17DC9D0&gt; [2018-01-09 20:56:43,716: WARNING/Worker-1] (2577, 1715) [2018-01-09 20:56:43,716: WARNING/Worker-1] None Has someone encountered the same issue?
has title: Python PIL image Verify returns None
type: AnsweredQuestion
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/83641175
type: Comment
has text: Even with lists containing a million items, multiprocessing will not be a good choice?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48327672

http://stackoverflow.com/comment/83675114
type: Comment
has text: @chatuur I have updated it.Please check:)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48330135

http://stackoverflow.com/a/48214055
has comment: http://stackoverflow.com/comment/83409854
downvote count: 0
score: 1
upvote count: 1
has body: I suspect what you want is size, not count, according to the docs at https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.html size gives the number of items in the ndarray.
type: Answer
answers question: http://stackoverflow.com/q/48214014

http://stackoverflow.com/q/48230953
tagged with: conda
tagged with: miniconda
upvote count: 4
answer count: 2
has title: permanent link to latest anaconda
has answer: http://stackoverflow.com/a/54839819
downvote count: 0
favorite count: 0
has body: There is a link to the latest miniconda that always points to the latest version: https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh But I could not find a similar link to the latest anaconda. Is there a way to obtain it?
type: Question
tagged with: anaconda
type: UnansweredQuestion
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/48231462

http://stackoverflow.com/q/48266265
tagged with: python-3.x
has title: Get NumPy slice from start/end coordinates
tagged with: python
has comment: http://stackoverflow.com/comment/83515898
tagged with: indexing
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83515825
downvote count: 0
answer count: 1
has body: Let's say I have a 3D 100x100x100 array and have some starting and ending coordinates, e.g.: (0,0,0) (50,20,20) How can I get extract a subarray bounded by cuboid defined by those vertices?
tagged with: slice
has answer: http://stackoverflow.com/a/48266355
favorite count: 0
accepted answer: http://stackoverflow.com/a/48266355
type: Question
upvote count: 2
tagged with: numpy

http://stackoverflow.com/q/48225511
answer count: 0
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83505375
tagged with: statsmodels
has title: Fitting an ARMA model and simulate new time series in Python
type: UnansweredQuestion
tagged with: arima
tagged with: python
has body: I am trying to fit an ARMA model on a given time series 'resid' of length 'tsteps' and use the obtained fitted model 'resid_model' to simulate a certain number of alternative time series with the same characteristics. Here is what I have tried so far (for only one simulation 'sim'): import numpy as np import statsmodels.tsa.api as smt resid_model = smt.ARMA(resid, (2, 1)).fit(maxlag=30, ic='aic', trend='nc',disp=False, transparams=True) sim = smt.arma_generate_sample(ar=np.append(1.,resid_model.arparams), ma=np.append(1.,resid_model.maparams), nsample=tsteps, sigma=resid_model.sigma2) However, I don't seem to be able to ensure stationarity, despite the 'transparams=True' parameter in the fit. What I obtain depends on the order of the ARMA model I try to fit, but in general tends to degenerate: obtained simulation 'sim' This is how my original sample looks like instead: original time series 'resid' What am I doing wrong? Thank you!
has comment: http://stackoverflow.com/comment/83445197

http://stackoverflow.com/a/48273523
accepted answer of: http://stackoverflow.com/q/48273473
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83530837
type: Answer
answers question: http://stackoverflow.com/q/48273473
has body: When you refer to the character variable inside your start function, it's assigning to a variable in the local scope (function scope). To let Python know you mean the character variable you defined in the global scope, you have to explicitly state so: def start(): global character characterchosen = False printslow("Welcome adventurer. Chose wisely.") ... You're also comparing the result of type to a string representation of that type. What you want is to compare it to the type directly: if type(character) == person: print("game here") Or better yet, use the isinstance built-in function: if isinstance(character, person): print("game here")
score: 0

http://stackoverflow.com/comment/83347532
comment on: http://stackoverflow.com/a/48183588
type: Comment
score: 0
type: AnswerComment
has text: I corrected the code, you also have to index the initialization of the conditional value `acc['parent'][o]` ; does it still not work now?

http://stackoverflow.com/a/48241129
has body: If I correctly understand what you want to do, you want to have already_ate track all the foods a person has eaten. It looks like your data structure is not correct for this job. You need to change your code to handle already_ate[person] as a list, not a single string: if person in already_ate: if not food in already_ate[person]: already_ate[person].append(food) else: already_ate[person] = [food] The else portion will both add the person key to your already_ate dictionary, and start the list with the eaten food. This way you can have multiple foods eaten by each person, but not have any given food appear in that person's list more than once.
answers question: http://stackoverflow.com/q/48240820
type: Answer
score: 0

http://stackoverflow.com/q/48280283
has comment: http://stackoverflow.com/comment/83544053
has comment: http://stackoverflow.com/comment/83612710
tagged with: django
tagged with: python
has title: Python Django Subcategory
has answer: http://stackoverflow.com/a/48280435
type: AnsweredQuestion
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83544151
type: Question
tagged with: django-templates
accepted answer: http://stackoverflow.com/a/48280435
has body: I want to print the subcategory names of each Main Category. The below code is now showing all subcategories for every Main category. How can I do? index.html {% for mainCatList in main_cat_list %} {{ mainCatList.main_category_name }} {% for subCat in cat_list %} {{ subCat.category_name }} {% endfor %} {% endfor %} views.html from django.shortcuts import render from .models import Product, Category, Main_Category def homePageView(request): main_cat_list = Main_Category.objects.all() cat_list = Category.objects.all() context = {'main_cat_list': main_cat_list, 'cat_list': cat_list} return render(request, 'index.html', context)

http://stackoverflow.com/comment/83375207
type: QuestionComment
has text: If the script runs normally (invoking *Python* on it), it should run from *py2exe* bundle. You're doing smth wrong. It's also possible embedding *Python*; You could take a look at https://stackoverflow.com/questions/39539089/what-files-are-required-for-py-initialize-to-run, or https://stackoverflow.com/questions/47942845/calling-python-function-with-parametrs-from-c-project-visual-studio, for more details but (both are on *Win*) but that's pretty much what *py2exe* does.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48196885

http://stackoverflow.com/q/48234157
has body: Get start and end date of quarter from date and fiscal year end provides great helper functions to get the current/prior quarter. I'm unable to generalize the prev_quarter_range function to include a quarters_ago param that returns the start &amp; end dates for a random quarter n quarters ago. Ideally, I want a function named get_quarter_start_end_dates that takes in (dt, quarters_ago) and outputs (start_dt, end_dt). Here are some sample inputs --> outputs: ('2017-01-01', 0) --> ('2017-01-01', '2017-04-01') ('2017-01-01', 1) --> ('2016-10-01', '2017-01-01') ('2017-01-01', 2) --> ('2016-07-01', '2016-10-01') ('2017-02-01', 12) --> ('2014-01-01', '2014-04-01')
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/67223576
linked to: http://stackoverflow.com/q/46019099
tagged with: python-datetime
tagged with: python
tagged with: date
has answer: http://stackoverflow.com/a/48234403
answer count: 4
score: 2
has answer: http://stackoverflow.com/a/61659030
upvote count: 3
type: UnansweredQuestion
has title: In python, how can I find the start & end dates for a random quarter in the past?
has answer: http://stackoverflow.com/a/48234733

http://stackoverflow.com/comment/83531214
comment on: http://stackoverflow.com/q/48273628
score: 0
has text: Martin Broadhurst's answer in the link maybe the answer,but: i += max(offset_table[len(needle) - 1 - j], char_table.get(haystack[i])); TypeError: '>' not supported between instances of 'NoneType' and 'int'
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83459997
score: 0
type: Comment
has text: I installed it using pip, pyhon 3.6.2
type: QuestionComment
comment on: http://stackoverflow.com/q/48238146

http://stackoverflow.com/comment/83563924
type: QuestionComment
has text: You're not modifying `list1`, you're modifying a copy of it.
score: 4
comment on: http://stackoverflow.com/q/48289480
type: Comment

http://stackoverflow.com/comment/83905819
type: QuestionComment
comment on: http://stackoverflow.com/q/48314365
score: 1
has text: Have you tried adding a property to your `CompanySetting` model which returns a trimmed url and let the `company_logo` field be the actual full url?
type: Comment

http://stackoverflow.com/q/48228150
favorite count: 0
type: Question
has body: I have already seen this question: How to execute Python code from within Visual Studio Code But all those answers are about tasks from old versions ("0.1.0" or "0.2.0"). VS Code is now version "2.0.0" and some parameters have changed. I'm trying to create this task through Run Task: tasks.json: { // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "2.0.0", "tasks": [ { "label": "Run File", "command": "python ${file}", "problemMatcher": [], "presentation": { "echo": true, "reveal": "always", "focus": true, "panel": "shared" }, "group": { "kind": "build", "isDefault": true } } ] } But it does not work! Error message: Terminal with ID 8 does not exist (has it already been disposed?) What can be wrong here? I can use Run Python File in Terminal or just enter python myFile.py in Terminal - both of them work!
tagged with: visual-studio-code
has title: Create simple Task for Python in Visual Studio Code
upvote count: 2
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/29987840
score: 2
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/83457769
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/68920824

http://stackoverflow.com/q/48313158
has title: python skimage.measure.label leads to segment fault in linux environment
score: 0
answer count: 1
tagged with: segment
has answer: http://stackoverflow.com/a/48682669
type: Question
has comment: http://stackoverflow.com/comment/83612152
tagged with: linux
has body: I use skimage.measure.label in my python program to process a series images, the code is: for i in range(n): label_img, num = label(img[i], return_num = True) then report segmental fault. And I rewrite the label function using bfs method, then success. I wonder if the the original label function is a dfs method. I think the dfs method leads to a Mem overflow, And if so , how to do with this problem?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83612222
tagged with: fault

ms-word
tag name: ms-word
type: Tag
tags question: http://stackoverflow.com/q/48324657

http://stackoverflow.com/a/48288529
has comment: http://stackoverflow.com/comment/83563559
has comment: http://stackoverflow.com/comment/83563334
has comment: http://stackoverflow.com/comment/83564899
has comment: http://stackoverflow.com/comment/83563710
has comment: http://stackoverflow.com/comment/83564012
has comment: http://stackoverflow.com/comment/83565401
has comment: http://stackoverflow.com/comment/83565097
has comment: http://stackoverflow.com/comment/83564430
has comment: http://stackoverflow.com/comment/83565507
has comment: http://stackoverflow.com/comment/83564853
has comment: http://stackoverflow.com/comment/83564461
has comment: http://stackoverflow.com/comment/83564981
has comment: http://stackoverflow.com/comment/83565070
has comment: http://stackoverflow.com/comment/83563784
type: Answer
has comment: http://stackoverflow.com/comment/83565221
has comment: http://stackoverflow.com/comment/83565165
has comment: http://stackoverflow.com/comment/83564688
has comment: http://stackoverflow.com/comment/83565304
score: 2
upvote count: 2
has body: The problem is with this part: K.cast_to_floatx(K.int_shape(K.flatten(d_i))[0] as a loss function is compiled before any shape is provided - this expression evaluates to None and this where your error comes from. I tried to set batch_input_shape instead of input_shape but this didn't work also (probably due to the way keras compiles the model). I advice to set this number to a constant in the following manner: def get_log_rmse(normalization_constant): def log_rmse(y_true, y_pred): d_i = (K.log(y_pred) - K.log(y_true)) loss1 = K.mean(K.square(d_i)) loss2 = K.square( K.sum( K.flatten(d_i),axis=-1))/(K.cast_to_floatx( 2 * normalization_constant ** 2) loss = loss1 - loss2 return loss return log_rmse and then compile: model.compile(..., loss=get_log_rmse(normalization_constant)) I guess that normalization_constant is equal to a batch_size but I'm not sure so I've made it generic. Update: After a suggestion by Marcin Możejko I updated the code but unfortunately the training loss is still Nan: def get_log_rmse(normalization_constant): def log_rmse(y_true, y_pred): d_i = (K.log(y_pred) - K.log(y_true)) loss1 = K.mean(K.square(d_i)) loss2 = K.square(K.sum(K.flatten(d_i),axis=-1))/K.cast_to_floatx(2 * normalization_constant ** 2) loss = loss1 - loss2 return loss return log_rmse Then the model is compiled via: model.compile(optimizer='adam', loss=get_log_rmse(batch_size)) Update 2: The model definition looks like this: input_shape = (160, 256, 3) print('Input_shape: %s'%str(input_shape)) base_model = keras.applications.vgg19.VGG19(include_top=False, weights='imagenet', input_tensor=None, input_shape=input_shape, pooling=None, # None, 'avg', 'max' classes=1000) for i in range(5): base_model.layers.pop() base_model = Model(inputs=base_model.input, outputs=base_model.get_layer('block4_pool').output) print('VGG19 output_shape: ' + str(base_model.output_shape)) x = Deconv(128, kernel_size=(4, 4), strides=1, padding='same', activation='relu')(base_model.output) x = UpSampling2D((2, …
downvote count: 0
has comment: http://stackoverflow.com/comment/83564601
has comment: http://stackoverflow.com/comment/83565555
accepted answer of: http://stackoverflow.com/q/48286504
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83565437
has comment: http://stackoverflow.com/comment/83564823
has comment: http://stackoverflow.com/comment/83565428
answers question: http://stackoverflow.com/q/48286504

http://stackoverflow.com/comment/83566577
score: 0
has text: Are you sure you have tensorflow installed in the right lib? do a `pip freeze` and `pip -V` to ensure you have tensorflow installed under Python3.5
type: QuestionComment
comment on: http://stackoverflow.com/q/48290565
type: Comment

http://stackoverflow.com/q/48199811
has comment: http://stackoverflow.com/comment/83381426
has title: How to write data in each row in csv file without overwriting in python
tagged with: python
has comment: http://stackoverflow.com/comment/83381495
linked to: http://stackoverflow.com/q/1170214
has comment: http://stackoverflow.com/comment/83381246
duplicate of: http://stackoverflow.com/q/1170214
score: 0
has comment: http://stackoverflow.com/comment/83513745
linked to: http://stackoverflow.com/q/3191528
tagged with: http://stackoverflow.com/tag/csv
has body: I want to write data in each row in csv file without overwriting. With this code I am able to write the data in every second row of the file. Please any help.This is the part of the code Im using these code .... dfl_origin= [dfl_origin_X,dfl_origin_Y] import csv c = csv.writer(open("C:/Config/Output/box1.csv","a")) c.writerow([dfl_origin[0],dfl_origin[1]]) .... And the output is these So . Why the second data is not written into second row? Any help? Thanks
has comment: http://stackoverflow.com/comment/83423800
has comment: http://stackoverflow.com/comment/83382719
has comment: http://stackoverflow.com/comment/83396538
has comment: http://stackoverflow.com/comment/83400738
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/83380858
type: UnansweredQuestion

http://stackoverflow.com/comment/83459353
comment on: http://stackoverflow.com/a/48235530
type: Comment
has text: Pandas return dataframe after reading csv. It's the object you showed printed to output in your question. It's full of helpful functions that work on `df` as well as `df["column"]`.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83518308
has text: can you tell me the input shape of your first layer?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48267053
type: AnswerComment

http://stackoverflow.com/comment/83524918
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48270609
has text: I'm afraid that you've oversimplified your question to the point that any answer provided may not generalise to your case, so I'd recommend broadening it a bit.

http://stackoverflow.com/q/48319914
has answer: http://stackoverflow.com/a/48320783
linked to: http://stackoverflow.com/q/14234917
has title: Django doesn't update the ImageField path
tagged with: django
tagged with: django-models
tagged with: python
has body: I am trying to upload a profile picture when model instance is being created. I want my profile picture to be stored in a folder, that is named according to the instance id, hence once the picture is uploaded I need to create a new dir and move the picture there. I followed this, which suggests overriding the default save() method in the model, and this, that proposes to use post_save signal to save the new file twice. My current code looks as follows: class Emp(models.Model): photo = models.ImageField("Photo", blank=True, null=True, default='default_avatar.png') def save(self, *args, **kwargs): # Call standard save super(Emp, self).save(*args, **kwargs) if self.photo.path: initial_path = self.photo.path new_path = os.path.join(settings.MEDIA_ROOT, 'profile_picture_of_emp_{0}/{1}'.format(self.pk, os.path.basename(initial_path))) # Create dir if necessary and move file if not os.path.exists(os.path.dirname(new_path)): os.makedirs(os.path.dirname(new_path)) os.rename(initial_path, new_path) # Save changes super(Emp, self).save(*args, **kwargs) So this actually moves the file and creates new_path correctly, however, the self.photo.path stills refers to the old location and I can't figure out a way to update this new path. The same happens with post_save signal as it doesn't update the path of moved file. Any suggestions? Thanks!
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/38372256
score: 0
has comment: http://stackoverflow.com/comment/83626616
answer count: 1
accepted answer: http://stackoverflow.com/a/48320783
type: Question

http://stackoverflow.com/q/48312189
has comment: http://stackoverflow.com/comment/83610263
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/83610211
downvote count: 3
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48312215
has comment: http://stackoverflow.com/comment/83610277
tagged with: python
score: -2
favorite count: 0
has body: I have the following dictionary: {'have.01':[':arg0',':arg1'], 'give.01':[':arg1',':arg2'], ':create.01':[':arg3', ':arg4']} I need to generate the following file: have.01, 1, 1, 0, 0 give.01, 0, 1, 1, 0 create.01, 0, 0, 1, 1 That is if the :argX is present, I put 1. I have no idea how to program this.
has title: How to create a tabular file?

http://stackoverflow.com/a/48289715
type: Answer
answers question: http://stackoverflow.com/q/48289610
upvote count: 2
score: 2
downvote count: 0
has body: I think you need replace all values not contains a and A to other by where and condition by isin and then use groupby by columns and Series s: s = df['End'].where(df['End'].isin(['a','A']), 'other') print (s) 0 a 1 other 2 other 3 A 4 other 5 other 6 A 7 other 8 other 9 a 10 other 11 other Name: End, dtype: object df = (df.groupby(['Type', 'Start', s]) .agg({'Count':'sum', 'Total':'mean'}) .reset_index()) Another similar solution is replace column End and use your original solution for groupby + agg: df['End'] = np.where(df['End'].isin(['a','A']), df['End'], 'other') #alternatively #df['End'] = df['End'].where(df['End'].isin(['a','A']), 'other') df = (df.groupby(['Type', 'Start', 'End'], as_index=False) .agg({'Count':'sum', 'Total':'mean'})) print (df) Type Start End Count Total 0 A x a 1 3 1 A x other 2 3 2 A y A 2 4 3 A y other 2 4 4 B x A 1 6 5 B x other 5 6 6 B y a 3 6 7 B y other 3 6

http://stackoverflow.com/comment/83480970
comment on: http://stackoverflow.com/a/48248922
type: AnswerComment
score: 0
has text: It's the OP's requirement, not mine.
type: Comment

http://stackoverflow.com/q/48275237
type: Question
has title: Python SNMP Trap Receiver
has answer: http://stackoverflow.com/a/53705355
tagged with: python
tagged with: snmp-trap
has comment: http://stackoverflow.com/comment/83909453
tagged with: pysnmp
score: 2
tagged with: snmp
has body: I received an SNMP trap message in Python3, and I got a hexadecimal number. How do I convert it to a String so I can see it? Received Data(Hex) b'0E\x02\x01\x01\x04\x06404040\xa78\x02\x04\x00\xf6\x17~\x02\x01\x00\x02\x01\x000*0\x0f\x06\x08+\x06\x01\x02\x01\x01\x03\x00C\x03\x01k+0\x17\x06\n+\x06\x01\x06\x03\x01\x01\x04\x01\x00\x06\t+\x06\x01\x06\x03\x01\x01\x05\x01' This is my SNMP trap receiver code import socket import sys port = 162 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(("", port)) while 1: data, addr = s.recvfrom(4048) print(data) This is my SNMP trap Sender code from pysnmp.hlapi.asyncore import * snmpEngine = SnmpEngine() sendNotification( snmpEngine, CommunityData('404040'), UdpTransportTarget(('192.168.0.160', 162)), ContextData(), 'trap', NotificationType(ObjectIdentity('SNMPv2-MIB', 'coldStart')), ) snmpEngine.transportDispatcher.runDispatcher()
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/94265281
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/33752602
favorite count: 0

http://stackoverflow.com/comment/83503173
comment on: http://stackoverflow.com/q/48256019
has text: please add more details to your question
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83499388
comment on: http://stackoverflow.com/a/48258431
type: AnswerComment
has text: I was just about to ask you to explain how "or" operator works on non-booleans, but you did it already. You have my upvote (and my axe!).
score: 0
type: Comment

http://stackoverflow.com/comment/83381495
type: Comment
score: 2
has text: Try using file mode `ab` instead of just `a`.
type: QuestionComment
comment on: http://stackoverflow.com/q/48199811

http://stackoverflow.com/comment/83422013
type: Comment
type: AnswerComment
has text: Any guess about my First problem?
comment on: http://stackoverflow.com/a/48218894
score: 1

http://stackoverflow.com/q/48174608
possible better answer: http://stackoverflow.com/a/48174710
has title: Count extracted values from Pandas value_counts()
has answer: http://stackoverflow.com/a/48174710
favorite count: 0
type: Question
has body: It seems simple but I haven´t found it exactly in other answers. How to assign to some variable the count of some condition in pandas, as example below: Command (to count the categories of a column in pandas dataframe): print(data.isBald.value_counts()) Output: Bald 2345 notBald 5432 Name: isBald, dtype: int64 Question is: isBaldCount = ? #2345 The result was print but how to assign it to a variable?
has answer: http://stackoverflow.com/a/48174649
tagged with: python
type: AnsweredQuestion
score: 3
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48174649
upvote count: 3
downvote count: 0

http://stackoverflow.com/a/78325636
has body: I do not understand how the code in the accepted answer ever worked; when I copy and run it, and I click on the Start button, I get: $ python3 my_qttest.py Traceback (most recent call last): File "C:/msys64/tmp/my_qttest.py", line 34, in long_task pool.apply_async(long_task, callback=callback) ^^^^ NameError: name 'pool' is not defined. Did you mean: 'Pool'? Mind you, I use: $ for ix in "uname -s" "python3 --version"; do echo "$ix: " $($ix); done uname -s: MINGW64_NT-10.0-19045 python3 --version: Python 3.11.8 And then I tried adding pool = Pool() before/above the def long_task(): - and suddenly I get a shitton of windows getting spawned, and ... File "C:/msys64/tmp/my_qttest.py", line 14, in <module> pool = Pool() ^^^^^^ File "C:/msys64/mingw64/lib/python3.11/multiprocessing/context.py", line 119, in Pool return Pool(processes, initializer, initargs, maxtasksperchild, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:/msys64/mingw64/lib/python3.11/multiprocessing/pool.py", line 215, in __init__ self._repopulate_pool() File "C:/msys64/mingw64/lib/python3.11/multiprocessing/pool.py", line 306, in _repopulate_pool return self._repopulate_pool_static(self._ctx, self.Process, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:/msys64/mingw64/lib/python3.11/multiprocessing/pool.py", line 329, in _repopulate_pool_static w.start() File "C:/msys64/mingw64/lib/python3.11/multiprocessing/process.py", line 121, in start self._popen = self._Popen(self) ^^^^^^^^^^^^^^^^^ File "C:/msys64/mingw64/lib/python3.11/multiprocessing/context.py", line 336, in _Popen return Popen(process_obj) ^^^^^^^^^^^^^^^^^^ File "C:/msys64/mingw64/lib/python3.11/multiprocessing/popen_spawn_win32.py", line 46, in __init__ prep_data = spawn.get_preparation_data(process_obj._name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:/msys64/mingw64/lib/python3.11/multiprocessing/spawn.py", line 164, in get_preparation_data _check_not_importing_main() File "C:/msys64/mingw64/lib…
answers question: http://stackoverflow.com/q/48262966
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/138086855
score: 1
type: Answer

http://stackoverflow.com/q/48240280
downvote count: 0
has answer: http://stackoverflow.com/a/48240349
tagged with: string
has title: create column flag containing word from list
accepted answer: http://stackoverflow.com/a/48240349
has comment: http://stackoverflow.com/comment/83462854
favorite count: 0
type: Question
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83466115
has body: I want to add a flag to my python pandas dataframe, if an entry in the column contains the word from a list for any separete row we can use any(word in train['a'][0] for word in words) I tried to make a pattern import pandas as pd import numpy as np words=['photos','pictures', ' pics ', 'pix', 'image'] pattern = '|'.join(words) train=pd.DataFrame() train['a']=words I've tried with contains but it didn't get the pattern def emb_col_1(tr, te, col, pat, suf): tr["0_"+col+suf]=0 tr.loc[tr[col].str.contains(pat), "0_"+col+suf] =1 #tr.loc[tr[col].str.count(pat)&gt;0, "0_"+col+suf] =1 #tr.loc[(word in tr[col].str for word in pat), "0_"+col+suf] =1 #tr["0_"+col+suf] = np.where(tr[col].str.contains(pat, case=False, na=False), 1, 0) #tr["0_"+col+suf] = np.where(any(word in train[col] for word in pat), 1, 0) emb_col_1(train, test, 'a', words, '_p') emb_col_1(train, test, 'a', pattern, '_p') Thank you in advance
tagged with: pandas
score: 1
answer count: 1

http://stackoverflow.com/comment/83529178
type: AnswerComment
has text: Are you aware that your `.count('rand')` is a second iteration through the complete input? That actually may be faster. But it isn't the cleanest version I can think of.
score: 0
comment on: http://stackoverflow.com/a/48267118
type: Comment

cron
tags question: http://stackoverflow.com/q/48272939
tags question: http://stackoverflow.com/q/48304723
tag name: cron
tags question: http://stackoverflow.com/q/48311909
tags question: http://stackoverflow.com/q/48321649
tags question: http://stackoverflow.com/q/48193436
tags question: http://stackoverflow.com/q/48203912
tags question: http://stackoverflow.com/q/48287185
tags question: http://stackoverflow.com/q/48210897
tags question: http://stackoverflow.com/q/48319338
type: Tag

http://stackoverflow.com/comment/83551875
type: QuestionComment
comment on: http://stackoverflow.com/q/48283625
has text: Please provide a minimal working example so that users can debug the problem. Also, did you make sure that the dimensions match? (3,3,3,64) is not (64,3,3,3) !
score: 0
type: Comment

cloudera-cdh
tag name: cloudera-cdh
type: Tag
tags question: http://stackoverflow.com/q/48264453

http://stackoverflow.com/q/48286143
score: -3
upvote count: 1
favorite count: 0
has body: I'm trying to use the eval function in the following scenario: Assuming I have two expressions : A ← A * 3 A ← 3 * A In the second half of these expressions I'd like to get True because they are equal. Assuming I have other two expressions : A ← A % 3 A ← 3 % A In the second half of these expressions I'd like to get False because they are not equal. I've done, with Stack Overflow's help, a large program, the part that I'm curious about is: import sys def main() : opt1_raw = "A ← T + 2" opt2_raw = "A ← 2 + T" opt1 = opt1_raw.split("←")[1] opt2 = opt2_raw.split("←")[1] for char in opt1 : if char.isdigit() or char.isalpha() : ascii_exp1 = ''.join(str(ord(char))) x = eval(ascii_exp1) The same goes for opt2 with y variable, then I compare two variables, x and y. At the end of my program I have these lines : if ( x != y ) : sys.exit() else : print("Equals") The result is not "Equals" for this example. Why doesn't it work?
has answer: http://stackoverflow.com/a/48288566
has comment: http://stackoverflow.com/comment/83559092
tagged with: python
has comment: http://stackoverflow.com/comment/83558068
has title: Using the eval function
has comment: http://stackoverflow.com/comment/83559449
has comment: http://stackoverflow.com/comment/83557663
type: Question
has comment: http://stackoverflow.com/comment/83557498
tagged with: python-3.x
downvote count: 4
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/83475276
comment on: http://stackoverflow.com/q/48246315
score: 0
type: Comment
type: QuestionComment
has text: And what have you tried so far, and why do you think it didn't work?

http://stackoverflow.com/a/48252976
upvote count: 3
has body: That is a bug. It appears to be related to the % in the index. With this code: df2 = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) abc = df2.describe() abc_fixed = abc.reset_index().replace( {'25%': '25_percent', '50%': '50_percent', '75%': '75_percent'} ).set_index('index') abc will not display, but abc_fixed will display.
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48248634
accepted answer of: http://stackoverflow.com/q/48248634
score: 3

http://stackoverflow.com/comment/83496513
comment on: http://stackoverflow.com/q/48256185
score: 0
type: Comment
type: QuestionComment
has text: Can you import pytz in your program? Or maybe `from pytz.lazy import LazyDict, LazyList, LazySet`?

http://stackoverflow.com/comment/83348096
score: 0
comment on: http://stackoverflow.com/a/48184005
has text: what about `skiprows=54`?
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48269587
tagged with: com
answer count: 1
has answer: http://stackoverflow.com/a/48291604
has title: "DllRegitserServer not found" error for python_com_server
type: Question
accepted answer: http://stackoverflow.com/a/48291604
tagged with: python
tagged with: regsvr32
tagged with: exe
type: AnsweredQuestion
score: 0
has body: Here is my code for com server (the file name is "python_com_server.py"): import pythoncom, win32com.server.register import win32traceutil class Python_COM_Server_4: _public_methods_ = ['MachineInfo'] _reg_progid_ = "PythonCOMServer_4" _reg_clsid_ = '{3B4B18D9-BE2C-43A5-B08C-A89B4334DFA1}' def MachineInfo(self, item=None): msg = "Your operating system: " print (msg) if __name__ == '__main__' or __name__ == 'python_com_server': win32com.server.register.UseCommandLine (Python_COM_Server_4) and here is my setup.py: from distutils.core import setup import py2exe import sys class Target: def __init__(self, **kw): self.__dict__.update(kw) # for the version info resources (Properties -- Version) self.version = "0.0.1" self.company_name = "my company" self.name = "my com server name" my_com_server_target = Target( description = "my com server", # use module name for win32com exe/dll server modules = ["python_com_server"], # specify which type of com server you want (exe and/or dll) create_exe = True, create_dll = False ) setup( name="my_com_server", # the following two parameters embed support files within exe/dll file options={"py2exe": {"bundle_files": 1, }}, zipfile=None, version="0.0.1", description="my com server", # author, maintainer, contact go here: author="First Last", author_email="some_name@some_company.com", # packages=["dir"], com_server=[my_com_server_target] ) I run the following command on the cmd line: python setup.py py2exe and it generates " python_com_server.exe" in the dist folder. I then try to register it using: regsvr32 dist\python_com_server.exe but I get this error: "The module "dist\pythion_com_server.exe" was loaded but the entry-point DllRegisterServer was not found. I am using python 2.7 32 bit on the windows server 2012. What am I missing?

http://stackoverflow.com/comment/83469717
score: 0
type: QuestionComment
type: Comment
has text: Also paste the trace back, it’s not clear where the error is caused.
comment on: http://stackoverflow.com/q/48243582

http://stackoverflow.com/comment/83604057
type: QuestionComment
score: 2
has text: Have you tried `image.reload()` ?
type: Comment
comment on: http://stackoverflow.com/q/48308776

http://stackoverflow.com/comment/83409971
type: Comment
type: AnswerComment
has text: I am going to add another field to the data frame to alter the fact that there is only one point per variable. That went completely over my head, thank you for the help
comment on: http://stackoverflow.com/a/48214082
score: 1

http://stackoverflow.com/comment/83856568
type: Comment
comment on: http://stackoverflow.com/a/48408031
type: AnswerComment
has text: You are right. Moving the library resources to `\WEB-INF\lib\Lib` (where the constructed `sys.path` is expecting them) or using a "full" standalone `jython.jar` works. Nevertheless, I wish I could use the `jython.home` initialization parameter [as shown in the JavaDoc](http://www.jython.org/javadoc/org/python/util/PyServlet.html). I edited my post: I had a look at [the initialization code](https://bitbucket.org/jython/jython/raw/d74f8c2cd56f24c7af8b1aab36433f941d0a44e9/src/org/python/util/PyServlet.java) and, yes, that parameter is supposed to work. Still don’t know why it doesn’t.
score: 0

http://stackoverflow.com/comment/83419579
comment on: http://stackoverflow.com/q/48218412
type: QuestionComment
type: Comment
has text: Tbh, I like your approach. I would start with `list_b = [list_a[0]] for val in list_a[1:]: if val == 1:` and use `round(list_b[-1] - 0.1, 1)` to get rid of float point inaccuracies, but otherwise I wouldn't change much.
score: 1

http://stackoverflow.com/q/48244659
type: Question
upvote count: 4
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/48244760
score: 4
has answer: http://stackoverflow.com/a/48244760
linked to: http://stackoverflow.com/q/31884175
type: AnsweredQuestion
has title: Multiprocessing - cannot write list to csv (TypeError: 'ApplyResult' object is not iterable)
downvote count: 0
answer count: 1
has body: I have a script for analyzing big csv files so I needed to start multiprocessing. I used multiprocessing module and it works fine but if I try to write the output list to a csv file, it throws an error: TypeError: 'ApplyResult' object is not iterable I looked up on some solutions including multiprocessing: TypeError: 'int' object is not iterable but could not solve the problem. Here is the code: from multiprocessing import Pool import csv pool = Pool() nodes = [['1001', '2008-01-06T02:12:13Z', ['']], ['1002', '2008-01-06T02:13:55Z', ['']], ['1003', '2008-01-06T02:13:00Z', ['Lion', 'Rhinoceros', 'Leopard', 'Panda']], ['1004', '2008-01-06T02:15:20Z', ['Lion', 'Leopard', 'Eagle', 'Panda', 'Tiger']], ['1005', '2008-01-06T02:15:48Z', ['Lion', 'Panda', 'Cheetah', 'Goat', 'Tiger']], ['1006', '2008-01-06T02:13:30Z', ['']], ['1007', '2008-01-06T02:13:38Z', ['Cheetah', 'Tiger', 'Goat']]] def nodes_to_links(nodes_list): output_list = [] for ii, elem in enumerate(nodes_list[:-1]): for jj in range(ii + 1, len(nodes_list)): common = set(elem[-1]).intersection( set(nodes_list[jj][-1])) if len(common) > 0 and common != {''}: output_list.append([elem[0], nodes_list[jj][0], ','.join(map(str, list(common)))]) return output_list #links = nodes_to_links(nodes) ###This works perfect without multiprocessing links = pool.apply_async(nodes_to_links, (nodes)) ### This works if I don't write the list "links" to a csv, but not otherwise # Write links to a csv file def writeCSV(list_to_write, OutputFileName): file = open(OutputFileName, 'w', newline='') writer = csv.writer(file, quotechar='"', delimiter=';',quoting=csv.QUOTE_ALL, skipinitialspace=True) for row in list_to_write: writer.writerow(row) writeCSV(links,'output_files/test.csv') I tried to use pool.join() and pool.close() but that also does not help. Can anyone please help. As a note, the list nodes is very big and I am just giving an example here, so multiprocessing is essential. Also can I know how to specify number of processors if …
favorite count: 0
tagged with: multiprocessing

http://stackoverflow.com/comment/83581286
comment on: http://stackoverflow.com/q/48286421
type: Comment
type: QuestionComment
score: 0
has text: pyspark is part of the Spark distribution, you don't need to download it separately

http://stackoverflow.com/comment/83393733
type: Comment
comment on: http://stackoverflow.com/a/48205962
score: 0
type: AnswerComment
has text: It didn't worked for string "U. OPERTER 4-5". Output I get is "U. OPERTER " instead of ['U. OPERTER', '4-5']. Any idea for this ?

http://stackoverflow.com/comment/83422607
type: QuestionComment
comment on: http://stackoverflow.com/q/48219403
score: 1
has text: have you tried `except the_library.ExceptionYouAreLookingFor:` ? I had a similar issue before, where I tried to catch a `ConnectionError` but it wouldn't return. Turns out I had catch `Requests.ConnectionError` as it was it's own special exception object in the imported module.
type: Comment

http://stackoverflow.com/a/48244978
score: 2
upvote count: 2
type: AcceptedAnswer
has body: You are assigning a new value to the same object on each iteration of the for loop. You need to create a new object each time and give it a value like this: class A(object): def __init__(self): self.val = 0 def __str__(self): return str(self.val) b = [] for i in range(10): b.append(A()) b[i].val = i; for a in b: print(a) which outputs 0 1 2 3 4 5 6 7 8 9
downvote count: 0
answers question: http://stackoverflow.com/q/48244926
accepted answer of: http://stackoverflow.com/q/48244926
type: Answer

http://stackoverflow.com/comment/83669307
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48217127
has text: @asheets: Is there a particular reason you talk about arrays of shape N * M * 3? If I understand properly, the task is to handle a list of points in 3dimensions, i.e. a N*3 array

http://stackoverflow.com/q/48186616
has answer: http://stackoverflow.com/a/53418041
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/83460291
has comment: http://stackoverflow.com/comment/83391432
has comment: http://stackoverflow.com/comment/83461732
tagged with: matplotlib
has answer: http://stackoverflow.com/a/54712746
has comment: http://stackoverflow.com/comment/83356990
tagged with: python
tagged with: image-processing
has comment: http://stackoverflow.com/comment/83391323
has comment: http://stackoverflow.com/comment/83461176
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/83355041
has comment: http://stackoverflow.com/comment/83352928
has title: open a .jpg image in python using matplotlib.image in python 3.6
has body: I am trying to open a JPG image using matplotlib in Python. Editor 'Spyder', Python3.6, WIndows 7 import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np # Read in the image and print some stats image = mpimg.imread(r'C:\Users\xxx\Python Code\mountain.jpg') print('This image is: ',type(image), 'with dimensions:', image.shape) But I am getting the following error... It says that except '.png' no other image format is supported. Error :-- image = mpimg.imread(r'C:\Users\xxx\Python Code\mountain.jpg') File "C:\temp\Continuum\anaconda3\lib\site-packages\matplotlib\image.py", line 1284, in imread 'more images' % list(handlers)) ValueError: Only know how to handle extensions: ['png']; with Pillow installed matplotlib can handle more images. I went through various documentations. Which says that, in order to open a '.jpg' image, 'Pillow' must be installed. If native matplotlib call fails to open a image then it automatically falls back on 'pillow'. (correct me if I am wrong) So I installed 'Pillow'. But I am still getting the error. Can you tell me what am I Missing ? (Strange thing is this same code is running in another computer. I have no way to verify what library is installed in that machine)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83357132
has comment: http://stackoverflow.com/comment/83466787
has comment: http://stackoverflow.com/comment/109107244
downvote count: 0
score: 13
has comment: http://stackoverflow.com/comment/83390163
has comment: http://stackoverflow.com/comment/83355420
upvote count: 13
has comment: http://stackoverflow.com/comment/83395357

http://stackoverflow.com/q/48211346
tagged with: tensorflow
type: Question
tagged with: opencv
has body: I am following this tutorial for image classification in Tensorflow: http://cv-tricks.com/tensorflow-tutorial/training-convolutional-neural-network-for-image-classification/. The training and test on a single image works fine. However my code for prediction on a large number of images is very slow and it consumes 100% of CPU and almost max out memory as well! For 2700 images it takes more than 24 hours! It is not practical. Is there a way to do batch testing the same way we did batch training? Please note I need to do normalization on the images as well. Here is my code: import tensorflow as tf import numpy as np import os,glob,cv2 import sys,argparse # First, pass the path of the image os.chdir("/somepath") i = 0 files = glob.glob('*.jpg') files.extend(glob.glob('*.JPG')) totalNumber = len(files) print("total number of images is:", totalNumber) image_size=128 num_channels=3 text_file = open("Results.txt", "w") for file in files: images = [] filename = file print(filename) text_file.write("\n") text_file.write(filename) # Reading the image using OpenCV image = cv2.imread(filename) # Resizing the image to our desired size and preprocessing will be done exactly as done during training image = cv2.resize(image, (image_size, image_size),0,0, cv2.INTER_LINEAR) images.append(image) images = np.array(images, dtype=np.uint8) images = images.astype('float32') images = np.multiply(images, 1.0/255.0) #The input to the network is of shape [None image_size image_size num_channels]. Hence we reshape. x_batch = images.reshape(1, image_size,image_size,num_channels) ## Let us restore the saved model sess = tf.Session() # Step-1: Recreate the network graph. At this step only graph is created. saver = tf.train.import_meta_graph('pathtomymeta/my_model-9909.meta') # Step-2: Now let's load the weights saved using the restore method. saver.restore(sess, tf.train.latest_checkpoint('pathtomycheckpoints/checkpoints/')) # Accessing the default graph which we have restored graph = tf.get_defau…
has title: Tensorflow prediction on large number of images is slow
tagged with: python
tagged with: computer-vision
has answer: http://stackoverflow.com/a/48211696
accepted answer: http://stackoverflow.com/a/48211696
type: AnsweredQuestion
score: 0
tagged with: deep-learning
answer count: 1

http://stackoverflow.com/comment/83446609
type: Comment
comment on: http://stackoverflow.com/a/48231599
score: 0
type: AnswerComment
has text: `user = mysql port=3306 socket = /opt/lampp/var/mysql/mysql.sock`

http://stackoverflow.com/q/48259933
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83502519
has body: I'm trying to make a script, that takes a folder as input, and deletes files older than one week. For some reason, my program does not output expected values. I used: os.stat('testFile1.txt').st_mtime os.stat('testFile1.txt').st_atime I expected atime to return the time the file was last accessed, and mtime last modification, in seconds. I get a really high number on both, even though I have just opened a file. Am I doing something wrong? Should I use another method to get the time?
tagged with: python
has answer: http://stackoverflow.com/a/48260069
accepted answer: http://stackoverflow.com/a/48260108
has answer: http://stackoverflow.com/a/48260056
has answer: http://stackoverflow.com/a/48260108
has comment: http://stackoverflow.com/comment/83502648
has title: Get the time since a file was last accessed in Python
upvote count: 2
type: AnsweredQuestion
answer count: 3
score: 1
possible better answer: http://stackoverflow.com/a/48260056

http://stackoverflow.com/q/48268453
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83584685
has comment: http://stackoverflow.com/comment/83523752
has answer: http://stackoverflow.com/a/48273759
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/48274170
answer count: 3
downvote count: 0
tagged with: image-processing
tagged with: scipy
favorite count: 0
has comment: http://stackoverflow.com/comment/83584054
tagged with: numpy
tagged with: opencv
type: Question
has body: I have an image showing some objects, where one object is always inside the other. The background is always black. I want to know the circumference of both objects and got to a solution. I use a filterkernel to get the 4-neighborhood of each pixel. Then I count the number of zero pixels around the pixel. This gives me the length in pixel units of the shape. I count only in the case, if the center pixel is the desired color. from scipy import misc, ndimage import numpy as np import time def get_circumference(arr, only=50, repl=50): def c_length(values): # 3rd value is the pixel if values[2] == only: return sum([x == 0 or (repl == 0 and x != only) for x in values[[0,1,3,4]]]) return 0 fp = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) res = ndimage.generic_filter(arr, c_length, footprint=fp) return np.sum(res, axis=None) x = ndimage.imread("image.png", mode='L') tic = time.time() inner = get_circumference(x, only=255, repl=0) outer = get_circumference(x, only=128, repl=128) print("Inner object: {}, outer object: {}, took: {}".format(inner, outer, time.time() - tic)) gives me: Inner object: 510, outer object: 1054, took: 0.8387038707733154 It works quite fine. But it is very slow. It takes about 500 to 1000 ms for a single image. As I need to do this for several thousand images, it will take too much time. Is there any way to speed this up? I know, that the images will always contain three colors and that the inner section will always fully enclosed by the outer one. Also there will never be the case of an shape crossing image boundaries. Of course there are different methods to actually calculate the circumference. Given just a single pixel, there are two possible solutions: 1 or 4. The first method just counts the number of pixels, i.e. a single pixel counts as a single unit of circumfernece. In the latter case, the actual edges of the pixel are counted. In my solution I used the latter method to count the circumfernece. If you count just by edge detection and histogra…
has answer: http://stackoverflow.com/a/48272266
has title: Is there a faster way for finding the circumference of a shape?
tagged with: python

http://stackoverflow.com/comment/83542951
type: QuestionComment
type: Comment
score: 0
has text: Could you explain what mean `<package>.rabbitmq.pika`?
comment on: http://stackoverflow.com/q/48273420

http://stackoverflow.com/comment/83531743
type: QuestionComment
comment on: http://stackoverflow.com/q/48273748
type: Comment
score: 0
has text: I did a stupid mistake by not normalizing my validation set after it the results are not that big, but still not satisfying: MAE: 88834.726562 MRE: 0.355447

http://stackoverflow.com/q/48215159
possible better answer: http://stackoverflow.com/a/48407274
type: AnsweredQuestion
upvote count: 3
score: 3
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50734595
tagged with: tensorflow
favorite count: 0
type: Question
has title: Error exporting inference graph (ValueError)
has body: So I'm following sentdex's object detection tutorial and I have gotten to the step where you are supposed to export the inference graph. I'm using the "export_inference_graph.py" script from Tensorflow's object_detection folder. The problem is that I'm getting this ValueError: Traceback (most recent call last): File "C:\Users\Zelcore-Dator\AppData\Local\Programs\Python\Python35\lib\site-packages\google\proto buf\internal\python_message.py", line 545, in _GetFieldByName return message_descriptor.fields_by_name[field_name] KeyError: 'layout_optimizer' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "export_inference_graph.py", line 119, in &lt;module&gt; tf.app.run() File "C:\Users\Zelcore-Dator\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\p ython\platform\app.py", line 48, in run _sys.exit(main(_sys.argv[:1] + flags_passthrough)) File "export_inference_graph.py", line 115, in main FLAGS.output_directory, input_shape) File "C:\Users\Zelcore-Dator\AppData\Local\Programs\Python\Python35\lib\site-packages\object_detec tion-0.1-py3.5.egg\object_detection\exporter.py", line 427, in export_inference_graph input_shape, optimize_graph, output_collection_name) File "C:\Users\Zelcore-Dator\AppData\Local\Programs\Python\Python35\lib\site-packages\object_detec tion-0.1-py3.5.egg\object_detection\exporter.py", line 391, in _export_inference_graph initializer_nodes='') File "C:\Users\Zelcore-Dator\AppData\Local\Programs\Python\Python35\lib\site-packages\object_detec tion-0.1-py3.5.egg\object_detection\exporter.py", line 72, in freeze_graph_with_def_protos layout_optimizer=rewriter_config_pb2.RewriterConfig.ON) File "C:\Users\Zelcore-Dator\AppData\Local\Programs\Python\Python35\lib\site-packages\google\proto buf\internal\python_message.py", line 484, in init field = _GetFieldByName(message_descriptor, field_name) File "C:\Users\Zelcore-Dator\AppData\Local\Programs\Python\Python35\lib\site-packages\goo…
has answer: http://stackoverflow.com/a/48285514
accepted answer: http://stackoverflow.com/a/48285514
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/48407274

http://stackoverflow.com/a/48633605
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48308693
downvote count: 1
type: Answer
has body: Thanks to Google Cloud Support - I was able to fix the issue. In summary: Clone the latest wordcount.py example (I have used an older version): git clone https://github.com/apache/beam.git The Google team updated the tutorial, so simply follow the code instructions. Make sure to include the @classmethod _add_argparse_args to be able to receive arguments during runtime, and use the new options when reading from the text file: wordcount_options = pipeline_options.view_as(WordcountTemplatedOptions) lines = p | 'read' >> ReadFromText(wordcount_options.input) Generate the template as instructed You should see the template under the template_location directory now Thanks!
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48308693
score: 1

http://stackoverflow.com/comment/83484498
type: Comment
has text: Thanks, now I need to look for APP_SECRET. What is the proxies?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48250330

http://stackoverflow.com/a/48177743
downvote count: 1
has comment: http://stackoverflow.com/comment/83335847
score: -1
has comment: http://stackoverflow.com/comment/83335780
answers question: http://stackoverflow.com/q/48176752
upvote count: 0
type: Answer
has body: I know you've "solved" the problem by leaving out a parameter, but the correct way to do this would be using a FormRequest yield scrapy.FormRequest( url=url, method='GET', formdata=payload, callback=self.parse_item )

http://stackoverflow.com/comment/83611053
comment on: http://stackoverflow.com/q/48312527
type: QuestionComment
has text: or use the `gmpy2` library
type: Comment
score: 0

http://stackoverflow.com/comment/83624519
comment on: http://stackoverflow.com/q/48318858
score: 3
type: Comment
type: QuestionComment
has text: One of them is coded in C. the other in pure Python so carries a lot of overhead. See the numpy section of Jake Vanderplas' book https://github.com/jakevdp/PythonDataScienceHandbook/blob/599aa0fe3f882c0001670e676e5a8d43b92c35fc/notebooks/02.00-Introduction-to-NumPy.ipynb (it continues with a couple of subsections).

http://stackoverflow.com/comment/83648121
has text: Yes, the second one does indeed have a scout file. ty for the tip on the dicomdir file, I found it and will see what I can get out of it. tbh I am not partial towards vtk, it is just want I have (because pcl uses it), and I will get DCMTK set up and try it out, thanks!
type: Comment
comment on: http://stackoverflow.com/a/48331074
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83550683
type: Comment
comment on: http://stackoverflow.com/a/48269334
type: AnswerComment
has text: While adding `.copy()` in front of view eliminates the FutureWarning from numpy 1.13, that line will still trigger the same ValueError from numpy 1.14.
score: 0

http://stackoverflow.com/a/48802007
answers question: http://stackoverflow.com/q/48276011
downvote count: 0
has body: Using a dictionary (if needed collections.OrderedDict) would make the looping easier. Using the recommendable anytree package it would give the wanted graphical output and the whole code would be just: import anytree # parent-child relations table = [ [1, 2], [5, 3], [2, 5], [2, 6], [2, 4], [6, 7], ] def build_tree_recursively(p_num, p_node): for c_num in parent_children[p_num]: # add children c_node = anytree.Node(str(c_num), parent=p_node) if c_num in parent_children: # dive into build_tree_recursively(c_num, c_node) # map parents to list of children parent_children = {} for p, c in table: # numbers if p in parent_children: parent_children[p].append(c) else: parent_children[p] = [c] p = 1 # assuming single root node (else add loop over elements not in column B) tree = anytree.Node(str(p)) build_tree_recursively(p, tree) # render for pre, fill, node in anytree.RenderTree(tree): print("{}{}".format(pre, node.name))
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/83357035
type: QuestionComment
comment on: http://stackoverflow.com/q/48188307
type: Comment
score: 0
has text: I wonder why downvotes... I have tried every method on google.

http://stackoverflow.com/a/72441252
score: 0
answers question: http://stackoverflow.com/q/48270038
has body: Tiny beginning of code fragment for writing your own Expression class for COALESCE(), see official documentation link below for full source. Note: not all databases have a COALESCE(), which I assume is why this isn't an official Expression already. It's probably possible to write some code which turns this into a standard Case(...) expression as a fallback, then use COALESCE() for the db specific sql conversions. I leave that as an exercise for the reader ;-) from django.db.models import Expression class Coalesce(Expression): template = 'COALESCE( %(expressions)s )' ... Official documentation for the full code: Django Models - Writing your own Query Expressions
type: Answer

http://stackoverflow.com/comment/83588663
comment on: http://stackoverflow.com/q/48301798
type: Comment
type: QuestionComment
score: 0
has text: instead of `for XandY in snakeList[:-1]:` you can do `for X, Y in snakeList[:-1]:` and then you can use `[X, Y, blockSize, blockSize]` instead of `[XandY[0], XandY[1], blockSize, blockSize]` - it will be more readable.

http://stackoverflow.com/a/48314533
upvote count: 33
score: 32
type: Answer
has comment: http://stackoverflow.com/comment/85426325
has comment: http://stackoverflow.com/comment/85405674
has comment: http://stackoverflow.com/comment/124047162
accepted answer of: http://stackoverflow.com/q/48313387
answers question: http://stackoverflow.com/q/48313387
type: AcceptedAnswer
has body: Stratification means to keep the ratio of each class in each fold. So if your original dataset has 3 classes in the ratio of 60%, 20% and 20% then stratification will try to keep that ratio in each fold. In your case, X = ["hey", "join now", "hello", "join today", "join us now", "not today", "join this trial", " hey hey", " no", "hola", "bye", "join today", "no","join join"] y = ["n", "r", "n", "r", "r", "n", "n", "n", "n", "y", "n", "n", "n", "y"] You have a total of 14 samples (members) with the distribution: class number of members percentage 'n' 9 64 'r' 3 22 'y' 2 14 So StratifiedKFold will try to keep that ratio in each fold. Now you have specified 10 folds (n_splits). So that means in a single fold, for class 'y' to maintain the ratio, at least 2 / 10 = 0.2 members. But we cannot give less than 1 member (sample) so that's why its throwing an error there. If instead of n_splits=10, you have set n_splits=2, then it would have worked, because than the number of members for 'y' will be 2 / 2 = 1. For n_splits = 10 to work correctly, you need to have atleast 10 samples for each of your classes.
downvote count: 1
has comment: http://stackoverflow.com/comment/85414557

http://stackoverflow.com/a/48254780
downvote count: 0
has body: Use np.searchsorted to index into a sorted version of C.price. p1 = D.price.values v = np.sort(C.price.values) p2 = v[np.searchsorted(v, p1) - 1] p2 array([ 0.34, 3.24, 0.34, 9.77, 3.24, 3.24, 6.34, 6.34, 0.34]) Now, subtract them p2 from p1. pd.Series(p1 - p2) 0 2.00 1 0.32 2 0.93 3 0.01 4 1.89 5 2.99 6 3.22 7 2.89 8 0.11 dtype: float64
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48254436
upvote count: 1

http://stackoverflow.com/comment/83524464
has text: Thanks for the response - added sample data above.
comment on: http://stackoverflow.com/q/48267483
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83636997
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48310269
has text: Not directly, but there is a delay or wait node which can either was it for a file creation event or a period of time after which you could test if there was new data in a loop
score: 0

http://stackoverflow.com/comment/83448332
type: QuestionComment
has text: Remove the "\" character from your query string. Multi-line strings start and end with triple quotes or triple single quotes. I think the backslash character is breaking your query. However, you should be getting an error if this is true. When you look at Redshift, do you see any new tables?
comment on: http://stackoverflow.com/q/48232367
score: 0
type: Comment

http://stackoverflow.com/q/48176802
tagged with: web-scraping
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48177309
has title: Trouble writing data in an excel file accordingly
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48176895
tagged with: python
has body: I'm very new to work with xlsxwriter in python. I have created a scraper in python and it is working flawlessly. However, when I try to write these data in an excel file using xlsxwriter I get stuck. What I have written so far can create an excel file and write the last populated data derived from the for loop. How can I rectify my script to write all the data rather than the last one. It would be better If i knew how to append the newly populated values on the fly. The bottom line is, I'm getting two issues: My script writes only the last populated values The two fields are being written in a line, as in row("A1"), row("A2") but I wish to have them like row("A1"), row("B1") and so on. Script I've tried with: import requests from bs4 import BeautifulSoup import xlsxwriter row = 0 col = 0 with xlsxwriter.Workbook('torrent.xlsx') as workbook: worksheet = workbook.add_worksheet() with requests.Session() as s: s.headers = {"User-Agent":"Mozilla/5.0"} res = s.get("https://www.yify-torrent.org/search/1080p/") soup = BeautifulSoup(res.text, 'lxml') for item in soup.select(".mv"): name = item.select("a")[0].text link = item.select("a")[0]['href'] data = name , link for elem in data: worksheet.write(row, col, elem) row += 1 The result I'm having like (in a line): title link Whereas, I wish to have them like (in separate rows): title link title1 link1 title2 link2 and so on.
score: 0
answer count: 2
tagged with: xlsxwriter

http://stackoverflow.com/q/48178560
score: 0
tagged with: list
answer count: 1
tagged with: python
tagged with: reference
type: Question
has title: Tkinter/Python: list1 updates even when it shouldn't when I only compare list2 to list1
accepted answer: http://stackoverflow.com/a/48178862
tagged with: tkinter
has answer: http://stackoverflow.com/a/48178862
has body: I'm confused as to why an index in the masterList is updated/changed when I don't update/touch it within my code under the updateCustomerList function. I only use it as a reference to my customerList. It only does this when i use a negative quantity value to basically delete or remove objects from the frame refreshMasterList() just allows me to refresh the frame so the frame will be populated by the new data updated inside the customerList. NOTE: If the indentation seems wrong, let me know. Also i created a gist to see the whole program If you want to run the program and check it out for yourself, just download this test excel doc and use 3605520297939 as the bar code def updateCustomerList(barCode, quantity): global customerList if not barCode.get(): return else: for i in range(len(masterList)): if int(barCode.get()) == masterList[i][4]: if len(customerList) == 0: customerList.append(masterList[i]) customerList[0].append(quantity.get()) print("Customer list is empty, before delete " + str(customerList) + " M " + str(masterList[i])) if customerList[0][5] &lt;= 0: del customerList customerList = [] print("Customer list is empty" + str(customerList) + " M " + str(masterList[i])) refreshMainFrame() else: print("~CustomerList is not empty " + str(masterList[i])) for j in range(len(customerList)): if int(barCode.get()) == customerList[j][4]: intQuantity = customerList[j][5] + quantity.get() if intQuantity &lt;= 0: del customerList[j] print("~~Customer list is not empty but w/ repeated bar code" + str(customerList) + " M " + str(masterList[i])) refreshMainFrame() return customerList.append(masterList[i]) #adds a masterList object inside customerList customerList[len(customerList)-1].append(quantity.get()) if customerList[len(customerList)-1][5] &lt;= 0: del customerList[len(customerList)-1] print("~~~Customer list is not empty" + str(customerList) + " " + str(masterList[i])) refreshMainFrame() refreshMainFrame() return
type: AnsweredQuestion

http://stackoverflow.com/q/48216748
has answer: http://stackoverflow.com/a/48217098
accepted answer: http://stackoverflow.com/a/48217098
downvote count: 1
tagged with: pygame
tagged with: collision-detection
has body: I'm attempting to make a game with python, where a character shoots at incoming waves of enemies. I have a list of bullets, a list of the enemies' bodies, and a list of their heads. For some reason when I shoot and the bullet collides with an enemy, there is one of two outcomes. Either I get an error: "List index out of range" or all the enemies that spawn after get deleted, and eventually I get the same error. How do I fix this? Also, I'm trying to get an image to appear every time I shoot a bullet (Muzzle flash), and I'm having some trouble. can anyone help from pygame import * import random import math import os #Displays the pygame window at the top left of the screen os.environ['SDL_VIDEO_WINDOW_POS'] = "%d, %d" %(0,25) init() #Starts pygame font.init() myfont = font.SysFont("arial", 18) #clock = time.Clock() LENGTH = 1000 #Creates Screen that is 1000 X 700 WIDTH = 700 SIZE = (LENGTH, WIDTH) Screen = display.set_mode(SIZE) lastTime = time.get_ticks() lastTime2 = time.get_ticks() lastTime3 = time.get_ticks() ShotCooldown = 300 GBSpawn_Rate = 1500 MuzzleFl_Length = 100 MuzzleFlash = image.load("MuzzleFlash.png") ForestBg = image.load('ForestBackground.jpg') RowOfBushes = image.load('Row of Bushes.png') #Defines colours BLACK = (0,0,0) WHITE = (255,255,255) RED = (255,0,0) GREEN = (0,255,0) YELLOW = (253,228,74) PATH = (232,224,136) GRASS = (112,200,160) CASTLE= (212,211,209) SKIN = (222,174,150) BULLET = (147,105,68) GRASS2 = (180,221,160) ROBOT = (150,150,150) myClock = time.Clock() running = True CaptainY = 500 Key = 0 BulletX = 900 BulletY = 0 RidgeY = 130 Shooting = False Shots = [] Flashes = [] Flashes_T = [] Gigabits = [] Gigabits_Heads = [] Gigabit_Health = [] Health = 100 Collided_bullet = 0 MoveUp = False MoveDown = False while running: for evnt in event.get(): # checks all events that happen if evnt.type == QUIT: # if event type is quit the program stops running running = False if evnt.type == KEYDOWN: Key = evnt.key if Key == K_UP: MoveUp = True if Key…
has comment: http://stackoverflow.com/comment/83416223
has comment: http://stackoverflow.com/comment/83415565
favorite count: 0
type: Question
answer count: 1
linked to: http://stackoverflow.com/q/1207406
tagged with: python
has comment: http://stackoverflow.com/comment/83416034
has comment: http://stackoverflow.com/comment/83415593
has comment: http://stackoverflow.com/comment/83415630
type: AnsweredQuestion
score: 0
has title: Collision detection issue within my code (python)
upvote count: 1

http://stackoverflow.com/q/48265360
tagged with: python
has body: I have a numeric vector. I want to enumerate over the vector and create a string as the result. For example, if I have a vector x = c(1, 3) I want the resulting string to be: y = '1x1 + 3x2' In Python, I would do this: l = [1, 3] equation = ' + '.join(['{}x{}'.format(coef, i + 1) for i, coef in enumerate(l)]) str = 'y = {}'.format(equation) How can the same thing be done in R?
has title: Create string from vector
type: Question
upvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/48265415
downvote count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
has answer: http://stackoverflow.com/a/48265415
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/48228674
type: Question
tagged with: pydev
has title: Error importing requests into python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48231312
tagged with: python
has body: I am writing a Merchant Data Export API in Python (Pydev plugin for eclipse) and I cannot import requests, is there some option for managing imports? I have the requests-master folder in my project, downloaded from GitHub. I have read the following articles for downloadingand installing, but nothing works for me. I am a new python user but would like to learn more. Thanks for any help!
score: 0
tagged with: api
answer count: 1
tagged with: eclipse
tagged with: import

http://stackoverflow.com/q/48263147
has answer: http://stackoverflow.com/a/48359618
type: Question
tagged with: layout
type: UnansweredQuestion
answer count: 1
tagged with: python
has body: I'm developing an App in Kivy technology and I want to display a pull to refresh behaviour. The most I've done is a scroll view and control if the scroll_y coordinate to refresh but this has the disadvantage of only working if there is scroll and doesn't work if there isn't. &lt;TrytonTree&gt; app: app container: container do_scroll_x: False on_scroll_y: root.init_pull(self.scroll_y) on_scroll_stop: root.pull(self.scroll_y) MDList: id: container ... class TrytonTree(ScrollView, TrytonTreeMixin): def pull(self, scroll_y): if scroll_y &gt;= 2: self.app.refresh_screen([self.get_model_name()]) Clock.schedule_once(self.app.disable_spinner, 2) def init_pull(self, scroll_y): if scroll_y &gt;= 2: self.app.enable_spinner() So my question is if there is a way of controlling the swipe gesture so I can call the refresh function or something similar. Thanks.
score: 0
has title: SwipeRefreshLayout in Kivy
tagged with: kivy

http://stackoverflow.com/a/48301767
has body: Here you go: Z = [['A', 'B', 'C'], [1], ['x', 'y']] import itertools for element in itertools.product(*Z): print(element) Result: ('A', 1, 'x') ('A', 1, 'y') ('B', 1, 'x') ('B', 1, 'y') ('C', 1, 'x') ('C', 1, 'y')
downvote count: 1
answers question: http://stackoverflow.com/q/48301633
type: Answer
score: 2
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48301633

http://stackoverflow.com/comment/122621486
type: QuestionComment
comment on: http://stackoverflow.com/q/48259511
score: 0
type: Comment
has text: Based on this study, https://hammer.purdue.edu/articles/thesis/Encoding_IP_Address_as_a_Feature_for_Network_Intrusion_Detection/11307287, splitting the IP address into four numbers.

http://stackoverflow.com/a/48187530
upvote count: 3
answers question: http://stackoverflow.com/q/48185513
downvote count: 0
type: Answer
score: 3
has body: It turns out I had a setup_class but no teardown_class, and my class instance was still active, and preventing the test session from ending.

http://stackoverflow.com/comment/83658765
type: QuestionComment
comment on: http://stackoverflow.com/q/48226392
type: Comment
has text: @ekhumoro I think I have adhered to the link you shared now. Could you be kind enough to help?
score: 0

http://stackoverflow.com/comment/83460814
has text: @Theo Then try replacing the full path and just use zf.write("original.file")?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48239129
score: 0

http://stackoverflow.com/comment/83487103
has text: The short answer is yes, it makes sense. In Python (and most/all of computer science), `True=1` and `False=0`. One-hot encoding transforms categorical variables into 1s and 0s by creating columns for each categorical variable. In the case of your data, that's already done. `df.corr()` returns the correlation between price and each of your columns. You could make the substitution I mentioned before and your results wouldn't change.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48241158

http://stackoverflow.com/a/48207059
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48207032
upvote count: 1
has body: use groupby + cumprod: In [6]: df['Product'] = df.groupby('Company')['Value'].cumprod() In [7]: df Out[7]: Company Year Value Product 0 A 1990 1 1 1 A 1991 2 2 2 A 1992 3 6 3 A 1993 4 24 4 B 1990 5 5 5 B 1991 6 30 6 B 1992 7 210 7 B 1993 8 1680
answers question: http://stackoverflow.com/q/48207032
has comment: http://stackoverflow.com/comment/83395222
has comment: http://stackoverflow.com/comment/83395159
type: Answer
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/83339227
score: 0
has text: Wouldn't it be sufficient to test that `send_money`is called?
comment on: http://stackoverflow.com/q/48179407
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48285057
type: UnansweredQuestion
tagged with: fabric
upvote count: 1
tagged with: python
has body: I have a fabfile that run several tasks on the hosts. This results in the creation of a file result.txt in each of the hosts. Now I want to get all these files locally. This is what I tried: from invoke import task @task def getresult(ctx): ctx.get('result.txt') I run with: fab -H host1 host2 host3 getresult In the end, I have only one file result.txt in my local machine (it seems to be the copy from the last host of the command line). I would like to get all the files. Is there a way to do this with fabric v2? I did not find anything in the documentation. It seems that this was possible in fabric v1, but I am not sure for the v2.
score: 1
has title: How to use the get method with multiple hosts in fabric v2?
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48395658

http://stackoverflow.com/a/48223348
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: This is because of the order in which you have put your middleware. request.user is added to the WSGI Request object by the AuthenticationMiddleware. place 'khxia.middlewares.PeeweeConnectionMiddleware', this middleware after AuthenticationMiddleware, or as the last middleware
answers question: http://stackoverflow.com/q/48222837
type: Answer
accepted answer of: http://stackoverflow.com/q/48222837

http://stackoverflow.com/comment/83639725
type: Comment
has text: @Peilonrayz, I have updated the question, please, take a look. PS I just finished a research on your answer to my previous question: the way you packed methods of checking the duplicates is very elegant and efficient. Each subsequent method is called only if the previous one didn't obtain the definite result. Took me some time to get it:)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48276339

http://stackoverflow.com/a/48383292
answers question: http://stackoverflow.com/q/48317624
has comment: http://stackoverflow.com/comment/83764342
type: Answer
has comment: http://stackoverflow.com/comment/83756842
downvote count: 0
upvote count: 1
score: 1
has body: I've managed to resolve the cert error of proxpy mentioned in your question, but still failed to proxy https request. If what you need is a proxy for examination of HTTP traffic, mitmproxy is a handy tool and best of the breed.

http://stackoverflow.com/comment/83432387
comment on: http://stackoverflow.com/a/48224243
type: Comment
has text: Added an alternative more drastic filter approach.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/107852092
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48207834
has text: and what if you wanted the first and last row of each window as well? tried the apply approach, it works but simply does not scale well.
type: Comment

http://stackoverflow.com/comment/83644879
type: Comment
comment on: http://stackoverflow.com/q/48313111
type: QuestionComment
score: 0
has text: I wrote a pretty nifty framework for Selenium on python 2.7/3.6 that has this feature baked in and works for any browser/webdriver. If you wanted to check it out https://github.com/neetjn/py-component-controller

http://stackoverflow.com/q/48322986
has title: python argparse - passing "argument" to argument
has comment: http://stackoverflow.com/comment/83639692
has body: I'd like to pass an "argument" to argument. I.e., in the following code: import argparse parser = argparse.ArgumentParser() parser.add_argument("-a") print parser.parse_args(['-a', 'hi']) print parser.parse_args(['-a', '-hi']) The output is: Namespace(a='hi') usage: problem.py [-h] [-a A] problem.py: error: argument -a: expected one argument While I'd like it to be: Namespace(a='hi') Namespace(a='-hi') How can I achieve that? I've seen in the help the section 15.4.4.3. Arguments containing -, but it seems to support only negative numbers. Also, they suggest passing "--", but it's not good in my use case, but everything after the "--" isn't treated as argument (if I understand correctly). But I want "-a" to consume only 1 argument, and then continue parsing the other arguments as real arguments. How can it be done? EDIT Adding a space before the argument works: print parser.parse_args(['-a', ' -hi']) But is there a way to achieve that, without requiring the user to add spaces?
score: 0
has comment: http://stackoverflow.com/comment/83632729
tagged with: argparse
has answer: http://stackoverflow.com/a/48327039
has comment: http://stackoverflow.com/comment/83634055
answer count: 1
linked to: http://stackoverflow.com/q/16174992
type: Question
duplicate of: http://stackoverflow.com/q/16174992
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83634861
tagged with: python

http://stackoverflow.com/comment/83469167
has text: You do understand that `print()` is just printing an empty line, right? ;)
score: 0
comment on: http://stackoverflow.com/q/48243348
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83642700
has text: If you don't understand what `word = "milliways"` does, you need to pick up a Python tutorial and learn the basics.
score: 1
comment on: http://stackoverflow.com/q/48328455
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83439786
has text: right. I mostly wanted it for debugging and twinkling code. It just gets on my nerves importing a module and then hitting up arrow to reload module after a code change and then realizing you need import importlib.reload instead
score: 0
comment on: http://stackoverflow.com/q/48228215
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48265995
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/48265852
upvote count: 2
has body: You need to tell Linux how to run Main.py i.e. specify 'python "Main.py"' (this isn't needed on Windows if python is set as the default program to use to open .py files, but it should still work fine to specify it on Windows regardless) e.g. ~ $ cat Main.py import sys name=sys.argv[1] send=sys.argv[2] print name+" "+send ~ $ python Python 2.7.12 (default, Nov 20 2017, 18:23:56) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; value="bar";id="foo" &gt;&gt;&gt; os.system('python "Main.py" %s %s' % (id, value)) foo bar 0 But most likely you shouldn't be running a second python script like this, but should instead be importing it and calling it's code directly.
answers question: http://stackoverflow.com/q/48265852
type: AcceptedAnswer
downvote count: 0

postgresql
tags question: http://stackoverflow.com/q/48218869
tags question: http://stackoverflow.com/q/48293666
tags question: http://stackoverflow.com/q/48291939
tags question: http://stackoverflow.com/q/48303923
tags question: http://stackoverflow.com/q/48286329
tags question: http://stackoverflow.com/q/48270038
tags question: http://stackoverflow.com/q/48221301
tags question: http://stackoverflow.com/q/48282281
type: Tag
tags question: http://stackoverflow.com/q/48296144
tags question: http://stackoverflow.com/q/48282546
tags question: http://stackoverflow.com/q/48230518
tags question: http://stackoverflow.com/q/48243602
tags question: http://stackoverflow.com/q/48176885
tags question: http://stackoverflow.com/q/48184300
tags question: http://stackoverflow.com/q/48288076
tags question: http://stackoverflow.com/q/48183177
tags question: http://stackoverflow.com/q/48177324
tags question: http://stackoverflow.com/q/48247365
tags question: http://stackoverflow.com/q/48214884
tags question: http://stackoverflow.com/q/48288109
tags question: http://stackoverflow.com/q/48208959
tags question: http://stackoverflow.com/q/48299705
tags question: http://stackoverflow.com/q/48215592
tags question: http://stackoverflow.com/q/48320868
tags question: http://stackoverflow.com/q/48226944
tags question: http://stackoverflow.com/q/48282792
tags question: http://stackoverflow.com/q/48176567
tags question: http://stackoverflow.com/q/48244194
tags question: http://stackoverflow.com/q/48221588
tags question: http://stackoverflow.com/q/48212717
tag name: postgresql
tags question: http://stackoverflow.com/q/48292735
tags question: http://stackoverflow.com/q/48326859
tags question: http://stackoverflow.com/q/48218146
tags question: http://stackoverflow.com/q/48301339
tags question: http://stackoverflow.com/q/48301694
tags question: http://stackoverflow.com/q/48237410

http://stackoverflow.com/comment/83347062
score: 0
has text: @byxor I understand, should I delete this question?
comment on: http://stackoverflow.com/q/48183646
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48243321
score: 1
has comment: http://stackoverflow.com/comment/83521147
has comment: http://stackoverflow.com/comment/83509432
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48199784
type: Answer
has body: I don't know of a specific issue with v0.12 that would lead to a segfault but before we dig in, I'd recommend upgrading to v1.0 which was released 2017-12-04. If you still encounter the same problem with 1.0 we can work to debug.

http://stackoverflow.com/q/48207313
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48207632
has body: I have this data: prodcutname,price_rate,price,quantity [['phone', '500', 450.0, 1], ['phone', '500', 2250.0, 5], ['camera', '200', 1080.0, 6], ['laptop', '600', 540.0, 1], ['laptop', '600', 540.0, 1],['laptop', '600', 540.0, 1]] Now, what I need to do is create a new list with only unique elements(products), and add other values of the same product and put them into list. The ideal output would look like: [['phone','500',2700,6],['camera','220',1080,6],....] I tried doing this using - unique_list = ['phone', '500', 450.0, 1] big_list = [] mylist = [] for i in range(len(larger_list)): for j in range(1,len(larger_list)): if(larger_list[i][0]==larger_list[j][0]): # Getting the sum or prices and number #Sum of price larger_list[j][2]=larger_list[i][2]+larger_list[j][2] #Sum of number larger_list[j][3]=larger_list[i][3]+larger_list[j][3] #Adding into a new list unique_list[0]=larger_list[i][0] unique_list[1]=larger_list[i][1] unique_list[2]=larger_list[j][2] unique_list[3]=larger_list[j][3] mylist.append(unique_list) big_list.append(mylist) mylist = [] return big_list But ran into a lot of error to no avail. I even tried by putting them into dictionary. How do I go about doing this in Python?
has answer: http://stackoverflow.com/a/48210646
score: 2
tagged with: list
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/83398039
has answer: http://stackoverflow.com/a/48208182
has comment: http://stackoverflow.com/comment/83396527
downvote count: 0
favorite count: 0
type: Question
has title: How to check the uniqueness of lists inside list?
has comment: http://stackoverflow.com/comment/83395614

http://stackoverflow.com/comment/83990822
type: QuestionComment
has text: It's working when I change the machine type image to Ubuntu instead of Debian. This is not the solution but just a workaround only.
comment on: http://stackoverflow.com/q/48275475
score: 0
type: Comment

http://stackoverflow.com/q/48173902
tagged with: google-url-shortener
has comment: http://stackoverflow.com/comment/83329248
has comment: http://stackoverflow.com/comment/83331795
has comment: http://stackoverflow.com/comment/83327544
tagged with: python
has title: Killing a Sub Process while using Multiprocessing
answer count: 0
score: 1
has body: I need to shorten multiple urls using the Google Shortener API. Since each shortening process is not interdependent I decided to use multiprocessing library in Python. raw_data is a data frame which contains my long url. Api_Key is a list which contains api key from multiple google accounts(as i dont want to hit the limit of api usage for a day) Here is the underlying code. import pandas as pd import time from multiprocessing import Pool import math import requests raw_data["Shortened"] = "xx" Api_Key_List1 = ['Key1', 'Key2', 'Key3'] raw_data = raw_data[0:3] LongUrl = raw_data['SMS Click traker'].tolist() args = [[LongUrl[index], Api_Key_List1[index]] for index,value in enumerate(LongUrl)] print("xxxx") def goo_shorten_url(url,key): post_url = 'https://www.googleapis.com/urlshortener/v1/url?key=%s'%key payload = {'longUrl': url} headers = {'content-type': 'application/json'} time.sleep(2) r = requests.post(post_url, data=json.dumps(payload), headers=headers) return(json.loads(r.text)["id"]) def helper(args): return goo_shorten_url(*args) if __name__ == '__main__': p = Pool(processes = 3) data = p.map(helper,args) print("main") raw_data["Shortened"]=data p.close() print(raw_data) Using this code i am successfully shorten multiple urls in one go thus saving a lot of time. Here are some questions which i am having difficulty in finding answers to: What is the optimal number of sub-processes that I shall be running? (I am using a simple quadcore processor 8 gb ram laptop, Windows 7) Sometimes due to some issues the api does not return a shortened url. The code is stuck forever. This was my experience when i was not using multiprocess. What happens to the process in such case? Assuming the subprocess will get stuck for a long set of urls (70 000). How do I kill it and also ensure the code safely returns me all remaining shortened urls with proper matching in the data frame? How can I identify those urls which were not Shortened? I am a newbie to python programming, bear …
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83329246
has comment: http://stackoverflow.com/comment/83327724
favorite count: 0
type: Question
tagged with: python-multiprocessing
type: UnansweredQuestion

http://stackoverflow.com/q/48229056
type: Question
has comment: http://stackoverflow.com/comment/83440182
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83440029
has comment: http://stackoverflow.com/comment/83440426
tagged with: if-statement
has comment: http://stackoverflow.com/comment/83440054
has title: Is it there a reason not to use a JavaScript object literal for conditionally returning functions over a switch statement?
has comment: http://stackoverflow.com/comment/83440127
has comment: http://stackoverflow.com/comment/83440201
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/48229237
tagged with: switch-statement
has answer: http://stackoverflow.com/a/48229237
has comment: http://stackoverflow.com/comment/83440096
has comment: http://stackoverflow.com/comment/83440068
downvote count: 2
answer count: 1
tagged with: javascript
upvote count: 1
favorite count: 0
has body: I have been thinking about the lack of the the switch statement in Python and wondered if the work around, using a Python dictionary, could be approached in the same way in JavaScript using an Object literal? In JavaScript, I have traditionally seen switch statements or even if / else statements used for conditionally returning functions. switch(service) { case 'netflix': return netflix_service(); }.... I am wondering wondering whether you can just use the object literal in JS, which to me at least seems more syntactically concise. For example: services = { netflix: netflix(), ... }; But is there a reason that I keep seeing switch statements or if / else statements over the object literal approach? Whether performance or convention? Thanks in advance.

http://stackoverflow.com/comment/83601418
type: QuestionComment
comment on: http://stackoverflow.com/q/48307878
has text: See this: https://stackoverflow.com/questions/2161752/how-to-count-the-frequency-of-the-elements-in-a-list
score: 0
type: Comment

http://stackoverflow.com/comment/83394268
score: 0
has text: This will however easily run out of memory. Furthermore some collections (not lists) will raise an exception for good reasons when altering a collection when iterating over it.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48206683

http://stackoverflow.com/a/48186278
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48186194
downvote count: 0
has body: Since enemy is not a Sprite, but a Group, using spritecollide is wrong. You're looking for groupcollide, so change the line to hitenemy = pygame.sprite.groupcollide(enemy, bulletsPlayer, True, True)
answers question: http://stackoverflow.com/q/48186194

http://stackoverflow.com/q/48243492
upvote count: 0
downvote count: 2
linked to: http://stackoverflow.com/q/10834960
has title: How to I apply 2 variables to each element of a list in Python?
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83469735
has body: Basically, I want to make an algorithm that apply a function to each element in my list. database = ['A', 'B', 'A', 'B', 'C'] And I have a function named Weighting. def weighting(speed, time): return (speed * time) I want to apply this function to each element of the array so, mylist[0] = speed * time mylist[1] = speed * time mylist[2] = speed * time etc.. And for each element, they have different speeds and time. Then, I want to display the new array where each elements have been calculated based on the function weighting. So far i did: def weight(speed, time): return_list = [] for x in return_list: x = speed * time return return_list def run(): database = ['A', 'B', 'A', 'B', 'C'] I am new to python, so could someone help me?
tagged with: algorithm
has answer: http://stackoverflow.com/a/48243617
type: UnansweredQuestion
score: -2
tagged with: python

http://stackoverflow.com/q/48240139
has title: Errors with apostrophes and lists
has answer: http://stackoverflow.com/a/48240529
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48240251
answer count: 3
accepted answer: http://stackoverflow.com/a/48240251
downvote count: 0
score: 1
upvote count: 1
has body: I'm trying to insert brackets into the start and end of a list made from two lists placed together through .extend() so it prints like so: ('dog','cat','mouse')('pig, 'cow', 'sheep'). However the output I'm getting is 'dog', 'cat', 'mouse', 'pig', 'cow', 'sheep'. Whilst you can insert a bracket in many ways- "(" , chr(40) etc)- the obvious flaw is that the brackets output in quotations. .join I understand can be used for whole lists. However, I have not found a way to use it for one item- does such a way exist? My code looks like this: all_animals= [] house_animals= ['dog','cat','mouse'] farm_animals= ['pig', 'cow', 'sheep'] all_animals.extend(house_animals) all_animals.extend(farm_animals) print(str(all_animals)[1:-1]) EDIT In a similar vein, If a dictionary features an apostrophe (') [bear with me: it gets to lists] the output is affected as it prints that particular word in quotes ("") rather that the normal apostrophes. EXAMPLE: living_beings= {"Reptile":"Snake's","mammal":"whale", "Other":"bird"} and if you use the following code (which I need to): new= [] for i in living_beings: r=living_beings[i] new.append(r) then the output is "snake's", 'whale', 'bird' (Note the difference between the first and other outputs). So My question is: How to stop the apostrophes affecting output.
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48240431
has answer: http://stackoverflow.com/a/48240431
tagged with: arrays

http://stackoverflow.com/comment/83415644
type: Comment
type: QuestionComment
has text: Are you sure you want the columns to be dates? I'd think you'd want the tickers as column headers, and the dates as an index... AAPL's stock ticker isn't going to change any time soon, and days change, well, daily.
score: 2
comment on: http://stackoverflow.com/q/48216057

http://stackoverflow.com/comment/83381376
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48198863
type: QuestionComment
has text: Because my final goal is to find the case where the panel body already published the Panel "Report". Panel established, not yet composed means it doesn't published the report yet.

http://stackoverflow.com/comment/83575493
comment on: http://stackoverflow.com/q/48294464
has text: Your question is not clear for me.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83403668
has text: Possible duplicate of [Mapping US zip code to time zone](https://stackoverflow.com/questions/2456324/mapping-us-zip-code-to-time-zone)
score: 0
comment on: http://stackoverflow.com/q/48211262
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48232709
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83450745
has body: parse method has to return a dict, Scrapy Item or a Request object (see the documentation). In your case, you yield a string. If you run the spider, you'll see an error in the output. Change the corresponding part of the code like this: ... def parse(self, response): items = response.xpath('//div[@class="f"]/text()').extract() for url in items: print(url) yield {'url': url}
has comment: http://stackoverflow.com/comment/83456783
type: Answer
answers question: http://stackoverflow.com/q/48232176
score: 1

http://stackoverflow.com/q/48230473
tagged with: python
tagged with: sleep
type: Question
accepted answer: http://stackoverflow.com/a/48230618
score: 0
has answer: http://stackoverflow.com/a/48230618
has body: Recently, when creating a loop with a very short wait at the end, I ran into an unexpected behaviour of time.sleep() when used in quick succession. I used this piece of code to look further into my problem import time import statistics def average_wait(func): waits=[] loops=0 while loops&lt;1000: start=time.time() func(1/1000) waits.append(time.time()-start) loops+=1 print(waits) print("Average wait for 0.001: {}".format(statistics.mean(waits))) average_wait(time.sleep) This function usually returns something around 0.0013 which is many many times less accurate than just calling time.sleep() once, upon further inspection of this problem by looking at the waits list, I found that the amount of time time.sleep() was actually sleeping for was either almost exactly the right amount of time or almost exactly double the amount of time. Here is a sample from waits: [0.0010008811950683594, 0.0020041465759277344, 0.0009999275207519531, 0.0019621849060058594, 0.0010418891906738281] Is there any reason for this behaviour and anything that can be done to avoid it?
answer count: 1
has title: Unexpected time.sleep() behaviour
tagged with: python-3.x
type: AnsweredQuestion
tagged with: performance
tagged with: time

http://stackoverflow.com/a/48286058
has body: The requires=authentication needs to go inside the hug.get decorator.
answers question: http://stackoverflow.com/q/48283928
score: 0
type: Answer

http://stackoverflow.com/a/48332378
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/48317921
score: 5
type: AcceptedAnswer
downvote count: 0
has body: Let me start with a small clarification. You can't reshape a 1000 x 25 array into a 5 x 5 array. The number of elements in the original and reshaped arrays has to be the same. From your code, looks like you are trying to reshape each row of h2o frame, with 1 x 25, dimension into 5 x 5 numpy array, which should results in a 1000 x 5 x 5 array, since there are 1000 rows. Here is an example to do that and you can modify/apply it to your specific case. import h2o import numpy as np # initialize h2o h2o.init() # create a (1000, 25) h2o frame with real values (no missing values) hf = h2o.create_frame(rows=1000, cols=25, real_fraction=1, missing_fraction=0) # First convert to a pandas df, then to a numpy array num_array = hf.as_data_frame().as_matrix() # Reshape the array reshaped_array = num_array.reshape(1000, 25, 25) # Check the dimensions of the reshaped array reshaped_array.shape # The output should be: (1000, 5, 5) Hope this helps with your problem.
accepted answer of: http://stackoverflow.com/q/48317921

http://stackoverflow.com/a/48330495
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48330400
has body: You can simply use extend: def countPairs(): print() with open("hello.txt") as lines: linsiz = [] for line in lines: line = line.rstrip('\n') linsiz.extend(line[i:i+2] for i in range(len(line))) print(linsiz)

http://stackoverflow.com/a/48253140
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48252926
has body: A1. In students=[lloyd,alice,tyler] for student in students: print(student['name']) print (student["homework"]) print (student["quizzes"]) print (student["tests"]) variable student will successively hold references to the same objects as do lloyd, alice and tyler. These objects happen to be dictionaries. So e.g. in the first iteration student refers to the same dict object as lloyd, so student ['name'] refers to the same dictionary entry as lloyd ['name'] A2. Your interpretation is correct A3. Your interpretation is correct
answers question: http://stackoverflow.com/q/48252926
downvote count: 0
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/83488792

http://stackoverflow.com/a/48200155
score: 0
has body: How about a one-line workaround along these lines: s = re.sub(r'KEEPME', '@mention3', re.sub(r'@[A-Za-z0-9]+', '', re.sub(r'@mention3', 'KEEPME', 'I playing with @mention1, @mention2 and @mention3 in the field'))) if I understood your problem properly? And I'd just make sure to use a unique string that won't appear in the real tweet, instead of 'KEEPME'.
answers question: http://stackoverflow.com/q/48199747
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48199747

http://stackoverflow.com/comment/83691661
score: 0
type: Comment
type: AnswerComment
has text: Hey there, @Ian Thompson. Thanks again for your help. It's interesting because the code that you provided works well on the original sample dataset, but not on this new one. It does not sort the 'color' column by the 'Trial' column. As mentioned above, I've tried sort_values() and several other ways, but I'm stumped. I thought it might be because the color columns in the new dataset are in a different order than the ones in the sample set you worked on, but despite changing the order in the script @ the value_vars, no dice. Any ideas?
comment on: http://stackoverflow.com/a/48230121

http://stackoverflow.com/q/48263664
tagged with: python
tagged with: pyodbc
has title: Python pyodbc insert in for loop
has comment: http://stackoverflow.com/comment/83510207
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83510185
has answer: http://stackoverflow.com/a/48263763
upvote count: 0
has body: I'm trying to get urls and using extruct json and rdfa data by using libraries. Somehow there is a mistake in code and getting an sql error. The code is below import pyodbc import requests from pprint import pprint import extruct cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost\SQLEXPRESS;DATABASE=WebCrawler; Trusted_Connection=yes') cursor = cnxn.cursor() cursor.execute("select Id, url from WebCrawlerEFs") rows = cursor.fetchall() for row in rows: print (row.Id,",", row.url) r = requests.get(row.url) data = extruct.extract(r.text, r.url) cursor.execute("INSERT INTO RdfaEFs(rdfa) VALUES ('"data"')") cnxn.commit()
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/83510288
favorite count: 0
accepted answer: http://stackoverflow.com/a/48263763
type: Question
has comment: http://stackoverflow.com/comment/83515398
score: -3

http://stackoverflow.com/comment/83416399
has text: @Kirk Good catch. Try `[so]` ([so]) sometime! ;-)
type: QuestionComment
comment on: http://stackoverflow.com/q/48216574
score: 0
type: Comment

http://stackoverflow.com/q/48256081
has comment: http://stackoverflow.com/comment/83603860
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48256142
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48256199
has title: Python function declare a dynamic global variable
tagged with: python
tagged with: global
has comment: http://stackoverflow.com/comment/83494960
score: 2
answer count: 2
tagged with: sympy
upvote count: 2
downvote count: 0
has body: I saw the code below and I'm speechless. Here it is: &gt;&gt;&gt; import sympy &gt;&gt;&gt; sympy.var('x') x &gt;&gt;&gt; x x &gt;&gt;&gt; type(x) &lt;class 'sympy.core.symbol.Symbol'&gt; &gt;&gt;&gt; Notice that that the variable x has never been assigned. What's going on? In my opinion the function sympy.var accepts a string as an input parameter and declares a global variable of type sympy.core.symbol.Symbol whose name is equivalent to the parameter. So every time the function is called, a new variable will be available whose name is the last parameter passed to the function.

http://stackoverflow.com/a/48257897
has comment: http://stackoverflow.com/comment/83498431
has body: Well before I give a Sample Code. I should warn you. This is not recommended. If you know how to open Maya software through Command Process then you can try something like this. command = "C:\\ProgramFiles\\Maya\\Maya.exe" #random command output = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) if output: output=str(output.stdout.read()) print "Output:",output conn.sendall(output) else: error=str(output.stderr.read()) print "Error:",error conn.sendall(error)
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48257793
has comment: http://stackoverflow.com/comment/83501178
type: Answer

http://stackoverflow.com/comment/83606820
comment on: http://stackoverflow.com/q/48310534
score: 1
has text: do you mean beautifulsoup?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48331004
tagged with: sift
has answer: http://stackoverflow.com/a/48355204
has comment: http://stackoverflow.com/comment/83679406
tagged with: feature-detection
tagged with: image-processing
score: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83696705
tagged with: opencv
has comment: http://stackoverflow.com/comment/83648145
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/48331105
answer count: 2
tagged with: python
type: UnansweredQuestion
has body: I want to use OpenCV Python to do SIFT feature detection on remote sensing images. These images are high resolution and can be thousands of pixels wide (7000 x 6000 or bigger). I am having trouble with insufficient memory, however. As a reference point, I ran the same 7000 x 6000 image in Matlab (using VLFEAT) without memory error, although larger images could be problematic. Does anyone have suggestions for processing this kind of data set using OpenCV SIFT? OpenCV Error: Insufficient memory (Failed to allocate 672000000 bytes) in cv::OutOfMemoryError, file C:\projects\opencv-python\opencv\modules\core\src\alloc.cpp, line 55 OpenCV Error: Assertion failed (u != 0) in cv::Mat::create, file (I'm using Python 2.7 and OpenCV 3.4 in the Spyder IDE on a Windows 64-bit with 32 GB of RAM.)
has title: Errors processing large images with SIFT OpenCV
has comment: http://stackoverflow.com/comment/122747254

http://stackoverflow.com/q/48271090
tagged with: django
accepted answer: http://stackoverflow.com/a/48271200
type: Question
type: AnsweredQuestion
score: 0
tagged with: python
has title: django The form does not show on the page
has answer: http://stackoverflow.com/a/48271200
has body: The form does not show on the page what is the problem I tried a lot but there was difficulty comment.html: {% csrf_token %} {{ form.as_p }} Save views.py : def post_detail_view(request,year, month, day, post): post = get_object_or_404(Post,slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) context ={ 'post':post } return render(request,'post/comment.html',context) comments = post.comments.filter(active=True) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.post = post new_comment.save() else: form = CommentForm() return render(request,'post/comment.html',{'post':post, 'comments': comments, 'form':form}) The form does not show on the page what is the problem I tried a lot but there was difficulty forms.py : from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name','email','body','website',) models.py : class Comment(models.Model): post= models.ForeignKey(Post,related_name='comments',on_delete=models.CASCADE) name = models.CharField(max_length=80) website = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering =('created',) def __str__(self): return 'Comment by {} on {}'.format(self.name,self.post) The form does not show on the page what is the problem I tried a lot but there was difficulty urls: from django.conf.urls import url from . import views urlpatterns = [ #url(r'^$',PostListView.as_view(),name='blog'), url(r'^$',views.post_list_view,name='post_list_view'), #url(r'^(?P<pk>\d+)/$',PostDetailView.as_view(),name='post_detail'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$',views.post_detail_view,name="post_detail_view"), ] The form does not show on t…
answer count: 1

http://stackoverflow.com/a/48213445
answers question: http://stackoverflow.com/q/48213328
has body: You have misdiagnosed what is happening. requests is returning the correct dictionary. But you are passing a dictionary to HttpResponse(), without any further processing. However, HttpResponse() is not set up to handle dictionaries. What happens is that HttpResponse() takes an iterable and will serve each value from the iterable as a string. In essence, you told Django to send only the keys, concatenated, to the client. From the HttpResponse() documentation: content should be an iterator or a string. If it’s an iterator, it should return strings, and those strings will be joined together to form the content of the response. and from the dict() documentation: iter(d) Return an iterator over the keys of the dictionary. This is a shortcut for iter(d.keys()). If you wanted to send JSON data, use a JSONResponse() object instead. It is set up to encode Python objects correctly: from django.http import JSONResponse import requests def say_something(request): resp = requests.get('http://127.0.0.1:9501/polls/test/') return JSONResponse(resp.json()) or don't bother with decoding and re-encoding, just pass on the original response data: from django.http import HttpResponse import requests def say_something(request): resp = requests.get('http://127.0.0.1:9501/polls/test/') return HttpResponse(resp.text, resp.headers['content-type']) Note: I removed the class and staticmethod decorator; there is little point in wrapping static view functions in a class when no state is shared. Use modules to create namespaces instead.
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48213328
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48288351
score: 6
linked to: http://stackoverflow.com/q/3024925
tagged with: python
accepted answer: http://stackoverflow.com/a/48288922
has comment: http://stackoverflow.com/comment/83561785
has answer: http://stackoverflow.com/a/48288922
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/3024925
answer count: 1
has body: I've got a situation where I have several items I'd like to open using a with block. In my case, these are external hardware devices which require some clean-up when closed -- but that doesn't really matter for the point at hand. Assuming a class something like: class Controller(object): def __init__(self, name): self._name = name def __enter__(self): # Do some work on entry print("Entering", self._name) return self def __exit__(self, type, value, traceback): # Clean up (restoring external state, turning off hardware, etc) print("Exiting", self._name) return False def work(self): print("Working on", self._name) I would (given a fixed number of Controllers), do something like with Controller("thing1") as c1: with Controller("thing2") as c2: c1.do_work() c2.do_work() However, I've run across a situation where I have a flexible number of things I need to manage in this manner. That is, I have a situation similar to: things = ["thing1", "thing2", "thing3"] # flexible in size for thing in things: with Controller(thing) as c: c.do_work() However, the above doesn't quite do what I need -- which is to have Controllers for all things in scope at one time. I've built a toy example which works through recursion: def with_all(controllers, f, opened=None): if opened is None: opened = [] if controllers: with controllers[0] as t: opened.append(t) controllers = controllers[1:] with_all(controllers, f, opened) else: f(opened) def do_work_on_all(controllers): for c in controllers: c.work() names = ["thing1", "thing2", "thing3"] controllers = [Controller(n) for n in names] with_all(controllers, do_work_on_all) but I don't like the recursion or the abstraction of the actual function call. I'm interested in ideas for doing this in a more "pythonic" way.
upvote count: 7
has comment: http://stackoverflow.com/comment/83561598
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/16083791
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83570575
has title: Is it possible to open an arbitrary number of items using `with` in python?

http://stackoverflow.com/a/48174042
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83327683
has comment: http://stackoverflow.com/comment/83327756
answers question: http://stackoverflow.com/q/48173975
score: 3
has comment: http://stackoverflow.com/comment/83328795
type: Answer
has body: You need to put your plot in the for loop. If you want them on a single plot then you need to use plot's ax kwarg to put them to plot on the same axis. Here I have created a fresh axis using subplots but this could be an already populated axis, import pandas as pd import numpy as np import matplotlib.pyplot as plt scenarios = ['scen-1', 'scen-2'] fig, ax = plt.subplots() for index, item in enumerate(scenarios): df = pd.DataFrame({'A' : np.random.randn(4)}) print df df.plot(ax=ax) plt.ylabel('y-label') plt.xlabel('x-label') plt.title('Title') plt.show()
accepted answer of: http://stackoverflow.com/q/48173975
upvote count: 3

http://stackoverflow.com/comment/83430442
comment on: http://stackoverflow.com/a/48223529
has text: let check the usage of requests library on bitbucket here: https://github.com/Sheeprider/BitBucket-api/blob/master/bitbucket/bitbucket.py
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48223590
has comment: http://stackoverflow.com/comment/126436776
accepted answer of: http://stackoverflow.com/q/48223558
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83429124
has comment: http://stackoverflow.com/comment/126358792
score: 27
has comment: http://stackoverflow.com/comment/83429342
answers question: http://stackoverflow.com/q/48223558
has comment: http://stackoverflow.com/comment/83429455
has comment: http://stackoverflow.com/comment/83428976
downvote count: 0
type: Answer
has body: Be explicit and always include -&gt; None for functions that return None That's because otherwise, for functions that don't take arguments, the type checker will assume that you did not use type hints at all. For example, is def foo(): going to return None, or was it simply not type hinted? PEP 484 - Type Hints indirectly addresses this: Note that the return type of __init__ ought to be annotated with -&gt; None. The reason for this is subtle. If __init__ assumed a return annotation of -&gt; None, would that mean that an argument-less, un-annotated __init__ method should still be type-checked? Rather than leaving this ambiguous or introducing an exception to the exception, we simply say that __init__ ought to have a return annotation; the default behavior is thus the same as for other methods.
upvote count: 27

http://stackoverflow.com/a/48289110
has comment: http://stackoverflow.com/comment/83564706
has comment: http://stackoverflow.com/comment/83564906
has body: How about: df.groupby('ID')['accuracy'].apply(lambda p : 2.*p.sum()/p.count() -1) Assuming that: O : count of ones Z : count of zeros N : total count = O+Z I used the fact: Z = N - O Hence : (O - Z)/N = (2*O - N)/N = 2*O/N -1
score: 2
has comment: http://stackoverflow.com/comment/83565640
has comment: http://stackoverflow.com/comment/83565228
has comment: http://stackoverflow.com/comment/83565130
has comment: http://stackoverflow.com/comment/83565278
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83565318
accepted answer of: http://stackoverflow.com/q/48288393
has comment: http://stackoverflow.com/comment/83565199
type: Answer
answers question: http://stackoverflow.com/q/48288393

http://stackoverflow.com/comment/83603821
comment on: http://stackoverflow.com/a/48289983
type: AnswerComment
has text: Hey Patrick, thank you for your answer. I especially like the first line. Is this something called a Dictionary Comprehension? I know list comprehensions, but never saw something like that...
score: 0
type: Comment

http://stackoverflow.com/q/48196510
type: AnsweredQuestion
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48196815
answer count: 1
has answer: http://stackoverflow.com/a/48196815
has title: Taking the sum and mean of multiple columns and appending the result as a single row
type: Question
has comment: http://stackoverflow.com/comment/83374390
has body: I read a csv file and I want to create a new row with some results as a sum()for 3 columns and a mean() for the rest columns. The problem is that my output is something like this: Total 1596260396 Total2 30453841 Tota3 3.024863813 Total4 19742.04 Total5 0.733696498 And I´m looking for this: Total 1596260396 30453841 3.024863813 19742.04 0.733696498 My code: # encoding=utf8 from io import StringIO import pandas as pd import os from pandas import ExcelWriter import sys reload(sys) sys.setdefaultencoding('utf-8') df1 = pd.read_csv("este_mes.csv", sep=',') df1.loc['Total'] = pd.Series(df1['Subastas'].sum(), index = ['Subastas']) df1.loc['Total2'] = pd.Series(df1['Impresiones_exchange'].sum(), index = ['Impresiones_exchange']) df1.loc['Tota3'] = pd.Series(df1['Fill_rate'].mean(), index = ['Fill_rate']) df1.loc['Total4'] = pd.Series(df1['Importe_a_pagar_a_medio'].sum(), index = ['Importe_a_pagar_a_medio']) df1.loc['Total5'] = pd.Series(df1['ECPM_medio'].mean(), index = ['ECPM_medio']) Some rows of my csv: Cliente,Fecha,Status,cl_fecha,Subastas,Impresiones_exchange,Fill_rate,Importe_a_pagar_a_medio,ECPM_medio jjj,01/01/2017,Alerta Fillrate - Revenue - Imp Vendidas,jjj_01/01/2017,2277331,25843,1.13,10.36,0.4 jjj,02/01/2017,Alerta Fillrate -- Incremento Revenue - Imp Vendidas - Subastadas,jjj_02/01/2017,6747816,42957,0.64,17.9,0.42 jjj,03/01/2017,Alerta Fillrate - Revenue - Imp Vendidas: aumento eCPM-- CRITICO,jjj_03/01/2017,6397915,27926,0.44,13.1,0.47 jjj,04/01/2017,Estable: descenso Revenue e Imp Vendidas,jjj_04/01/2017,5764124,22940,0.4,11.14,0.49 jjj,05/01/2017,Estable,jjj_05/01/2017,5635852,23924,0.42,11.24,0.47 Output I want: Cliente,Fecha,Status,cl_fecha,Subastas,Impresiones_exchange,Fill_rate,Importe_a_pagar_a_medio,ECPM_medio jjj,01/01/2017,Alerta Fillrate - Revenue - Imp Vendidas,jjj_01/01/2017,2277331,25843,1.13,10.36,0.4 jjj,02/01/2017,Alerta Fillrate -- Incremento Revenue - Imp Vendidas - Subastadas,jjj_02/01/2017,6747816,42957,0.64,17.9,0.42 jjj,03/01/2017,Ale…
has comment: http://stackoverflow.com/comment/83374145
has comment: http://stackoverflow.com/comment/83374362
has comment: http://stackoverflow.com/comment/83374433
has comment: http://stackoverflow.com/comment/83374538
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/83374576

http://stackoverflow.com/a/48242618
accepted answer of: http://stackoverflow.com/q/48242387
type: Answer
answers question: http://stackoverflow.com/q/48242387
score: 0
type: AcceptedAnswer
has body: You appear to have linked a to b to import the types b defines. Don't do this. Instead, import b like you would any other Python module. In other words, the dependency on b should be handled entirely by the Python binary, not by your OS's dynamic library loading structures. Use the C-API import functions to import b. At that point it should not matter how b is imported; it's just a bunch of Python objects from that point onwards. That's not to say that b can't produce a C-level API for those objects (NumPy does this too), you just have to make sure that it is Python that loads the extension, not your library. Incidentally, NumPy defines helper functions that do the importing for you, see the import_umath() code generator for an example.

http://stackoverflow.com/a/48316172
answers question: http://stackoverflow.com/q/48315921
has body: In python, everything is an object. When you write dict1 = {} what you're doing is assigning an instance of the dictionary object which is empty, dict() to the object named dict1. But when you write this line dict2=dict1, you're telling python to assign the object dict2 to reference the exact same object as dict1. Meaning whatever changes happen to one will happen to the other. What you would want to do is write dict2 = dict(dict1), which tells python dict2 is a new instance of the dictionary object which is the same values of dict1. Now when you change the value in one it won't affect the other.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48315921
score: 1
type: Answer

python-collections
type: Tag
tag name: python-collections
tags question: http://stackoverflow.com/q/48325475

contextmanager
tags question: http://stackoverflow.com/q/48219177
type: Tag
tag name: contextmanager
tags question: http://stackoverflow.com/q/48299554

http://stackoverflow.com/comment/83394915
score: 4
type: AnswerComment
has text: @AndyG __str__ is called only when you are printing the object or when you call str() on that object, basically it is a special method which is used to convert an object to string, and won't be called automatically when you are trying to concatenate
type: Comment
comment on: http://stackoverflow.com/a/48206902

http://stackoverflow.com/q/48264274
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: How to make sure that a file is loaded into script
tagged with: python
has body: Is there any way to make sure that a csv, or just any file in general, is loaded into a script? I'm trying to make an interactive menu, and I want to make sure, that the menu options are only running when a valid file has been loaded to the script: #Load new data. if choice == 1: while True: filename = input("Please enter .csv filename: ") path = os.listdir(os.getcwd()) #If the file is in the path, the code will run if filename in path[:len(path)]: print("\nData has been loaded!\n") loadcsv = pd.read_csv(filename) break else: print("\nFile has not been found.") #Check for errors. if choice == 2: if filename not in sys.modules: print("Please upload a file") else: pass Here i tried to use the code: if choice == 2: if filename not in sys.modules: print("Please upload a file") else: pass But it just says that the filename is not defined.
has comment: http://stackoverflow.com/comment/83512716
score: 2
answer count: 0
upvote count: 2
downvote count: 0
tagged with: python-interactive
tagged with: file-upload

http://stackoverflow.com/comment/83440481
comment on: http://stackoverflow.com/a/48229151
score: 0
type: AnswerComment
has text: Thanks for your time. I will just change it to this way and rewrite every function that changes sys...
type: Comment

http://stackoverflow.com/comment/83367413
has text: I do need to take action when the checkbox is checked. This field shown in the view is not boolean.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48193325
score: 0

http://stackoverflow.com/comment/83575229
comment on: http://stackoverflow.com/q/48286209
has text: @Doobeh This should be added as an answer I think. This problem is definitely very common now.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83567778
score: 0
has text: @MaxU In this particular case yes. They are all 125 elements long.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48291170

http://stackoverflow.com/comment/83566216
score: 0
comment on: http://stackoverflow.com/a/48269740
type: Comment
type: AnswerComment
has text: Can you post the entire traceback? In any case, make sure the process that is running django has permission to write on `C://mydoc/logs/`

http://stackoverflow.com/comment/83517247
type: AnswerComment
has text: Thank you for your answer. But in the definition of my model I also feed a list of arrays. Okay, when I do what you suggested I get this error: ValueError: The model expects 4 input arrays, but only received one array. Found: array with shape (4L,)
type: Comment
comment on: http://stackoverflow.com/a/48267053
score: 0

http://stackoverflow.com/q/48251082
answer count: 2
has answer: http://stackoverflow.com/a/48251121
has comment: http://stackoverflow.com/comment/83484717
upvote count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
favorite count: 0
has body: My program only prints "Access Granted" if I type password correctly in first try "Secret password request : ". If I type correct password in other try, let's say second or sixth, it just repeats "Acces Denied, try again : " even if I type correct password. Any help how to fix that? my_input = input(str("Secret password request : ")) my_input = my_input.lower() password = "secret1379" condition = my_input == password if condition: print("Access granted") while not condition: my_input = input("Acces Denied, try again : ") if condition: print("Access granted")
has comment: http://stackoverflow.com/comment/83484913
score: -1
has answer: http://stackoverflow.com/a/48251161
type: Question
has title: Infinite loop in python simple password program

http://stackoverflow.com/q/48290256
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
has body: I'm running a Kubernetes cluster with three Celery pods, using a single Redis pod as the message queue. Celery version 4.1.0, Python 3.6.3, standard Redis pod from helm. At a seemingly quick influx of tasks, the Celery pods to stop processing tasks whatsoever. They will be fine for the first few tasks, but then eventually stop working and my tasks hang. My tasks follow this format: @app.task(bind=True) def my_task(some_param): result = get_data(some_param) if result != expectation: task.retry(throw=False, countdown=5) And are generally queued as follows: from my_code import my_task my_task.apply_async(queue='worker', kwargs=celery_params) The relevant portion of my deployment.yaml: command: ["celery", "worker", "-A", "myapp.implementation.celery_app", "-Q", "http"] The only difference between this cluster and my local cluster, which I use docker-compose to manage, is that the cluster is running a prefork pool and locally I run eventlet pool to be able to put together a code coverage report. I've tried running eventlet on the cluster but I see no difference in the results, the tasks still hang. Is there something I'm missing about running a Celery worker in Kubernetes? Is there a bug that could be affecting my results? Are there any good ways to break into the cluster to see what's actually happening with this issue?
tagged with: kubernetes
answer count: 1
tagged with: celery
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: redis
tagged with: python
has title: Celery Does Not Process Task in Kubernetes with Redis
has answer: http://stackoverflow.com/a/49963318
accepted answer: http://stackoverflow.com/a/49963318

http://stackoverflow.com/q/48211095
tagged with: python
has comment: http://stackoverflow.com/comment/83426078
has body: Consider the following problem. I have a DataFrame that lists items. Each item has multi-value properties A and B with zero or more values per item. The properties are stored in own DataFrame instances. For each item I want to get a set of all values both for A and B and perform some operation on both of these sets including the case when any of the sets is empty. My initial solution was to group properties by items, then iterate over items and for each item use get_group to get its values both for A and B and perform the operation on these groups. This works in the following case: # A sample toy operation. One should assume that my_operation # takes array-like arguments that can be Python lists, # pandas.Series etc. def my_operation(array_a, array_b): return len(array_a) - len(array_b) def example1(): items = pd.DataFrame({'Item': ['i1', 'i2', 'i3']}) items_a = pd.DataFrame({'Item': ['i1', 'i1', 'i2', 'i3'], 'A': [1, 2, 3, 0]}) items_b = pd.DataFrame({'Item': ['i1', 'i2', 'i2', 'i3'], 'B': [-1, 4, 5, 6]}) grouped_a = items_a.groupby('Item') grouped_b = items_b.groupby('Item') for row in items.itertuples(): a = grouped_a.get_group(row.Item)['A'] b = grouped_b.get_group(row.Item)['B'] print(row.Item, my_operation(a, b)) example1() which prints expected: i1 1 i2 -1 i3 0 However, this does not work when some of the items have zero values. For example, the following generate the KeyError: def my_operation(array_a, array_b): return len(array_a) - len(array_b) def example2(): items = pd.DataFrame({'Item': ['i1', 'i2', 'i3', 'i4']}) items_a = pd.DataFrame({'Item': ['i1', 'i1', 'i2'], 'A': [1, 2, 3]}) items_b = pd.DataFrame({'Item': ['i2', 'i2', 'i3'], 'B': [4, 5, 6]}) grouped_a = items_a.groupby('Item') grouped_b = items_b.groupby('Item') for row in items.itertuples(): a = grouped_a.get_group(row.Item)['A'] b = grouped_b.get_group(row.Item)['B'] print(row.Item, my_operation(a, b)) example2() I can fix that by checking before calling the get_group that the group exists and …
has comment: http://stackoverflow.com/comment/83426837
downvote count: 0
tagged with: pandas
upvote count: 1
score: 1
tagged with: dataframe
has answer: http://stackoverflow.com/a/48226502
has answer: http://stackoverflow.com/a/48212490
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83406419
has title: Iterating over groups in several DataFrames when groups may absent

http://stackoverflow.com/q/48257321
tagged with: http://stackoverflow.com/tag/csv
has title: What am I doing wrong when I am trying to read my csv file in python?
tagged with: spyder
tagged with: python
has comment: http://stackoverflow.com/comment/83497429
score: -1
has body: I am using Spyder through the Anaconda bundle on a Macbook and keep getting this error when I use the below commands import pandas as pd file = ('/Users/JDMacBook/.spyder-py3/US Mass Shootings.csv') df = pd.read_csv(file) print(df.head) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd1 in position 87: invalid continuation byte Sorry if this is a duplicate -- I googled and youtube'd and even stackflowed the crap out of this question but I cant seem to figure this out. Can you please help this newbie?
has comment: http://stackoverflow.com/comment/83497326
upvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/48257732
downvote count: 1
tagged with: data-science
favorite count: 0
has comment: http://stackoverflow.com/comment/83497298
type: Question
linked to: http://stackoverflow.com/q/46180610
has comment: http://stackoverflow.com/comment/83497790
linked to: http://stackoverflow.com/q/48259515
tagged with: anaconda
has answer: http://stackoverflow.com/a/48257564
type: UnansweredQuestion

http://stackoverflow.com/comment/139476470
has text: @sigvaldm Depends on your idea of _better_. There's `Path('foo', 'bar').with_suffix('.tmp')` -> `foo/bar.tmp` _or_ `p = Path('foo', 'bar.dat') p.with_stem(p.name).with_suffix('.tmp')` -> `foo/bar.bat.tmp`.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48190959
type: QuestionComment

http://stackoverflow.com/q/48246135
possible better answer: http://stackoverflow.com/a/48246281
has comment: http://stackoverflow.com/comment/83474958
has comment: http://stackoverflow.com/comment/83475078
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48246281
has comment: http://stackoverflow.com/comment/83475125
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83475071
accepted answer: http://stackoverflow.com/a/48246152
has answer: http://stackoverflow.com/a/48246152
tagged with: python
has body: I have arrays A = np.array([ [1,6,5], [2,3,4], [8,3,0] ]) B = np.array([ [3,2,1], [9,2,8], [2,1,8] ]) Doing a = np.argwhere(A &gt; 4) gives me an array of position/indexes of values in array A that are greater than 4 i.e. [[0 1], [0 2], [2 0]]. I need to use these indexes/position from a = np.argwhere(A &gt; 4) to replace the values in array B to zero at these specific position i.e. array B should now be B = np.array([ [3,0,0], [9,2,8], [0,1,8] ]) I am big time stuck any help with this will be really appreciated. Thank You :)
tagged with: numpy
answer count: 2
has title: Put zeros in the given index values of a 2D array in Python
tagged with: arrays
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/48249068
tagged with: django-admin
has body: I have all the static files, but for some reason only the normal html loads with no css. I have tried using collectstatic and creating a new project but it doesn't work on any. STATIC_URL is also specified along with static in the url.py . Nothing seems to be working.
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83558507
tagged with: css
score: 0
tagged with: django-templates
has title: django server doesn't load css when it is run
answer count: 1
has comment: http://stackoverflow.com/comment/83481043
has answer: http://stackoverflow.com/a/48249892
type: Question
has comment: http://stackoverflow.com/comment/83498654

http://stackoverflow.com/a/48219676
has body: remove all the commas (',') after each field in the model and try to makemigrations and migrate and then check the admin panel class Game(models.Model): player_turn = models.IntegerField() game_state = models.BooleanField() rolled = models.BooleanField() rolled_double = models.BooleanField() last_roll = models.IntegerField() test_text = models.CharField(max_length = 200)
accepted answer of: http://stackoverflow.com/q/48219626
has comment: http://stackoverflow.com/comment/83421134
answers question: http://stackoverflow.com/q/48219626
type: Answer
score: 13
upvote count: 13
has comment: http://stackoverflow.com/comment/122396368
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48252967
type: UnansweredQuestion
tagged with: django
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48253263
has title: Insert JSON data into database for python
answer count: 2
has body: I'm currently doing a system that scrap data from foursquare. Right now i have scrap the review from the website using python and beautiful soup and have a json file like below {"review": "From sunset too variety food u cant liked it.."}{"review": "Byk motor laju2"}{"review": "Good place to chill"}{"review": "If you wan to play bubble and take photo, here is the best place"}{"review": "Scenic view for weekend getaway... coconut shake not taste as original klebang coconut shake..."}{"review": "Getting dirtier"}{"review": "Weekend getaway!"}{"review": "Good for casual walk &amp; watching sunset with loved ones since my last visit macam2 ade kat sini very packed during public holidays"}{"review": "Afternoon time quite dry..beach is normal. Maybe evening/night might be better. The coconut shake they add vanilla ice cream,hmmm"}{"review": "Pantai awesome beb"}{"review": "Nice place for picnic"}{"review": "Cannot mandi here. Good place for recreation.. Calm place for weekdays! Haha"}{"review": "Very bz place. Need to go there early if you want to lepak. If not, no parking for you"}{"review": "So many good attraction here, worth a visit"}{"review": "Beautiful place for sunset"}{"review": "New beach! Like all beaches, awesome view &amp; windy. Some stretch got many small crabs."}{"review": "There is bustel \"hotel in a bus\" can get coconut shake or fried seafood in the evening at 5pm. Bustel rate is from RM80. Bus cafe, bus toilet... Total bus transformation"}{"review": "Too crowded la"}{"review": "Muzium kapal selam closed since 1/3 until further notice..\ud83d\ude29"}{"review": "If you are looking for public toilets, look for a red bus. An old bus was modified and transformed to operate as toilets. Cool."}{"review": "Most of the shops closed after 12 midnight..helloo,this place should be the place for the late nighters..late night supposed to be the peak hour for business..live band bar maybe?? :-P"} My question is how do i insert the data into a database right away? Is …
tagged with: http://stackoverflow.com/tag/json
tagged with: pymongo
tagged with: mysql
has comment: http://stackoverflow.com/comment/83625570
linked to: http://stackoverflow.com/q/4251124
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83488448
has answer: http://stackoverflow.com/a/48253131
upvote count: 0

http://stackoverflow.com/comment/83549127
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48282585
has text: I already know that the algorithm works visually. I have saved the array: "labels" as .csv using the algorithm "numpy. savetxt" and it contains only zeros. Why?
type: Comment

http://stackoverflow.com/comment/83486150
comment on: http://stackoverflow.com/a/48251338
score: 0
type: AnswerComment
has text: That appears to be an implementation detail in CPython rather than part of the language definition. Do you have some info to the contrary?
type: Comment

http://stackoverflow.com/q/48265736
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83515883
has title: How to create several temporary files with the same basename and a numbered ending using python?
has comment: http://stackoverflow.com/comment/83515301
answer count: 0
score: 1
tagged with: temporary-files
upvote count: 1
has comment: http://stackoverflow.com/comment/83514894
favorite count: 0
type: Question
has body: I want to create temporary files and call a program to open them as a batch using python. However, this program requires the files to have a specific naming to be accepted as a batch: some_name_{number}.ending Now I would like to use tempfile.NamedTemporary (link) for this, but it can only create one temporary file. I have a manual recipe (see below) but it is not secure (a lot could happen between the check whether the files exist and the actual creation). from os import path from glob import glob import string import random def generate_files(dir, num_files, name_length=12, ending='.blob'): chars=string.ascii_uppercase + string.digits for i in range(1000): file_name = ''.join(random.choice(chars) for _ in range(name_length)) if not glob(path.join(dir, file_name)+"*"): return (file_name+'_{}'.format(number)+ending for number in range(num_files)) raise RuntimeError('I give up, all filenames I tried already exist') A sample usage is &gt;&gt;&gt; filenames = list(generate_files('.', 3)) &gt;&gt;&gt; filenames ['9R3ZK913P39K_0.blob', '9R3ZK913P39K_1.blob', '9R3ZK913P39K_2.blob'] &gt;&gt;&gt; # Now create the files &gt;&gt;&gt; # ... Questions: Is there a library function that does this? (That would be the preferred answer) If no to the first question: How can the code above be improved in terms of avoiding file conflicts?

http://stackoverflow.com/q/48276955
upvote count: 2
tagged with: python.net
answer count: 0
downvote count: 0
has title: pythonnet not working and no error displayed
tagged with: pythonnet
tagged with: .net
has comment: http://stackoverflow.com/comment/83629650
favorite count: 0
type: Question
has body: I am trying to use pythonnet to run a python script from a .Net application , i installed pip , python and the project on git hub , also i did all the installation steps mentioned on https://github.com/pythonnet/pythonnet/wiki/Installation and the troubleshooting steps on https://github.com/pythonnet/pythonnet/wiki/Troubleshooting-on-Windows,-Linux,-and-OSX when i created a windows application to run a python script, the project was built successfully , however when i click the button to execute a python script the application will exit showing the following output : The program '[30236] WindowsFormsApplication1.vshost.exe: Program Trace' has exited with code 0 (0x0). The program '[30236] WindowsFormsApplication1.vshost.exe' has exited with code 1 (0x1). the code i am using to execute the python file : try { using (Py.GIL()) { var test1 = ""; dynamic np = Py.Import("sum"); Console.WriteLine(np.cos(np.pi * 2)); } } catch (Exception ex) { MessageBox.Show(ex.Message); } when i tried to check where exactly the project stops , it was in the Python.RunTime project => runtime.cs =? Initialize() . P.S : i am using pythonnet because i am using python 3.X and IronPython does not support this version. Is there additional troubleshooting steps i must do ? or any more reference i should add ?
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83600399
score: 2

http://stackoverflow.com/q/48221195
has comment: http://stackoverflow.com/comment/83425954
tagged with: logfile
downvote count: 0
has comment: http://stackoverflow.com/comment/83423983
has comment: http://stackoverflow.com/comment/83423864
upvote count: 1
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83424626
answer count: 0
has title: python telnet and put the message in a particular log file
type: UnansweredQuestion
tagged with: python
tagged with: telnetlib
has body: hi I am coding the python script to login telnet and it has to write log file to op.txt the absolute path is /netperf/mntpt/array1/home/prg_use/op.txt the python code ptlog.py import getpass import sys import telnetlib import time host ="12.12.1.123" user ="user_name" passwd ="telnet_password" tn = telnetlib.Telnet(host) tn.read_until("login: ") tn.write(user + "\n") tn.read_until("Password: ") tn.write(passwd + "\n") tn.write("touch op.txt \n") time.sleep(5) tn.write("lr \n") str_all=tn.read_until("$") #f=open("/netperf/mntpt/array1/home/prg_use/op.txt", "w") f=open("op.txt", "w") f.write(str_all) f.close() tn.write("exit \n") print tn.read_all() the server side in terminal is $ lr: not found $ however, I wanna it wrote lr: not found in op.txt but it did not happen, can any one tell me how to do it, thank you if I code f=open("/netperf/mntpt/array1/home/prg_use/op.txt", "w") it will show no such file or directory '/netperf/mntpt/array1/home/prg_use/op.txt' I think it is not the path problem, I can touch op.txt , its str_all=tn.read_until("$") can not copy the return message and then write in op.txt
has comment: http://stackoverflow.com/comment/83424470
tagged with: telnet

http://stackoverflow.com/q/48219015
tagged with: templates
type: Question
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/48219989
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83419886
has body: Say I have this data and I'm passing to my template: apps = [ {'category': 'one', 'item': 'blah'}, {'category': 'one', 'item': 'blah'}, {'category': 'two', 'item': 'blah'}, {'category': 'two', 'item': 'blah'}, {'category': 'three', 'item': 'blah'} ] Then in my template I want to add one div withe the id 'category' but not repeat any divs if they've been added before with the id. So something similar to: {% for app in apps %} &lt;div id="{{app.category}}"&gt;&lt;/div&gt; {% endfor %} But I only want these to be rendered: &lt;div id="one"&gt;&lt;/div&gt; &lt;div id="two"&gt;&lt;/div&gt; &lt;div id="three"&gt;&lt;/div&gt;
score: 0
has title: Django- template loop but exclude repeats

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/48228241
tags question: http://stackoverflow.com/q/48197104
tags question: http://stackoverflow.com/q/48271293
tags question: http://stackoverflow.com/q/48208307
tags question: http://stackoverflow.com/q/48294381
tags question: http://stackoverflow.com/q/48230684
tags question: http://stackoverflow.com/q/48176564
tags question: http://stackoverflow.com/q/48178289
tags question: http://stackoverflow.com/q/48329749
tags question: http://stackoverflow.com/q/48179772
tags question: http://stackoverflow.com/q/48214857
tags question: http://stackoverflow.com/q/48273657
tags question: http://stackoverflow.com/q/48295750
tags question: http://stackoverflow.com/q/48176532
tags question: http://stackoverflow.com/q/48273530
tags question: http://stackoverflow.com/q/48292771
tags question: http://stackoverflow.com/q/48187592
tags question: http://stackoverflow.com/q/48222296
tags question: http://stackoverflow.com/q/48176665
tags question: http://stackoverflow.com/q/48248653
tags question: http://stackoverflow.com/q/48280643
tags question: http://stackoverflow.com/q/48241548
tags question: http://stackoverflow.com/q/48235825
tags question: http://stackoverflow.com/q/48262523
tags question: http://stackoverflow.com/q/48319723
tags question: http://stackoverflow.com/q/48267084
tags question: http://stackoverflow.com/q/48291996
tags question: http://stackoverflow.com/q/48230590
type: Tag
tags question: http://stackoverflow.com/q/48311151
tags question: http://stackoverflow.com/q/48257156
tag name: html
tags question: http://stackoverflow.com/q/48293541
tags question: http://stackoverflow.com/q/48247029
tags question: http://stackoverflow.com/q/48249963
tags question: http://stackoverflow.com/q/48216663
tags question: http://stackoverflow.com/q/48329002
tags question: http://stackoverflow.com/q/48287470
tags question: http://stackoverflow.com/q/48216573
tags question: http://stackoverflow.com/q/48303583
tags question: http://stackoverflow.com/q/48225503
tags question: http://stackoverflow.com/q/48253733
tags question: http://stackoverflow.com/q/48230761
tags question: http://stackoverflow.com/q/48326983
tags question: http://stackoverflow.com/q/48249705
tags question: http://stackoverflow.com/q/48232703
tags question: http://stackoverflow.com/q/48270721
tags question: http://stackoverflow.com/q/48236529
tags question: http://stackoverflow.com/q/48200341
tags question: http://stackoverflow.com/q/48272778

http://stackoverflow.com/a/48241388
answers question: http://stackoverflow.com/q/48241326
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Try to install scipy, since it complains about that module missing. pip install scipy It installs scipy/numpy. As a side note - if someone has old, and new python - then pip3 should be used, since pip installs modules for python 2 in this case.
accepted answer of: http://stackoverflow.com/q/48241326
type: Answer

http://stackoverflow.com/a/48245057
has comment: http://stackoverflow.com/comment/83482483
has comment: http://stackoverflow.com/comment/83481880
has comment: http://stackoverflow.com/comment/83479674
accepted answer of: http://stackoverflow.com/q/48240470
has comment: http://stackoverflow.com/comment/83474091
has comment: http://stackoverflow.com/comment/83508660
has comment: http://stackoverflow.com/comment/83479885
has comment: http://stackoverflow.com/comment/83482898
answers question: http://stackoverflow.com/q/48240470
has comment: http://stackoverflow.com/comment/83479604
has comment: http://stackoverflow.com/comment/83481638
has comment: http://stackoverflow.com/comment/83481527
has comment: http://stackoverflow.com/comment/83482659
has comment: http://stackoverflow.com/comment/83480775
has comment: http://stackoverflow.com/comment/83481507
has comment: http://stackoverflow.com/comment/83478837
has comment: http://stackoverflow.com/comment/83480908
has comment: http://stackoverflow.com/comment/83536717
has comment: http://stackoverflow.com/comment/83473324
has comment: http://stackoverflow.com/comment/83478520
has comment: http://stackoverflow.com/comment/83481675
has comment: http://stackoverflow.com/comment/83482183
has comment: http://stackoverflow.com/comment/83478612
has comment: http://stackoverflow.com/comment/83478670
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83479153
type: Answer
has comment: http://stackoverflow.com/comment/83481076
has comment: http://stackoverflow.com/comment/83481217
has comment: http://stackoverflow.com/comment/83478354
has comment: http://stackoverflow.com/comment/83479288
has comment: http://stackoverflow.com/comment/83482313
has comment: http://stackoverflow.com/comment/83476163
has comment: http://stackoverflow.com/comment/83480975
has comment: http://stackoverflow.com/comment/83473015
has body: I'm not familiar with the library you're using for your client object, but you should be able to set the Content-Type header in your headers dictionary. headers = { 'basic_auth': 'brofewfefwefewef:EKAXsWkdt5H6yJEmtexN', 'Content-Type': 'application/json' } client = Client(ClientConfig(), headers=headers, refresh=True) Unfortunately this doesn't seem to be possible because headers is passed (unpacked) to urllib3.util.make_headers and it does not accept a content_type argument. Also you can't access FileDownloader._http.headers in Client, because it's a local variable. A possible FileDownloader 'hack': class FileDownloader(object): ...Line 152... def _get_http_pool(self, secure=True): if secure: _http = urllib3.PoolManager(cert_reqs=str('CERT_REQUIRED'), ca_certs=certifi.where()) else: _http = urllib3.PoolManager() if self.headers: content_type = self.headers.get('Content-Type') if 'Content-Type' in self.headers: del self.headers['Content-Type'] _headers = urllib3.util.make_headers(**self.headers) _http.headers.update(_headers) if content_type: _http.headers['content-type'] = content_type print(_http.headers) return _http This should allow you to pass a Content-Type header in Client. I don't recommend modifying the source code of your libs, but if you have no other choice...
score: 0

http://stackoverflow.com/comment/83362081
score: 0
has text: do you really mean to convert `Some text` to `sometext` , etc? You'll need to define rules on why `follow up text` got converted to `followup text`. but `more text` remains `more text` (or cleanup your example). ALSO, what have you tried? Good luck.
type: QuestionComment
comment on: http://stackoverflow.com/q/48190801
type: Comment

http://stackoverflow.com/q/48240351
answer count: 1
favorite count: 0
has body: How can I use a subset of my age data within a boxplot? I only want to include rows with positive age values as you can see below: import seaborn as sns fig, ax = plt.subplots(nrows=1, ncols=1,figsize=(15, 8)) sns.boxplot(x='country_destination', y='age', data=train['age' &gt; -1], palette="muted", ax =ax) ax.set_ylim([10, 60]) The error message I get is: TypeError: '>' not supported between instances of 'str' and 'int'
type: Question
has title: Subsetting data in Python seaborn
tagged with: seaborn
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83463025
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48240450
accepted answer: http://stackoverflow.com/a/48240450
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83467567

http://stackoverflow.com/comment/83596261
comment on: http://stackoverflow.com/a/48305542
has text: Thanks CoryKramer. This also helps answering my more general question (I would replace `self.r == other.r ...` by `True`, and use, e.g., `Complex(_, _)` instead of `Complex(1, 1)`).
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48180225
type: Question
accepted answer: http://stackoverflow.com/a/48180269
possible better answer: http://stackoverflow.com/a/48180367
tagged with: python-unicode
tagged with: python
has title: How can I parse a bytestring in Python 3?
has answer: http://stackoverflow.com/a/48180269
score: 4
upvote count: 4
type: AnsweredQuestion
answer count: 2
tagged with: python-3.5
downvote count: 0
tagged with: string-parsing
has answer: http://stackoverflow.com/a/48180367
has body: Basically, I have two bytestrings in a single line like this: b'\xe0\xa6\xb8\xe0\xa6\x96 - \xe0\xa6\xb6\xe0\xa6\x96\n' This is a Unicode string that I'm importing from an online file using urllib, and I want to compare the individual bytestrings so that I can replace the wrong ones. However, I can't find out any way to parse the string so that I get \xe0\xa6\xb8\xe0\xa6\x96 and \xe0\xa6\xb6\xe0\xa6\x96 in two different variables. I tried converting it into a raw string like str(b'\xe0\xa6\xb8\xe0\xa6\x96') and the indexing actually works, but in that case I can't revert back to the original bytestring in the first place. Is it possible?
favorite count: 0

http://stackoverflow.com/comment/113020326
type: AnswerComment
comment on: http://stackoverflow.com/a/49366428
has text: Btw, when Seb says that "it turned out to be because I had added fields to a model and forgotten to makemigrations and migrate", this include's ANY change in models. Seriously, django is not f'ing around here! Even if you modify the help_text of a model's field, you will get this issue. If makemigrations and migrate is not helping, then look at your file differences and you will surely see that you have modified a model in some way, shape, or form that affects the model's database fields. Good luck!
score: 1
type: Comment

http://stackoverflow.com/comment/83548878
comment on: http://stackoverflow.com/a/48280859
type: Comment
type: AnswerComment
score: 0
has text: This is totally possible with Python and I suggest you use pyqt for it.

http://stackoverflow.com/comment/83440855
has text: are you sure you want to convert the PIL? i would have thought it would make more sense to convert you `data` array?
type: QuestionComment
comment on: http://stackoverflow.com/q/48229318
score: 0
type: Comment

http://stackoverflow.com/comment/83491983
type: AnswerComment
has text: Hi @Maxim, Thank you. This solves my current issue. Can you please explain why I just had to initialize weights and biases of fully_connected_1 layer and not of the previous layer (fully_connected).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48254369

http://stackoverflow.com/q/48235781
type: Question
tagged with: numpy
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/83454617
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83489194
has comment: http://stackoverflow.com/comment/83455810
tagged with: python
tagged with: logarithm
tagged with: vectorization
has title: Most efficient way to take log of numpy array but ignore 0's
has comment: http://stackoverflow.com/comment/84465878
has body: I'd like to take the natural logarithm of a numpy array but not calculate the logarithm of 0-entries at all. I.e. I'd like to implement the convention log(0)=0 over numpy arrays. import numpy as np import timeit foo = np.random.rand(500) %timeit np.log(foo) %timeit np.log(foo,where=foo&gt;0) For the first call, this yields The slowest run took 12.63 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 2.06 µs per loop For the second call, we get The slowest run took 8.35 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 4.31 µs per loop So avoiding the 0's (even if there are no zeros in the array in this case) is much more expensive. This is clearly different if we look at sparse arrays, but is there a more efficient way to avoid zeros even in the non-sparse case?
tagged with: performance
has comment: http://stackoverflow.com/comment/83455525
has comment: http://stackoverflow.com/comment/83454592
has comment: http://stackoverflow.com/comment/83456216
has comment: http://stackoverflow.com/comment/83457345
has comment: http://stackoverflow.com/comment/83454773
has comment: http://stackoverflow.com/comment/83454566
has comment: http://stackoverflow.com/comment/83454548
favorite count: 0

http://stackoverflow.com/q/48243001
linked to: http://stackoverflow.com/q/47110454
has comment: http://stackoverflow.com/comment/84354525
has comment: http://stackoverflow.com/comment/91631979
has title: Python FIX API - no response at Logon
tagged with: bitcoin
upvote count: 5
tagged with: python
has body: I've been trying to set up a connection to the FIX API for the GDAX crpyto exchange, but I can't seem to logon properly. I'm using the code below to generate the message: import time import simplefix import socket import base64 import hmac import hashlib from datetime import datetime s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("127.0.0.1", 4197)) API_KEY = "KEY_GOES_HERE" PASSPHRASE = "PASSPHRASE_GOES_HERE" API_SECRET = "SECRET_GOES_HERE" seq_num = "1" sendingTime = str(datetime.utcnow()).replace("-","").replace(" ", "-")[:-3] rawSig = "\x01".join([sendingTime, "A", seq_num, API_KEY, "Coinbase", PASSPHRASE]).encode("utf-8") hmac_key = base64.b64decode(API_SECRET) signature = hmac.new(hmac_key, rawSig, hashlib.sha256) sign_b64 = base64.b64encode(signature.digest()).decode() msg = simplefix.FixMessage() msg.append_pair(8, "FIX.4.2") msg.append_pair(35, "A") msg.append_pair(49, API_KEY) msg.append_pair(52, sendingTime) msg.append_pair(56, "Coinbase") msg.append_pair(98, "0") msg.append_pair(108, "30") msg.append_pair(554, PASSPHRASE) msg.append_pair(96, sign_b64) msg.append_pair(8013, "Y") print(msg.encode()) s.sendall(msg.encode("ascii")) print(s.recv(4096)) And I'm getting 0 bytes of response from the server. As far as I can tell, the stunnel is working properly (connects and validates certificates successfully, but disconnects after sending my logon message). Have just tried with a newly generated API key, passphrase and secret but to no avail. For reference, I was working from the question asked here: How to send FIX logon message with Python to GDAX but I'm not allowed to comment there. If anyone has any ideas, would be appreciated. Below is an example of the fix message generated, passwords removed in post: 8=FIX.4.2\x019=161\x0135=A\x0149=[KEY_REMOVED]\x0152=20180113-18:24:07.889\x0156=Coinbase\x0198=0\x01108=30\x01554=[PASSPHRASE_REMOVED]\x0196=jueSJHoSNQM2BOCN3KM0mgB2/9tXpICbg4amqDKc2wY=\x018013=Y\x0110=053\x01
favorite count: 0
type: Question
tagged with: gdax-api
has comment: http://stackoverflow.com/comment/85031658
answer count: 0
type: UnansweredQuestion
tagged with: algorithmic-trading
score: 4
tagged with: fix-protocol
downvote count: 1

http://stackoverflow.com/comment/83603527
type: QuestionComment
type: Comment
score: 2
has text: You forgot the parenthses on `readdata.filename()`. Instead of calling the function, you passed the function itself as the file name to `open`.
comment on: http://stackoverflow.com/q/48309004

http://stackoverflow.com/q/48201944
has body: I want to use browsermob to monitor the network connections when doing a GUI test with selenium. I have found some information and documentation here and here and here, but its absolutely unclear how to really use it. In the documentation it reads: server = Server("path/to/browsermob-proxy") But what is that path? Where to find it? Also I see java -jar browsermob.jar --port 9090 but no explanation at all as to what this jar file is, if it is part of the browsermob installation, or something unrelated. I would appreciate if someone can provide a COMPLETE and WORKING example on how to use browsermob, and what ALL I need to install...
has answer: http://stackoverflow.com/a/48266639
has comment: http://stackoverflow.com/comment/83511342
downvote count: 0
tagged with: selenium
has answer: http://stackoverflow.com/a/48202061
accepted answer: http://stackoverflow.com/a/48387421
has answer: http://stackoverflow.com/a/55987075
has title: How to use browsermob with python-selenium?
has answer: http://stackoverflow.com/a/48387421
tagged with: browsermob
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83511618
possible better answer: http://stackoverflow.com/a/48266639
has comment: http://stackoverflow.com/comment/83511372
has comment: http://stackoverflow.com/comment/83511061
tagged with: python
has comment: http://stackoverflow.com/comment/83511862
answer count: 4
score: 25
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48315438
upvote count: 25
linked to: http://stackoverflow.com/q/36744627
has comment: http://stackoverflow.com/comment/83511827

http://stackoverflow.com/a/48236707
score: 0
answers question: http://stackoverflow.com/q/48236622
has body: Here is an example with a different set of data, but overall should be able to be easy to apply it to your data. Use np.masked_where() to split the data into two chunks then plot it. The t variable is defining the frame from 0.0 to 2.0 and the scale by 0.01. import numpy as np import matplotlib.pyplot as plt import pandas as pd t = np.arange(0.0, 2.0, 0.01) s = np.sin(2 * np.pi * t) lower = 0 supper = np.ma.masked_where(s &gt; lower, s) slower = np.ma.masked_where(s &lt; lower, s) cmap = colors.ListedColormap(['green']) cmap.set_bad(color='red') fig, ax = plt.subplots() ax.plot(t, slower, color='green') ax.plot(t, supper, color='red') plt.show() graph
type: Answer

http://stackoverflow.com/comment/83471866
comment on: http://stackoverflow.com/a/48244628
type: AnswerComment
score: 1
has text: Nice that I get to see some great numpy solutions to pandas questions every now and then.
type: Comment

http://stackoverflow.com/q/48298857
answer count: 1
has title: Geometry('POINT') column being returned as str object
downvote count: 0
has comment: http://stackoverflow.com/comment/83660686
has answer: http://stackoverflow.com/a/48341804
accepted answer: http://stackoverflow.com/a/48341804
has body: I have an sqlalchemy model object which has the following column: gps = Column(Geometry('POINT')) I have implemented a to_dict function in the model class, for which I need to deconstruct the gps object to give me lat and long. This successfully works for me in another model. But for some reason, in the class in question, the following piece of code results in an attribute error ('str' object has no attribute 'data'): point = wkb.loads(bytes(self.gps.data)) I store the gps data like so: gps = Point(longitude, latitude).wkt Here's the table description from postgresql: Column | Type | Modifiers | Storage | Stats target | Description -------------+-----------------------------+---------------------------------------------------+---------+--------------+------------- id | integer | not null default nextval('pins_id_seq'::regclass) | plain | | gps | geometry(Point) | | main | | I am calling the as dict method as soon as the Pin object gets created like so: gps = Point( float(data['longitude']), float(data['latitude']) ).wkt pin = Pin(gps=gps) # Commit pin to disk # otherwise fields will # not return properly with transaction.manager: self.dbsession.add(pin) transaction.commit() print (pin.as_dict()) What's driving me insane is the fact that the exact some code works for the other model. Any insight would be mucho appreciated. Edit: Following Ilja's comment, I understood that the issue is that the object isn't getting written to the disk, and apparently the Geometry column will get treated as a string till that happens. But I am getting the same error even now. Basically, at this point, the transaction.commit() function isn't doing what I think it is supposed to... Relevant to that is the configuration of the session object. Since all this is under the Pyramid web framework, I am using the default session configuration, as described here (you can skip the first few paragraphs, until they start discussing the /models/__init__.py file. Ctrl + F if need be). In case I have …
tagged with: sqlalchemy
favorite count: 0
type: Question
tagged with: pyramid
has comment: http://stackoverflow.com/comment/83659567
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: geoalchemy2
has comment: http://stackoverflow.com/comment/83658733
has comment: http://stackoverflow.com/comment/83661065

http://stackoverflow.com/q/48257845
downvote count: 0
upvote count: 1
tagged with: matplotlib-basemap
favorite count: 0
has title: what's wrong with basemap projection="cyl"?
type: Question
tagged with: projection
answer count: 2
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/55177723
has body: In recent days, I have visualized my ncep reanalysis data using Basemap. It is found that only half data appears when using Basemap(projection="cyl",lon_0=0.0,lat_0=0.0, resolution="c") , but the whole data occurs when using Basemap(projection="cyl",lon_0=180.0,lat_0=0.0, resolution="c") . Furthermore, I changes the projection, but still set the central longitude to 0 degree like Basemap(projection="hammer",lon_0=0.0,lat_0=0.0, resolution="c"), but the whole data . The whole data occurs. what happens ? Your answers are appreciated very much.
has answer: http://stackoverflow.com/a/48278594
score: 1

http://stackoverflow.com/q/48234072
has body: I am trying to sort a list of objects using the date attribute with list_of_objects.sort(key=lambda x: x.date, reverse=True) but some dates are just None, which means that I get the error TypeError: can't compare datetime.datetime to NoneType is there a way to account for this? e.g. Have objects with date == None at the top or bottom of the sorted list—or do I need to do this manually?
upvote count: 16
has answer: http://stackoverflow.com/a/48234099
tagged with: python
score: 15
has title: How to sort a list and handle None values properly?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83450748
answer count: 3
has answer: http://stackoverflow.com/a/48234107
downvote count: 1
accepted answer: http://stackoverflow.com/a/48234099
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48235298
possible better answer: http://stackoverflow.com/a/48235298

http://stackoverflow.com/comment/83509301
type: Comment
has text: alright. I get it now. I'll create the models then.
type: QuestionComment
comment on: http://stackoverflow.com/q/48262939
score: 0

http://stackoverflow.com/q/48182920
tagged with: python
has comment: http://stackoverflow.com/comment/83345432
has comment: http://stackoverflow.com/comment/83345565
has title: Python3 `__name__ == '__main__': execution paractices & execution
tagged with: ftp
has body: I have FTP code which I'm testing with __name__ == '__main__' method which works in certain condition and fails on other. This is basically doing FTP to a site with user name password and then traverse into a Directory where we need to inlist the files using ftplib module. Along with I have kept the exception handling if could not find the Files in the Dir path then come with a error. #!/usr/bin/python3 import ftplib from ftplib import FTP def FtpMirroList(): with FTP("ftp.rraka.com") as ftp: ftp.login("rar1", "Hf090rFD") ftp.cwd("mirror/Nimble/1522_rc/optimize_gather/") #ftp.retrlines('LIST') try: FileList = ftp.retrlines('LIST') except ftplib.error_perm as resp: if str(resp) == "550 No files found": print("No files in this directory") else: raise def main(): for files in FtpMirroList(): print(files) #main() if __name__ == '__main__': FtpMirroList() When I execute this without main() which I have hashed in the code then it runs fine. $ ./ftplib-example-4.py total 19535864 -rw-r--r-- 1 rar1 ftpsecure 9963085277 Jan 09 07:09 15.22.s039.20180109-043530_pslv3.tar.gz -rw-rw-r-- 1 rar1 ftpsecure 387 Jan 09 06:02 15.22.s039.20180109-043530_pslv3.tar.gz.README -rw-rw-r-- 1 rar1 ftpsecure 9963166015 Jan 09 14:08 15.22.s039.20180109-164514_pslv3.tar.gz -rw-rw-r-- 1 rar1 ftpsecure 387 Jan 09 14:11 15.22.s039.20180109-164514_pslv3.tar.gz.README If I will run this code with main() then it will produce the Error for 'NoneType' object as follows: Traceback (most recent call last): File "./ftplib-example-4.py", line 22, in &lt;module&gt; main() File "./ftplib-example-4.py", line 19, in main for files in FtpMirroList(): TypeError: 'NoneType' object is not iterable Please advise best practice to use with __name__ == '__main__' method while using with functions and calling main(). What i see there is no need of the second function... after editing it works as expected #!/usr/bin/python3 import ftplib from ftplib import FTP def FtpMirroList(): with FTP("ftp.rraka.com") as ftp: ftp.log…
score: 0
has comment: http://stackoverflow.com/comment/83345639
has answer: http://stackoverflow.com/a/48185182
has comment: http://stackoverflow.com/comment/83345820
has comment: http://stackoverflow.com/comment/83345507
has comment: http://stackoverflow.com/comment/83346354
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83345496
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83345555

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/48305611
tags question: http://stackoverflow.com/q/48249057
tags question: http://stackoverflow.com/q/48252295
tags question: http://stackoverflow.com/q/48219986
tags question: http://stackoverflow.com/q/48223192
tags question: http://stackoverflow.com/q/48213235
tag name: decision-tree
tags question: http://stackoverflow.com/q/48239242

http://stackoverflow.com/comment/83369872
score: 0
type: Comment
has text: Monika, thanks for the pointers. I had to tweak the Xpath you provided slightly for it to run, but I still am getting an empty list back from the driver.find_elements_by_xpath command. My Xpath is now '//*[name()="svg"]//*[name()="g"]//*[@class="highcharts-markers"]/*[name="path"]' do you have any other advice on how to fix this?
comment on: http://stackoverflow.com/a/48183359
type: AnswerComment

http://stackoverflow.com/a/48200689
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/48195931
type: Answer
answers question: http://stackoverflow.com/q/48195931
has body: You should be aware of the concept of traces, where we can place two types of charts in the same graph. To see the concept in action refer Multiple Chart Types in Same Graph. Just as a starting point please refer the below code snippet which does what you want. from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot import plotly.graph_objs as go from datetime import datetime init_notebook_mode(connected=True) trace0 = go.Scatter( x=[1, 2, 3, 4], y=[10, 11, 12, 13], mode='markers', marker=dict( size=[40, 60, 80, 100], ) ) trace1 = go.Scatter( x = [1, 2, 3, 4], y = [10, 11, 12, 13], line = dict( color = ('rgb(22, 96, 167)'), width = 4, dash = 'line') ) data = [trace0, trace1] iplot(data, filename='bubblechart-size') The line that you require can also be generated using plotly shapes. Please read more about this here

http://stackoverflow.com/a/49385753
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48294599
answers question: http://stackoverflow.com/q/48294599
type: Answer
has body: My team happen to face this problem as well and we solve it by creating a CustomMqttClient that inherit from mqtt.Client and override the _handle_on_message(self, message) function. class CustomMqttClient(mqtt.Client): def _handle_on_message(self, message): try: super(ChatqMqttClient, self)._handle_on_message(message) except Exception as e: error = {"exception": str(e.__class__.__name__), "message": str(e)} self.publish("device/exception", json.dumps(error)) Then instead of using mqtt.Client(), we do this: client = CustomMqttClient() client.on_connect = on_connect client.on_message = on_message This catches all exception and actually publish it to our topic device/exception. Our other services can actually subscribe to it and actually get some useful information out of it.

win32gui
type: Tag
tag name: win32gui
tags question: http://stackoverflow.com/q/48306887
tags question: http://stackoverflow.com/q/48265569

http://stackoverflow.com/q/48179134
has comment: http://stackoverflow.com/comment/83338515
downvote count: 1
has answer: http://stackoverflow.com/a/48179261
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83338591
has title: How can i change an already printed out character into another discarding the printed text?
linked to: http://stackoverflow.com/q/6169217
has body: Can i change an already printed out character to another while having the previous deleted? For example how can a program show '_' for 2 seconds, (delete or change it) and show the character 's'?
tagged with: python
duplicate of: http://stackoverflow.com/q/6169217
linked to: http://stackoverflow.com/q/18320431
score: 0
has comment: http://stackoverflow.com/comment/83338597
type: UnansweredQuestion
answer count: 1
upvote count: 1

http://stackoverflow.com/q/48245651
tagged with: python
tagged with: deep-learning
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has body: I am currently trying to implement a modified form (discussed later) of this paper. In particular equations 5,7 and 8 can be summarized as follows: Given an input batch of data points x, we calculate the following value ei = xiAr (where A and r are tensors of appropriate dimensions) Then normalize the values of ei across a batch and finally calculate a single representation for the entire batch This works fine. A point worth mentioning is that these batches are not randomly created but rather represent a specific group of data points collectively forming a group representation. Thus in a particular batch we can only pass data points that represent a particular group. In this case, the batch sizes are variable since each group can have different number of data points. Now for my use case, we go one step further. Let us assume we have a pseudo batch size of 32. In a single training step, we pass K1 + K2 .... K32 = K data points where K1, K2 .... K32 represent the different sizes of the subgroups. And so after the evaluation of the above equations, instead of getting 1 output representation for the entire batch, we would want 32 output representations, 1 for each group. What would be the best way to do such kind of an operation? One thing that could be (or probably would be) necessary is to pass group numbers to an additional placeholder, something as follows Data_Point 1 --> Sub-Batch 1 Data_Point 2 --> Sub-Batch 1 Data_Point 3 --> Sub-Batch 1 Data_Point 4 --> Sub-Batch 2 Data_Point 5 --> Sub-Batch 2 .... .... Data_Point K --> Sub-Batch 32 However, I am unable to come up with a definitive technique to go further. Any help would be highly appreciated. EDIT 1: I have created a small toy setup of the above problem here As you can see, currently the shape of generated group representation is 1*10. However it should be 5*10 EDIT 2: I got it to work but I am concerned about the correctness/optimization of my code. Would be great if someone could help me in checking if the c…
has answer: http://stackoverflow.com/a/48337177
has title: Handling Variable Size Sub-Batches inside a mini batch in Tensorflow

http://stackoverflow.com/comment/83438005
type: AnswerComment
score: 1
type: Comment
has text: Um, what makes you think that they are necessary? The function you are using most certainly does *not* have this max/min. You are imposing them. And your data values fall *exactly* on these bounds. The fit algorithm *will* have a very hard time satisfying your arbitrary bounds. Python is *not* failing.
comment on: http://stackoverflow.com/a/48226927

http://stackoverflow.com/a/48304614
has comment: http://stackoverflow.com/comment/83597840
has comment: http://stackoverflow.com/comment/83598689
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83597268
score: 0
has body: You can use itertools.groupby: import itertools s = [(1,2),(2,3),(6,4),(7,5),(8,15)] new_data = [d for c, d in [(a, list(b)) for a, b in itertools.groupby(s, key=lambda (x, y):(abs(x-y) &lt; 2, abs(x-y) &lt; 3))]] Output: [[(1, 2), (2, 3)], [(6, 4), (7, 5)], [(8, 15)]] Since the above answer utilizes lambda tuple unpacking, it will not work for Python3. However, for a Python3 compatible solution, use the code below: import itertools s = [(1,2),(2,3),(6,4),(7,5),(8,15)] new_data = [d for c, d in [(a, list(b)) for a, b in itertools.groupby(s, key=lambda x:(abs(x[0]-x[1]) &lt; 2, abs(x[0]-x[1]) &lt; 3))]]
has comment: http://stackoverflow.com/comment/83596904
downvote count: 1
answers question: http://stackoverflow.com/q/48304365
has comment: http://stackoverflow.com/comment/83598370

http://stackoverflow.com/q/48208307
tagged with: python-3.x
has body: I am trying to learn web scraping, I need to get the all the select tags in the web page. But they are not getting detected by BeautifulSoup4. Here is my code in python 3 from urllib.request import Request, urlopen from bs4 import BeautifulSoup import lxml req = Request('https://www.nseindia.com/', headers={'User-Agent': 'Mozilla/5.0'}) webpage = urlopen(req).read() soup = BeautifulSoup(webpage, "lxml") #print(soup.find("select", id="QuoteSearch")) #print(soup.find_all("div", {'class':'equity'})) print(soup.find("select")) Output None Also, I am planning to make my script choose a certain option in the select tag. I would love it if someone could tell me how this can be done. Thanks in advance.
type: Question
has comment: http://stackoverflow.com/comment/83397679
has comment: http://stackoverflow.com/comment/84117263
has comment: http://stackoverflow.com/comment/83397694
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/83398716
tagged with: python
type: UnansweredQuestion
has title: BeautifulSoup4 Not detecting Select tag
linked to: http://stackoverflow.com/q/47965265
has comment: http://stackoverflow.com/comment/83397540
has comment: http://stackoverflow.com/comment/83397847
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/83397496
score: 1
tagged with: web-scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/83399925
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/q/48253310
tagged with: python
upvote count: 2
score: 2
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83490693
has title: Python3.6 not displaying output in Sublime-Text3
has answer: http://stackoverflow.com/a/48253552
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/10604409
tagged with: python-3.x
linked to: http://stackoverflow.com/q/28198563
has answer: http://stackoverflow.com/a/48253665
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48253798
has body: When inputting the name Python3.6 is not displaying the required output And here is the image of my build-system

function
tags question: http://stackoverflow.com/q/48328561
tags question: http://stackoverflow.com/q/48328938
tags question: http://stackoverflow.com/q/48249270
type: Tag
tags question: http://stackoverflow.com/q/48274138
tag name: function
tags question: http://stackoverflow.com/q/48293503
tags question: http://stackoverflow.com/q/48302926
tags question: http://stackoverflow.com/q/48226330
tags question: http://stackoverflow.com/q/48285534
tags question: http://stackoverflow.com/q/48262202
tags question: http://stackoverflow.com/q/48312602
tags question: http://stackoverflow.com/q/48186549
tags question: http://stackoverflow.com/q/48323850
tags question: http://stackoverflow.com/q/48245554
tags question: http://stackoverflow.com/q/48284350
tags question: http://stackoverflow.com/q/48312954
tags question: http://stackoverflow.com/q/48274084
tags question: http://stackoverflow.com/q/48330128
tags question: http://stackoverflow.com/q/48254119
tags question: http://stackoverflow.com/q/48252926
tags question: http://stackoverflow.com/q/48307377
tags question: http://stackoverflow.com/q/48189696
tags question: http://stackoverflow.com/q/48231913
tags question: http://stackoverflow.com/q/48183296
tags question: http://stackoverflow.com/q/48243202
tags question: http://stackoverflow.com/q/48288267
tags question: http://stackoverflow.com/q/48249317
tags question: http://stackoverflow.com/q/48242369
tags question: http://stackoverflow.com/q/48236890
tags question: http://stackoverflow.com/q/48180706
tags question: http://stackoverflow.com/q/48217284
tags question: http://stackoverflow.com/q/48181072

http://stackoverflow.com/a/48701634
has comment: http://stackoverflow.com/comment/84514220
has comment: http://stackoverflow.com/comment/84652563
has comment: http://stackoverflow.com/comment/84514039
downvote count: 0
has comment: http://stackoverflow.com/comment/84428483
has comment: http://stackoverflow.com/comment/84428470
upvote count: 1
answers question: http://stackoverflow.com/q/48216786
has comment: http://stackoverflow.com/comment/84440569
has comment: http://stackoverflow.com/comment/84869013
score: 1
has body: Regarding question 3: I suggest you run several training and validation cycles with different hyperparameters to find what works best for your data and requirements. You can take a look at my implementation here (https://github.com/fritzfitzpatrick/tensorflow-seq2seq-generic-example) where I have built a very simple training &amp; validation loop that stops once the validation loss has not gone down for a number of cycles to prevent overfitting. Regarding question 2: I am still working on a CustomHelper implementation at the moment, and it looks like it is going somewhere. You can find the full sample code here (https://github.com/fritzfitzpatrick/tensorflow-seq2seq-generic-example/blob/master/tensorflow_custom_helper.ipynb). batch_size = 5 features_dec_inp = 2 # number of features in target sequence go_token = 2 end_token = 3 sess = tf.InteractiveSession() def initialize_fn(): finished = tf.tile([False], [batch_size]) start_inputs = tf.fill([batch_size, features_dec_inp], go_token) return (finished, start_inputs) def next_inputs_fn(time, outputs, state, sample_ids): del time, sample_ids # finished needs to update after last step. # one could use conditional logic based on sequence length # if sequence length is known in advance finished = tf.tile([False], [batch_size]) # next inputs should be the output of the dense layer # unless the above finished logic returns [True] # in which case next inputs can be anything in the right shape next_inputs = tf.fill([batch_size, features_dec_inp], 0.5) return (finished, next_inputs, state) helper = tf.contrib.seq2seq.CustomHelper( initialize_fn = initialize_fn, sample_fn = tf.identity, next_inputs_fn = next_inputs_fn) print(helper) Regarding question 1: This is the code that I am using to reduce the dimensionality of my decoder output to the number of features in my target sequence: train_output_dense = tf.layers.dense( train_dec_out_logits, # [batch_size x seq_length x num_units] features_dec_exp_out) # [batch_size x seq_lengt…
has comment: http://stackoverflow.com/comment/84427922
type: Answer
has comment: http://stackoverflow.com/comment/89093504
has comment: http://stackoverflow.com/comment/84428618
has comment: http://stackoverflow.com/comment/84426066
has comment: http://stackoverflow.com/comment/84869714
has comment: http://stackoverflow.com/comment/84514298
has comment: http://stackoverflow.com/comment/84419381

http://stackoverflow.com/q/48193822
tagged with: ipython
has answer: http://stackoverflow.com/a/56657073
tagged with: jupyter-notebook
has title: Import of package works in IPython shell but not in Jupyter notebook
type: AnsweredQuestion
tagged with: python-import
accepted answer: http://stackoverflow.com/a/56565659
answer count: 3
upvote count: 3
has answer: http://stackoverflow.com/a/56565659
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83368357
type: Question
score: 3
possible better answer: http://stackoverflow.com/a/56614880
linked to: http://stackoverflow.com/q/36076395
has answer: http://stackoverflow.com/a/56614880
tagged with: python
has body: I think this question is probably closely related to another one I had, but I'm not sure what the best general-purpose answer is. On my laptop, if I log into the IPython shell, I can execute In [1]: import matplotlib without error. But if I try to do the same thing in a Jupyter notebook, I get the following error: --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) &lt;ipython-input-2-82be63b7783c&gt; in &lt;module&gt;() ----&gt; 1 import matplotlib ModuleNotFoundError: No module named 'matplotlib' What explains this? What should I do to fix this? Why does the IPython shell have access to a package that Jupyter notebook doesn't have access to?

http://stackoverflow.com/comment/83456711
type: Comment
has text: Disagree. `while cur and cur.next` is idiomatic. PEP8 only says to use `is` rather than `==` when comparing to `None`. It doesn't insist that one use `value is not None` over simply `value`.
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48237025

http://stackoverflow.com/comment/83357367
score: 0
comment on: http://stackoverflow.com/q/48188547
type: Comment
has text: Have you even try to do smthg ? What are `num_students`, `num_message` ? Please try to make your problem clear...
type: QuestionComment

http://stackoverflow.com/comment/83387971
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48203449
score: 0
has text: I'm trying to remove the number in the end of each element in the name column

http://stackoverflow.com/comment/83376127
type: AnswerComment
has text: Is this specific to Python 3? I do not observe the issue with Python 2.
comment on: http://stackoverflow.com/a/48197521
type: Comment
score: 0

http://stackoverflow.com/comment/83410722
has text: Regarding your implementation of Otsu, it is supposed to be more efficient than this. Read here: https://en.wikipedia.org/wiki/Otsu%27s_method . In short, at each loop iteration, you can update the estimated means and variances, rather than computing them from all bins in every iteration. This changes the algorithm from O(*n*^2) to O(*n*) (with *n* the number of bins in the histogram, admittedly not a large value).
comment on: http://stackoverflow.com/q/48213278
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48260892
answers question: http://stackoverflow.com/q/48260503
score: 1
upvote count: 1
type: Answer
has body: All your classes should call their super(), e. g.: class Sqroot(object): def __init__(self): print 'Inside sqroot class' super(Sqroot, self).__init__() def sqroot(self, num): print 'The square root of the number is ',num**0.5 Add this for all your base classes to enable a proper calling of all constructors (__init__()s). Python's internal logic will take care that the calls are chained properly, i. e. Child will call Add, Add will call Sub, Sub will call Mul, etc. until Div will call object (which does nothing). Here's a diagram for a similar chain: Yours would look more like this: Add &lt;--. ↓ \ Sub \ ↓ \ object &lt;-. Mul Child \ ↓ \ Sqroot \ ↓ Div
downvote count: 0

http://stackoverflow.com/comment/83533337
type: AnswerComment
has text: it gives following error WebDriverException: Message: unknown error: cannot focus element
type: Comment
comment on: http://stackoverflow.com/a/48230503
score: 0

branch
tag name: branch
tags question: http://stackoverflow.com/q/48301542
type: Tag

http://stackoverflow.com/a/48329645
accepted answer of: http://stackoverflow.com/q/48329498
upvote count: 1
answers question: http://stackoverflow.com/q/48329498
has comment: http://stackoverflow.com/comment/83647453
has comment: http://stackoverflow.com/comment/83649347
has body: This is because it's located in the tests directory, but you're running test_suite.py from the parent directory of tests. The reason why it worked when you ran test_website_loads.py is because you were running it from within the tests directory. When resolving imports, the Python interpreter checks a series of locations for the module, starting with the current directory and then moving to other locations such as those in your PYTHONPATH environment variable, and the site-packages directory in your Python install location. I duplicated this on my system but changed the import statement to tests.special_module.special_module_file and it worked. If you don't like this solution, you will need to change the location of the special_module directory or add it to your PYTHONPATH or something similar. Edit: In response to your comment below, I assume your test_suite.py file looks something like this: from tests.test_website_loads import some_function, some_class result = some_function() obj = some_class() This still runs into the problem described above, because the Python interpreter is still being run in the top-level directory. When it searches for modules, it searches the current directory where it only finds test_suite.py and tests/. Then it checks your PYTHONPATH environment variable. If it still finds nothing, it will check then installation-dependent default location (such as the site-packages directory), and if no such module is found, it throws an exception. I think the best solution would be to add special_module to the PYTHONPATH environment variable as described in the link I included above. Otherwise, you could create a symbolic link to the module in the top-level directory with ln -s tests/special_module special_module, assuming that you're running on a UNIX-like system. However, this would not be considered best practice; the first method is preferred.
type: Answer
has comment: http://stackoverflow.com/comment/83647509
has comment: http://stackoverflow.com/comment/83647328
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/52650324
has body: These are keys in your chrome profile. For example if you were to to open it you can go to profile.content_settings.exceptions.plugins. https://sessionbuddy.com/chrome-profile-location/ https://developer.chrome.com/extensions/contentSettings
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48317163
upvote count: 1
score: 1

http://stackoverflow.com/q/48270451
linked to: http://stackoverflow.com/q/47308335
tagged with: dataframe
tagged with: python
score: -1
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48270523
has comment: http://stackoverflow.com/comment/83524886
upvote count: 0
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/48270523
downvote count: 1
has body: I have a pandas dataframe with three columns, and I want to drop all rows where the unique combination of df['person'], df['id'], and df['day'] only occur twice or less. Is there a simple way to do this in pandas? [In]: person id day 1 2 1 1 2 1 1 2 1 1 2 1 1 1 1 1 1 1 1 1 1 1 0 1 1 2 2 2 2 2 2 2 2 2 2 2 1 3 1 1 3 1 1 3 1 1 0 1 2 2 2 [Out]: person id day 1 2 1 1 2 1 1 2 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 1 3 1 1 3 1 1 3 1 2 2 2
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48270587
has title: Deleting rows in pandas that occur less than a certain amount based on three columns
accepted answer: http://stackoverflow.com/a/48270587

http://stackoverflow.com/comment/83397098
score: 0
has text: Both urls look identical, so the response should be the same. The only think that think of is the line breaks. Can you try again with the url in a single line?
comment on: http://stackoverflow.com/q/48202387
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83385672
has text: @harpratap In the particular code example given in the question, `self.country` is definitely *not* returning the instance's country attribute. There is no such attribute defined on the instance so it is returning the value of `country` defined on the type `State` instead.
type: Comment
comment on: http://stackoverflow.com/a/48198410
type: AnswerComment
score: 2

http://stackoverflow.com/q/48298724
favorite count: 0
has comment: http://stackoverflow.com/comment/83582194
tagged with: fft
type: Question
tagged with: signals
has body: I collected some data(178,432) of motor vibration signal, and the unit was g(Acceleration). The Sampling rate of signal is 25000/sec, motor speed is 1500rpm(25hz). But while I try to do the FFT using python, the picture isn't right. Can anyone help me with it? my data : https://drive.google.com/file/d/12V8H3h6ved4lBflVxoHo2Qv5rfVZqXf0/view?usp=sharing Here is my code: import scipy.fftpack import numpy as np import pandas as pd import matplotlib.pyplot as plt nor = pd.read_csv('normal.csv', header=1) N = nor.size # data size T = 1.0 / 25000.0 # inverse of sampling rate x = np.linspace(0.0, N*T, N) y = nor.values yf = np.abs(scipy.fft(y)) xf = scipy.fftpack.fftfreq(nor.size, d=T) fig, ax = plt.subplots() ax.plot(np.abs(xf), np.abs(yf)) plt.show() my FFT plot:
has title: Fast Fourier Transform on motor vibration signal in python
downvote count: 0
has comment: http://stackoverflow.com/comment/83581934
tagged with: python
has answer: http://stackoverflow.com/a/48299323
type: AnsweredQuestion
score: 3
tagged with: pandas
upvote count: 3
answer count: 1
accepted answer: http://stackoverflow.com/a/48299323

optimization
tags question: http://stackoverflow.com/q/48324152
tags question: http://stackoverflow.com/q/48177815
tags question: http://stackoverflow.com/q/48269471
tags question: http://stackoverflow.com/q/48250644
tags question: http://stackoverflow.com/q/48252227
tags question: http://stackoverflow.com/q/48191589
tags question: http://stackoverflow.com/q/48300979
tags question: http://stackoverflow.com/q/48278482
tag name: optimization
tags question: http://stackoverflow.com/q/48330128
tags question: http://stackoverflow.com/q/48268826
tags question: http://stackoverflow.com/q/48304756
tags question: http://stackoverflow.com/q/48281026
tags question: http://stackoverflow.com/q/48314127
tags question: http://stackoverflow.com/q/48289257
tags question: http://stackoverflow.com/q/48274772
tags question: http://stackoverflow.com/q/48242168
tags question: http://stackoverflow.com/q/48292403
tags question: http://stackoverflow.com/q/48287289
tags question: http://stackoverflow.com/q/48232932
tags question: http://stackoverflow.com/q/48233306
tags question: http://stackoverflow.com/q/48219522
tags question: http://stackoverflow.com/q/48211136
type: Tag
tags question: http://stackoverflow.com/q/48288286
tags question: http://stackoverflow.com/q/48233950
tags question: http://stackoverflow.com/q/48212068
tags question: http://stackoverflow.com/q/48301044

http://stackoverflow.com/comment/83626239
type: QuestionComment
comment on: http://stackoverflow.com/q/48320432
score: 0
has text: Well, then you got your answer from Coldspeed.
type: Comment

pepper
tags question: http://stackoverflow.com/q/48204925
tag name: pepper
type: Tag

http://stackoverflow.com/q/48211738
has comment: http://stackoverflow.com/comment/83404845
has answer: http://stackoverflow.com/a/48212649
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83405170
tagged with: python
has title: Nested for loop to transpose matrix
linked to: http://stackoverflow.com/q/4937491
has comment: http://stackoverflow.com/comment/83404820
has answer: http://stackoverflow.com/a/48213439
has comment: http://stackoverflow.com/comment/83414580
answer count: 2
has body: def transpose_matrix(matrix): n = len(matrix) vertical_to_horizontal = [[0]*n]*n for i in range(n): for j in range(n): vertical_to_horizontal[i][j] = matrix[j][i] return vertical_to_horizontal print(transpose_matrix([[1,2],[3,4]])) The function is supposed to transpose a n*n matrix, but I get [[2, 4], [2, 4]] instead of the correct answer ([1,3],[2,4]). I know that there are other ways to transpose a matrix, but my problem is to understand why the code above doesn't give the expected result.
tagged with: matrix
score: 1
upvote count: 3
downvote count: 2
tagged with: nested
has comment: http://stackoverflow.com/comment/83404875
has comment: http://stackoverflow.com/comment/83404686
favorite count: 0
has comment: http://stackoverflow.com/comment/83404768
type: Question

http://stackoverflow.com/q/48320642
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83626585
type: UnansweredQuestion
tagged with: python
has title: How to insert values containing '/' into sqlite?
has body: conn = sqlite3.connect(self.__database_name) c = conn.cursor() sql = 'INSERT OR IGNORE INTO ' + self.__article_url_table_name + ' (url) values (%s)' % (href) c.execute(sql) conn.commit() I get the following error in the line where I call: c.execute(sql) sqlite3.OperationalError: near "/": syntax error The url variable is a string which contains a url like: https://www.foo.com/bar.html What is the error in my code ?
has answer: http://stackoverflow.com/a/48320817
score: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48320760

http://stackoverflow.com/q/48214852
linked to: http://stackoverflow.com/q/1373164
has body: Suppose I want the variables a_1, a_2, a_3, a_4 to be random numbers from the uniform distribution U(0,100). I could write import random a_1 = random.uniform(0,100) a_2 = random.uniform(0,100) a_3 = random.uniform(0,100) a_4 = random.uniform(0,100) But I was wondering if there is a more efficient way to do this. I tried the following, import random for i in range(4): a_i = random.uniform(1,100) print(a_i) However, this did not work. For example, when I call a_1 later on, it says a_1 is not defined. How can I fix this?
has answer: http://stackoverflow.com/a/48218086
possible better answer: http://stackoverflow.com/a/48218086
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83418299
tagged with: python-3.x
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/83411611
has title: How can I generate random numbers and assign them to variables in python?
has answer: http://stackoverflow.com/a/48237436
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48214912
has comment: http://stackoverflow.com/comment/83418313
accepted answer: http://stackoverflow.com/a/48214912
linked to: http://stackoverflow.com/q/5036700
has comment: http://stackoverflow.com/comment/83411476
type: Question
has comment: http://stackoverflow.com/comment/83411627
upvote count: 0

http://stackoverflow.com/q/48307078
possible better answer: http://stackoverflow.com/a/48307337
tagged with: python
accepted answer: http://stackoverflow.com/a/48307296
has title: Trying to create a virtualenv in python and activate it
has answer: http://stackoverflow.com/a/62697558
has answer: http://stackoverflow.com/a/48307296
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83599552
answer count: 3
downvote count: 0
tagged with: virtualenv
has body: I am having a hard time to create a virtualenv in Python and activating it. I am working on the Windows Operating system. In command prompt, I have installed virtualenv by typing the following command: pip install virtualenv Then, to create a virtual environment in it, I used the following: virtualenv ENV But, I am not sure if this right. Next, I am unable to understand how to activate it. For Linux, i found that activation would be done using source /bin/activate. But, unable to find the one for Windows. Please help me out in creating the virtualenv and activating it.
has answer: http://stackoverflow.com/a/48307337
favorite count: 0
type: Question
score: 5
upvote count: 5
tagged with: windows

http://stackoverflow.com/comment/83641611
has text: Does your original data file handle the summertime correctly? Because I usually can't use your (correct) line, as it will throw an "AmbiguousTimeError" or "NonExistentTimeError", as almost no datafile I come across handles this properly. Below an answer for this case.
type: QuestionComment
comment on: http://stackoverflow.com/q/48315955
score: 0
type: Comment

http://stackoverflow.com/comment/83363351
comment on: http://stackoverflow.com/a/48191407
type: AnswerComment
has text: Thank you SO MUCH!!
score: 0
type: Comment

http://stackoverflow.com/a/48253455
type: Answer
has body: If you remove matches from a set, then the left over set is what you are after: Code: skus = set(sku) for x in isbn: skus -= {i for i in skus if x in i} Test Code: isbn = ["1111", "2222", "3333", "4444", "5555"] sku = ["k1 1111", "k2 2222", "k3 3333", "k4 4444", "k5 5555", "k6 6666", "k7 7777", "k8 8888", "k9 1111"] skus = set(sku) for x in isbn: skus -= {i for i in skus if x in i} print(skus) Results: {'k6 6666', 'k7 7777', 'k8 8888'}
score: 0
answers question: http://stackoverflow.com/q/48253396
has comment: http://stackoverflow.com/comment/83489502
has comment: http://stackoverflow.com/comment/83489536

http://stackoverflow.com/comment/83503628
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48260209
has text: What's the point of "conveying" a _wrong_ "conceptual understanding" ? Explaining Python variables to C programmers (well, to people who's been taught that "a variable is a label for a memory location") again and again is already boring enough. You could have explained the same thing in a way that is at least as "understandable" while "conceptually correct" for both C-type variables and Python-type variables like: "it is an action that associates the symbolic name 'a' to the numeric value '3' ". No need to talk about memory locations here.
type: AnswerComment

http://stackoverflow.com/comment/83594370
score: 0
type: Comment
has text: Thank you @Martijn Pieters, that is a very important point. I didn't know that.
comment on: http://stackoverflow.com/a/48304390
type: AnswerComment

http://stackoverflow.com/a/48284050
downvote count: 0
upvote count: 1
has body: The following can work, assuming we want to pad with 0s when needed: data_1 = data.copy() data_2 = data.copy() data_1.index = data_1.index+1 data_2.index = data_2.index+2 df= pd.concat([data, data_1, data_2], axis=1).fillna(0) X = df.apply(lambda x: np.split(x, 3), axis=1) I'm leaving the Q open in case someone has a better solution!
type: Answer
answers question: http://stackoverflow.com/q/48278162
score: 1
accepted answer of: http://stackoverflow.com/q/48278162
type: AcceptedAnswer

http://stackoverflow.com/q/48306817
linked to: http://stackoverflow.com/q/40138780
has comment: http://stackoverflow.com/comment/83599290
has comment: http://stackoverflow.com/comment/83599840
has comment: http://stackoverflow.com/comment/83600067
tagged with: python
has title: Is it possible to use readlines with boto3?
type: Question
has comment: http://stackoverflow.com/comment/83608873
has body: I'm trying to run a diff on two files that are stored in S3, and would like to avoid downloading the files if possible. The sample code I am working with is as so: import difflib file1 = open('sample1.csv', 'r'); file2 = open('sample2.csv', 'r'); diff = difflib.ndiff(file1.readlines(), file2.readlines()) I see with boto3 package, I can open the file from S3, but how can I pass the equivalent of file1.readlines() and file2.readlines() into the ndiff function?
type: UnansweredQuestion
answer count: 1
linked to: http://stackoverflow.com/q/45513538
has comment: http://stackoverflow.com/comment/83599590
has answer: http://stackoverflow.com/a/50320839
score: 0
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/83608921

http://stackoverflow.com/comment/83627498
comment on: http://stackoverflow.com/a/48312048
has text: @kulijana Please, check my updates. It seems that you do something wrong while running the script. BTW did you set some special `PYTHONPATH`?
score: 0
type: Comment
type: AnswerComment

list-comprehension
tags question: http://stackoverflow.com/q/48306122
tags question: http://stackoverflow.com/q/48241302
type: Tag
tags question: http://stackoverflow.com/q/48246653
tags question: http://stackoverflow.com/q/48270080
tags question: http://stackoverflow.com/q/48277357
tags question: http://stackoverflow.com/q/48255358
tags question: http://stackoverflow.com/q/48227410
tags question: http://stackoverflow.com/q/48223587
tags question: http://stackoverflow.com/q/48227848
tags question: http://stackoverflow.com/q/48231943
tags question: http://stackoverflow.com/q/48220279
tags question: http://stackoverflow.com/q/48189750
tags question: http://stackoverflow.com/q/48255952
tags question: http://stackoverflow.com/q/48277115
tags question: http://stackoverflow.com/q/48210056
tags question: http://stackoverflow.com/q/48191826
tags question: http://stackoverflow.com/q/48248867
tag name: list-comprehension
tags question: http://stackoverflow.com/q/48287929
tags question: http://stackoverflow.com/q/48204633

http://stackoverflow.com/q/48241274
has comment: http://stackoverflow.com/comment/83465182
has body: Please tell me what is wrong with my code. The function returned False for the palindrome(11) and True for some cases. Below is the code : def palindrome(x): if(x &lt; 0 or (x%10 == 0 and x != 0)): return False revertedNumber = 0 while(x &gt; revertedNumber): revertedNumber = revertedNumber * 10 + x%10 x = x/10 return(x == revertedNumber or x == revertedNumber/10) Above code returned false for the input 11
duplicate of: http://stackoverflow.com/q/1282945
score: 0
has comment: http://stackoverflow.com/comment/83465391
answer count: 0
has comment: http://stackoverflow.com/comment/83465154
linked to: http://stackoverflow.com/q/2958684
tagged with: palindrome
upvote count: 1
tagged with: python
type: UnansweredQuestion
downvote count: 1
favorite count: 0
type: Question
has title: Reversing a number failed in python
has comment: http://stackoverflow.com/comment/83464977
linked to: http://stackoverflow.com/q/1282945
has comment: http://stackoverflow.com/comment/83464952
has comment: http://stackoverflow.com/comment/83465254
tagged with: python-3.x

http://stackoverflow.com/comment/83487761
score: 0
has text: It's complaining that `META-INF/container.xml` doesn't exist. Does it? What does `unzip -l` on the file produced by your script look like?
comment on: http://stackoverflow.com/q/48252192
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48324898
has comment: http://stackoverflow.com/comment/83646232
tagged with: python
tagged with: pygame
has title: pygame camera initialization fails with NotImplementedError
linked to: http://stackoverflow.com/q/16266244
has body: On a Linux computer with pygame 1.9.3 I am puzzled by the implementation of the initialization of the pygame camera. The code below demonstrates the surprising behavior: In the first call to Camera (pygame.camera.Camera) the camera will be initialized, while the second call (Camera) raises a NotImplementedError. &gt;&gt;&gt; from pygame.camera import Camera, init as camera_init &gt;&gt;&gt; import pygame.camera &gt;&gt;&gt; &gt;&gt;&gt; camera_init() &gt;&gt;&gt; camera = pygame.camera.Camera("/dev/video0") &gt;&gt;&gt; camera = Camera("/dev/video0") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.5/dist-packages/pygame/camera.py", line 102, in __init__ raise NotImplementedError() NotImplementedError It must arise from the Camera class being declared a global variable and redefined to point to the actual implementation in the camera.py file. The first call uses the redefined variable while the second uses the original Camera class. It strikes me as an surprising implementation that may take some time to debug. Could this not be implemented under a factory pattern?
type: Question
score: 0
answer count: 0
duplicate of: http://stackoverflow.com/q/16266244
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83681970
favorite count: 0
tagged with: camera

http://stackoverflow.com/q/48227649
has body: Anybody aware of a string similarity method that would give the correct results for the below? I'm dealing with alphanumeric IDs where: a change in the early part of the string matters more than in the latter part. I guess I could do ngrams? Although that might break down in the scenario where one string has a prefix? The difference in what character gets substrituted matters as changing an "a" to "b" is less of a change than changing it to "c". Levenstein and Jaro-Winkler don't seem to be doing the right thing. See example below. import jellyfish t1="100" t21=["100a","a100"] # case 1. expecting: similar, not similar t22=["101","105","200"] # case 2. expecting: similar, less similar, least similar fun = jellyfish.levenshtein_distance print([fun(t1, t) for t in t21]) # all the same print([fun(t1, t) for t in t22]) # all the same fun = jellyfish.jaro_winkler print([fun(t1, t) for t in t21]) # all the same print([fun(t1, t) for t in t22]) # all the same For added fun, a scenario where the first string has a prefix which is essentially irrelevant to the string as an ID but messes up string similarity. t1="pre-100" t21=["100a","a100"] # expecting: similar, not similar t22=["101","105","200"] # expecting: similar, less similar, least similar fun = jellyfish.levenshtein_distance print([fun(t1, t) for t in t21]) # picks the wrong one print([fun(t1, t) for t in t22]) # all the same fun = jellyfish.jaro_winkler print([fun(t1, t) for t in t21]) # picks the wrong one print([fun(t1, t) for t in t22]) # picks the right one
linked to: http://stackoverflow.com/q/11980000
type: Question
has title: String similarity where order and difference in ascii code matters
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83439075
downvote count: 0
has comment: http://stackoverflow.com/comment/83441158
upvote count: 1
tagged with: string
tagged with: levenshtein-distance
favorite count: 0
has comment: http://stackoverflow.com/comment/87193368
has comment: http://stackoverflow.com/comment/83439000
tagged with: jaro-winkler
score: 1
tagged with: python

http://stackoverflow.com/a/48197475
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48197398
type: Answer
score: 2
has body: You can use a list comprehension to go through the old list and generate a new one. Use list unpacking to separate the list of two values at each outer list location. a = [[float(s), v] for s,v in a]

http://stackoverflow.com/q/48201898
tagged with: flask
answer count: 1
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48219950
type: Question
has answer: http://stackoverflow.com/a/48219950
has title: Python Flask - How to start python server using flask and execute it multiple times using multiple argumens
has comment: http://stackoverflow.com/comment/83384655
has comment: http://stackoverflow.com/comment/83386303
tagged with: python
has comment: http://stackoverflow.com/comment/83385685
score: -2
tagged with: flask-restful
has comment: http://stackoverflow.com/comment/83386270
has comment: http://stackoverflow.com/comment/83384737
downvote count: 4
has comment: http://stackoverflow.com/comment/83385299
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83385652
has comment: http://stackoverflow.com/comment/83386051
has body: I have tested basic Flask script (hello.py) and it is working fine. I have commented out the main function routing part and just executed the script. from flask import Flask app = Flask(__name__) ''' #Commenting the Main function part @app.route("/") def main(): return "Welcome!" ''' if __name__ == "__main__": app.run(host= '0.0.0.0') As expected, the server is started and I got the following message as well : C:\&gt;python hello.py * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Now my requirement is once this python server is started, how to execute another python script and route to this python server. For example I have the following script which needs to be executed via browser (since the python server is already up and running) by accessing http://127.0.0.1:5000/arg1/arg2 import ..... from flask import Flask app = Flask(__name__) @app.route('/&lt;string:arg1&gt;/&lt;string:arg2&gt;') def main(): do something ........ call sub-function(arg1, arg2) do something ........ if __name__ == '__main__': arg1 = 100 arg2 = 50 #app.run(debug=True) **#I should not run this again as server is already started.So commented it out** main(arg1, arg2) #Calling Main function using two IDs as arguments. Note : If i keep app.run() in the actual program script which needs to be executed, then it is working fine. But my requirement is server start script actual program script should be different but somehow interlinked via app. I am not sure how to achieve this.

http://stackoverflow.com/a/48208182
score: 3
upvote count: 3
has body: A Dictionary in Python means fairly the same thing as the word Dictionary. This implies, You can so easily lookup the Value of any keyword using the Keyword directly. This is, unfortunately, not possible with a list since lists are numerically indexed. It is thus recommended to first Convert your list into a Dictionary for 2 reasons: 1: Easier Mapping of the given Data to Individual Keys. 2: Processing the Data-Values to obtain your desired result. As the Result of the Print shows, it is now easier to access any data by using the Key (even within a loop). For example, to get the Price of Phones, You can simply do: dictList['phone']['price'] which is much more easier than doing something like: flatList[0][2] which is really not so intuitive.... product_list = [ ['phone', '500', 450.0, 1], ['phone', '500', 2250.0, 5], ['camera', '200', 1080.0, 6], ['laptop', '600', 540.0, 1], ['laptop', '600', 540.0, 1], ['laptop', '600', 540.0, 1] ] # CREATE A LIST OF DICTIONARY FROM GIVEN DATA FOR EASIER MAPPING item = ["product_name", "price_rate", "price", "quantity"] dictList = {} for data in product_list: if data[0] not in dictList: dictList[data[0]] = dict(zip(item, data)) else: tmpD = dict(zip(item, data)) dictList[data[0]]["price"] = float(dictList[data[0]]["price"]) + float(tmpD['price']) dictList[data[0]]["quantity"] = float(dictList[data[0]]["quantity"]) + float(tmpD['quantity']) # dictList[data[0]]["price_rate"] = float(dictList[data[0]]["price_rate"]) + float(tmpD['price_rate']) print(dictList) ## PRINTS: ## { ## 'phone': {'product_name': 'phone', 'price_rate': '500', 'price': 2700.0, 'quantity': 6.0}, ## 'camera': {'product_name': 'camera', 'price_rate': '200', 'price': 1080.0, 'quantity': 6}, ## 'laptop': {'product_name': 'laptop', 'price_rate': '600', 'price': 1620.0, 'quantity': 3.0} ## } However, if for any reason you need to have your Data as a List, it is also quite easier with a simple list composition like so: item = ["product_name", "price_rate", "price", "quan…
type: Answer
has comment: http://stackoverflow.com/comment/83397476
answers question: http://stackoverflow.com/q/48207313
has comment: http://stackoverflow.com/comment/83397399
has comment: http://stackoverflow.com/comment/83419375
downvote count: 0

http://stackoverflow.com/comment/83335023
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48177422
has text: negate: `~[true, true, false] = [false, false, true]`
score: 1

http://stackoverflow.com/q/48236321
has body: I want obtain the tuple in span and the str of macht, but i dont know how acces to this object, the methods from the documentation dont work import re s = 'sd(asdf(xf))fg' if re.findall('\([A-z ]+\)', s): m = re.finditer('\([A-z ]+\)', s) m = list(m) print(m) I get this output: [&lt;_sre.SRE_Match object; span=(7, 11), match='(xf)'&gt;] What process or method i need for get (7, 11) and '(xf)'?
has title: Get span and match from finditer
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/48236372
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48236372
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/48257519
tagged with: ajax
has comment: http://stackoverflow.com/comment/83497886
linked to: http://stackoverflow.com/q/618557
score: 0
has answer: http://stackoverflow.com/a/48257617
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/83497823
has body: I am trying to use AJAX to make a POST request to DRF. One of my fields is a multiple select box. I can't seem to find a way to make the request work properly. &lt;select class="full-width" data-init-plugin="select2" id='roles' name="roles" multiple&gt; {% for role in roles %} &lt;option value="{{role.id}}"&gt;{{role.name}}&lt;/option&gt; {% endfor %} &lt;/select&gt; I have tried posting the entire select box like below. var roles = $('#roles').val(); I have also tried posting an array of the values. var roles = $('#roles').find('option:selected').map(function(){return $(this).val()}).get(); My AJAX call looks like this: $.ajax({ method: "POST", url: "/v1.0/relationships/" + url, data: {roles: roles} ) My API view looks like this: class RelationshipSingle(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView): """ /relationship/{id} Method Action GET Return details of relationship with ID {id}. POST Invalid option. PATCH Edit the relationship. DELETE Delete the relationship. """ queryset = Relationship.objects.all() serializer_class = RelationshipSerializer def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def patch(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) My serializer looks like this: class RelationshipSerializer(serializers.ModelSerializer): class Meta: model = Relationship fields = '__all__'
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: jquery
has title: How to POST data from a multiple select box in Django Rest Framework
tagged with: django-rest-framework

http://stackoverflow.com/q/48272175
type: Question
has comment: http://stackoverflow.com/comment/83556227
upvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/48273873
possible better answer: http://stackoverflow.com/a/48273873
has comment: http://stackoverflow.com/comment/83529828
tagged with: django
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48285882
has body: I have this model: class Product(models.Model): art_name = models.CharField(max_length=100) plu_num = models.IntegerField(default=0, unique=True) sales_price_brutto = models.FloatField(null=True) sales_price_netto = models.FloatField(null=True) last_price = models.FloatField(null=True) purchase_price_brutto = models.FloatField(null=True) purchase_price_netto = models.FloatField(null=True) entry_date = models.DateField() margin = models.FloatField(null=True) stock = models.IntegerField(default=0) I created for example two user groups. Then I want to each group of users have different values in stock and sales_price_brutto (save method of model calculate rest of the fields values depending on sales_price_brutto and purchase_price_brutto). I tried adding one more field: owner = models.ForeignKey(Group, editable=False) But it seems to not work as I want. I don't really know if there is a way to do that.
accepted answer: http://stackoverflow.com/a/48285882
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83529083
has title: Different field values for each user
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/48219602
answers question: http://stackoverflow.com/q/48219540
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48219540
type: AcceptedAnswer
downvote count: 0
has body: Works in Python 3.6: b = ' '.join(format(ord(x), 'b') for x in contents) ''.join([chr(int(bc, 2)) for bc in b.split(' ')])

http://stackoverflow.com/comment/83569776
has text: Ah I did forget the inheritance in my example code. It still bothers me that this attribute is basically completely avoided in the docs, but I guess this is as good as it's going to get.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48291786
type: Comment

http://stackoverflow.com/q/48240551
favorite count: 0
type: Question
upvote count: 12
has answer: http://stackoverflow.com/a/48240819
accepted answer: http://stackoverflow.com/a/48240819
has comment: http://stackoverflow.com/comment/83463745
answer count: 2
tagged with: python
downvote count: 4
has comment: http://stackoverflow.com/comment/83463522
type: AnsweredQuestion
has title: How to generate a digital signature of a string in Python?
has comment: http://stackoverflow.com/comment/83463427
possible better answer: http://stackoverflow.com/a/77289046
has answer: http://stackoverflow.com/a/77289046
has body: I have a string and I need to generate a digital signature for it using my private key? How can I do it in Python?
tagged with: digital-signature
score: 8

http://stackoverflow.com/a/48196250
type: AcceptedAnswer
downvote count: 0
has body: The difference is easy: from numpy import * imports all names from the top-level NumPy module into your current "module" (namespace). import numpy as np will just make that top-level NumPy module available if you use np.xxx. However there is one reason why you shouldn't use from any_module import *: It may just overwrite existing names. For example NumPy has its own any, max, all and min functions, which will happily shadow the built-in Python any, max, ... functions (a very common "gotcha"). My advise: Avoid from numpy import * even if it seems like less effort than typing np. all the time!
answers question: http://stackoverflow.com/q/48196195
score: 3
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/48196195

http://stackoverflow.com/a/48253611
has comment: http://stackoverflow.com/comment/83524582
answers question: http://stackoverflow.com/q/48252846
has comment: http://stackoverflow.com/comment/83522183
score: 1
has body: scipy has a special optimizer for this case, nnls. The problem is that standard errors and inference are not standard and not easy to implement for the general case. (I haven't managed yet to figure out how to get standard errors.) https://github.com/statsmodels/statsmodels/issues/1211 I used nnls in a case where I did not need standard errors and it works fine. There is a second usecase for inequality or bounds constraints that are required during optimization where, however, the outcome is in general in the interior. Those cases can be handled by reparameterization and is used in several cases, e.g. log or logit link function for discrete or generalized linear models or for variance function estimation. If the optimum is in the interior, then standard inference applies. edit One way to get "approximate" standard errors is to find the parameters for the inequality constraint problem with an appropriate optimizer and then impose the constraints that turn out to be binding in estimating the standard model like OLS. For non-negativity constraints variables that have estimated parameters at the zero bound can just be dropped. That is, we treat the inequality constraints that are binding as equality constraints. However, the computed standard errors in this case are under the assumption that we know which constraints are binding and do not take the uncertainty about inequality constraints that may or may not be binding into account.
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/q/48267845
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83521685
has comment: http://stackoverflow.com/comment/83518964
answer count: 1
has comment: http://stackoverflow.com/comment/83519055
has comment: http://stackoverflow.com/comment/83521734
has comment: http://stackoverflow.com/comment/83520787
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48286843
has answer: http://stackoverflow.com/a/48286843
has title: how to make my python code do a task after specific time?
has body: im using raspberry pi and raspberry pi camera to make a project .. the project is basically glasses that can record videos and take pictures using an IR sensor and I went with TCRT5000 ... What I want to do exactly is when the sensor reads low value nothing happens and when it reads high and the the time since it read high is for 2 seconds it takes a picture and when the time its been high for more than 3 seconds it records a video... import RPi.GPIO as GPIO from picamera import PiCamera from time import sleep import time camera = PiCamera() GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN) while True: sensor=GPIO.input(18) if sensor==1 and : sleep(2) camera.capture("/home/pi/Desktop/Project/Pictures/image%s.jpg") print("I TOOK A PICTURE ") sleep(2) print(" IM RECORDING A VIDEO !!!") camera.start_recording('/home/pi/Desktop/Project/Videos/video.h264') camera.stop_recording() sleep(10) print("NOTHING") sleep(1) elif sensor==0 : print("NOTHING") sleep(1) this is the code im going with for the moment can anyone help me ?

http://stackoverflow.com/comment/83593445
comment on: http://stackoverflow.com/a/48303877
type: Comment
score: 0
type: AnswerComment
has text: Yes this solution worked for me. Thank you so much for quick response.

geocoding
tags question: http://stackoverflow.com/q/48320087
tag name: geocoding
type: Tag

http://stackoverflow.com/comment/83425307
has text: `print("Collecting data”)` has a wrong ending quote (`RIGHT DOUBLE QUOTATION MARK`). Probably unrelated, but still an error.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48221962
type: QuestionComment

http://stackoverflow.com/comment/83468791
type: Comment
score: 0
type: AnswerComment
has text: I dont really understand the line of code print(d[word], end='') any way to write is differently?
comment on: http://stackoverflow.com/a/48243135

http://stackoverflow.com/q/48219927
answer count: 2
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
has title: Importing my own python module
has answer: http://stackoverflow.com/a/48219956
has body: Can I import the test01.py like os, sys module? I want to import the test01.py like: import test01.py In this case now, I only can import it like this: from testDemo02 import test01 Is it possible to reach it?
linked to: http://stackoverflow.com/q/2349991
has answer: http://stackoverflow.com/a/48220013
tagged with: python
has comment: http://stackoverflow.com/comment/83421479
type: Question
duplicate of: http://stackoverflow.com/q/2349991

http://stackoverflow.com/a/56126354
type: Answer
has body: If you would be OK using R I think you could also use bbmle's mle2 function to optimize the least squares likelihood function and calculate 95% confidence intervals on the nonnegative nnls coefficients. Furthermore, you can take into account that your coefficients cannot go negative by optimizing the log of your coefficients, so that on a backtransformed scale they could never become negative. Here is a numerical example illustrating this approach, here in the context of deconvoluting a superposition of gaussian-shaped chromatographic peaks with Gaussian noise on them : (any comments welcome) First let's simulate some data : require(Matrix) n = 200 x = 1:n npeaks = 20 set.seed(123) u = sample(x, npeaks, replace=FALSE) # peak locations which later need to be estimated peakhrange = c(10,1E3) # peak height range h = 10^runif(npeaks, min=log10(min(peakhrange)), max=log10(max(peakhrange))) # simulated peak heights, to be estimated a = rep(0, n) # locations of spikes of simulated spike train, need to be estimated a[u] = h gauspeak = function(x, u, w, h=1) h*exp(((x-u)^2)/(-2*(w^2))) # shape of single peak, assumed to be known bM = do.call(cbind, lapply(1:n, function (u) gauspeak(x, u=u, w=5, h=1) )) # banded matrix with theoretical peak shape function used y_nonoise = as.vector(bM %*% a) # noiseless simulated signal = linear convolution of spike train with peak shape function y = y_nonoise + rnorm(n, mean=0, sd=100) # simulated signal with gaussian noise on it y = pmax(y,0) par(mfrow=c(1,1)) plot(y, type="l", ylab="Signal", xlab="x", main="Simulated spike train (red) to be estimated given known blur kernel &amp; with Gaussian noise") lines(a, type="h", col="red") Let's now deconvolute the measured noisy signal y with a banded matrix containing shifted copied of the known gaussian shaped blur kernel bM (this is our covariate/design matrix). First, let's deconvolute the signal with nonnegative least squares : library(nnls) library(microbenchmark) microbenchmark(a_nnls &lt;-…
answers question: http://stackoverflow.com/q/48252846
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/83472357
type: Comment
type: AnswerComment
has text: Thanks a lot! I'll probably need to rework this code over anyway, but you definitely made it a bit quicker.
score: 0
comment on: http://stackoverflow.com/a/48239372

http://stackoverflow.com/q/48320834
has comment: http://stackoverflow.com/comment/83627062
has body: I am attempting to access data from a related database table and display that in some tables on the front end but struggling to do so. This is what I currently have (reduced to important code). Database Model: class Client(Base): __tablename__ = 'Client' id = db.Column(db.Integer, primary_key=True) clientname = db.Column(db.String(50), unique=True, nullable=False) provider = db.Column(db.Boolean, default=False) sessions = db.relationship('Session', backref='client') contacts = db.relationship('Contact', backref='client') region_id = db.Column(db.Integer, db.ForeignKey('Region.region_name'), nullable=False) class Contact(Base): __tablename__ = 'Contact' id = db.Column(db.Integer, primary_key=True) contact_name = db.Column(db.String(50), nullable=False) contact_phone = db.Column(db.String(50), nullable=False) contact_email = db.Column(db.String(50), nullable=False) client_id = db.Column(db.Integer, db.ForeignKey('Client.clientname'), nullable=False) And then my table containing Jinja templating: &lt;tbody&gt; {% for item in client_details %} &lt;tr&gt; &lt;td&gt;{{ item.clientname }}&lt;/td&gt; &lt;td&gt;{{ item.contacts.contact_name }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/tbody&gt; And the query I am passing to my render_template: session_details = Session.query.all() return render_template('tables.session.html', session_details=session_details, passing_alert=passing_alert) Yet I cannot access the Contact.contact_name. Can anyone point me in the right direction?
answer count: 1
tagged with: jinja2
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/48324783
type: UnansweredQuestion
has title: Accessing SQLAlchemy relationship data from Jinja
tagged with: python
score: 0

http://stackoverflow.com/comment/83498903
score: 0
type: Comment
type: AnswerComment
has text: @TanviMirza Thanks for letting me know!!
comment on: http://stackoverflow.com/a/48252365

http://stackoverflow.com/comment/129458159
has text: If you need to handle non-existent column names, the [`df.filter`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.filter.html) function provides a cleaner and shorter syntax than the `.loc[:, df.columns.isin()]` syntax proposed here. See my answer below for more details
type: AnswerComment
comment on: http://stackoverflow.com/a/48198034
score: 0
type: Comment

http://stackoverflow.com/a/48338893
has body: Thonny uses its own virtual environment by default. Open "Tools => Manage packages" or "Tools => Open system shell" in order to install into this environment.
upvote count: 8
has comment: http://stackoverflow.com/comment/113336695
type: Answer
score: 8
accepted answer of: http://stackoverflow.com/q/48240195
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48240195

http://stackoverflow.com/comment/83718806
comment on: http://stackoverflow.com/q/48314234
type: QuestionComment
type: Comment
has text: Hi @Hannu , thanks for the comment - could you please go into more detail or link to anything that could provide an example of how to use multiprocessing.process to create/manage a "pool"?
score: 0

http://stackoverflow.com/comment/83403534
has text: @khelwood That feels like it would work, but unfortunately it doesnt. Got same error: **TypeError: unbound method do_something() must be called with OtherPerson instance as first argument (got nothing instead)**
type: QuestionComment
comment on: http://stackoverflow.com/q/48210900
type: Comment
score: 0

http://stackoverflow.com/comment/83366937
has text: I've done a little research and found the following facts: 1. Specific syntax of individual URL from RFC 1738 has been discarded by RFC 2396 (page 2). 2. This part of URI string that begins with ';' char calls "param" and defined in RFC 2396 (page 14) 3. RFC 3986 (page 22) does not support this "params" 4. RFC 1945 (HTTP 1.0 protocol) directly define params with ';' char 5. RFC 2616 (HTTP 1.1 protocol) looks like it does support "params" as it adopts this part from RFC 2396. 6. HTTP 2.0 (RFC 7540) uses RFC 3986 7. Apache server treats ';' char as a part of path
comment on: http://stackoverflow.com/q/48190236
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83643858
type: QuestionComment
has text: Python doesn't really use getters and setters like other popular language. Just access the variable you need.... object.variable_name=
comment on: http://stackoverflow.com/q/48328255
type: Comment
score: 0

http://stackoverflow.com/comment/83447570
type: QuestionComment
type: Comment
score: 0
has text: ahh, I had no idea about that "test" thing, seems like a warning about that should be in the documentation somewhere where you shouldn't name your modules "test" renaming it to "ttest.py" instead of "test.py" fixed it
comment on: http://stackoverflow.com/q/48215649

http://stackoverflow.com/q/48198863
has answer: http://stackoverflow.com/a/48199491
accepted answer: http://stackoverflow.com/a/48199491
type: Question
has comment: http://stackoverflow.com/comment/83380795
has comment: http://stackoverflow.com/comment/83381416
has body: I'd like to crawl every case whose Panel Reoport has already composed from the WTO official page. and As you can check at the above image (or refer to https://www.wto.org/english/tratop_e/dispu_e/dispu_status_e.htm, Every case is indexed with "DS XXX" and right at the below it denotes whether the "Panel Composed" or still yet "in Consultation". If I inspect, they all share the same &lt;p class = "panel-text-simple"&gt; So I had tried following two commands: elem_info = driver.find_element_by_class_name("panel-title-simple") elem_info = driver.find_element_by_xpath("//p[@class='panel-title-simple']"); but every one of them only gives me the top most case, the most recent one. I have to locate every case's info, then should make a for-loop to check whether the panel composed or not. How could I do that?
has title: Get the List of Multiple Element with Same ClassName
tagged with: python
has comment: http://stackoverflow.com/comment/83381376
tagged with: xpath
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83381408
tagged with: getelementsbyclassname
has answer: http://stackoverflow.com/a/48199401
possible better answer: http://stackoverflow.com/a/48199401
tagged with: selenium

http://stackoverflow.com/q/48273829
has comment: http://stackoverflow.com/comment/83531633
has comment: http://stackoverflow.com/comment/83531291
tagged with: python
has comment: http://stackoverflow.com/comment/83531229
has comment: http://stackoverflow.com/comment/83531375
type: Question
has comment: http://stackoverflow.com/comment/83531301
has comment: http://stackoverflow.com/comment/83531696
answer count: 0
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83531917
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83531370
has comment: http://stackoverflow.com/comment/83531593
has comment: http://stackoverflow.com/comment/83531458
has comment: http://stackoverflow.com/comment/83531830
has comment: http://stackoverflow.com/comment/83531648
has title: Decode arbitrary base encoded value to string
has comment: http://stackoverflow.com/comment/83531539
favorite count: 0
tagged with: radix
linked to: http://stackoverflow.com/q/2267362
has body: Trying to decode what appears to be base encoded. (24 characters total, ends with padding '=='. I would post it but I am not sure what it contains...) I expect a human readable value and I've tried guessing at the encoding type/base. One solution could be to iterate over possible base encoding values and then eyeball them. But that would also require dynamically determining the corresponding alphabet library for each base encoding... How to convert an integer in any base to a string? How can the base encoding be determined for an arbitrary base encoded value?
score: 1

http://stackoverflow.com/comment/83570051
score: 0
has text: @ShadowRanger @Ken White Thank you for your suggestion, using `shutil`. I will definitely look it up.
comment on: http://stackoverflow.com/q/48292152
type: Comment
type: QuestionComment

object-detection
tags question: http://stackoverflow.com/q/48230786
tags question: http://stackoverflow.com/q/48312094
tags question: http://stackoverflow.com/q/48316020
type: Tag
tags question: http://stackoverflow.com/q/48207956
tag name: object-detection
tags question: http://stackoverflow.com/q/48191975
tags question: http://stackoverflow.com/q/48247921
tags question: http://stackoverflow.com/q/48195442
tags question: http://stackoverflow.com/q/48185719
tags question: http://stackoverflow.com/q/48284884

http://stackoverflow.com/q/48219469
has title: How to find the character \u1ec1 in my 300MB XML file?
has comment: http://stackoverflow.com/comment/83421016
has comment: http://stackoverflow.com/comment/83421019
has comment: http://stackoverflow.com/comment/83424245
tagged with: encoding
score: 0
answer count: 0
has body: I have a complicated process that boils down to: I need to find where this one character is that's breaking my XSL transform. Because of the system I'm using, the only info I can get from the XSLT is "it didn't work." I happen to know that it's getting hung up on the character \u1ec1. Reading the XML line by line, how can I determine if that character is in the line, and so purge/correct/ignore the offending record? My most powerful tool at the moment is Python, so I'm focusing on that. I've tried: buffer = [] for line in lines: for letter in line: if (u'\u1ec1') in line: buffer.append(line) Then write out the buffer, which should show me every occurrence, and at least get me closer. It failed to encode the character... duh. I've tried: buffer = [] previous_line = "&lt;start&gt;" with open(file, 'r') as lines: for line in lines: for letter in str(line): if ord(letter) &gt; 127: buffer.append(previous_line) previous_line = line Then I can write out the previous line without having to worry about encoding errors and whatnot. So far, I get either no results at all, or an encoding error. This is a relatively insignificant yak that I need to shave on the way to solving a much more important problem. I.e. gross solutions are acceptable, so long as it helps me find the line that's breaking my XSLT. (I have no access to any XSL IDE, except insofar as one can call Notepad++ an XSL IDE).
has comment: http://stackoverflow.com/comment/83421041
has comment: http://stackoverflow.com/comment/83420935
has comment: http://stackoverflow.com/comment/83420819
has comment: http://stackoverflow.com/comment/83420989
type: Question
has comment: http://stackoverflow.com/comment/83421064
tagged with: xslt-2.0
has comment: http://stackoverflow.com/comment/83420983
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48276837
has answer: http://stackoverflow.com/a/48276904
accepted answer: http://stackoverflow.com/a/48276904
downvote count: 0
score: 2
type: AnsweredQuestion
tagged with: pandas
tagged with: datetime
has title: Fill missing dates
has body: I have dataframe contains temperature readings from different areas and in different dates I want to add the missing dates for each location with zero temperature for example: df=pd.DataFrame({"area_id":[1,1,1,2,2,2,3,3,3], "reading_date":["13/1/2017","15/1/2017" ,"16/1/2017","22/3/2017","26/3/2017" ,"28/3/2017","15/5/2017" ,"16/5/2017","18/5/2017"], "temp":[12,15,22,6,14,8,30,25,33]}) What is the most efficient way to fill dates gap per area (by zeros) as shown below Many Thanks.
tagged with: dataframe
tagged with: python
tagged with: date
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48276997
possible better answer: http://stackoverflow.com/a/48276997
answer count: 2
upvote count: 2

http://stackoverflow.com/q/48250225
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83483164
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83483234
has body: I´m trying to do a scatter plot in python with matplotlib. I have the following scenario: There is a list of participants and each participant has costs in three different markets: market1, market2 and market3 On the x - axis I have the name of different participants like: name1, name2, etc. On the y-axis I distinguish between three different costs: There are costs in the market1, market2 and market3. How can I create a scatter plot for that ? I know that this isn´t a platform for solutions but I even don´t know to to beginn with it! I tried the following: sumName1Market1 = dfMarket1["name1"].sum() sumName2Market1 = dfMarket1["name2"].sum() sumName1Market2 = dfMarket2["name1"].sum() sumName2Market2= dfMarket2["name2"].sum() sumName1Market3 = dfMarket3["name1"].sum() sumName2Market3 = dfMarket3["name2"].sum() name1Costs= (sumSpotThree, sumSpotFive, sumSpotSeven) name2Costs= (sumCAThree, sumCAFive, sumCASeven) plt.scatter(x=["name1", "name2"], y=[name1Costs, name2Costs]) But it says that x and y must be the same size but I my numbers of participants and the number of the markets are not the same size. Maybe I should use a subplot?
has comment: http://stackoverflow.com/comment/83515925
tagged with: python
score: -3
tagged with: plot
has answer: http://stackoverflow.com/a/48269537
upvote count: 0
tagged with: matplotlib
answer count: 1
downvote count: 3
has title: Python: Scatter Plot with matplotlib

http://stackoverflow.com/comment/83478505
comment on: http://stackoverflow.com/q/48241158
type: QuestionComment
type: Comment
has text: That's my question, I'm not sure ?
score: 0

http://stackoverflow.com/a/48194319
type: Answer
has body: Check out "The Request Object" section of the Flask Quickstart documentation here: http://flask.pocoo.org/docs/0.12/quickstart/ To access parameters submitted in the URL (?key=value) you can use the args attribute: searchword = request.args.get('key', '') make sure you include this in your imports: from flask import request
score: 0
answers question: http://stackoverflow.com/q/48181508

http://stackoverflow.com/a/48254180
has comment: http://stackoverflow.com/comment/83491048
has comment: http://stackoverflow.com/comment/83491447
has comment: http://stackoverflow.com/comment/84064130
type: Answer
accepted answer of: http://stackoverflow.com/q/48253684
has body: You can shorten by encoding your options through your own dictionary ( for example if some options are only 128,256,512 you can decide it will be A B or C) but you will lose readability. In fact, I think you are on a wrong way. The name is not the place to store your 20 parameters. What happens if 21 or if a very long option ? You are already in trouble. If i have to do, i will use a general name for the log file (ex: Mylog+datetime) and either put the 20 parameters as my first log line, either adding a secondary file with same root (ex: mylog+datetime+. desc) to store and retreive these values. Hth It seems you want to design a cms (content management system) using file name as descriptor. This is (a little) meaningful if you need to move these folders as individuals. If your store will stay same place, using a sqlite db to link a folder name with its parameters will be much more powerful and quite simple in python.
score: 0
answers question: http://stackoverflow.com/q/48253684
type: AcceptedAnswer

export-to-csv
tags question: http://stackoverflow.com/q/48290671
tag name: export-to-csv
tags question: http://stackoverflow.com/q/48294616
type: Tag

http://stackoverflow.com/q/48179778
has answer: http://stackoverflow.com/a/48179848
has title: TypeError: login() missing 2 required positional arguments: 'username' and 'password'
type: AnsweredQuestion
tagged with: tkinter
linked to: http://stackoverflow.com/q/6920302
downvote count: 0
upvote count: 1
score: 1
answer count: 1
tagged with: authentication
accepted answer: http://stackoverflow.com/a/48179848
favorite count: 0
type: Question
tagged with: typeerror
has comment: http://stackoverflow.com/comment/83339715
has body: I have the code below: from tkinter import * from customer import Customer from admin import Admin from account import Account from tkinter import ttk root = Tk() global username global password def login(self, username, password): name = username.get() passphrase = password.get() msg = self.customer_login(name, passphrase) root.config(height=500, width=500) frame = Frame(root) Label(root, text="Login").grid(row=0, columnspan=4) Label(root, text="Username").grid(row=3, sticky=W, padx=4) username = Entry(root).grid(row=3, column=2, sticky=W, pady=4) Label(root, text="Password").grid(row=4, sticky=W, padx=4,) password = Entry(root, show="*").grid(row=4, column=2, sticky=W, pady=4) loginButton = Button(root, text="Login", width=40) loginButton.grid(row=5, columnspan=4, pady=4, padx=4) loginButton.bind("&lt;Button-1&gt;", login) root.mainloop() The error I keep getting is: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__ return self.func(*args) TypeError: login() missing 2 required positional arguments: 'username' and 'password' Why do I get this error?
tagged with: arguments
tagged with: python

http://stackoverflow.com/q/48310130
duplicate of: http://stackoverflow.com/q/26337003
accepted answer: http://stackoverflow.com/a/48310169
has answer: http://stackoverflow.com/a/48310169
tagged with: python
possible better answer: http://stackoverflow.com/a/48310166
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48310166
answer count: 3
has body: sandwichType="" totalCost=0 sandwiches=["Baguette", "Bagel", "Sub", "Wrap", "White"] sandwichVAL={"Baguette":3.50, "Bagel":2.10, "Sub":3.99, "Wrap":4.15, "White":0.90} choice="" while choice!="Baguette" or choice!="Bagel" or choice!="Sub" or choice!="Wrap" or choice!="White": choice=str(input("What type of sandwich would you like?\n&gt;Baguette - £3.50\n&gt;Bagel - £2.10\n&gt;Sub - £3.99\n&gt;Wrap - £4.15\n&gt;White - £0.90\n")) if choice!="Baguette" or choice!="Bagel" or choice!="Sub" or choice!="Wrap" or choice!="White": print("Unfortunately, that is not a valid choice! Please pick again and remember to capitalise the first letter!") else: print() totalCost+=sandwichVAL[choice] print(totalCost) This code keeps returning Unfortunately, that is not a valid choice! Please pick again and remember to capitalise the first letter! even when the choice variable is correct. What edits should I make to make it print the total cost?
has comment: http://stackoverflow.com/comment/83606097
linked to: http://stackoverflow.com/q/26337003
has title: Python loop keeps returning incorrectly, how can I amend this?
downvote count: 0
tagged with: loops
upvote count: 1
score: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48310181

http://stackoverflow.com/q/48321616
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48321665
has comment: http://stackoverflow.com/comment/83628712
tagged with: python
tagged with: regex
score: 4
has title: while-loop in python as long as regex matches
upvote count: 4
type: AnsweredQuestion
tagged with: while-loop
has comment: http://stackoverflow.com/comment/83628533
answer count: 1
has comment: http://stackoverflow.com/comment/83628793
downvote count: 0
has body: Ok, I'm aware that it's probably not the best way to edit a string with regex expressions in loops. Just for the sake of interest: How would I have to build a loop, that executes a regex pattern as long as it matches, run in a loop and stop when it doesn't hit anymore? Im doing this in python. match = re.search(r'pattern, repl, str) while match (is True, == True?): sub = re.sub(r'pattern, repl, str) else: Do something else
accepted answer: http://stackoverflow.com/a/48321665

http://stackoverflow.com/comment/83613506
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48289674
type: Comment
has text: You'll probably need to the same prepending of `//research` of `//domain_adaptation` targets to `//research/domain_adaptation` in this `BUILD` file https://github.com/gcscoding/models/blob/master/research/domain_adaptation/pixel_domain_adaptation/BUILD

http://stackoverflow.com/a/48234086
has comment: http://stackoverflow.com/comment/83451051
has comment: http://stackoverflow.com/comment/83451017
has comment: http://stackoverflow.com/comment/83451263
type: Answer
has comment: http://stackoverflow.com/comment/83450758
has body: I suspect your data is tab delimited, so you need to indicate as such, and you may need to remove spaces. def get_data(IndFut): with open('IndFut.csv','r') as csvfile: csvFileReader = csv.reader(csvfile, delimiter='\t') next(csvFileReader) for row in csvFileReader: try: dates.append(int(row[0].split('/')[0])) prices.append(float(row[1])) except: print(f"failed to process row {row}") [Edit] Not sure I understand why...but try this; def get_data(IndFut): with open('IndFut.csv','r') as csvfile: csvFileReader = csv.reader(csvfile, delimiter='\t') next(csvFileReader) for row in csvFileReader: split_row = row[0].split(';')[:-1] try: dates.append(int(split_row[0].split('/')[0])) prices.append(float(split_row[1])) except: print(f"failed to process row {split_row}")
answers question: http://stackoverflow.com/q/48233692
score: 0

http://stackoverflow.com/comment/83535321
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48257446
has text: **The system will automatically discard your process.** CPU access, RAM allocation, process tree creation, hardware access permissions, etc. `Rasperry Pi can be toy but you can't play with the kernel inside!`

http://stackoverflow.com/q/48265902
downvote count: 2
tagged with: python
upvote count: 4
tagged with: flask
has comment: http://stackoverflow.com/comment/83515111
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/83515309
has answer: http://stackoverflow.com/a/48270995
accepted answer: http://stackoverflow.com/a/48270995
has comment: http://stackoverflow.com/comment/83516829
has title: Python/Flask/Jinja2 not working with Material Design Components for Web
answer count: 1
tagged with: material-design
favorite count: 0
type: Question
has body: I have been trying to convert a Python Flask/Flask-Bootstrap/Jinja2 webapp to use Material Design Components for Web, and parts of the application work - I'm trying to make the presentation of the webapp as client side as possible. I have the latest version of material-components-web.min.js and material-components-web.min.css loaded into a web page template used to generate all pages served up by Flask. MDC for Web appears to rely entirely on the use of Node.js, and I am not sure that the .js and .css files that I have found and mentioned in the previous paragraph are simply drop in and use (it's a local webapp, so size isn't an issue), and there aren't any readily compiled .css files for all the subcomponents, only .sass. Anyway, although some of the styling is correct, dynamic functionality such as floating labels on text fields, validation and so on don't work, and a lot of the positions of the elements are wrong. I am sure I am missing something small, but what is it?

http://stackoverflow.com/q/48218262
tagged with: dxf
type: UnansweredQuestion
tagged with: python
has title: How to remove layer tag from vertex in dxf generated using dxfwrite ,Polyline
score: 0
has body: I am trying to create dxf exporter. I am using dxfwrite in python. When I add vertex it adds some extra fields as layer information automatically. But I want to remove the layer information from VERTEX in DXF file. For example : in python I wrote the following code: from dxfwrite import DXFEngine as dxf out = dxf.polyline(linetype='DOT') out.add_vertices( [(0,20), (3,20), (6,23), (9,23)] ) self.drawing.add(out) It results in following data under POLYLINE Field in dxf file: VERTEX 8 0 10 0 20 20 30 0 0 VERTEX 8 0 10 3 20 20 30 0 0 VERTEX 8 0 10 6 20 23 30 0 0 VERTEX 8 0 10 9 20 23 30 0 0 But it should be like : VERTEX 10 0 20 20 30 0 0 VERTEX 10 3 20 20 30 0 0 VERTEX 10 6 20 23 30 0 0 VERTEX 10 9 20 23 30 0 0
answer count: 1
has answer: http://stackoverflow.com/a/48219280
type: Question

http://stackoverflow.com/comment/83586265
score: 0
type: AnswerComment
has text: This is an interesting approach to the problem, but it discards information that probably makes it easier to solve.
comment on: http://stackoverflow.com/a/48300032
type: Comment

http://stackoverflow.com/q/48307008
has answer: http://stackoverflow.com/a/54009199
has body: I am trying to insert some data in a table I have created. I have a data frame that looks like this: I created a table: create table online.ds_attribution_probabilities ( attribution_type text, channel text, date date , value float ) And I am running this python script: engine = create_engine("postgresql://@e.eu-central-1.redshift.amazonaws.com:5439/mdhclient_encoding=utf8") connection = engine.raw_connection() result.to_sql('online.ds_attribution_probabilities', con=engine, index = False, if_exists = 'append') I get no error, but when I check there are no data in my table. What can be wrong? Do I have to commit or do an extra step?
score: 40
upvote count: 40
has answer: http://stackoverflow.com/a/78799681
has answer: http://stackoverflow.com/a/52812845
linked to: http://stackoverflow.com/q/9298296
tagged with: sqlalchemy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/76333295
has answer: http://stackoverflow.com/a/77895994
has answer: http://stackoverflow.com/a/79534772
has answer: http://stackoverflow.com/a/54785860
has answer: http://stackoverflow.com/a/55406717
downvote count: 0
has answer: http://stackoverflow.com/a/64717206
has title: Pandas to_sql doesn't insert any data in my table
tagged with: python
has answer: http://stackoverflow.com/a/76226167
answer count: 13
possible better answer: http://stackoverflow.com/a/57005991
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/75745865
tagged with: pandas
has answer: http://stackoverflow.com/a/57005991
has answer: http://stackoverflow.com/a/48307108
accepted answer: http://stackoverflow.com/a/48307108

http://stackoverflow.com/a/48245690
score: 0
answers question: http://stackoverflow.com/q/48244739
type: AcceptedAnswer
has body: You code is extremely badly written, but the real problem is in the statement x -= 1: The value of x is decremented at each iteration of the inner loop and at the end of the first inner loop, x is 99. This makes the condition if x &gt;= 100 false for all consequent iterations of the outer loop. Add x=999 immediately after for element in reversed(range(100, 1000)). Or, better, learn some good programming and rewrite the program entirely.
type: Answer
has comment: http://stackoverflow.com/comment/83478233
accepted answer of: http://stackoverflow.com/q/48244739

http://stackoverflow.com/q/48260793
type: Question
has title: How to split string with numbers, letters and white spaces in python ?
type: UnansweredQuestion
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/48261106
has comment: http://stackoverflow.com/comment/83504771
tagged with: split
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83504514
has body: I want to split a string with number, letters and specific white spaces into specific components. consider the string ATLANTYS2_I - 3103 aRNH_profile - 121 2.7e-35 118.7 0.0 1 1 2.7e-37 5.6e-35 117.7 0.0 2 120 1342 1458 1341 1459 0.98 Gypsy Arabidopsis thaliana_+1 now let the string be content[3]. I ran the command the import re result = re.split(r'\s{2,}', content[3]) which gave me ['ATLANTYS2_I', '-', '3103 aRNH_profile', '-', '121', '2.7e-35', '118.7', '0.0', '1', '1', '2.7e-37', '5.6e-35', '117.7', '0.0', '2', '120', '1342', '1458', '1341', '1459 0.98 Gypsy\tArabidopsis thaliana_+1'] I have split the string by 2 spaces. but the last entry 1459 0.98 Gypsy\tArabidopsis thaliana_+1 is still grouped as one. I thought of splitting the last entry by one space, deleting the last entry in the result and adding the split by one space. However this seems to me rather clunky. Is there a way to split this elegantly so that I would get the following result for the last entry '1459','0.98', Gypsy\tArabidopsis thaliana_+1'?
upvote count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/83504356
downvote count: 1
has answer: http://stackoverflow.com/a/48263600
favorite count: 0

http://stackoverflow.com/comment/83510203
score: 0
comment on: http://stackoverflow.com/q/48262920
has text: I think i got the error. I have the statement : while err>1e-3: before first for line and this is what is causing the error.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/56720394
score: 0
answers question: http://stackoverflow.com/q/48179496
has body: Here is a solution that runs in O(n log n): ﻿﻿﻿ind1 = numpy.argsort(_list) ind2 = numpy.argsort(_list2) pairs = [] i = 0 j = 0 while i&lt;ind1.size and j&lt;ind2.size: e1 = _list[ind1[i]] e2 = _list2[ind2[j]] if e1==e2: pairs.append((ind1[i],ind2[j])) i = i + 1 j = j + 1 elif e1&lt;e2: i = i +1 elif e2&lt;e1: j = j + 1 print(pairs)
type: Answer

python-3.x
tags question: http://stackoverflow.com/q/48272315
tags question: http://stackoverflow.com/q/48271643
tags question: http://stackoverflow.com/q/48197398
tags question: http://stackoverflow.com/q/48235156
tags question: http://stackoverflow.com/q/48217036
tags question: http://stackoverflow.com/q/48273222
tags question: http://stackoverflow.com/q/48226089
tags question: http://stackoverflow.com/q/48243369
tags question: http://stackoverflow.com/q/48233812
tags question: http://stackoverflow.com/q/48261673
tags question: http://stackoverflow.com/q/48235169
tags question: http://stackoverflow.com/q/48291939
tags question: http://stackoverflow.com/q/48197324
tags question: http://stackoverflow.com/q/48295984
tags question: http://stackoverflow.com/q/48201841
tags question: http://stackoverflow.com/q/48323493
tags question: http://stackoverflow.com/q/48252312
tags question: http://stackoverflow.com/q/48287929
tags question: http://stackoverflow.com/q/48266265
tags question: http://stackoverflow.com/q/48241269
tags question: http://stackoverflow.com/q/48256062
tags question: http://stackoverflow.com/q/48266011
tags question: http://stackoverflow.com/q/48234119
tags question: http://stackoverflow.com/q/48236321
tags question: http://stackoverflow.com/q/48224245
tags question: http://stackoverflow.com/q/48281593
tags question: http://stackoverflow.com/q/48270745
tags question: http://stackoverflow.com/q/48248014
tags question: http://stackoverflow.com/q/48329815
tags question: http://stackoverflow.com/q/48245595
tags question: http://stackoverflow.com/q/48323217
tags question: http://stackoverflow.com/q/48267633
tags question: http://stackoverflow.com/q/48263543
tags question: http://stackoverflow.com/q/48192954
tags question: http://stackoverflow.com/q/48201478
tags question: http://stackoverflow.com/q/48199717
tags question: http://stackoverflow.com/q/48240139
tags question: http://stackoverflow.com/q/48243425
tags question: http://stackoverflow.com/q/48225770
tags question: http://stackoverflow.com/q/48278853
tags question: http://stackoverflow.com/q/48187790
tags question: http://stackoverflow.com/q/48320642
tags question: http://stackoverflow.com/q/48324189
tags question: http://stackoverflow.com/q/48253335
tags question: http://stackoverflow.com/q/48230981
tags question: http://stackoverflow.com/q/48252663
tags question: http://stackoverflow.com/q/48227381
tags question: http://stackoverflow.com/q/48241779
tags question: http://stackoverflow.com/q/48188845
tags question: http://stackoverflow.com/q/48309356
tags question: http://stackoverflow.com/q/48242217
tags question: http://stackoverflow.com/q/48254058
tags question: http://stackoverflow.com/q/48241666
tags question: http://stackoverflow.com/q/48225664
tags question: http://stackoverflow.com/q/48249270
tags question: http://stackoverflow.com/q/48252610
tags question: http://stackoverflow.com/q/48308933
tags question: http://stackoverflow.com/q/48277961
tags question: http://stackoverflow.com/q/48196655
tags question: http://stackoverflow.com/q/48175967
tags question: http://stackoverflow.com/q/48306122
tags question: http://stackoverflow.com/q/48244991
tags question: http://stackoverflow.com/q/48250410
tags question: http://stackoverflow.com/q/48288773
tags question: http://stackoverflow.com/q/48245860
tags question: http://stackoverflow.com/q/48236584
tags question: http://stackoverflow.com/q/48268908
tags question: http://stackoverflow.com/q/48183643
tags question: http://stackoverflow.com/q/48281261
tags question: http://stackoverflow.com/q/48325908
tags question: http://stackoverflow.com/q/48215763
tags question: http://stackoverflow.com/q/48308560
tags question: http://stackoverflow.com/q/48228211
tags question: http://stackoverflow.com/q/48208119
tags question: http://stackoverflow.com/q/48221500
tags question: http://stackoverflow.com/q/48182920
tags question: http://stackoverflow.com/q/48232080
tags question: http://stackoverflow.com/q/48289552
tags question: http://stackoverflow.com/q/48276011
tags question: http://stackoverflow.com/q/48184487

http://stackoverflow.com/comment/83441088
type: QuestionComment
has text: by clicking stop program
comment on: http://stackoverflow.com/q/48229422
score: 0
type: Comment

http://stackoverflow.com/q/48217392
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has body: I'm trying to do some AWS pricing analysis using Pandas, and it involves bringing EC2 pricing data into a df using their API. Unfortunately, the dataset is headed by 5 rows and 2 columns of descriptors before the useful data starts (see image). This causes an error when my code encounters the start of the useful data, which has 51 columns. How can I tell it to ignore the first 5 rows, and to treat the 6th row as my column headers? Here's where I'm at: import pandas as pd import requests import io pricing_url = "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/index.csv" pricing_r = requests.get(pricing_url).content pricing = pd.read_csv(io.StringIO(pricing_r.decode('utf-8'))) ParserError: Error tokenizing data. C error: Expected 2 fields in line 6, saw 51
upvote count: 2
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: 2
accepted answer: http://stackoverflow.com/a/48217414
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/48217414
has title: pd.read_csv - Disregard first N rows

http://stackoverflow.com/comment/83634881
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48324405
has text: It appears that I've found a way to make it "work", which is to put the imports inside the get(self): function, but to be quite honest, this looks absolutely terrible...
score: 0

http://stackoverflow.com/a/48206368
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48205540
has comment: http://stackoverflow.com/comment/83640019
score: 2
has body: I completely agree @ZiTAL when saying that parsing the files as XML would be much faster and nicer. A few simple lines of code would solve your problem: import xml.etree.ElementTree as ET tree = ET.parse('file.xml') root = tree.getroot() # If you prefer to parse the text directly do root = ET.fromstring(' example ') values = [el.attrib['value'] for el in root.findall('.//option')] print(values)
has comment: http://stackoverflow.com/comment/83530518
type: Answer

http://stackoverflow.com/a/48222156
has comment: http://stackoverflow.com/comment/83489170
has comment: http://stackoverflow.com/comment/83476748
has comment: http://stackoverflow.com/comment/83499951
has body: I am not sure if I understand your problem, it seems you just want all the combinations of the elements two arrays, is that correct? If so, you could do: import numpy as np cars = [1, 2] dates = [3, 4] result = np.stack(np.meshgrid(cars, dates), -1).reshape(-1, 2) or in plain Python (no numpy): result = [] for c in cars: for d in dates: result.append([c,d]) I here provide examples with basic types, since you didn't provide working code in your question.
type: Answer
accepted answer of: http://stackoverflow.com/q/48221710
score: 0
answers question: http://stackoverflow.com/q/48221710
type: AcceptedAnswer

http://stackoverflow.com/a/48315956
has comment: http://stackoverflow.com/comment/83617565
type: Answer
downvote count: 0
score: 7
upvote count: 7
has body: This question has many answers already, but consider the function split into bytecode: def f(): lie = 0 if lie is lie is lie: print('Lie') dis.dis(f) 2 0 LOAD_CONST 1 (0) 2 STORE_FAST 0 (lie) 3 4 LOAD_FAST 0 (lie) 6 LOAD_FAST 0 (lie) 8 DUP_TOP 10 ROT_THREE 12 COMPARE_OP 8 (is) 14 JUMP_IF_FALSE_OR_POP 22 16 LOAD_FAST 0 (lie) 18 COMPARE_OP 8 (is) 20 JUMP_FORWARD 4 (to 26) &gt;&gt; 22 ROT_TWO 24 POP_TOP &gt;&gt; 26 POP_JUMP_IF_FALSE 36 4 28 LOAD_GLOBAL 0 (print) 30 LOAD_CONST 2 ('Lie') 32 CALL_FUNCTION 1 34 POP_TOP &gt;&gt; 36 LOAD_CONST 0 (None) 38 RETURN_VALUE This suggests that all lies are being checked to see if they match, in a linear fashion. If one fails, it should break/return. To confirm, consider: &gt;lie is lie is lie is lie is lie True &gt;lie is not lie is lie is lie is lie is lie False &gt;lie is lie is lie is lie is lie is not lie False
answers question: http://stackoverflow.com/q/48315777

http://stackoverflow.com/comment/83642619
type: QuestionComment
comment on: http://stackoverflow.com/q/48328498
score: 1
has text: Any reason you're forbidden to put your checkboard in a frame?
type: Comment

http://stackoverflow.com/q/48272832
tagged with: x11
has comment: http://stackoverflow.com/comment/108139661
favorite count: 0
has title: Docker container built for Python/Kivy crashes when starting to run
type: Question
score: 3
has body: I’m trying to run a GUI application written in Python and Kivy language in Debian/Jesse, but have run into an issue when trying to run the container. So, I wrote the Docker file, built the image and getting this issue when the container starts to run halfway through. By the looks of it, the problem is related to building a connection between host machine and the container for SDL2 /X11. Would be very much appreciated if someone could give some ideas on this. I have shared the my Dockerfile and error below. Thanks in advance. Dockerfile - FROM resin/rpi-raspbian:jessie RUN apt-get update &amp;&amp; apt-get install -y libsdl2-dev libsdl2-image-dev libsdl2-mixer-dev libsdl2-ttf-dev pkg-config libgl1-mesa-dev libgles2-mesa-dev python-setuptools libgstreamer1.0-dev git-core python-dev gcc python-pip gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly gstreamer1.0-alsa gstreamer1.0-omx xclip libmtdev-dev python-pygame RUN pip install cython RUN pip install git+https://github.com/kivy/kivy.git@master ENV XDG_RUNTIME_DIR=/run/user/1000 ADD animate.py / CMD [“python”,“animate.py”] Error log is below - pi@raspberrypi:~/dockTest $ docker container run kivydock [WARNING] [Config ] Older configuration version detected (0 instead of 20) [WARNING] [Config ] Upgrading configuration in progress. [INFO ] [Logger ] Record log in /root/.kivy/logs/kivy_18-01-16_0.txt [INFO ] [Kivy ] v1.10.1.dev0, git-00c161d, 20180115 [INFO ] [Python ] v2.7.9 (default, Sep 17 2016, 20:26:04) [GCC 4.9.2] [INFO ] [Factory ] 194 symbols loaded [INFO ] [Image ] Providers: img_tex, img_dds, img_sdl2, img_gif (img_pil, img_ffpyplayer ignored) [INFO ] [Text ] Provider: sdl2 [INFO ] [OSC ] using for socket [INFO ] [Window ] Provider: sdl2([‘window_egl_rpi’] ignored) [CRITICAL] [Window ] Unable to find any valuable Window provider. egl_rpi - ImportError: cannot import name bcm File “/usr/local/lib/python2.7/dist-packages/kivy/core/init.py”, line 59, in core_sele…
tagged with: python
tagged with: kivy
tagged with: sdl-2
tagged with: docker
has comment: http://stackoverflow.com/comment/83529525
has comment: http://stackoverflow.com/comment/108142030
answer count: 0
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83530312
downvote count: 0

http://stackoverflow.com/comment/83556548
type: QuestionComment
comment on: http://stackoverflow.com/q/48246740
score: 0
has text: @Ultraviolet I've been looking for a solution for this problem and I can't seem to find anything that works, do you know any method I can use to make tensorflow recognize my GPU?
type: Comment

http://stackoverflow.com/q/48251501
has answer: http://stackoverflow.com/a/48256429
has answer: http://stackoverflow.com/a/48262561
upvote count: 1
has answer: http://stackoverflow.com/a/48390563
linked to: http://stackoverflow.com/q/26408022
accepted answer: http://stackoverflow.com/a/48261709
favorite count: 0
tagged with: image-manipulation
has body: Sorry, I don't have the right terminology to ask this question, but in simple terms, I have several images like this one. The white areas are not always the same size but are mostly rectangular. The colors are always the same. It's one image and I need to isolate the figures from the white background, or explained in a different way, I need to change the black background to white... and make it look like this. Note some of the figures are touching the edges where white meets the black. The tool, library, or programming language doesn't matter as long as it gets it done.
type: Question
has answer: http://stackoverflow.com/a/48261709
answer count: 9
has comment: http://stackoverflow.com/comment/83492007
has answer: http://stackoverflow.com/a/48393454
downvote count: 0
has comment: http://stackoverflow.com/comment/83487372
has comment: http://stackoverflow.com/comment/83490349
has title: Isolating figures from a background
tagged with: python
has answer: http://stackoverflow.com/a/48252536
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48260214
possible better answer: http://stackoverflow.com/a/48254417
tagged with: imagemagick
score: 1
has answer: http://stackoverflow.com/a/48254417
has answer: http://stackoverflow.com/a/48272433
has comment: http://stackoverflow.com/comment/83492381
has comment: http://stackoverflow.com/comment/83491196

http://stackoverflow.com/comment/83773025
type: QuestionComment
has text: Hi, @ImportanceOfBeingErnest, don't thing that "This question has been asked before". Yes, there is a answer to this question in "How to make IPython notebook matplotlib plot inline", but the way of questioning it is different and maybe my question can help people who are having "Trouble in creating graphics with matplotlib in a Jupyter notebook".
comment on: http://stackoverflow.com/q/48267427
score: 0
type: Comment

http://stackoverflow.com/q/48287588
type: AnsweredQuestion
has title: Type hints for generic code
score: 1
tagged with: type-hinting
tagged with: django-models
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
has body: Let's say, I have this piece of code: class BaseModel(object): pass class AppleModel(BaseModel): pass class OrangeModel(BaseModel): pass def get_record(model, pk): try: result = model.objects.get(pk=pk) # Some code working with BaseModel.. return result except model.DoesNotExist: return None Now, I want to use it like in this example with proper type annotation... myApple = get_record(AppleModel, 12) myApple. # type hints for AppleModel myOrange = get_record(OrangeModel, 433) myOrange. # type hints for OrangeModel How should I annotate the get_record function? I tried something like def get_record(model: Type[BaseModel], id: int) -&gt; Optional[BaseModel]: # ... But then, I lose info about subclasses. I tried to use Generic, but without success.
downvote count: 0
has answer: http://stackoverflow.com/a/48314696
upvote count: 1
accepted answer: http://stackoverflow.com/a/48314696
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/83560500

http://stackoverflow.com/a/56375088
type: Answer
has body: This worked for me: chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--incognito") driver = webdriver.Chrome("driver path", chrome_options=chrome_options)
answers question: http://stackoverflow.com/q/48277136
score: 0

http://stackoverflow.com/comment/83437911
has text: Are you in interactive mode? If so, `plt.ioff()`?
comment on: http://stackoverflow.com/q/48227892
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48249159
accepted answer: http://stackoverflow.com/a/48249789
has answer: http://stackoverflow.com/a/48249452
has comment: http://stackoverflow.com/comment/83481593
has answer: http://stackoverflow.com/a/48249789
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/83481147
has comment: http://stackoverflow.com/comment/83481039
has title: How to remove list elements within a loop effectively in python
has body: I have a code as follows. for item in my_list: print(item[0]) temp = [] current_index = my_list.index(item) garbage_list = creategarbageterms(item[0]) for ele in my_list: if my_list.index(ele) != current_index: for garbage_word in garbage_list: if garbage_word in ele: print("concepts: ", item, ele) temp.append(ele) print(temp) Now, I want to remove the ele from mylist when it gets appended to temp (so, that it won't get processed in the main loop, as it is a garbage word). I know it is bad to remove elements straightly from the list, when it is in a loop. Thus, I am interested in knowing if there is any efficient way of doing this? For example, if mylist is as follows; mylist = [["tim_tam", 879.3000000000001], ["yummy_tim_tam", 315.0], ["pudding", 298.2], ["chocolate_pudding", 218.4], ["biscuits", 178.20000000000002], ["berry_tim_tam", 171.9], ["tiramusu", 158.4], ["ice_cream", 141.6], ["vanilla_ice_cream", 122.39999999999999]] 1st iteration for the first element tim_tam, I get garbage words such as yummy_tim_tam and berry_tim_tam. So they will get added to my temp list. Now I want to remove yummy_tim_tam and berry_tim_tam from the list (because they have already added to temp), so that it won't execute from the beginning. 2nd iteration Now, since yummy_tim_tam is no longer in the list this will execute pudding. For pudding I get a diffrent set of garbage words such as chocolate_pudding, biscuits, tiramu. So, they will get added to temp and will get removed. 3rd iteration ice_cream will be selected. and the process will go on. My final objective is to get three separate lists as follows. ["tim_tam", 879.3000000000001], ["yummy_tim_tam", 315.0], ["berry_tim_tam", 171.9] , ["pudding", 298.2] ["chocolate_pudding", 218.4], ["biscuits", 178.20000000000002], ["tiramusu", 158.4] ["ice_cream", 141.6], ["vanilla_ice_cream", 122.39999999999999]
has answer: http://stackoverflow.com/a/48249710
possible better answer: http://stackoverflow.com/a/48249452
upvote count: 4
type: AnsweredQuestion
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83481266
has comment: http://stackoverflow.com/comment/83481125
has comment: http://stackoverflow.com/comment/83480910
favorite count: 0
has comment: http://stackoverflow.com/comment/83481040
type: Question

seaborn
tags question: http://stackoverflow.com/q/48194193
tags question: http://stackoverflow.com/q/48302284
tags question: http://stackoverflow.com/q/48219684
tags question: http://stackoverflow.com/q/48179687
tags question: http://stackoverflow.com/q/48213642
tags question: http://stackoverflow.com/q/48301568
tags question: http://stackoverflow.com/q/48273065
tag name: seaborn
tags question: http://stackoverflow.com/q/48204780
tags question: http://stackoverflow.com/q/48264330
tags question: http://stackoverflow.com/q/48176920
tags question: http://stackoverflow.com/q/48240351
tags question: http://stackoverflow.com/q/48288366
tags question: http://stackoverflow.com/q/48272437
tags question: http://stackoverflow.com/q/48175870
tags question: http://stackoverflow.com/q/48173798
type: Tag
tags question: http://stackoverflow.com/q/48181698
tags question: http://stackoverflow.com/q/48286431

http://stackoverflow.com/q/48219986
answer count: 1
accepted answer: http://stackoverflow.com/a/48260611
has title: DecisionTreeClassifier predict_proba returns 0 or 1
has comment: http://stackoverflow.com/comment/83422145
downvote count: 1
has answer: http://stackoverflow.com/a/48260611
tagged with: sklearn-pandas
favorite count: 0
type: Question
tagged with: roc
has body: I m trying to use the decision tree classified to identify two classes (renamed 0 and 1) based on certain parameters. I train it using a dataset and then run it on the "test dataset". When I try to calculate the probability for each data point in the test dataset, it returns 0 or 1, only. I wonder what is the problem. Here is the sample code : clf=tree.DecisionTreeClassifier(random_state=0) trained=clf.fit(data,identifier) # training data where identifier is 0 or 1 predict=trained.predict(test_data) The results from this are : In [9]: predict Out[9]: array([0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]) In [10]: trained.predict_proba(test_data)[:,1] Out[10]: array([ 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 1., 1., 1., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 1., 1., 0., 1., 0., 1., 0., 0., 1., 0., 0., 0., 1., 1., 1., 1., 0., 1., 1., 0., 0., 1., 0., 0., 0., 1., 0., 0., 0.]) I would like to generate and ROC, which at this point just returns 3 data points for FPR/TPR. Here is the complete data set : Identifier is the last column of "data". Train data : Spectral_Index,W1-W2,W2-W3,HR0.3-100,HR50-2,Gamma,Class 1.4304664,0.61,2.18,0.3819051,0.99992716,1.93,0 1.6969398,0.54,1.93,0.66479063,0.9999814,2.11,0 2.233997,1.02,3.18,0.55532146,0.9999979,2.07,0 2.230639,0.77,2.34,0.0012237767,1.0,1.81,0 1.7325432,0.71,2.27,0.34395835,1.0,1.9,0 1.8728518,0.8,2.14,0.4255796,1.0,1.96,0 1.9818852,0.7,2.18,-0.08978904,1.0,1.66,0 2.3864453,0.95,2.51,0.109010585,0.98401743,1.81,0 2.5911317,0.94,2.49,0.60381645,0.99991965,2.03,0 1.9564596,0.81,2.29,0.3843,0.9999495,2.08,0 2.1506176,0.93,2.62,0.28551856,0.9999999,1.91,0 1.9069784,0.62,1.76,0.041608978,1.0,1.86,0 1.6216202,0.77,2.11,-0.14271076,1.0,1.7,0 2.276335,0.68,2.14,0.40399882,1.0,2.06,0 2.2430172,1.0,2.94,0.61844856,1.0,2.12,0 1.0226197,0.66,2.07,-0.14886126,1.0,1.84,0 2.2564504,1.06,2.77,0.6974536,0.99844635,2.16,0 2.2819016,0.…
has comment: http://stackoverflow.com/comment/83441199
score: 13
tagged with: decision-tree
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83499084
upvote count: 14
has comment: http://stackoverflow.com/comment/83499185

http://stackoverflow.com/comment/83511841
type: AnswerComment
score: 0
has text: Your analysis regarding the cause for the delayed behavior of the Button is correct. The sleep is a simple enough implementation for a needed "wait" between the two write commands to the controller. I believe that it will take around the 2 seconds without the sleep. So the parallelization of the script is more than needed. Don't you also think so ?
type: Comment
comment on: http://stackoverflow.com/a/48263391

http://stackoverflow.com/comment/122050979
type: AnswerComment
comment on: http://stackoverflow.com/a/48638741
score: 0
has text: A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](//meta.stackexchange.com/a/8259) so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted](//stackoverflow.com/help/deleted-answers).
type: Comment

http://stackoverflow.com/q/48192785
has comment: http://stackoverflow.com/comment/83366133
has comment: http://stackoverflow.com/comment/83366400
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83366470
has body: I'm learning python and our teacher told us to write a function that will return the sum of a list no matter what the type of its values are. If the list is Integers, then: sum([1, 4, 5, 6]) = 16 If the list is Strings, then: sum(['a','b',c']) = 'abc' The list can also be made of tuples and lists inside of it. The code needs to be as short and simple as possible. I tried writing this: element = list[0] for thing in list: for thingy in thing: element += thingy print element but it isn't working.. Any idea how to do this?
has comment: http://stackoverflow.com/comment/83366046
upvote count: 2
accepted answer: http://stackoverflow.com/a/48193041
tagged with: python
has answer: http://stackoverflow.com/a/48193041
linked to: http://stackoverflow.com/q/3055477
has title: Sum of list with any type of items
has comment: http://stackoverflow.com/comment/83366188
possible better answer: http://stackoverflow.com/a/48192820
has comment: http://stackoverflow.com/comment/83366214
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48192820
has answer: http://stackoverflow.com/a/48192893
tagged with: list
has comment: http://stackoverflow.com/comment/83366352
answer count: 3
has comment: http://stackoverflow.com/comment/83366113
has comment: http://stackoverflow.com/comment/83366273
score: 2
downvote count: 0

http://stackoverflow.com/q/48188547
has title: Python dataset aggregation
has comment: http://stackoverflow.com/comment/83356833
type: AnsweredQuestion
downvote count: 3
tagged with: pandas
has body: I have a dataset as follows, stored in pd.DataFrame object: df topic student level week 1 sun a 1 1 1 sun b 2 1 1 moon a 3 1 2 tree a 1 2 2 tree b 2 2 2 tree a 3 2 2 tree b 4 2 3 cloud c 1 2 3 cloud b 2 2 3 cloud c 3 2 3 cloud a 4 2 3 house b 5 2 I would like to aggregate per id containing columns as number of students and number of messages. id topic num_students num_messages 1 sun 2 2 1 moon 1 1 2 tree 2 4 3 cloud 3 4 3 house 1 1 Where num_students is the number of unique student in df1 per id/topic pair, and num_messages the number of id/topic pair. Does anybody have an idea?
upvote count: 1
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48188649
tagged with: aggregation
accepted answer: http://stackoverflow.com/a/48188649
score: -2
has comment: http://stackoverflow.com/comment/83357367
tagged with: python
has comment: http://stackoverflow.com/comment/83356865

http://stackoverflow.com/q/48244542
tagged with: hadoop
has title: How to distribute jobs to multiple machines and keep same job on the same machine?
tagged with: scheduling
has comment: http://stackoverflow.com/comment/83472356
tagged with: algorithm
type: UnansweredQuestion
tagged with: python
has body: I have a list of 1000 jobs that needs to be ran periodically, I'm putting 5 machines to ran these jobs, each machine will check the list from top to bottom and find the first one that needs to be ran (by comparing last_run_time and current time and the interval value of that job it knows whether a job needs to be ran again) and ran it. While one machine starts running a job, it updates the job to say it's running so other machines won't double run it. Job table in DB: job_id | last_run_time | interval (sec)| running 1 11:05 60 False 2 07:12 100 True ... 1000 12:56 3000 False Each task can be ran 10% faster if ran on the same machine of last run because it needs result from previous run, if on the same machine it doesn't need to download that, so I want that to happen as often as possible. I'm thinking about naming each machine and include machine names as an extra column (last_run_on_machine) of this table, but that's troublesome and I want to be able to add more machines or shut down some of the machines whenever I want. What's a good algorithm or if there exists some tool/library that can do this? I'm using Python, the DB is MySQL, completing each task takes about 10 - 60 seconds.
score: 0
answer count: 0
tagged with: distributed-computing
has comment: http://stackoverflow.com/comment/83472609
type: Question

http://stackoverflow.com/q/48328561
accepted answer: http://stackoverflow.com/a/48328712
has comment: http://stackoverflow.com/comment/83643603
has comment: http://stackoverflow.com/comment/83642755
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83645347
has answer: http://stackoverflow.com/a/48328712
answer count: 3
tagged with: syntax
upvote count: 3
has comment: http://stackoverflow.com/comment/83643630
has comment: http://stackoverflow.com/comment/83643493
has comment: http://stackoverflow.com/comment/83644468
has comment: http://stackoverflow.com/comment/83643834
possible better answer: http://stackoverflow.com/a/48328656
favorite count: 0
has body: I'm learning Python and, so far, I absolutely love it. Everything about it. I just have one question about a seeming inconsistency in function returns, and I'm interested in learning the logic behind the rule. If I'm returning a literal or variable in a function return, no parentheses are needed: def fun_with_functions(a, b): total = a + b return total However, when I'm returning the result of another function call, the function is wrapped around a set of parentheses. To wit: def lets_have_fun(): return(fun_with_functions(42, 9000)) This is, at least, the way I've been taught, using the A Smarter Way to Learn Python book. I came across this discrepancy and it was given without an explanation. You can see the online exercise here (skip to Exercize 10). Can someone explain to me why this is necessary? Is it even necessary in the first place? And are there other similar variations in parenthetical syntax that I should be aware of? Edit: I've rephrased the title of my question to reflect the responses. Returning a result within parentheses is not mandatory, as I originally thought, but it is generally considered best practice, as I have now learned.
type: Question
has answer: http://stackoverflow.com/a/48328656
has title: Best practice for using parentheses in Python function returns?
tagged with: return
tagged with: function
downvote count: 2
has answer: http://stackoverflow.com/a/48328671
tagged with: python
has comment: http://stackoverflow.com/comment/83644292
score: 1
tagged with: parentheses

http://stackoverflow.com/comment/83336349
comment on: http://stackoverflow.com/q/48176665
type: Comment
type: QuestionComment
score: 0
has text: You did all the hard work, all I did was pointed out where you need to pay attention. Give yourself a pat on the back!

http://stackoverflow.com/q/48321543
downvote count: 0
answer count: 1
upvote count: 1
tagged with: objectinstantiation
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48322116
tagged with: bioinformatics
has answer: http://stackoverflow.com/a/48322116
tagged with: python
has body: @staticmethod def _select_tournament_population(pop): tournament_pop = Population(0) i = 0 while i &lt; TOURNAMENT_SELECTION_SIZE: tournament_pop.get_chromosomes().append(pop.get_chromosomes()[random.randrange(0, POPULATION_SIZE)]) i += 1 tournament_pop.get_chromosomes().sort(key=lambda x: x.get_fitness(), reverse=True) return tournament_pop def _print_population(self, pop, gen_number): print("\n------------------------------------------------") print("Generation #", gen_number, "| Fittest chromosome fitness:", pop.get_chromosomes()[0].get_fitness()) print("Target Chromosome:", TARGET_CHROMOSOME) print("------------------------------------------------") i = 0 for x in pop.get_chromosomes(): print("Chromosome #", i, " :", x, "| Fitness: ", x.get_fitness()) i += 1 chromosome fitness terminal output I am trying to get the value of the object, but I receive the location of the object in memory: ('Chromosome #', 0, ' :', &lt;__main__.Chromosome instance at 0x7f7c81a41050&gt;, '| Fitness: ', 10)
type: AnsweredQuestion
has title: Get value of object used in genetic algorithm
score: 1
tagged with: genetic-algorithm
has comment: http://stackoverflow.com/comment/83629006

http://stackoverflow.com/a/48255571
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48255333
has body: You can use regular expressions to scrape the currency converter: import urllib from bs4 import BeautifulSoup import re def convert(**kwargs): url = "http://www.xe.com/currencyconverter/convert/?Amount={amount}&amp;From={from_curr}&amp;To={to_curr}".format(**kwargs) data = str(urllib.urlopen(url).read()) val = map(float, re.findall("(?&lt;=uccResultAmount'&gt;)[\d\.]+", data)) return val[0] url="https://coinmarketcap.com/currencies/verge/" page=urllib.urlopen(url) soup=BeautifulSoup(page,"html.parser") find_value=soup.find('span',attrs={'class':'text-large2'}) print convert(amount = float(find_value.text), from_curr = 'USD', to_curr = 'AUD') Output: 0.170358
type: Answer
accepted answer of: http://stackoverflow.com/q/48255333
score: 1

http://stackoverflow.com/q/48306299
favorite count: 0
has body: I'm working currently on a authentication project using a Raspberry Pi 3 a Fingerprint Scanner - TTL (GT-511C3) and python as a programming language. I managed to connect the scanner to the pi and make it work. Since i'm still a beginner i don't know how i should compare two fingerprints to know if they're identical. Currently i'm saving the prints as png files and earlier i was saving them as pickle files. My question now is : what is the best way to compare two fingerprints and what is the percentage that i should work with in my comparison to consider two fingerprints identical and how i could achieve that in python. NOTE : I'm going to create a database to store the fingerprints of the users that they're allowed to enter the room for example. And everytime a fingerprint was taken it should go to the database and search if there is a similar one. Thank you in advance. Here is two png files of a fingerprint of the same person taken twice :
has comment: http://stackoverflow.com/comment/84694303
upvote count: 1
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83597741
type: Question
tagged with: fingerprint
has comment: http://stackoverflow.com/comment/83597899
has comment: http://stackoverflow.com/comment/83598242
has comment: http://stackoverflow.com/comment/83597719
has comment: http://stackoverflow.com/comment/84695078
type: UnansweredQuestion
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/7205489
has answer: http://stackoverflow.com/a/79492158
tagged with: raspberry-pi3
has title: Fingerprint comparison

http://stackoverflow.com/a/48292240
type: Answer
answers question: http://stackoverflow.com/q/48292058
score: 0
has body: Since you mentioned you want to use Counter, you can do it like this: result = Counter() for (month, _, _, s) in arr: result[month] += s print(result) Which outputs: Counter({1: 165939})

http://stackoverflow.com/comment/83644418
type: Comment
has text: Please fix your indentation, or at the very least verify that the above code supposed to be running.
type: QuestionComment
comment on: http://stackoverflow.com/q/48328498
score: 0

http://stackoverflow.com/q/48207774
type: Question
has answer: http://stackoverflow.com/a/48207834
type: AnsweredQuestion
tagged with: pandas
score: 7
tagged with: dataframe
tagged with: python
has body: I am using the Pandas rolling window tool on a one-column dataframe whose index is in datetime form. I would like to compute, for each window, the difference between the first value and the last value of said window. How do I refer to the relative index when giving a lambda function? (in the brackets below) df2 = df.rolling('3s').apply(...)
tagged with: sliding-window
downvote count: 0
answer count: 1
upvote count: 7
tagged with: lambda
accepted answer: http://stackoverflow.com/a/48207834
has title: Computing the difference between first and last values in a rolling window
favorite count: 0

http://stackoverflow.com/a/71197737
has body: The syntax you're using is wrong, the attribute eth belongs to a WEB3 object, not the class itself try this it shall work from web3 import Web3 # Create an object from the WEB3 lib w3 = Web3(Web3.IPCProvider()) #then use the eth attribute on it w3.eth.getBlock("1028201")
answers question: http://stackoverflow.com/q/48181275
score: 3
upvote count: 3
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83388516
type: Comment
has text: Thanks for the additional adding of caps to the error bars!
type: AnswerComment
comment on: http://stackoverflow.com/a/48192246
score: 0

http://stackoverflow.com/q/48233127
has comment: http://stackoverflow.com/comment/83450808
linked to: http://stackoverflow.com/q/1504717
type: Question
has comment: http://stackoverflow.com/comment/83448756
has comment: http://stackoverflow.com/comment/83449429
answer count: 0
has comment: http://stackoverflow.com/comment/83450864
type: UnansweredQuestion
tagged with: python
has title: python: compare sliced string to string with "is" equals False
has comment: http://stackoverflow.com/comment/83451586
has comment: http://stackoverflow.com/comment/83450135
score: 0
linked to: http://stackoverflow.com/q/13650293
has comment: http://stackoverflow.com/comment/83451336
has body: Comparing a sliced string with more than 1 character to another string with is equals False. See Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result? But comparing only 1 character slices with is equals True. Why? >>>> 'ab'[1:] is 'b' True >>>> 'abb'[1:] is 'bb' False
duplicate of: http://stackoverflow.com/q/1504717

http://stackoverflow.com/comment/83465712
type: QuestionComment
comment on: http://stackoverflow.com/q/48241601
has text: The usage of *sparse* does not sound right for your task (including title and tag-usage)! Furthermore it's quite broad. It sounds somewhat like: how can i implement my own matrix-routines for my task, which is not trivial. Feature 1 can be exploited by using a byte or less as type and feature 2 is common in sparse-matrix tools sou there is a lot of literature.
score: 1
type: Comment

http://stackoverflow.com/a/48321959
downvote count: 0
type: Answer
has body: You can use tolist: In [1]: [np.array(b'000914_0017_01_0017_P00_01.tifresize.jpg', dtype='|S40').tolist()] Out[1]: ['000914_0017_01_0017_P00_01.tifresize.jpg'] UPDATE: You can also extend / improve this to the following with using flatten: In [2]: np.array([np.array(b'000914_0017_01_0017_P00_01.tifresize.jpg', dtype='|S40').tolist()]).flatten() Out[2]: array(['000914_0017_01_0017_P00_01.tifresize.jpg'], dtype='|S40') This also works with loadtxt: In [3]: np.array([np.loadtxt('split_file_name', dtype=bytes).tolist()]).flatten() Out[3]: array(['000914_0017_01_0017_P00_01.tifresize.jpg', '000925_0017_01_0006_P00_01.tifresize.jpg', '000919_0017_01_0012_P00_01.tifresize.jpg'], dtype='|S40')
score: 2
has comment: http://stackoverflow.com/comment/83634790
answers question: http://stackoverflow.com/q/48321394
has comment: http://stackoverflow.com/comment/83631489
upvote count: 2

http://stackoverflow.com/q/48295798
tagged with: regex
has answer: http://stackoverflow.com/a/78542077
has comment: http://stackoverflow.com/comment/83577787
score: 2
has comment: http://stackoverflow.com/comment/83587821
tagged with: pandas
has body: I have a directory of files with names of the form 2018-1-7.csv and I need them to be in the form of 2018-01-07.csv. I need a leading Zero for one digit days. I have tried a few things but my regex-fu is weak. Can anyone suggest how to perform this?
downvote count: 0
favorite count: 0
type: Question
has title: Rename all files to different date format in Python
upvote count: 2
type: UnansweredQuestion
tagged with: datetime
answer count: 1
tagged with: python

http://stackoverflow.com/comment/83344860
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ This has been fixed/improved in a recent release of CPython. In python 2 it doesn't throw an error, but silently produces an unexpected result instead. (For example `re.split(r'(?=a)', '1a2')` -> `['1a2']`)
comment on: http://stackoverflow.com/q/48182561
score: 1
type: Comment

http://stackoverflow.com/a/48195810
answers question: http://stackoverflow.com/q/48195724
downvote count: 0
upvote count: 1
has body: An easy mistake to make, but stay at it! List Comprehensions are really useful ways to help shorten code. The last line should read: return [x for x in l if isinstance(x, int)]
score: 1
type: Answer

http://stackoverflow.com/comment/83485751
type: Comment
comment on: http://stackoverflow.com/a/48247633
score: 0
type: AnswerComment
has text: For an N of 5 - I should get [3, 1, 0, 0]*[[1], [2], [3], [4]] and [0, 1, 1, 0]*[[1], [2], [3], [4]] but I don't.

http://stackoverflow.com/comment/83338966
has text: I tried to replace the source code even with the numpy function, but I couldn't find the definition of the function signal.sigtools._correlateND wich is neccessary.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48178915
type: Comment

http://stackoverflow.com/a/48209552
has comment: http://stackoverflow.com/comment/83430965
has comment: http://stackoverflow.com/comment/83431143
has comment: http://stackoverflow.com/comment/83400055
has body: The data in the Content key appears to be a standard CSV format, so you could create a list of dictionaries as follows: from io import StringIO import csv data = {u'Content': 'a,b,c\n1,2,3\n4,5,6'} list_of_dicts = list(csv.DictReader(StringIO(data['Content']))) print(list_of_dicts) Which for this simple example would give you: [OrderedDict([('a', '1'), ('b', '2'), ('c', '3')]), OrderedDict([('a', '4'), ('b', '5'), ('c', '6')])]
accepted answer of: http://stackoverflow.com/q/48209088
type: Answer
answers question: http://stackoverflow.com/q/48209088
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83431182

http://stackoverflow.com/comment/83447537
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48232511
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ, that would work for positive, but for -4 it would return 'c' instead. Though I would argue that's what it's supposed to be instead of what OP expects.

http://stackoverflow.com/q/48201152
answer count: 4
type: AnsweredQuestion
score: 0
has body: I have three dicts as given below, d1 = {1:'a',2:'k',3:'l'} d2 = {1:'j',2:'k',3:'j',4:'n'} d3 = {1:'j',2:'k',3:'j',4:'i',5:'j'} Is there a way that these three dictionaries can be merged that d1 is written same it is written above in d_merged and then same keys from d2 are written by adding 1 in max key of d1 and likewise same keys from d3 will be appended in d_merged by adding 1 in max key of d_merged as shown below: d_merged = {1:'a',2:'k',3:'l',4:'j',5:'k',6:'j',7:'n',8:'j',9:'k',10:'j',11:'i',12:'j'}
has comment: http://stackoverflow.com/comment/83383599
accepted answer: http://stackoverflow.com/a/48201330
has answer: http://stackoverflow.com/a/48201330
has answer: http://stackoverflow.com/a/48201339
type: Question
has title: Merging dictionaries by appending same numerical keys
tagged with: python
has answer: http://stackoverflow.com/a/48201468
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/48201339
has answer: http://stackoverflow.com/a/48201372

http://stackoverflow.com/q/48237821
has answer: http://stackoverflow.com/a/48238622
score: -2
has body: I'm new to data analysis so please excuse me if this is a bit of a newbie question. I am running a PLS regression on same data where X comprises of ordinal variables and y is a binary variable indicating whether an event occurred or not. I generated some cross-validation scores and got the following: X = threat.iloc[:,2:96] y = threat.iloc[:,1] pls1 = PLSRegression(n_components=10) result = pls1.fit_transform(X, y) scoresT = cross_val_score(pls1, X, y, cv=5) print(scoresT) [ 0. 0. 0. 0.55965802 0. ] I know that each number represents the score for each "fold", but I expected a series of numbers like [0.2, 0.4, 0.6, 0.7, 0.3] rather than [0, 0, 0, 0.5, 0] so I am unsure of what exactly this is saying about my data or model. Does anyone have any insights?
tagged with: cross-validation
tagged with: python
has comment: http://stackoverflow.com/comment/83458686
accepted answer: http://stackoverflow.com/a/48238622
type: AnsweredQuestion
upvote count: 0
downvote count: 2
answer count: 1
tagged with: scikit-learn
favorite count: 0
type: Question
has title: Cross-validation score of 0

http://stackoverflow.com/comment/83535431
comment on: http://stackoverflow.com/q/48276015
score: 0
has text: Where's your code?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83621981
has text: The loop beraks when no more reviews are avaliable, but you could break sooner if you want (eg after 50 reviews). So i updated the code to collect reviews in a list, and modified `ajax_url` so that it should work with any imdb reviews url. Cheers!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48304067
type: Comment

http://stackoverflow.com/q/48199899
tagged with: python
has comment: http://stackoverflow.com/comment/83380910
answer count: 2
has answer: http://stackoverflow.com/a/48200043
score: 1
downvote count: 0
has title: Content of list change unexpected in Python 3
upvote count: 1
has comment: http://stackoverflow.com/comment/83382151
has body: I am building one example to create all the subsets of one list: My code is like follow, I have copy result value to another temp list and manipulate in the temp list, but don't know why in step 1 and step 3 the 'result' I print is different. I haven't make any change yet. a=[1,2,3] result=[] temp=[] def sub_sets(i,result): print("1start result:",result) temp=result[:] for j in range(len(temp)): temp[j].append(i) temp.append([i]) print("2temp:",temp) print("3 middle result:",result) result.extend(temp) print("4end result:",result) for i in range(len(a)): sub_sets(a[i],result) Results: 1start result: [] 2temp: [[1]] 3 middle result: [] 4end result: [[1]] 1start result: [[1]] 2temp: [[1, 2], [2]] 3 middle result: [[1, 2]] 4end result: [[1, 2], [1, 2], [2]] 1start result: [[1, 2], [1, 2], [2]] 2temp: [[1, 2, 3, 3], [1, 2, 3, 3], [2, 3], [3]] 3 middle result: [[1, 2, 3, 3], [1, 2, 3, 3], [2, 3]] 4end result: [[1, 2, 3, 3], [1, 2, 3, 3], [2, 3], [1, 2, 3, 3], [1, 2, 3, 3], [2, 3], [3]]
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48199999
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/114556110
type: AnswerComment
comment on: http://stackoverflow.com/a/48175227
type: Comment
has text: If you pass a DataFrame instead of a list to row_colors, the column names are displayed
score: 4

http://stackoverflow.com/comment/83539637
score: 0
comment on: http://stackoverflow.com/q/48278091
has text: and lowercase myString in all function
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48176298
answers question: http://stackoverflow.com/q/48176103
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48176103
score: 3
has comment: http://stackoverflow.com/comment/83332462
type: Answer
has comment: http://stackoverflow.com/comment/83332569
upvote count: 3
has body: This is a really good beginning attempt at a function! 2 things to fix: 1) The question variable shouldn't have a print in it. Putting a variable in input() will print it for you. This would be better: question = string+" "+cubed+qmark 2) The bottom section isn't quite right. Maybe you want something like this? The last line calls the whole function again - this is called "recursion". user = int(input(question)) if (user == rand): print ("\nCorrect!") elif (user != rand): print ("\tIncorrect!, the cube root of", cubed, "is", rand) user = input("\n\tWould you like to try again?").lower() if user == "y": guess() Put together, here is the final Code: # Purpose: 'guess' randomly selects a number between 0 and 100 (including those # numbers) and calculate the cube of that number. It also prompts the user to # guess the cube root of the cubed number, displaying 'Correct!' if correct, and # asking the user if they would like to try again if incorrect. def guess(): import random rand = random.randint (0, 100) cubed = rand*rand*rand # Forming the input question string = "What is the cube root of" cubed = str(cubed) qmark = "?" question = string+" "+cubed+qmark #################### Remove print here. Input will do it for you. user = int(input(question)) if (user == rand): print ("\nCorrect!") elif (user != rand): print ("\tIncorrect!, the cube root of", cubed, "is", rand) user = input("\n\tWould you like to try again?").lower() if user == "y": guess() else: print("Goodbye") guess() I have only started programming recently myself, and this is my first time I have helped someone! Edit: following a suggestion in the comments, here is a way to do it without using recursion, by putting everything in a "While True Loop", also known as a forever loop: def guess(): while True: import random rand = random.randint (0, 100) cubed = rand*rand*rand # Forming the input question string = "What is the cube root of" cubed = str(cubed) qmark = "?" question = string+" "+cubed+qmark ############…

http://stackoverflow.com/comment/83349958
score: 0
has text: Excellent, thank you!
comment on: http://stackoverflow.com/q/48174374
type: Comment
type: QuestionComment

cluster-analysis
tags question: http://stackoverflow.com/q/48227180
tags question: http://stackoverflow.com/q/48178527
tag name: cluster-analysis
type: Tag
tags question: http://stackoverflow.com/q/48281026

http://stackoverflow.com/q/48203397
has answer: http://stackoverflow.com/a/48204534
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83691459
upvote count: 8
score: 8
tagged with: python-asyncio
has answer: http://stackoverflow.com/a/48280824
has answer: http://stackoverflow.com/a/48211916
tagged with: python
possible better answer: http://stackoverflow.com/a/48204534
has comment: http://stackoverflow.com/comment/83387827
answer count: 4
has title: Python: Lib to use epoll if available, fallback to select
has comment: http://stackoverflow.com/comment/83400383
has body: I would like to use select.epoll() in my Python library. Unfortunately epoll is not available everywhere. I need a way to fallback to select.select(). I tried to find something at pypi, but failed to find a matching package: https://pypi.python.org/pypi?%3Aaction=search&amp;term=epoll&amp;submit=search How could I solve this "fallback from epoll to select if epoll is not available"?
accepted answer: http://stackoverflow.com/a/48280141
tagged with: select
downvote count: 0
tagged with: epoll
has answer: http://stackoverflow.com/a/48280141
has comment: http://stackoverflow.com/comment/83740618

http://stackoverflow.com/comment/83466516
has text: `raw_input` is Python 2, `print()` is Python 3.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48241137
type: AnswerComment

http://stackoverflow.com/a/48300846
accepted answer of: http://stackoverflow.com/q/48294013
has comment: http://stackoverflow.com/comment/83654303
has comment: http://stackoverflow.com/comment/83654344
has comment: http://stackoverflow.com/comment/83653876
has body: Here's a small class that I use for saving data like this. You can use it by doing something like.. dc = DataContainer() dc.trials = &lt;your list of trial objects here&gt; dc.save('mydata.pkl') Then to load do.. dc = DataContainer.load('mydata.pkl') Here's the DataContainer file: import gzip import cPickle as pickle # Simple container with load and save methods. Declare the container # then add data to it. Save will save any data added to the container. # The class automatically gzips the file if it ends in .gz # # Notes on size and speed (using UbuntuDialog data) # pkl pkl.gz # Save 11.4s 83.7s # Load 4.8s 45.0s # Size 596M 205M # class DataContainer(object): @staticmethod def isGZIP(filename): if filename.split('.')[-1] == 'gz': return True return False # Using HIGHEST_PROTOCOL is almost 2X faster and creates a file that # is ~10% smaller. Load times go down by a factor of about 3X. def save(self, filename='DataContainer.pkl'): if self.isGZIP(filename): f = gzip.open(filename, 'wb') else: f = open(filename, 'wb') pickle.dump(self, f, protocol=pickle.HIGHEST_PROTOCOL) f.close() # Note that loading to a string with pickle.loads is about 10% faster # but probaly comsumes a lot more memory so we'll skip that for now. @classmethod def load(cls, filename='DataContainer.pkl'): if cls.isGZIP(filename): f = gzip.open(filename, 'rb') else: f = open(filename, 'rb') n = pickle.load(f) f.close() return n Depending on your use case you could use this as described at the top, as a base class, or simply copy the pickle.dump line into your code. If you really have a lot of data and you don't use all of it with every run of your test program, there are a few other options such a database but the above is about the best simple option assuming you need most of the data with each run.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48294013
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/48329959
favorite count: 0
accepted answer: http://stackoverflow.com/a/48332060
type: Question
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48332060
has comment: http://stackoverflow.com/comment/83645904
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83645766
has body: I have a question for Counter with python dictionary. I build dictionary using Counter (it helps me to build adjacency matrix) {48: {Note(note=48, duration=200): 4, Note(note=52, duration=200): 2}} I use namedtuple for this example. The values stored 48 - fourfold 52 - double? Let do this with list in dict: {48: ['48','48','48','48','52','52']} Now I will choose a random value from a given key (48). What is the probability for the list in the dictionary and for the dictionary with counter? It's better to do this with list in dictionary? Does it matter? I wonder the extract of dic with counter give me {48: {48,48,48,48}, {52,52}} or Counter only store number of elements? The real question is: Which way I should use to get random value from key? Dict with list or Dict with counter? It's the same? I woring on Markov Chain to generate music. I have set of notes and I build a dictionary.
has title: Python Counter in dict vs list in dict probability of choosing an element
answer count: 1
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/83629147
type: Comment
score: 1
has text: How do you compare those strings by ASCII code?
type: QuestionComment
comment on: http://stackoverflow.com/q/48322058

http://stackoverflow.com/comment/83463133
comment on: http://stackoverflow.com/q/48239968
score: 0
has text: in the future, and for any big project, I would probably do just that. but for this thing, I'm trying to pride myself on making a lean little program, so I'd rather keep dependencies out of it... but I appreciate that comment... I do recall that one can do arrays in a more normal feeling way using libraries
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83456390
type: AnswerComment
score: 1
type: Comment
has text: Nicely done. It could be improved by turning *python documentation* into a link. Better yet, turn the *Python xx* references into links to the appropriate documentation.
comment on: http://stackoverflow.com/a/48236843

http://stackoverflow.com/comment/83488775
has text: In the [docs for `str.replace()`](https://docs.python.org/2/library/string.html#string.replace), note that a _copy_ of the string is _returned_--the string isn't modified in place.
score: 0
comment on: http://stackoverflow.com/q/48252914
type: Comment
type: QuestionComment

http://stackoverflow.com/a/56365560
has body: To complete the answer of @banderlog013, I think the Gimp Doc specifies that the end pixels of each channel are first discarded, then the remaining ranges are stretched. I believe the right code is : img = cv2.imread('test.jpg') balanced_img = np.zeros_like(img) #Initialize final image for i in range(3): #i stands for the channel index hist, bins = np.histogram(img[..., i].ravel(), 256, (0, 256)) bmin = np.min(np.where(hist&gt;(hist.sum()*0.0005))) bmax = np.max(np.where(hist&gt;(hist.sum()*0.0005))) balanced_img[...,i] = np.clip(img[...,i], bmin, bmax) balanced_img[...,i] = (balanced_img[...,i]-bmin) / (bmax - bmin) * 255 I obtain good results with it, try it out !
accepted answer of: http://stackoverflow.com/q/48268068
type: Answer
upvote count: 4
score: 4
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/119035579
answers question: http://stackoverflow.com/q/48268068
has comment: http://stackoverflow.com/comment/119031251

http://stackoverflow.com/comment/83444928
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48230646
type: QuestionComment
has text: The original input file is like this (before the x_train, y_train separation): https://ibb.co/cfrVhR Then the x_train is a list containing all the reviews i.e. the first column. https://ibb.co/g9dt2R

http://stackoverflow.com/a/48288922
downvote count: 0
answers question: http://stackoverflow.com/q/48288351
accepted answer of: http://stackoverflow.com/q/48288351
upvote count: 8
type: Answer
score: 8
has body: Yes there is a more pythonic way to do that, using the standard library contextlib, which has a class ExitStack which does excatly what you want: with ExitStack() as stack: controllers = [stack.enter_context(Controller(n)) for n in names] This should do what you want.
type: AcceptedAnswer

http://stackoverflow.com/a/74253760
answers question: http://stackoverflow.com/q/48210749
upvote count: 3
downvote count: 0
has body: 3000 views and 4 years later, things might have changed a bit. In matplotlib 3.3.3 (tested) 3.6 (docs) accessing the cells is much simpler than the code above, as the table can be addressed as a list directly: cell = table[row_number,column_number] Also the function _text.set_horizontalalignment('left') which is reported as not working above, now seems to work. However setting _loc sets _loc but seems to have no effect on the display (according to doc 3.6, it should) but it does not seem to do any harm. My belt and braces code to setting column col to left alignment is for i in range(0,nrows) tb[i, col]._loc = 'left' tb[i, col]._text.set_horizontalalignment('left') Thanks to the contributors above for getting me on the right track
score: 3
type: Answer

http://stackoverflow.com/comment/83486135
comment on: http://stackoverflow.com/a/48250968
type: AnswerComment
has text: Thanks. I've tried this already but it didn't give me the needed result as I get another problem when I try to save this to_csv
score: 0
type: Comment

http://stackoverflow.com/comment/83563395
has text: This is indeed a named entity recognition (NER) problem. Regular expressions, like any other hard-coded rules, won't get you far down this road. There are many available trained NER models for human names available on the web.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48288763

tkinter
tags question: http://stackoverflow.com/q/48252682
tags question: http://stackoverflow.com/q/48328498
tags question: http://stackoverflow.com/q/48228475
tags question: http://stackoverflow.com/q/48249890
tags question: http://stackoverflow.com/q/48186571
tags question: http://stackoverflow.com/q/48178560
tags question: http://stackoverflow.com/q/48312372
tags question: http://stackoverflow.com/q/48259089
tags question: http://stackoverflow.com/q/48177683
tags question: http://stackoverflow.com/q/48200355
tags question: http://stackoverflow.com/q/48263043
tags question: http://stackoverflow.com/q/48255105
tags question: http://stackoverflow.com/q/48217059
tags question: http://stackoverflow.com/q/48330657
tags question: http://stackoverflow.com/q/48191375
tags question: http://stackoverflow.com/q/48189696
tags question: http://stackoverflow.com/q/48173820
tags question: http://stackoverflow.com/q/48236579
tags question: http://stackoverflow.com/q/48176353
tags question: http://stackoverflow.com/q/48242280
tags question: http://stackoverflow.com/q/48311972
tags question: http://stackoverflow.com/q/48271438
tags question: http://stackoverflow.com/q/48327765
tags question: http://stackoverflow.com/q/48216159
tags question: http://stackoverflow.com/q/48243798
tags question: http://stackoverflow.com/q/48292632
tags question: http://stackoverflow.com/q/48200825
tags question: http://stackoverflow.com/q/48306462
tags question: http://stackoverflow.com/q/48198529
tags question: http://stackoverflow.com/q/48330086
tags question: http://stackoverflow.com/q/48214483
tags question: http://stackoverflow.com/q/48310132
tags question: http://stackoverflow.com/q/48233613
tags question: http://stackoverflow.com/q/48268506
tags question: http://stackoverflow.com/q/48292804
tags question: http://stackoverflow.com/q/48212417
tags question: http://stackoverflow.com/q/48183419
tags question: http://stackoverflow.com/q/48278832
tags question: http://stackoverflow.com/q/48239889
tags question: http://stackoverflow.com/q/48184238
tags question: http://stackoverflow.com/q/48291898
tag name: tkinter
tags question: http://stackoverflow.com/q/48213664
tags question: http://stackoverflow.com/q/48191904
tags question: http://stackoverflow.com/q/48278853
tags question: http://stackoverflow.com/q/48281391
tags question: http://stackoverflow.com/q/48295904
tags question: http://stackoverflow.com/q/48298195
tags question: http://stackoverflow.com/q/48237211
tags question: http://stackoverflow.com/q/48309112
tags question: http://stackoverflow.com/q/48310413
tags question: http://stackoverflow.com/q/48307249
tags question: http://stackoverflow.com/q/48269139
tags question: http://stackoverflow.com/q/48272772
tags question: http://stackoverflow.com/q/48271046
tags question: http://stackoverflow.com/q/48304549
tags question: http://stackoverflow.com/q/48180989
tags question: http://stackoverflow.com/q/48250311
tags question: http://stackoverflow.com/q/48232001
tags question: http://stackoverflow.com/q/48185104
tags question: http://stackoverflow.com/q/48245132
tags question: http://stackoverflow.com/q/48229580
tags question: http://stackoverflow.com/q/48244119
tags question: http://stackoverflow.com/q/48195505
tags question: http://stackoverflow.com/q/48179403
tags question: http://stackoverflow.com/q/48283746
tags question: http://stackoverflow.com/q/48291140
tags question: http://stackoverflow.com/q/48232844
tags question: http://stackoverflow.com/q/48246360
tags question: http://stackoverflow.com/q/48289171
tags question: http://stackoverflow.com/q/48199545
tags question: http://stackoverflow.com/q/48186906
tags question: http://stackoverflow.com/q/48311136
tags question: http://stackoverflow.com/q/48218934
tags question: http://stackoverflow.com/q/48268089
tags question: http://stackoverflow.com/q/48220788
tags question: http://stackoverflow.com/q/48199486
tags question: http://stackoverflow.com/q/48269599
tags question: http://stackoverflow.com/q/48327849
tags question: http://stackoverflow.com/q/48299396

http://stackoverflow.com/q/48295909
has answer: http://stackoverflow.com/a/51033787
score: 1
accepted answer: http://stackoverflow.com/a/51033787
upvote count: 1
tagged with: swagger
linked to: http://stackoverflow.com/q/68428892
has answer: http://stackoverflow.com/a/59892272
answer count: 4
has answer: http://stackoverflow.com/a/48296442
favorite count: 0
type: Question
tagged with: gunicorn
has title: how to use gunicorn with swagger_server on flask
has answer: http://stackoverflow.com/a/48296041
possible better answer: http://stackoverflow.com/a/48296041
has body: I'm trying to start the swagger server using gunicorn on ec2 instance by using the following code: I tried : gunicorn -w 4 -b 0.0.0.0:8080 -p pidfile -D swagger_server:app and this: gunicorn -w 4 -b 0.0.0.0:8080 -p pidfile -D "python3 -m swagger_server":app and even this : gunicorn -w 4 -b 0.0.0.0:8080 -p pidfile -D __main__:app How can I get it to work? RAW python code which works : python3 -m swagger_server
tagged with: python
tagged with: flask
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/83451634
comment on: http://stackoverflow.com/a/48234525
type: Comment
type: AnswerComment
score: 2
has text: ... which is the same way as to do it in a lambda, of course. This syntax is no longer supported in Python 3.x, however.

http://stackoverflow.com/comment/83455297
type: Comment
has text: similar to this https://sourceforge.net/p/dclib/discussion/442518/thread/12152368/. over 30 minutes now. top is showing this https://imgur.com/a/OJjmO. is it the RAM ? aws free tier RAM not enough ?
comment on: http://stackoverflow.com/a/48235816
score: 0
type: AnswerComment

http://stackoverflow.com/q/48319489
accepted answer: http://stackoverflow.com/a/48320278
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83625132
answer count: 1
has comment: http://stackoverflow.com/comment/83624863
has body: I have a QTreeWidget which contains two columns and some rows. I would like to set a flag so that if an item in the second column is either a zero or empty, it cannot be edited. If the item clicked is not numeric, it will be shown with a red text. My code: def qtree_check_item(self, item, column): item.setFlags(QtCore.Qt.ItemIsEnabled) if column == 1: if item.text(1) != '0': item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable) if not item.text(1).isnumeric(): item.setForeground(1, QtGui.QBrush(QtGui.QColor("red"))) This works if the item is zero. If I replace: if item.text(1) != '0': with if item.text(1) != '': This works for empty strings. But if I combine both using: if item.text(1) != '0' or item.text(1) != '': The flags are not set. What am I doing wrong?
type: Question
tagged with: qt
has answer: http://stackoverflow.com/a/48320278
tagged with: qtreewidget
has title: How to set flag for an item in a QTreeWidget?
tagged with: pyqt4
tagged with: python

pipeline
type: Tag
tags question: http://stackoverflow.com/q/48271342
tag name: pipeline
tags question: http://stackoverflow.com/q/48266749

http://stackoverflow.com/q/48174916
answer count: 1
has title: pattern matching the directory contents in python
type: Question
has answer: http://stackoverflow.com/a/48174954
accepted answer: http://stackoverflow.com/a/48174954
tagged with: python
has body: I have a directory with a list of files and I would like to match the contents of the direcotry with a pattern &gt;&gt;os.listdir(os.getcwd()) gives [2010.1.1-19999, 2011.1.1-124444] &gt;&gt; fnmatch.filter(os.listdir(os.getcwd()),"\d+\.\d\.\d\-\d+") [] The result is null and the fnmatch function does not pattern match the contents of the directory listing. what is the error here ?
type: AnsweredQuestion
tagged with: python-2.7
score: 0

http://stackoverflow.com/q/48221731
has body: I need little help here. For your information, I'm a very new to Python, and just trying to tinker with it. So, I have this website 'The hitchhiker's guide to python'. Now, I'm on a section of 'Installing Python 3 on Mac OS X'. Here is the link -> http://docs.python-guide.org/en/latest/starting/install3/osx/#pip Anyway I wanted to do it right, so freshly formatted my Mac, and Xcode as well. And I followed the instruction which says 'xcode-select --install' . After that, I started install homebrew within the terminal $ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" I guess I coped with this until now, but here is the problem occurs. He says Once you’ve installed Homebrew, insert the Homebrew directory at the top of your PATH environment variable. You can do this by adding the following line at the bottom of your ~/.profile file So, with some searches, I edited my path in nano. by following sudo nano /etc/paths /usr/local/bin /usr/local/sbin &lt;&lt;&lt;--When I opened the paths, there wasn't this 'usr/local/sbin' So I typed it. /usr/bin /bin /usr/sbin/ /sbin When I opened the path, there was no '/usr/local/sbin'. so I typed it. And I quit the terminal, echo the path out, nothing happend. If I do which python it shows me /usr/bin/python. I do have python3 installed, But when I do python -V, it's still Python 2.7.10 How can I insert the Homebrew directory at the top of your PATH environment variable? By means, How can I set my mac to set python3 to default??? Appreciate it in advance!
has comment: http://stackoverflow.com/comment/83456267
tagged with: python
has comment: http://stackoverflow.com/comment/83424877
score: 0
has answer: http://stackoverflow.com/a/48221852
has answer: http://stackoverflow.com/a/48221846
tagged with: installation
answer count: 3
has answer: http://stackoverflow.com/a/48221906
has title: How to insert the Homebrew directory at the top of your PATH environment variable?
tagged with: macos
type: Question
tagged with: python-3.x
tagged with: terminal
type: UnansweredQuestion

http://stackoverflow.com/comment/83561966
comment on: http://stackoverflow.com/q/48272093
type: Comment
type: QuestionComment
has text: @cowbert ,By 400 column limit, i meant we have exhausted all the extra columns that we have created for our future use. They are not part of sort key. Our sort key is a date column on which users filter. I am open to NoSQL as well but we need a reporting solution on top of this. Not sure if NoSQL supports reporting solutions.
score: 0

http://stackoverflow.com/q/48190951
accepted answer: http://stackoverflow.com/a/48191121
tagged with: python
tagged with: module
tagged with: global-variables
has comment: http://stackoverflow.com/comment/83362803
linked to: http://stackoverflow.com/q/606561
has title: How to make main.py's global variable visible in imported module?
has body: When using this main.py from mymodule import myfunc GENERALPARAM = "6878623" for i in xrange(10000): myfunc(i) and this mymodule.py: def myfunc(a): # very fast computation here if condition(a): log(a, GENERALPARAM) how to make that GENERALPARAM is available in mymodule.py's myfunc? By using a global variable (how?)? Of course I could pass it as a parameter: #main.py for i in xrange(10000): myfunc(i, GENERALPARAM) #mymodule.py def myfunc(a, GENERALPARAM): ... but I would like to avoid to pass millions of times (for very short computation) the same variable as parameter.
type: AnsweredQuestion
score: 0
duplicate of: http://stackoverflow.com/q/15959534
has answer: http://stackoverflow.com/a/48191121
answer count: 1
has comment: http://stackoverflow.com/comment/83362152
type: Question

http://stackoverflow.com/comment/83389594
has text: yeah we need to wait for webelement to apper in DOM after that only we are able to interact with it
comment on: http://stackoverflow.com/a/48204057
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48198770
favorite count: 0
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/48633736
has answer: http://stackoverflow.com/a/48227272
possible better answer: http://stackoverflow.com/a/54701671
type: Question
answer count: 3
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83436109
type: AnsweredQuestion
has title: TensorFlow 1.5.0-rc0: error using `tf.app.flags`
has answer: http://stackoverflow.com/a/54701671
accepted answer: http://stackoverflow.com/a/48227272
tagged with: tensorflow
has body: The following flags were defined in a misc_fun.py file to include machine and directories info: import tensorflow as tf flags = tf.app.flags FLAGS = flags.FLAGS # definitions flags.DEFINE_string( 'DEFAULT_IN', '~/PycharmProjects/myNN/Data/', """Default input folder.""") ... It worked fine in TensorFlow 1.0 - 1.4 versions (with Pycharm). After updating to TensorFlow 1.5.-rc0, the following error occurred: Usage: from misc_fun import FLAGS FLAGS.DEFAULT_IN = FLAGS.DEFAULT_DOWNLOAD # change default input folder Error: UnparsedFlagAccessError: Trying to access flag --DEFAULT_DOWNLOAD before flags were parsed. However print(FLAGS) worked fine, which gives: misc_fun: --DEFAULT_DOWNLOAD: default download folder for large datasets. (default: '/home/username/Downloads/Data/') --DEFAULT_IN: default input folder. (default: '~/PycharmProjects/myNN/Data/') ... I tried FLAGS = flags.FLAGS(sys.argv), resulting in the following error: UnrecognizedFlagError: Unknown command line flag 'f' Although there is a workaround using the class object, I wonder what could be the problem here.

http://stackoverflow.com/comment/88770346
comment on: http://stackoverflow.com/q/48263154
score: 0
has text: No :( Still need to figure out how to do it.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83660809
score: 0
type: AnswerComment
has text: @AkshayNevrekar I assumed that. That's why I mentioned the edge cases. Try adding to your question to tell us what to do in these cases. Otherwise this answer solves the problem stated in your question.
type: Comment
comment on: http://stackoverflow.com/a/48321058

http://stackoverflow.com/comment/83560550
type: QuestionComment
comment on: http://stackoverflow.com/q/48262716
has text: So it coud be a bug with PyQt. I'll contact their support and keep you posted.
score: 0
type: Comment

http://stackoverflow.com/q/48328133
has title: Find numpy array coordinates of neighboring maximum
accepted answer: http://stackoverflow.com/a/48328890
tagged with: multidimensional-array
has answer: http://stackoverflow.com/a/48328890
tagged with: python
score: 4
type: AnsweredQuestion
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/3986345
has body: I used the accepted answer in this question to obtain local maxima in a numpy array of 2 or more dimensions so I could assign labels to them. Now I would like to also assign these labels to neighboring cells in the array, depending on gradient – i.e. a cell gets the same label as the neighboring cell with the highest value. This way I can iteratively assign labels to my entire array. Assume I have an array A like &gt;&gt;&gt; A = np.array([[ 1. , 2. , 2.2, 3.5], [ 2.1, 2.4, 3. , 3.3], [ 1. , 3. , 3.2, 3. ], [ 2. , 4.1, 4. , 2. ]]) Applying the maximum_filter I get &gt;&gt;&gt; scipy.ndimage.filters.maximum_filter(A, size=3) array([[ 2.4, 3. , 3.5, 3.5], [ 3. , 3.2, 3.5, 3.5], [ 4.1, 4.1, 4.1, 4. ], [ 4.1, 4.1, 4.1, 4. ]]) Now, for every cell in this array I would like to have the coordinates of the maximum found by the filter, i.e. array([[[1,1],[1,2],[0,3],[0,3]], [[2,1],[2,2],[0,3],[0,3]], [[3,1],[3,1],[3,1],[3,2]], [[3,1],[3,1],[3,1],[3,2]]]) I would then use these coordinates to assign my labels iteratively. I can do it for two dimensions using loops, ignoring borders highest_neighbor_coordinates = np.array([[(argmax2D(A[i-1:i+2, j-1:j+2])+np.array([i-1, j-1])) for j in range(1, A.shape[1]-1)] for i in range(1, A.shape[0]-1)]) but after seeing the many filter functions in scipy.ndimage I was hoping there would be a more elegant and extensible (to >=3 dimensions) solution.
favorite count: 0
type: Question
upvote count: 4
tagged with: numpy

http://stackoverflow.com/comment/83470136
type: QuestionComment
comment on: http://stackoverflow.com/q/48243652
score: 0
has text: Good spot! I was registering my models incorrectly. I tried to register all in one line, but got an error that there were too many arguments, so I split it up into two lines, which felt wrong, and apparently is wrong. I still need to figure out how to register 4 models, but when I commented it all out, the migration worked. Thanks!
type: Comment

http://stackoverflow.com/comment/83424744
type: Comment
type: QuestionComment
has text: The problem is, whenever I add some text to it, there is always empty line at the end.
comment on: http://stackoverflow.com/q/48220788
score: 0

http://stackoverflow.com/comment/83805671
comment on: http://stackoverflow.com/q/48249253
has text: based on a quick look, if you have constant calls to previous function and the functions are the same, aka Same Sub Component. Then it is very similar to a Dynamic Programming approach, such as Knapsack. You could materialize the previous function result using the parameter input as index. Then every function performs a result lookup (if result is already computed) and a computation (if result is not computed).
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48227027
has comment: http://stackoverflow.com/comment/83436584
has comment: http://stackoverflow.com/comment/83436274
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48226506
score: 3
has body: Use sklearn.feature_extraction.text.CountVectorizer: from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(vocabulary=toxic) r = pd.SparseDataFrame(cv.fit_transform(df['text']), df.index, cv.get_feature_names(), default_fill_value=0) Result: In [127]: r Out[127]: bad horrible disguisting 0 0 1 0 1 0 0 0 2 1 0 1 In [128]: type(r) Out[128]: pandas.core.sparse.frame.SparseDataFrame In [129]: r.info() &lt;class 'pandas.core.sparse.frame.SparseDataFrame'&gt; RangeIndex: 3 entries, 0 to 2 Data columns (total 3 columns): bad 3 non-null int64 horrible 3 non-null int64 disguisting 3 non-null int64 dtypes: int64(3) memory usage: 104.0 bytes In [130]: r.memory_usage() Out[130]: Index 80 bad 8 # &lt;--- NOTE: it's using 8 bytes (1x int64) instead of 24 bytes for three values (3x8) horrible 8 disguisting 8 dtype: int64 joining SparseDataFrame with the original DataFrame: In [137]: r2 = df.join(r) In [138]: r2 Out[138]: text bad horrible disguisting 0 You look horrible 0 1 0 1 You are good 0 0 0 2 you are bad and disguisting 1 0 1 In [139]: r2.memory_usage() Out[139]: Index 80 text 24 bad 8 horrible 8 disguisting 8 dtype: int64 In [140]: type(r2) Out[140]: pandas.core.frame.DataFrame In [141]: type(r2['horrible']) Out[141]: pandas.core.sparse.series.SparseSeries In [142]: type(r2['text']) Out[142]: pandas.core.series.Series PS in older Pandas versions Sparsed columns loosed their sparsity (got densed) after joining SparsedDataFrame with a regular DataFrame, now we can have a mixture of regular Series (columns) and SparseSeries - really nice feature!
type: Answer
answers question: http://stackoverflow.com/q/48226506
has comment: http://stackoverflow.com/comment/83436257
downvote count: 0
has comment: http://stackoverflow.com/comment/83436197
has comment: http://stackoverflow.com/comment/83436646
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83435919

http://stackoverflow.com/comment/116497051
score: 1
comment on: http://stackoverflow.com/a/57893015
type: AnswerComment
type: Comment
has text: brilliant use of `pathlib suffix`

http://stackoverflow.com/q/48174821
upvote count: 1
accepted answer: http://stackoverflow.com/a/48174969
downvote count: 1
has comment: http://stackoverflow.com/comment/83329475
has comment: http://stackoverflow.com/comment/83329433
has comment: http://stackoverflow.com/comment/83329685
has body: I'm getting the name of a file in Django after an Image save : path-&gt; 'companies/92_dsa/log/Hydrangeas.jpg' as it is in database I do a clone of the file, an resize (is an image) and want to save the new file with a different name. I get the directory of the original file: folder = os.path.dirname(path) the filename and extension: filename, extension = os.path.splitext(os.path.basename(media_path)) then create a new_filename = filename + '_sz' + extension and the I want to recreate the path: new_path = os.path.join(folder, new_filename) and the problem(slash-backslash before the filename): 'companies/94_sda/logos\Hydrangeas_sz.jpg' I'm working in Windows, bur the final deploy probably will be on Linux, so I want a fix indifferent of the OS.
favorite count: 0
type: Question
tagged with: python-os
has comment: http://stackoverflow.com/comment/83329622
has answer: http://stackoverflow.com/a/48174969
possible better answer: http://stackoverflow.com/a/48175528
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83329575
has answer: http://stackoverflow.com/a/48175528
has title: os.path operation in Django, change/join path issue
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83329697

http://stackoverflow.com/comment/83334590
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48177074
has text: Since the code from the linked answer runs fine for everyone, you need to think for yourself what could be different in your case - or if you have no clue, make your case as reproducible for others as possible, clearly stating how you run it, what versions you are using, posting a screenshot that allows to judge on other possible problems.
type: Comment

http://stackoverflow.com/comment/83526409
comment on: http://stackoverflow.com/a/48270006
type: Comment
type: AnswerComment
has text: Yes, absolutely the same.
score: 0

http://stackoverflow.com/comment/83742650
type: QuestionComment
comment on: http://stackoverflow.com/q/48273112
has text: @Fraz Which answer were you looking for?
score: 0
type: Comment

http://stackoverflow.com/q/48211105
has comment: http://stackoverflow.com/comment/83403594
linked to: http://stackoverflow.com/q/1832940
score: 1
has comment: http://stackoverflow.com/comment/83403419
tagged with: python
has comment: http://stackoverflow.com/comment/83403604
has body: In python2, if I want to print something like: print 'enrollment:' + str(len(enrollment)) print 'submissions:' + str(len(submissions)) I need to output the title and the length ; tried to format: print ('%d:' + str(len('%d'))) %enrollment which gives me: "TypeError: %d format: a number is required, not dict" BTW both "enrollment" and "submissions" are variables storing dictionary Is there a way to apply a placeholder for both string and the variable name?
has comment: http://stackoverflow.com/comment/83403758
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/48211340
has title: Placehold for variable names in python2
has comment: http://stackoverflow.com/comment/83403378
has answer: http://stackoverflow.com/a/48211340
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83403541
possible better answer: http://stackoverflow.com/a/48211713
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48211713

http://stackoverflow.com/comment/83498072
type: AnswerComment
comment on: http://stackoverflow.com/a/48257510
type: Comment
has text: Just used the code you made and no luck again. Still shows my username in their tweet.
score: 0

http://stackoverflow.com/comment/83527660
comment on: http://stackoverflow.com/q/48271675
score: 0
type: Comment
has text: What you will not be able to do in your first example is to import `mydir.test` from outside. The linked questions explain that in Python 3 you have to use explicit relative (or absolute) imports for [intra-package references](https://docs.python.org/3/tutorial/modules.html#intra-package-references) (compare to the same part of Python 2 docs).
type: QuestionComment

pybrain
type: Tag
tag name: pybrain
tags question: http://stackoverflow.com/q/48206159

http://stackoverflow.com/comment/83477703
type: AnswerComment
has text: `*` means something like "content"; a long time ago the default API output used XML, and the text was inside `<wikitext>`, and the JSON output needed to differentiate between the contents of that tag and attributes in that tag and ended up with an object containing the attributes as fields and the content as the `*` field. You can get a less convoluted output using [`formatversion=2`](https://en.wikipedia.org/w/api.php?action=parse&prop=wikitext&format=jsonfm&formatversion=2&page=norway&section=7).
score: 0
comment on: http://stackoverflow.com/a/48175848
type: Comment

http://stackoverflow.com/q/48277271
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/83537945
answer count: 1
tagged with: loops
has title: how to get from previous for loop value(hard to title)
accepted answer: http://stackoverflow.com/a/48277391
has comment: http://stackoverflow.com/comment/83538010
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83538021
has answer: http://stackoverflow.com/a/48277391
has comment: http://stackoverflow.com/comment/83537949
has comment: http://stackoverflow.com/comment/83538056
has body: Hey guys I am newbie in Python , hope for some help here :) My question is how to make for loop like this : for x in range(5): print x + value which i got in previous loop Maybe I am not super clear here so I will try to explain for loop is going to print for me numbers 0,1,2,3,4 , right? So what i want is every time it will print a value for example "3" it will plus previous one which in this case "2". Anybody can help me to explain how to do that ? I am newbie in coding , so please be easy on me :D Thank you!
score: -2
has comment: http://stackoverflow.com/comment/83538994
has comment: http://stackoverflow.com/comment/83537903
tagged with: python
has comment: http://stackoverflow.com/comment/83537927
type: AnsweredQuestion
tagged with: for-loop

http://stackoverflow.com/q/48310216
tagged with: pandas
has answer: http://stackoverflow.com/a/48310316
has comment: http://stackoverflow.com/comment/83606340
has comment: http://stackoverflow.com/comment/83606414
favorite count: 0
has comment: http://stackoverflow.com/comment/83606377
has answer: http://stackoverflow.com/a/72039601
type: Question
has comment: http://stackoverflow.com/comment/83606767
accepted answer: http://stackoverflow.com/a/48310316
has answer: http://stackoverflow.com/a/48310277
possible better answer: http://stackoverflow.com/a/48310277
tagged with: division
tagged with: python
has title: pandas dividing rows by its total
has body: I have this df: Name num1 num2 num3 A 1 2 3 B 4 5 6 C 7 8 9 My goal is to divide each row by the total. This is what I came up with: df.loc[:,"num1":"num3"] = df.loc[:,"num1":"num3"].div(df["total"], axis=0) It works well. However, if there are more "numx" columns added in after num3, I would have to manually update the code to "num1":"numx". Is there a way to work around this?
type: AnsweredQuestion
upvote count: 3
score: 3
linked to: http://stackoverflow.com/q/44241521
tagged with: row
answer count: 3
downvote count: 0

http://stackoverflow.com/q/48294492
has comment: http://stackoverflow.com/comment/83640550
linked to: http://stackoverflow.com/q/35159967
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83640431
has title: Where to put Google Cloud client/service account secret json file?
favorite count: 0
has answer: http://stackoverflow.com/a/59845267
tagged with: http://stackoverflow.com/tag/json
has body: So I have the following code in my project flow = flow_from_clientsecrets(client_secrets_file, scope=flow_scope, redirect_uri='urn:ietf:wg:oauth:2.0:oob') Which reads from a client_secret.json file in order for me to use Google Cloud API. Here's another piece of code that sets an environment variable for Google Cloud Storage. os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.join(dir, '../config/service_account.json') Normally, I would put these info in environment variables, but I don't know how to do that with json files. Where should I put these files or how should I alter them so that I can safely push my code online without revealing my credentials? Any help is appreciated.
tagged with: python
tagged with: secret-key
score: 4
tagged with: google-cloud-storage
type: Question
upvote count: 4
tagged with: google-cloud-platform
type: UnansweredQuestion

http://stackoverflow.com/a/52532776
upvote count: 8
has body: Just to ellaborate on Seans answer: It can be done quite easily using the python-telegram-bot library. Whenever the location did update it can be found in update.edited_message. This only works if the user is manually sharing live location with the bot of course. def location(bot, update): message = None if update.edited_message: message = update.edited_message else: message = update.message current_pos = (message.location.latitude, message.location.longitude) location_handler = MessageHandler(Filters.location, location) dispatcher.add_handler(location_handler)
has comment: http://stackoverflow.com/comment/103478565
type: Answer
score: 7
downvote count: 1
answers question: http://stackoverflow.com/q/48238445

http://stackoverflow.com/a/48289710
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48283090
score: 1
upvote count: 1
has body: I solved this by using saturate_cast(). It appears that the uint8 --> float32 or float32 --> uint8 conversion (I suspect the latter) led to an overflow. The fixed section of code is image_as_float = tf.saturate_cast(image, dtype = tf.float32) image_4d = tf.expand_dims(image_as_float, 0) # Add in a batch dimension (of size 1) bb_2d = tf.expand_dims(bb, 0) # Add in dimension of size 1 (num_bounding_boxes) bb_3d = tf.expand_dims(bb_2d, 0) # Add in dimension of size 1 (batch) bb_image = tf.image.draw_bounding_boxes(image_4d, bb_3d) bb_image_uint = tf.saturate_cast(bb_image, dtype = tf.uint8) Thanks to de1 for the suggestion, which came just as I was testing the fixed code.

http://stackoverflow.com/comment/83417039
score: 0
type: AnswerComment
has text: Think I may have been a bit brief in my question and not mentioned that I needed the product advertising API. I’m assuming this is an AWS api and not the product API, right?
comment on: http://stackoverflow.com/a/48217376
type: Comment

http://stackoverflow.com/comment/83488689
type: QuestionComment
comment on: http://stackoverflow.com/q/48224513
score: 0
type: Comment
has text: I was able to resolve this problem and it had got to do with the building of the gtest library. I was not building it properly and when I did it properly, the above script worked fine. Thanks for the support!

http://stackoverflow.com/a/48274304
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/129817139
accepted answer of: http://stackoverflow.com/q/48274259
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48274259
has body: You need MultiIndex here df=pd.DataFrame(np.random.randint(0,100,size=(10, 4)), columns=list('ABCD')) df.columns=pd.MultiIndex.from_product([['Sep'],df.columns]) df Out[666]: Sep A B C D 0 33 91 64 27 1 46 5 32 40 2 64 55 13 13 3 65 80 82 64 4 78 21 55 10 5 15 15 55 32 6 65 18 11 30 7 32 37 83 8 8 82 59 2 87 9 9 69 56 70
score: 5

http://stackoverflow.com/comment/83519457
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48265876
has text: In fact the problem comes from the structure of the CNN, there are problem in the size of layer. I try to use the deep mnist tutorial and modify the shape according to the input image (224x172). So how should be the internal structure of the CNN with my input?
type: Comment

http://stackoverflow.com/comment/83411556
has text: @CrisLuengo Yeah, I just need to add cmap = 'gray' to plt.show() to have it output in black and white.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48213278

http://stackoverflow.com/q/48218897
tagged with: concurrent.futures
favorite count: 0
tagged with: python-multiprocessing
type: Question
tagged with: process-pool
possible better answer: http://stackoverflow.com/a/49880788
score: 5
upvote count: 5
has title: Python doctest hangs using ProcessPoolExecutor
has answer: http://stackoverflow.com/a/49880788
has body: This code runs fine under regular CPython 3.5: import concurrent.futures def job(text): print(text) with concurrent.futures.ProcessPoolExecutor(1) as pool: pool.submit(job, "hello") But if you run it as python -m doctest myfile.py, it hangs. Changing submit(job to submit(print makes it not hang, as does using ThreadPoolExecutor instead of ProcessPoolExecutor. Why does it hang when run under doctest?
tagged with: python
has answer: http://stackoverflow.com/a/49789623
accepted answer: http://stackoverflow.com/a/49789623
answer count: 4
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86770820
has answer: http://stackoverflow.com/a/48221001
has answer: http://stackoverflow.com/a/49781577
tagged with: doctest

http://stackoverflow.com/q/48242369
has comment: http://stackoverflow.com/comment/83467316
tagged with: math
has answer: http://stackoverflow.com/a/48242587
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48242587
upvote count: 2
has title: Mathematical approach to derive function
tagged with: algorithm
tagged with: function
has comment: http://stackoverflow.com/comment/83467961
score: -3
downvote count: 5
tagged with: python
has body: I have a data sheet which lots of data, all spread out over several columns. The data extracted below will show the problem I am facing: This table represents changes in an inventory system. Positive amount changes mean new items were added to the inventory and the item price for these are known. The item price equals the import purchasing price. When an order was made, the corresponding amount change is negative, and the price is unknown. The algorithm should fill in these unknown prices. The items that have been the longest in stock should be sold first, at the same price they were bought. Once such a batch is depleted, the next batch should be used to determine the price of a sale. For example, in row 3, 3 items were sold, and we are left with 9 items in the inventory. We know by looking at the data, that the single item price for these 3 products is 49.55. But of course, it starts to get more complicated as items have been added and subtracted: Take the last row. At that moment, the first batch (at 49.55) has already been sold completely. The next batch (at 48.25) only has 2 items -- not enough for the 7 that are ordered. The batch after that (at 47.23) has enough to provide for the remaining 5 items. The price per item should thus be a weighted average of these two prices. So now, I am looking for a function or algorithm to determine the item price that should be used when an order was placed.
has comment: http://stackoverflow.com/comment/83467299
has comment: http://stackoverflow.com/comment/83467223
type: AnsweredQuestion

http://stackoverflow.com/q/48261569
has comment: http://stackoverflow.com/comment/83506068
has comment: http://stackoverflow.com/comment/83506099
has comment: http://stackoverflow.com/comment/83505975
downvote count: 0
has answer: http://stackoverflow.com/a/48261775
upvote count: 1
has comment: http://stackoverflow.com/comment/83506181
score: 1
answer count: 1
favorite count: 0
has body: I am creating a very simple Rock, Paper, Scissors game, using Python, but can't get past this problem. Every time I type in the answers into Command Prompt, it outputs the message 'Invalid input, try again!' which is what I have told it to do if there is an invalid input. But, I am not putting an invalid input in, this keeps printing out instead of 'Rock wins!' etc. And the 'Do you want to play again? (True or False)' prints out before the answer, and when I type True, it comes up with the Invalid input. I have tried moving around the rematch line, but nothing is working. Here is the game, showing the error: What's your name? Bob And your name? Bill Bob, Do you want to choose rock, paper, or scissors? rock Bill, Do you want to choose rock, paper, or scissors? paper Do you want to play again? (True or False) True Invalid input, try again! Here is my code: import sys user1 = input('What\'s your name?') user2 = input('And your name?') user1_answer = input('%s, Do you want to choose rock, paper, or scissors?' % user1) user2_answer = input('%s, Do you want to choose rock, paper, or scissors?' % user2) def compare(u1, u2): if u1 == u2: return('It\'s a tie!') elif u1 == 'rock': if u2 == 'scissors': return('Rock wins!') else: ('Paper wins!') elif u1 == 'scissors': if u2 == 'rock': return('Rock wins!') else: ('Paper wins!') elif u1 == 'scissors': if u2 == 'paper': return('Scissors wins!') else: ("Rock wins!") elif u1 == 'paper': if u2 == 'scissors': return('Scissors wins!') else: ('Rock wins!') elif u1 == 'paper': if u2 == 'rock': return('Paper wins!') else: ('Scissors wins!') elif u1 == 'rock': if u2 == 'paper': return('Paper wins!') else: ('Scissors wins!') else: return('Invalid input, try again!') rematch = bool(input('Do you want to play again? (True or False)')) print(compare(user1_answer, user2_answer))
has comment: http://stackoverflow.com/comment/83505834
has comment: http://stackoverflow.com/comment/83505821
type: Question
accepted answer: http://stackoverflow.com/a/48261775
has comment: http://stackoverflow.com/comment/83505957
tagged with: python
has comment: http://stackoverflow.com/comment/83505798
has title: Rock, Paper, Scissors Issue
has comment: http://stackoverflow.com/comment/83506033
type: AnsweredQuestion

http://stackoverflow.com/comment/83495949
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48256374
has text: I see, though with this implementation I'm not passing values to the thread, rather updating the instance's values from within the thread.
type: QuestionComment

http://stackoverflow.com/comment/83566529
has text: Unfortunately I'm drawing data locally from csv files.
score: 0
comment on: http://stackoverflow.com/q/48290687
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83434109
score: 0
has text: Please show the full traceback
type: Comment
comment on: http://stackoverflow.com/q/48226225
type: QuestionComment

deep-learning
tags question: http://stackoverflow.com/q/48274941
tags question: http://stackoverflow.com/q/48217119
tags question: http://stackoverflow.com/q/48219272
tags question: http://stackoverflow.com/q/48216772
tags question: http://stackoverflow.com/q/48265926
tags question: http://stackoverflow.com/q/48230786
tags question: http://stackoverflow.com/q/48309346
tags question: http://stackoverflow.com/q/48222433
tags question: http://stackoverflow.com/q/48315094
tags question: http://stackoverflow.com/q/48274929
tags question: http://stackoverflow.com/q/48251943
tags question: http://stackoverflow.com/q/48285129
tags question: http://stackoverflow.com/q/48219296
tags question: http://stackoverflow.com/q/48257255
tags question: http://stackoverflow.com/q/48245651
tags question: http://stackoverflow.com/q/48231457
type: Tag
tags question: http://stackoverflow.com/q/48270395
tags question: http://stackoverflow.com/q/48311807
tags question: http://stackoverflow.com/q/48220660
tags question: http://stackoverflow.com/q/48247301
tags question: http://stackoverflow.com/q/48309322
tags question: http://stackoverflow.com/q/48282762
tags question: http://stackoverflow.com/q/48192342
tags question: http://stackoverflow.com/q/48264676
tags question: http://stackoverflow.com/q/48230031
tags question: http://stackoverflow.com/q/48272913
tags question: http://stackoverflow.com/q/48216137
tags question: http://stackoverflow.com/q/48247771
tags question: http://stackoverflow.com/q/48271513
tags question: http://stackoverflow.com/q/48303166
tags question: http://stackoverflow.com/q/48259511
tags question: http://stackoverflow.com/q/48211346
tags question: http://stackoverflow.com/q/48241486
tag name: deep-learning
tags question: http://stackoverflow.com/q/48238656
tags question: http://stackoverflow.com/q/48253906
tags question: http://stackoverflow.com/q/48324152
tags question: http://stackoverflow.com/q/48327962
tags question: http://stackoverflow.com/q/48252481
tags question: http://stackoverflow.com/q/48238227
tags question: http://stackoverflow.com/q/48231233
tags question: http://stackoverflow.com/q/48197871
tags question: http://stackoverflow.com/q/48253841

http://stackoverflow.com/a/48215060
type: Answer
has comment: http://stackoverflow.com/comment/83414526
has body: I'm not sure if the setup from the question using a while loop and plt.ion() is actually supposed to work. At least for me using python 2.7 and matplotlib 2.1 it doesn't. I would have though that this is to be expected, because the application freezes and becomes unresponsive as long as it waits for user input. In any case, since it is always a bit delicate to mix the console and a GUI application, I would choose to work completely inside the event loop of the GUI. You may connect "key_press_event"s to the "1" and "q" key and show new data inside the open matplotlib window. import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=(6,6)) ax = plt.subplot(111) def plot_data(ax, data): ax.clear() ax.plot(data) ax.figure.canvas.draw_idle() def press(event=None): if event: if event.key == "1": data = np.random.choice(1000,100, replace = False) plot_data(ax, data) elif event.key == "q": plt.close() cid= fig.canvas.mpl_connect("key_press_event", press) plt.show() In case you want to create several figures, this would look like import matplotlib.pyplot as plt import numpy as np def create_figure(data): fig, ax = plt.subplots(figsize=(6,6)) ax.plot(data) cid = fig.canvas.mpl_connect("key_press_event", press) fig.show() def plot_data(): data = np.random.choice(1000,100, replace = False) create_figure(data) def press(event=None): if event: if event.key == "1": plot_data() elif event.key == "q": plt.close("all") else: plot_data() press() plt.show() For more complicated input, you may create a small GUI, which collects the input and calls the function for plotting. As an example, one may use Tkinter for that purpose. from Tkinter import * # use from tkinter import * if using python3 import matplotlib.pyplot as plt import numpy as np def create_figure(data): fig, ax = plt.subplots(figsize=(6,6)) ax.plot(data) fig.show() def plot_data(n, amp): try: n = int(n) amp = float(amp) data = amp*np.random.rand(n) create_figure(data) except: pass def closeall(): for i in …
has comment: http://stackoverflow.com/comment/83415473
has comment: http://stackoverflow.com/comment/83447860
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48198334
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83415280
answers question: http://stackoverflow.com/q/48198334
has comment: http://stackoverflow.com/comment/83431353
has comment: http://stackoverflow.com/comment/83415434
has comment: http://stackoverflow.com/comment/83415368
score: 1
has comment: http://stackoverflow.com/comment/83413925

http://stackoverflow.com/comment/83362238
comment on: http://stackoverflow.com/q/48190973
type: Comment
type: QuestionComment
has text: show us your expected out put
score: 0

http://stackoverflow.com/comment/83469634
has text: I've added a link to the full source code,
comment on: http://stackoverflow.com/q/48242383
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48272772
has title: How to change the data output received externally in realtime within a program's text window?
tagged with: tkinter
has body: I have been reluctant to ask this question - I have been trying to solve it and have looked everywhere! So, I run a company where we have several third parties emailing us with notifications of sales - all to different addresses. Each email to us is exactly one sale. The issue is that nowhere in the office is it possible to see the current total of sales (submissions) for that moment. I have been dying to learn Python since I was young so I figured that I would find a cool way to graphically display a sort of ticker that has a big number on a screen that we can hang on a wall in the office for everyone to see, via a Raspberry Pi and an LCD. But my gawd is this tough to do. Outside of Python, it's all good to go, I have figured out the emailing to one inbox and I have managed to set a timer on our Gmail to mark the reads after 24hrs. The problem I am having is that I really want the program to update its counting of the unreads in real-time automatically without scrolling forever down the screen. I have looked everywhere, loops don't seem to refresh the number on the window, nothing works apart from restarting the program again which is not automated and requires myself to start the program again. So, please, any help on this would be great. I plan to add graphics later, and maybe a little sound that goes ping or CHaaaChing when a sale comes in, but I thought I'd get this hard stuff out of the way first. Here is my code: #! /usr/bin/env python3.4 import imaplib import email from tkinter import * root = Tk() def window(main): main.title('submissions counter') width = 500 height = 500 x = (main.winfo_screenwidth() //2 ) - (width // 2) y = (main.winfo_screenheight() //2 ) - (height // 2) main.geometry('{}x{}+{}+{}'.format(width, height, x, y)) mail=imaplib.IMAP4_SSL('imap.gmail.com',993) mail.login('email@gmail.com','Password') mail.select("Submissions") typ, messageIDs = mail.search(None, "UNSEEN") messageIDsString = str( messageIDs[0], encoding='utf8' ) listOfSplitStr…
linked to: http://stackoverflow.com/q/18089506
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48276807
accepted answer: http://stackoverflow.com/a/48276807
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83529490
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83536683
favorite count: 0
type: Question

http://stackoverflow.com/comment/83528359
comment on: http://stackoverflow.com/q/48272315
score: 0
type: Comment
type: QuestionComment
has text: `re.sub(r"\/", "/", soup)`

http://stackoverflow.com/comment/83764793
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ Yes, I know ;) I want to give some more buffer time for others and see if I get better approaches. Else I will surely accept the best solution! Thanks
score: 0
comment on: http://stackoverflow.com/q/48245987
type: Comment

http://stackoverflow.com/comment/83592772
type: AnswerComment
has text: @KamilZabielski: yes. Slicing just creates a new string. replacing tests the input string (which is always there). Moreover, you would need a regex or if the pattern is somewhere else in the string, it could be replaced twice.
comment on: http://stackoverflow.com/a/48303793
type: Comment
score: 0

http://stackoverflow.com/a/55526862
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/48178884
has body: You are trying to min-max scale between 0 and 1 only the second column. Using sklearn.preprocessing.minmax_scale, should easily solve your problem. e.g.: from sklearn.preprocessing import minmax_scale column_1 = foo[:,0] #first column you don't want to scale column_2 = minmax_scale(foo[:,1], feature_range=(0,1)) #second column you want to scale foo_norm = np.stack((column_1, column_2), axis=1) #stack both columns to get a 2d array Should yield array([[0. , 0. ], [0.13216 , 0.06609523], [0.25379 , 1. ], [0.30874 , 0.09727968]]) Maybe you want to min-max scale between 0 and 1 both columns. In this case, use: foo_norm = minmax_scale(foo, feature_range=(0,1), axis=0) Which yields array([[0. , 0. ], [0.42806245, 0.06609523], [0.82201853, 1. ], [1. , 0.09727968]]) note: Not to be confused with the operation that scales the norm (length) of a vector to a certain value (usually 1), which is also commonly referred to as normalization.
upvote count: 6
type: Answer

http://stackoverflow.com/a/48220791
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48220717
accepted answer of: http://stackoverflow.com/q/48220717
type: Answer
has comment: http://stackoverflow.com/comment/83423570
has comment: http://stackoverflow.com/comment/83423440
has body: Firstly, you should be saving to MEDIA_ROOT. Secondly, you need to put an actual URL - ie relative to MEDIA_URL - in your img src, not just a filename. Third, you need to have something serving files at that URL.

http://stackoverflow.com/comment/83349873
type: QuestionComment
has text: @ZayajungC By appending them to a list?
type: Comment
comment on: http://stackoverflow.com/q/48184374
score: 1

http://stackoverflow.com/comment/83517059
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48265667
has text: Pl tell me if this keyword is right!! (we dont have access to execute thats the reason) Select Required Tenant Groups [Documentation] Clicks on Checkbox button to select the given value [Arguments] @{Tenant_Groups_To_Select} :For ${item} IN RANGE @{Tenant_Groups_To_Select} \ Selenium2Library.Select Checkbox //*[@id="ctl00_PageBody_TenantsList"]/tbody/tr/td/label[normalize-space(text())='${item}']/preceding-sibling::input

http://stackoverflow.com/a/48331236
accepted answer of: http://stackoverflow.com/q/48330855
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/48330855
downvote count: 0
type: AcceptedAnswer
has body: There are several options here: Pass your code as a multi-line string. Note that " is used to delimit Python strings rather than the original ' here for the sake of simplicity: A POSIX-compatible mechanism to embed a literal ' in a single-quoted string is possible, but quite ugly. extractImageIds() { python -c ' import sys, json for image in json.load(sys.stdin)["Images"]: print image["ImageId"] ' "$@" } Use bash's C-style escaped string syntax ($'') to embed newlines, as with $'\n'. Note that the leading $ is critical, and that this doesn't work with /bin/sh. See the bash-hackers' wiki on ANSI C-like strings for details. extractImageIds() { python -c $'import sys, json\nfor image in json.load(sys.stdin)["Images"]:\n\tprint image["ImageId"]' "$@"; } Use __import__() to avoid the need for a separate import command. extractImageIds() { python -c 'for image in __import__("json").load(__import__("sys").stdin)["Images"]: print image["ImageId"]' "$@"; } Pass the code on stdin and move the input onto argv; note that this only works if the input doesn't overwhelm your operating system's allowed maximum command-line size. Consider the following example: extractImageIds() { # capture function's input to a variable local input=$(&lt;/dev/stdin) || return # ...and expand that variable on the Python interpreter's command line python - "$input" "$@" &lt;&lt;'EOF' import sys, json for image in json.loads(sys.argv[1])["Images"]: print image["ImageId"] EOF } Note that $(&lt;/dev/stdin) is a more efficient bash-only alternative to $(cat); due to shell builtin support, it works even on operating systems where /dev/stdin doesn't exist as a file. All of these have been tested as follows: extractImageIds &lt;&lt;&lt;'{"Images": [{"ImageId": "one"}, {"ImageId": "two"}]}' To efficiently provide stdin from a variable, one could run extractImageIds &lt;&lt;&lt;"$variable" instead. Note that the "$@" elements in the wrapper are there to ensure that sys.argv is populated with arguments to the …

http://stackoverflow.com/q/48175219
has body: I am trying to parse information from the output of multiple interfaces from a Cisco router. My goal is a dictionary where i can use named regex captures to pull out required information. I have tried using predefined sub patterns using the Python PyPi regex module but am having issues getting multiple named captures per match. Ideally, i would like to have all items captured to a single match per interface: Match 1: Interface: x/x/x/1 MTU: 1234 BIA: x.x.x.1 Match 2: Interface: x/x/x/2 MTU: 4321 BIA: x.x.x.2 And so on for every interface i have in my output. Here is my regex that i have so far, its working great until i try to capture any additional output. Once i add regex to match other items (ie. MTU) i no longer get any matches. What am I missing? (?(DEFINE) (?&lt;intfs&gt;) (?&lt;mtus&gt;) (?&lt;end&gt;^$|\Z) ) ^(?P&lt;intf&gt;(?&amp;intfs)[Gig|Ten|Hun]\S+) MTU\ (?P&lt;mtu&gt;\d+)(?&amp;mtus) (?P&lt;misc&gt;(?!^$)[\s\S]+?) (?&amp;end) Test string: TenGigE0/1/0/0 is up, line protocol is up Interface state transitions: 7 Hardware is TenGigE, address is 0026.982f.6fc0 (bia 0026.982f.6fc0) Layer 1 Transport Mode is LAN Description: LAB1 Internet address is 172.25.26.1/31 MTU 9172 bytes, BW 10000000 Kbit (Max: 10000000 Kbit) reliability 255/255, txload 62/255, rxload 192/255 HundredGigE0/1/0/1 is up, line protocol is up Interface state transitions: 1 Hardware is TenGigE, address is 0026.982f.6fc1 (bia 0026.982f.6fc1) Layer 1 Transport Mode is LAN Description: LAB2 Internet address is 172.25.25.1/31 MTU 9192 bytes, BW 10000000 Kbit (Max: 10000000 Kbit) reliability 255/255, txload 150/255, rxload 20/255 Goal: {'interfaces': {'HundredGigE0/1/0/1': {'IP Address': '172.25.25.1/31', 'MTU': '9192', 'bia': '0026.982f.6fc1'}, 'TenGigE0/1/0/0': {'IP Address': '172.25.26.1/31', 'MTU': '9172', 'bia': '0026.982f.6fc0'}}}
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/48184526
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83332571
has comment: http://stackoverflow.com/comment/83332724
answer count: 1
has comment: http://stackoverflow.com/comment/83332340
upvote count: 1
has comment: http://stackoverflow.com/comment/83332189
downvote count: 1
favorite count: 0
type: Question
has title: Parse Cisco interfaces using regex/python
has answer: http://stackoverflow.com/a/48184526
has comment: http://stackoverflow.com/comment/83333494

http://stackoverflow.com/q/48240345
tagged with: python
score: 0
has title: Error while using threads to scrape a website
tagged with: multithreading
answer count: 1
tagged with: web-scraping
type: Question
has answer: http://stackoverflow.com/a/48240500
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/2333400
has body: I am trying to build a bot that will scrap the purchase history of purchased domains. So far I was able to extract the domain from the csv file and store them into a list (PS: there are 10k domains). The problem accures when I am trying to scrap the website with them. I have tried doing this with two domains and it works perfectly. Does anyone know what error is this and how I can fix it? Thank you very much in advance. my code: datafile = open('/Users/.../Documents/Domains.csv', 'r') myreader = csv.reader(datafile, delimiter=";",) domains = [] for row in myreader: domains.append(row[1]) del domains[0] print("The Domains have been stored into a list") nmb_sells_record = 0 def result_catcher(domains,queue): template_url = "https://namebio.com/{}".format(domain) get = requests.get(template_url) results = get.text last_sold = results[results.index("last sold for ")+15:results.index(" on 2")].replace(",","") last_sold = int(last_sold) if not "No historical sales found." in results: sold_history = results[results.index(""):results.index(" USD on <span class=\"label")] queue.put(results) #domains = ["chosen.com","koalas.com"] queues = {} nmb=0 for x in range(len(domains)): new_queue = "queue{}".format(nmb) queues[new_queue] = queue.Queue() nmb += 1 count = 0 for domain in domains: for queue in queues: t = threading.Thread(target=result_catcher, args=(domain,queues[queue])) t.start() print("The Requests were all sent, now they are beeing analysed") for queue in queues: response_domain = queues[queue].get() nmb_sells_record = response_domain.count("for $") + response_domain.count("USD") print("The Bot has recorded {} domain sells".format(nmb_sells_record)) The output of my code: Exception in thread Thread-345: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/urllib3/connection.py", line 141, in _new_conn (self.host, self.port), self.timeout, **extra_kw) File "/Library/Frameworks/Python.framework/Versions/…

http://stackoverflow.com/comment/83525771
comment on: http://stackoverflow.com/a/48271006
type: Comment
score: 0
type: AnswerComment
has text: This is not how the OP is currently using `self.median`, but this is the correct way to do what the OP wants to do.

http://stackoverflow.com/q/48211174
tagged with: anaconda
answer count: 5
tagged with: python
possible better answer: http://stackoverflow.com/a/63534360
has answer: http://stackoverflow.com/a/48212099
accepted answer: http://stackoverflow.com/a/48212099
has answer: http://stackoverflow.com/a/63534360
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/54195188
has answer: http://stackoverflow.com/a/50775003
downvote count: 0
score: 8
upvote count: 8
favorite count: 0
has body: I have an Anaconda virtual environment in which I have a lot of Python packages installed multiple times, often in different versions, for example: $ conda list ... singledispatch 3.4.0.3 py35_0 sip 4.18 py35_0 six 1.10.0 &lt;pip&gt; six 1.11.0 &lt;pip&gt; six 1.10.0 py35_0 snowballstemmer 1.2.1 py35_0 sockjs-tornado 1.0.3 py35_0 sphinx 1.5.4 py35_0 spyder 3.1.3 py35_0 sqlalchemy 1.1.9 py35_0 sqlite 3.13.0 0 statsmodels 0.8.0 np111py35_0 sympy 1.0 py35_0 tensorflow-gpu 1.3.0 &lt;pip&gt; tensorflow-gpu 1.0.1 &lt;pip&gt; tensorflow-tensorboard 0.1.6 &lt;pip&gt; terminado 0.6 py35_0 testpath 0.3 py35_0 Theano 0.9.0 &lt;pip&gt; tk 8.5.18 0 toolz 0.8.2 py35_0 tornado 4.4.2 py35_0 tqdm 4.11.2 &lt;pip&gt; tqdm 4.15.0 py35_0 traitlets 4.3.2 py35_0 unicodecsv 0.14.1 py35_0 wcwidth 0.1.7 py35_0 werkzeug 0.12.1 py35_0 Werkzeug 0.12.2 &lt;pip&gt; wheel 0.29.0 &lt;pip&gt; wheel 0.30.0 &lt;pip&gt; wheel 0.29.0 py35_0 ... I don't know how I got to this state, but how can I safely get rid of the duplicate packages? Also, if a program imports the six package, how does Python determine which version to import? EDIT: I know now where the problem came from. I probably installed some packages using pip's --ignore-installed option. Am I fine with all the duplicates being installed like this or should I get rid of them?
type: Question
has title: Anaconda: How to safely remove duplicate packages
has answer: http://stackoverflow.com/a/53402138
has comment: http://stackoverflow.com/comment/83405103

http://stackoverflow.com/q/48283048
has title: finding the max integer from scattered data types, Python
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48283175
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83549987
has body: I'm trying to find the largest value and put it in a column from each row. Per the below, there is a scatter of strings, NaNs and integers. I guess just running the max function won't work due to the mix of data types. df['max']=df'team', 'so', 'ibb', 'hpb', 'sh', 'gidp'.max(axis=1) df2 so ibb hbp sh sf gidp year team 2008 DET 176.0 3.0 10.0 4.0 8.0 28.0 212.0 3.0 9.0 16.0 6.0 17.0 NaN 141.0 8.0 9.0 3.0 8.0 29.0 LAN 310.0 24 NYN 23.0 18.0 15.0 48.0 188.0 51.0 8 SFN 16.0 6.0 41.0 140.0 NaN 5.0 NaN 8.0 TEX 16.0 TOR 265.0 16.0 12.0 4.0 16.0 38.0
score: 0
tagged with: pandas

http://stackoverflow.com/q/48286431
has comment: http://stackoverflow.com/comment/83560840
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/83557595
has title: Seaborn distplot: unsupported operand type(s) for /: 'str' and 'int'
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48319476
has comment: http://stackoverflow.com/comment/83557479
tagged with: seaborn
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83558415
tagged with: python
has body: I have been tampering with this script for some time now and cannot seem to figure out what I am doing wrong. The script: import seaborn as sns import pandas as pd import matplotlib.pyplot as plt import numpy as np import glob # Load data set dataset = { 1:{"Oxy":[], "De-oxy":[]}, 2:{"Oxy":[], "De-oxy":[]}, 3:{"Oxy":[], "De-oxy":[]}, 4:{"Oxy":[], "De-oxy":[]}, 5:{"Oxy":[], "De-oxy":[]}, 6:{"Oxy":[], "De-oxy":[]}, 7:{"Oxy":[], "De-oxy":[]}, 8:{"Oxy":[], "De-oxy":[]}, 9:{"Oxy":[], "De-oxy":[]}, 10:{"Oxy":[], "De-oxy":[]}, 11:{"Oxy":[], "De-oxy":[]}, 12:{"Oxy":[], "De-oxy":[]}, 13:{"Oxy":[], "De-oxy":[]}, 14:{"Oxy":[], "De-oxy":[]}, 15:{"Oxy":[], "De-oxy":[]}, 16:{"Oxy":[], "De-oxy":[]}, 17:{"Oxy":[], "De-oxy":[]}, 18:{"Oxy":[], "De-oxy":[]}, 19:{"Oxy":[], "De-oxy":[]}, 20:{"Oxy":[], "De-oxy":[]}, 21:{"Oxy":[], "De-oxy":[]}, 22:{"Oxy":[], "De-oxy":[]}, 23:{"Oxy":[], "De-oxy":[]}, 24:{"Oxy":[], "De-oxy":[]}, 25:{"Oxy":[], "De-oxy":[]}, 26:{"Oxy":[], "De-oxy":[]}, 27:{"Oxy":[], "De-oxy":[]}, 28:{"Oxy":[], "De-oxy":[]}, 29:{"Oxy":[], "De-oxy":[]}, 30:{"Oxy":[], "De-oxy":[]}} oxy_files = glob.glob("/Users/gabagaba/Documents/MATLAB/Subject-output/Oxy/*.txt") deoxy_files = glob.glob("/Users/gabagaba/Documents/MATLAB/Subject-output/DeOxy/*.txt") for item in sorted(oxy_files): # Put all oxy readings in dataset_oxy with open(item) as file: content = "" for line in file: content = content + line.replace("\n", ",") items = content.split(',') count = 1 for i in items: if ( count &lt; 31 ): dataset[count]['Oxy'].append(i) else: pass count += 1 for item in sorted(deoxy_files): # Put all de-oxy readings in dataset_deoxy with open(item) as file: content = "" for line in file: content = content + line.replace("\n", ",") items = content.split(',') count = 1 for i in items: if ( count &lt; 31 ): dataset[count]['De-oxy'].append(i) else: pass count += 1 fig = plt.figure(figsize = (15,10)) ax = plt.gca() j = 1 for a in sorted(dataset.keys()): val = pd.DataFrame({'Oxy': dataset[a]['Oxy'], 'D…
has comment: http://stackoverflow.com/comment/83585541
has comment: http://stackoverflow.com/comment/83564886
has comment: http://stackoverflow.com/comment/83560788
tagged with: numpy
has comment: http://stackoverflow.com/comment/83587702
tagged with: pandas
upvote count: 2

http://stackoverflow.com/comment/83595146
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48305006
has text: This would result in the problem that if you write `'a' if 0 > 1 else 'b' if 1 > 2 else 'c'` would be ambiguous to parse.
score: 1

http://stackoverflow.com/q/48179297
tagged with: dataframe
tagged with: python
upvote count: 19
has comment: http://stackoverflow.com/comment/83338808
type: AnsweredQuestion
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/83338745
accepted answer: http://stackoverflow.com/a/48179385
answer count: 1
tagged with: reindex
tagged with: multi-index
score: 19
favorite count: 0
type: Question
has body: I have a DataFrame with two indices and would like to reindex it by one of the indices. from pandas_datareader import data import matplotlib.pyplot as plt import pandas as pd # Instruments to download tickers = ['AAPL'] # Online source one should use data_source = 'yahoo' # Data range start_date = '2000-01-01' end_date = '2018-01-09' # Load the desired data panel_data = data.DataReader(tickers, data_source, start_date, end_date).to_frame() panel_data.head() The reindexing goes as follows: # Get just the adjusted closing prices adj_close = panel_data['Adj Close'] # Gett all weekdays between start and end dates all_weekdays = pd.date_range(start=start_date, end=end_date, freq='B') # Align the existing prices in adj_close with our new set of dates adj_close = adj_close.reindex(all_weekdays, method="ffill") The last line gives the following error: TypeError: '&lt;' not supported between instances of 'tuple' and 'int' This is because the DataFrame index is a list of tuples: panel_data.index[0] (Timestamp('2018-01-09 00:00:00'), 'AAPL') Is it possible to reindex adj_close? By the way, if I don't convert the Panel object to a DataFrame using to_frame(), the reindexing works as it is. But it seems that Panel objects are deprecated...
has title: Reindexing a specific level of a MultiIndex dataframe
has answer: http://stackoverflow.com/a/48179385

http://stackoverflow.com/a/48206754
upvote count: 0
has body: import numpy as np from pyspark.ml.linalg import Vectors arr = np.array([[2,3], [2,8], [2,3],[4,5]]) df = np.concatenate(arr).reshape(1000,-1) dff = map(lambda x: (int(x[0]), Vectors.dense(x[1:])), df) mydf = spark.createDataFrame(dff,schema=["label", "features"]) mydf.show(5)
answers question: http://stackoverflow.com/q/48206622
has comment: http://stackoverflow.com/comment/83394499
downvote count: 1
type: Answer
score: -1

http://stackoverflow.com/comment/83547833
comment on: http://stackoverflow.com/q/48282109
type: Comment
type: QuestionComment
score: 6
has text: `if s:` checks whether `s` is a *Truthy* value - not whether it is specifically the value `True`. `s == True` checks whether it is the exact value `True` - which it isn't, it's a string (but evaluates to being *Truthy* since it is not empty).

http://stackoverflow.com/a/48236530
upvote count: 1
has body: Think about organizing your data this way (I've left off 2017-03-01 because you don't show prices for that date and it makes the example more concise): Date AAPL Return GOOG Return AAPL Weight GOOG Weight 2017-01-01 1.4 1.083 0.6 0.4 2017-02-01 0.7 1.077 0.7 0.3 Above, Return is (close price / open price). Now multiply for each stock: Date AAPL WgtRet GOOG WgtRet Sum WgtRet Cum WgtRet 2017-01-01 0.84 0.4332 1.2732 1.2732 2017-02-01 0.49 0.3231 0.8131 1.0352 Above, Sum WgtRet is like sum(axis=1), and Cum WgtRet is like cumprod(Sum WgtRet). Now, simply take your starting capital and multiply by Cum WgtRet to get the month-end balances: Date End Balance 2017-01-01 127320 2017-02-01 103520 Each of the above operations is easily done in vectorized form, without loops. You can "pivot" the stock column from row labels to column labels at the beginning. If you want to add the "Shares Bought" columns, just shift(1) the End Balance to make a Begin Balance column, and multiply by the weights.
answers question: http://stackoverflow.com/q/48236364
has comment: http://stackoverflow.com/comment/83455809
has comment: http://stackoverflow.com/comment/83455857
type: Answer
accepted answer of: http://stackoverflow.com/q/48236364
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48199096
accepted answer: http://stackoverflow.com/a/48220364
has title: Natural Language Calculator Conversion Issues
has answer: http://stackoverflow.com/a/48220364
has comment: http://stackoverflow.com/comment/83379588
type: Question
has body: I'm working on a small nlp project, which will basically take natural language and work with it. The aspect that I am dealing with is taking a fairly basic sentence, "I have 32 apples, 8 oranges, and 10 bananas." What I want to do with it, is search the string for integers, convert them to an array, and sum it. Here is what I currently have: import re import numpy as np myString = 'i have 32 apples, 8 oranges, and 10 bananas.' def evaluation (foo): numsineval = re.findall(r'\d+', foo) myarray = np.asarray(numsineval) yay = np.cumsum(myarray) print(yay) evaluation(myString) I have been banging my head against this wall for a couple days and would really love some help. Thanks! I have found an NLP calculator that other people have written, but am unable to decipher their code in such a way as to make it useful. If someone could help me out, I'd greatly appreciate it.
has answer: http://stackoverflow.com/a/48199248
tagged with: python
has comment: http://stackoverflow.com/comment/83379701
tagged with: calculator
tagged with: nlp
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48199248
type: AnsweredQuestion
score: 0
answer count: 2

pycharm
tags question: http://stackoverflow.com/q/48304718
tags question: http://stackoverflow.com/q/48283875
tags question: http://stackoverflow.com/q/48247091
tags question: http://stackoverflow.com/q/48209506
tags question: http://stackoverflow.com/q/48314549
tags question: http://stackoverflow.com/q/48205276
tags question: http://stackoverflow.com/q/48272860
tags question: http://stackoverflow.com/q/48290403
tags question: http://stackoverflow.com/q/48216438
tags question: http://stackoverflow.com/q/48267322
tags question: http://stackoverflow.com/q/48198573
tag name: pycharm
tags question: http://stackoverflow.com/q/48248816
tags question: http://stackoverflow.com/q/48201478
tags question: http://stackoverflow.com/q/48309356
tags question: http://stackoverflow.com/q/48192741
tags question: http://stackoverflow.com/q/48215763
tags question: http://stackoverflow.com/q/48229326
type: Tag
tags question: http://stackoverflow.com/q/48227892
tags question: http://stackoverflow.com/q/48256565
tags question: http://stackoverflow.com/q/48248634
tags question: http://stackoverflow.com/q/48184668
tags question: http://stackoverflow.com/q/48185422
tags question: http://stackoverflow.com/q/48202897
tags question: http://stackoverflow.com/q/48313654
tags question: http://stackoverflow.com/q/48274696
tags question: http://stackoverflow.com/q/48254689
tags question: http://stackoverflow.com/q/48238192
tags question: http://stackoverflow.com/q/48230706
tags question: http://stackoverflow.com/q/48275024

http://stackoverflow.com/comment/83498061
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48257301
has text: Thanks @Skycc, that worked like charm. Could you please post your this one liner simple answer for me to accept it?
score: 0

http://stackoverflow.com/a/48199305
accepted answer of: http://stackoverflow.com/q/48199221
has body: gourpby + cumcount+unstack df1=df.assign(n=df.groupby('Box').cumcount()).set_index(['Box','n']).unstack(1) df1.columns=df1.columns.map('{0[0]}{0[1]}'.format) df1 Out[141]: Code0 Code1 Category0 Category1 Box Blue 9820 4530 Active Active Green 1221 8391 Active Inactive Red 3709 2911 Inactive Pending
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48199221
has comment: http://stackoverflow.com/comment/83380947
has comment: http://stackoverflow.com/comment/83381088
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/48174398
has comment: http://stackoverflow.com/comment/83441694
linked to: http://stackoverflow.com/q/45426843
has comment: http://stackoverflow.com/comment/83328593
linked to: http://stackoverflow.com/q/43848680
has comment: http://stackoverflow.com/comment/83328467
has comment: http://stackoverflow.com/comment/83328482
type: AnsweredQuestion
has title: New Dataframe column as a generic function of other rows (pandas)
possible better answer: http://stackoverflow.com/a/48222049
has comment: http://stackoverflow.com/comment/83423030
tagged with: pandas
has comment: http://stackoverflow.com/comment/83329170
has answer: http://stackoverflow.com/a/48222049
has answer: http://stackoverflow.com/a/48221724
tagged with: dataframe
favorite count: 0
type: Question
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/83328788
accepted answer: http://stackoverflow.com/a/48221724
has comment: http://stackoverflow.com/comment/83329781
linked to: http://stackoverflow.com/q/48174484
downvote count: 0
has comment: http://stackoverflow.com/comment/83515770
has comment: http://stackoverflow.com/comment/83328592
tagged with: python
score: 4
has body: What is the fastest (and most efficient) way to create a new column in a DataFrame that is a function of other rows in pandas ? Consider the following example: import pandas as pd d = { 'id': [1, 2, 3, 4, 5, 6], 'word': ['cat', 'hat', 'hag', 'hog', 'dog', 'elephant'] } pandas_df = pd.DataFrame(d) Which yields: id word 0 1 cat 1 2 hat 2 3 hag 3 4 hog 4 5 dog 5 6 elephant Suppose I want to create a new column bar containing a value that is based on the output of using a function foo to compare the word in the current row to the other rows in the dataframe. def foo(word1, word2): # do some calculation return foobar # in this example, the return type is numeric threshold = some_threshold for index, _id, word in pandas_df.itertuples(): value = sum( pandas_df[pandas_df['word'] != word].apply( lambda x: foo(x['word'], word), axis=1 ) &lt; threshold ) pandas_df.loc[index, 'bar'] = value This does produce the correct output, but it uses itertuples() and apply(), which is not performant for large DataFrames. Is there a way to vectorize (is that the correct term?) this approach? Or is there another better (faster) way to do this? Notes / Updates: In the original post, I used edit distance/levenshtein distance as the foo function. I have changed the question in an attempt to be more generic. The idea is that the function to be applied is to compare the current rows value against all other rows and return some aggregate value. If foo was nltk.metrics.distance.edit_distance and the threshold was set to 2 (as in the original post), this produces the output below: id word bar 0 1 cat 1.0 1 2 hat 2.0 2 3 hag 2.0 3 4 hog 2.0 4 5 dog 1.0 5 6 elephant 0.0 I have the same question for spark dataframes as well. I thought it made sense to split these into two posts so they are not too broad. However, I have generally found that solutions to similar pandas problems can sometimes be modified to work for spark. Inspired by this answer to my spark version of this question, I tried to use a ca…
tagged with: vectorization

http://stackoverflow.com/comment/83327686
type: Comment
has text: You're not using `set()` on a list of tuples... check the result of your `map()` statement.
score: 0
comment on: http://stackoverflow.com/q/48174013
type: QuestionComment

matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/48200784
tags question: http://stackoverflow.com/q/48257845
tag name: matplotlib-basemap
tags question: http://stackoverflow.com/q/48204616
tags question: http://stackoverflow.com/q/48191593

http://stackoverflow.com/q/48230073
tagged with: python
has comment: http://stackoverflow.com/comment/83450393
type: AnsweredQuestion
score: 0
tagged with: pagination
type: Question
accepted answer: http://stackoverflow.com/a/48243414
has answer: http://stackoverflow.com/a/48243414
answer count: 1
has body: I have a job-object and a content-object. A job object gets created when a user wants to retrieve a set of content-objects in exchange for credits. models.py: class JobId(models.Model): user = models.ForeignKey(User, blank=True, null=True, default=None) job_time = models.DateTimeField(auto_now_add=True) class content(models.Model): job_id_list = models.ManyToManyField(JobId , related_name='JobId', blank=True) job_id_list_not_provided = models.ManyToManyField(JobId , related_name='JobIdFailed', blank=True) free_content = models.CharField(max_length=500, null=True, blank=True) paying_content = models.CharField(max_length=500, null=True, blank=True) For all content-objects part of the job, the JobId-object is added to the job_id_list - not keeping credit levels in mind. Different user can all run multiple jobs on the content objects. For too-big jobs exceeding the credit amount of the user, the content-objects that would push the credit level below zero, get also the JobID-object added to the job_id_list_not_provided field of the content-object. For a a specific user, we can retrieve the two sub-sets of found and not-found content-objects with following queries: views.py: found_results_list = results_list.filter(job_id_list_not_provided__user= None).distinct() not_found_results_list = results_list.filter(job_id_list_not_provided__user=request.user).distinct() My challenge: Result lists are over 100-objects in size, so I would like to use pagination to get a nice view on my page When not considering pagination, I could simply pass the 2 lists (found and not found) and loop over each list with a template from django: Html: {% for result in found_results_list %} {{result.free_content}} {{result.paying_content}} {% empty %} no result {% endfor %} {% for result in not_found_results_list %} {{result.free_content}} pay for the content {% empty %} no result {% endfor %} But what to do if I want to use pagination? It seems you can only use one result-list. views.py (I used .dis…
has title: Filter on variable of ManyToMany-field inside Django Template
tagged with: django

http://stackoverflow.com/a/48216375
type: Answer
score: 0
has body: Since my application is in python (Django App), I collected all the static files using "python manage.py collectstatic -c" and then mounted that directory (which contains these static files - /apps/test_app/static ) on the host server running both docker and nginx. The command I used to mount was docker run --net=host -v /static:/apps/test_app/static -d -p 8000:8000 image_id Here static is the directory on the host server where as /apps/test_app/static is directory inside the container. Once this is done, I added the following lines inside the nginx.conf or ssl.conf file location /static/ { # root /var/www/app/static/; alias /static/; autoindex off; } Followed by nginx restart and then that solved the problem.
answers question: http://stackoverflow.com/q/48198045

http://stackoverflow.com/comment/83572918
has text: the data is in sql file
type: AnswerComment
comment on: http://stackoverflow.com/a/48293646
score: 0
type: Comment

http://stackoverflow.com/comment/83373645
score: 0
has text: I'm still not sure I'd expect assignment to a single column to unpack values of strings. If you specify multiple columns with an equal number of values, then the best bet is that you want to unpack. If I _wanted_ a list in that column, how else could I do it with this syntax? Just don't give a single-item list. I can see it both ways.
comment on: http://stackoverflow.com/q/48195993
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83481040
score: 0
comment on: http://stackoverflow.com/q/48249159
type: Comment
type: QuestionComment
has text: @JCena Are you only trying to remove `yunny_tim_tam` and `berry_tim_tam` from `temp`? Or are their other words your trying to remove? Could you not just add everything and filter out what you don't want at the end of the loop? Or you could have some sort of pre-checking beforehand so you never add them to begin with.

http://stackoverflow.com/comment/83615758
has text: @cricket_007 Like Saint Thomas... https://vgy.me/UWil4G.png
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48311185

http://stackoverflow.com/comment/83648416
score: 0
comment on: http://stackoverflow.com/q/48326732
type: QuestionComment
has text: Nice, that worked like a charm! Thank you.
type: Comment

http://stackoverflow.com/comment/83476569
score: 0
type: Comment
has text: Or, `df.at['Header I, II and III; x', 2]`
type: QuestionComment
comment on: http://stackoverflow.com/q/48246955

http://stackoverflow.com/q/48188978
has comment: http://stackoverflow.com/comment/83384030
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83359235
answer count: 1
tagged with: selenium
downvote count: 0
score: 6
linked to: http://stackoverflow.com/q/70351421
tagged with: logging
favorite count: 0
has comment: http://stackoverflow.com/comment/83357917
has answer: http://stackoverflow.com/a/48198116
has comment: http://stackoverflow.com/comment/83384097
has comment: http://stackoverflow.com/comment/83362185
has comment: http://stackoverflow.com/comment/83357947
tagged with: python
has title: How to get browser console error messages using Selenium WebDriver + python
has comment: http://stackoverflow.com/comment/124360273
upvote count: 6
has comment: http://stackoverflow.com/comment/83357796
type: Question
tagged with: selenium-chromedriver
has body: Console error png We have been trying to print the console errors for the particular site by using the following code. But we are unable to catch console errors. Can anyone give quick response But we are getting Line of Code : driver.get_log('browser') Error : [{u'source': u'deprecation', u'message': u"https://xxxxx/static/vendor/vendor.bundle.js?v=16 902 Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.", u'timestamp': 1515593047810, u'level': u'WARNING'}] Line of Code : driver.get_log('driver') Error : [{u'timestamp': 1515593061561, u'message': u'Unable to evaluate script: disconnected: not connected to DevTools\n', u'level': u'WARNING'}, {u'timestamp': 1515593071847, u'message': u'Unable to evaluate script: disconnected: not connected to DevTools\n', u'level': u'WARNING'}] Code Block : from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities capabilities = DesiredCapabilities.CHROME capabilities['loggingPrefs'] = { 'browser':'ALL' } driver = webdriver.Chrome(desired_capabilities=capabilities) driver.get('url') elem = driver.find_element_by_id('username') elem.send_keys('xxxx') elem1 = driver.find_element_by_name('password') elem1.send_keys('xxxx') elem2 = driver.find_element_by_class_name('btn-info') elem2.click() driver.get('url') for entry in driver.get_log('browser'): print entry
tagged with: browser
has comment: http://stackoverflow.com/comment/83358031

http://stackoverflow.com/a/65201523
score: -2
has comment: http://stackoverflow.com/comment/115270140
type: Answer
has comment: http://stackoverflow.com/comment/115272184
answers question: http://stackoverflow.com/q/48209010
downvote count: 2
has body: db = sqlite3.connect("lahman2016.db") cursor = db.cursor() cursor.execute(''' SELECT parkname FROM Parks WHERE city = 'Toronto' ''')
upvote count: 0

http://stackoverflow.com/comment/83490306
comment on: http://stackoverflow.com/q/48253210
score: 1
type: Comment
type: QuestionComment
has text: I see the same pattern with symmetric operation like `+`.

http://stackoverflow.com/comment/83619732
has text: Just use `If ` instead of `while` and change `or` instead of `and` and try .
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48317127
type: Comment

http://stackoverflow.com/comment/83476992
type: QuestionComment
comment on: http://stackoverflow.com/q/48247021
score: 0
has text: No worries and thanks, "frame" is a variable "xxxx.fram" is actually can.Frame which is the library call for a CAN network message. "(xxx, [1, 2, 3, 4, 5, 6, 7, 8])" sets a message ID and sends the message of 112233445566788 to that message ID. in the while loop script it starts at 0000000000000001 and adds 1 until it reaches FFFFFFFFFFFFFFFF. I am trying to take what I had previously created in the while loop and incorporate it into the "frame" variable. My initial thought was:
type: Comment

http://stackoverflow.com/comment/83608026
has text: `os.write()` returns the number of bytes written, which you should add to `bytes_written` on each loop iteration. It's possible there are short writes. What is the relative speed of the Python test to the fio test?
comment on: http://stackoverflow.com/q/48304612
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83559537
has text: @NeelabhPant yw~ :-)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48177433
type: Comment

http://stackoverflow.com/q/48240792
has body: I need to plot this graph (exactly as in the picture). It is sin and cos of x, where x are equally spaced 100 numbers between 0 and 2 pi. So far, I wrote x=np.linspace(0, 2*math.pi,100) import matplotlib.pyplot as plt %matplotlib inline plt.figure(figsize=(10,5)) plt.yticks(np.arange(-1,1.25,0.25)) plt.xticks(np.arange(0, 7, 1)) plt.plot(x,np.cos(x),'r',label="sine") plt.plot(x,np.sin(x),'b',label="cosine") plt.xlabel('x (in radians)') plt.legend(loc=3) But the plot I get looks like this How do I make the legend smaller, the box for the legend in grey and the plot indented? Editing: I am using the version of Matplotlib 2.1.0 [proof][https://i.sstatic.net/FFXFV.png]
tagged with: matplotlib
tagged with: legend
answer count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83464774
favorite count: 0
type: Question
tagged with: legend-properties
has comment: http://stackoverflow.com/comment/83464699
has comment: http://stackoverflow.com/comment/83465157
has title: How do I plot a function in python that looks like the one in the picture?
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/83465047
upvote count: 1
has comment: http://stackoverflow.com/comment/83464726
has comment: http://stackoverflow.com/comment/83464735
tagged with: plot
has answer: http://stackoverflow.com/a/48240968

http://stackoverflow.com/q/48233427
linked to: http://stackoverflow.com/q/45155377
has comment: http://stackoverflow.com/comment/83449833
has comment: http://stackoverflow.com/comment/83450103
has comment: http://stackoverflow.com/comment/83453591
score: 1
has comment: http://stackoverflow.com/comment/83573090
tagged with: python
has comment: http://stackoverflow.com/comment/83450545
has comment: http://stackoverflow.com/comment/83573140
type: Question
has comment: http://stackoverflow.com/comment/83449781
has comment: http://stackoverflow.com/comment/83602716
answer count: 0
has comment: http://stackoverflow.com/comment/83450047
has comment: http://stackoverflow.com/comment/83449882
has comment: http://stackoverflow.com/comment/83568963
has comment: http://stackoverflow.com/comment/83602426
has comment: http://stackoverflow.com/comment/83449806
has comment: http://stackoverflow.com/comment/83449926
has comment: http://stackoverflow.com/comment/83449662
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83450176
has body: What I am trying to do? A Python script that would read a large file (1-8G), match on a field called record (which can be "r" or "f") and can have same ID. If the ID is same, combine the "f" and "r" lines and save it to dictionary with ID as the key. In order to speed up the process, I split the file in multiple small ones and ran the function on separate files in different processes. In the end combine the dictionaries created by each process. First I tried using multiprocessing Pool, but it is making the processing slower. Read somewhere to try multiprocessing Processes and Queue, but I am trying to put dictionary (which is large) in the Queue and looks like Queue is not able to handle the size. The script hangs at this point. Any suggestions on how I can improve the processing time? PS: I am sure this is CPU bound because I did a "pass" while reading the lines and it took 97sec and when ran the entire script, it took 600 sec. import multiprocessing def rLine(line, resultDict): id= line[2] rOutput= line[4]+" "+line[5] #this is a long string rList= rOutput.split(" ") resultDict[id].extend(rList) def fLine(line, resultDict): id= line[7] fOutput= line[4]+" "+line[5] #this is a long string fList= rOutput.split(" ") resultDict[id].extend(fList) def mainFunction(thisFile, output): resultDict= defaultdict(list) with gzip.open(thisFile) as f: for lines in f: line= lines.split(" ") record= line[0] if record=="f": fLine(line, resultDict) else: rLine(line, resultDict) output.put(resultDict) if __name__=='__main__': finalDict= defaultdict(list) output= multiprocessing.Queue() processes= list() files= ["f1.log.gz", "f2.log.gz"] #long list for f in files: process.append(multiprocessing.Process(target=mainFunction, args=(f,output)) for p in processes: p.start() for p in processes: p.join() for p in process: finalDict.update(output.get()) print finalDict
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83449630
has comment: http://stackoverflow.com/comment/83601555
favorite count: 0
has title: How to use multiprocessing.Process when output is large for multiprocessing.Queue?
tagged with: multiprocessing

http://stackoverflow.com/q/48245637
type: Question
has title: Python 3.5 and openpyxl installation process
has answer: http://stackoverflow.com/a/48245981
tagged with: python
has body: I just installed Python3.5.4 and version 2.5 of Openpyxl 2.5. I'm using Windows 10 (64bit). What I have done so far is that I copied the openpyxl folder into Python's lib folder. In the Command Prompt when I run: pip install openpyxl I am getting an error about "jdcal" and when I run: pip install jdcal I am getting the same error. As you can see on the image "error". With this, I have summarized my queries below, Is Openpyxl2.5 is compatible with Python3.5? Is this something to do with pip? Do I need to install pip? Do I need to install jdcal? the error says: could not create c:\program files\python35\lib\site packages\jdcal.py
score: 0
type: UnansweredQuestion
tagged with: openpyxl
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/83393010
comment on: http://stackoverflow.com/q/48205806
score: 0
has text: Could you post your code please? [Loops](https://www.learnpython.org/en/Loops) are really powerful and worth learning how to use. You also might need to understand [how to use array indexing in Numpy](https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html) (i.e. how to refer to certain sub-arrays within a larger array).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83636785
has text: Nope, there will be an arbitrary number. I should have made a better example. Example now updated.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48325414

http://stackoverflow.com/comment/83679716
has text: @cᴏʟᴅsᴘᴇᴇᴅ I wasn't able to use your solution as I kind of oversimplified my question. I had to hack together something that is probably not elegant enough to be posted here. As your solution probably answers the question asked, im going to give you the right answer. Thanks for your help.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48231959
type: Comment

http://stackoverflow.com/comment/83682891
has text: I tried using that, and got "Broken DAG: [...] Timeout" I haven't been able to find anything specific to that error. Do you have any clues?
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48254444

http://stackoverflow.com/comment/83448045
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48232641
has text: @SuperStew I'll look into it, thank you!
score: 0

http://stackoverflow.com/a/48230710
has comment: http://stackoverflow.com/comment/83495683
has comment: http://stackoverflow.com/comment/83444122
has comment: http://stackoverflow.com/comment/83775196
has comment: http://stackoverflow.com/comment/83511554
has comment: http://stackoverflow.com/comment/83511669
type: Answer
has body: The error says it all : selenium.common.exceptions.WebDriverException: Message: unknown error: cannot determine loading status from unknown error: missing or invalid 'entry.level' Your main issue is the version compatibility among the binaries you are using as follows : You are using chromedriver=2.29.461591 (which is as per the logs, though you mentioned Chromedriver 2.35 in your question) Release Notes of chromedriver=2.29.461591 clearly mentions the following : Supports Chrome v56-58 You are using chrome=65.0.3315.3 Release Notes of chromedriver=2.35 clearly mentions the following : Supports Chrome v62-64 You are using Selenium Version 2.53.1. Your JDK version is unknown to us. Solution Upgrade JDK to recent levels JDK Version 8 Update 151. Upgrade ChromeDriver to ChromeDriver v2.35 level. Keep Chrome to Chrome v64.x levels. (as per ChromeDriver v2.35 release notes) Upgrade Selenium to current levels Version 3.8.1. Clean the Project Workspace from your IDE &amp; Rebuild All. Run CCleaner tool to wipe off all the OS chores. If your Chrome base version is too old, uninstall Chrome through Revo Uninstaller and install a recent GA Release version of Chrome. Take a System Reboot. Execute your Test.
answers question: http://stackoverflow.com/q/48230370
has comment: http://stackoverflow.com/comment/83509498
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48230370
upvote count: 7
score: 7
has comment: http://stackoverflow.com/comment/83444269
type: AcceptedAnswer

http://stackoverflow.com/q/48259511
has answer: http://stackoverflow.com/a/48260431
tagged with: neural-network
tagged with: machine-learning
tagged with: python
has title: How to use IP address as a feature in a neural network
tagged with: keras
possible better answer: http://stackoverflow.com/a/76888029
score: 6
has comment: http://stackoverflow.com/comment/122621486
has answer: http://stackoverflow.com/a/76888029
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48260431
has answer: http://stackoverflow.com/a/72329342
answer count: 3
has comment: http://stackoverflow.com/comment/83502171
tagged with: deep-learning
has body: Using Keras, I want to build an LSTM neural net to analyze user behavior in my system. One of my features is a string containing the user IP address, that could be IPv4 or IPv6. As I see it I need to embed the address so it can be use as a feature. In Keras documentation there is no clear explanation how to do such a thing. What would be a good place to start?
has comment: http://stackoverflow.com/comment/83502360
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83501986
upvote count: 8
downvote count: 2
has comment: http://stackoverflow.com/comment/83502408

http://stackoverflow.com/comment/83566341
comment on: http://stackoverflow.com/a/48290556
type: Comment
score: 0
type: AnswerComment
has text: thanks. I thought that with recursive functions it will be more complicated :)

http://stackoverflow.com/comment/83604301
has text: @MattR I figured it out, thanks!
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48308698

http://stackoverflow.com/a/48271251
accepted answer of: http://stackoverflow.com/q/48271116
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83529269
score: 0
answers question: http://stackoverflow.com/q/48271116
has body: If I understood correctly you want to count how many numbers in a are also in b in the same position (strikes) or in another position (balls). If this is correct the this should do it: for i in range(0, 3): if a[i] in b: if a[i] == b[i]: strikes = strikes + 1 else: balls = balls + 1
has comment: http://stackoverflow.com/comment/83528205
type: Answer
has comment: http://stackoverflow.com/comment/83529177

http://stackoverflow.com/a/48219251
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48219116
type: AcceptedAnswer
downvote count: 0
has body: If I'm not mistaken, an iterator is just a copy of a pointer to some data. This is sort of correct, but not entirely. The main confusion is that you're not directly handling any iterators in your second code block. There is an iterator being used (inside the for loop), and there is a reference (a pointer in other words) to some data, but they're not the same thing. The bit variable is only getting a reference to the value yielded by the iterator. It's not the iterator itself. You can write your own version of a for loop, explicitly handling the iterator. Instead of for bit in A:, you'd have: _iterator = iter(A) while True: try: bit = next(_iterator) except StopIteration: break # body of the for loop goes here! del _iterator Notice that bit gets its value assigned on each cycle of the loop. If you reassign it later (in the body of the original loop), neither the original value or the list it came from gets modified. You could see a similar thing happen in a slightly modified version of your first code: def flipBits(A): for i in range(len(A)): bit = A[i] if bit == 1: bit = 0 else: bit = 1 return A This version will not modify A for the same reason the for loop version of your code did not. Rebinding bit (which is a local variable) is not the same thing as rebinding A[i], even though they are both references to the same value. Note that if you don't need to modify A in place, a more "Pythonic" way to solve this problem is to create a new list with the flipped bits in it, using a list comprehension: def flipBits(A): return [1-bit for bit in A] # you could also use "0 if bit == 1 else 1" instead of 1-bit
type: Answer
answers question: http://stackoverflow.com/q/48219116
score: 2

http://stackoverflow.com/q/48262409
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: apache-spark-2.2
type: UnansweredQuestion
tagged with: pyspark
tagged with: spark-structured-streaming
tagged with: python
has title: writestream aggregate windowed watermarked dataframe doesn't wok:
has body: I am working with a CSV dataset as input, read by readStream as below: inDF = spark \ .readStream \ .option("sep", ",") \ .option("maxFilesPerTrigger", 1) \ .schema(rawStreamSchema) \ .csv(rawEventsDir) Below the schema: inDF schema = root |-- timeStamp: timestamp (nullable = true) |-- machine: string (nullable = true) |-- module: string (nullable = true) |-- component: string (nullable = true) |-- plateID: integer (nullable = true) |-- measureProgr: integer (nullable = true) |-- measure: string (nullable = true) |-- value: double (nullable = true) I need to make some aggregation, as below: byMeasureDF = inDF \ .withWatermark('timeStamp', '600 seconds') \ .groupBy(window(inDF.timeStamp, windowSize, windowStart) , inDF.machine, inDF.module , inDF.component, inDF.measure) \ .agg(min(inDF.value).alias('minValue') , max(inDF.value).alias('maxValue') , avg(inDF.value).alias('avgValue') , stddev(inDF.value).alias('stdevValue')) that works, indeed the output schema is correct: byMeasureDF schema = root |-- window: struct (nullable = true) | |-- start: timestamp (nullable = true) | |-- end: timestamp (nullable = true) |-- machine: string (nullable = true) |-- module: string (nullable = true) |-- component: string (nullable = true) |-- measure: string (nullable = true) |-- minValue: double (nullable = true) |-- maxValue: double (nullable = true) |-- avgValue: double (nullable = true) |-- stdevValue: double (nullable = true) but, when I run the below query: q_byMeasure = byMeasureDF \ .writeStream \ .format('csv') \ .option('delimiter', ',') \ .option('header', 'true') \ .outputMode('append') \ .queryName('byMeasure') \ .start(path = confStreamMiningByMeasureDir , checkpointLocation = chkStreamMiningByMeasureDir) I get the following error: Traceback (most recent call last): File "/home/roberto/BOTT-G80216/Programs/Version_00.01.00/Python/2_fromRawToConformed.py", line 87, in &lt;module&gt; , checkpointLocation = chkStreamMiningByMeasureDir) File "/home/roberto/spark/python/py…
answer count: 0
tagged with: apache-spark

http://stackoverflow.com/q/48275198
has answer: http://stackoverflow.com/a/48275621
accepted answer: http://stackoverflow.com/a/48275621
tagged with: python
upvote count: 4
type: AnsweredQuestion
score: 3
answer count: 1
downvote count: 1
has body: I am new to Numpy. I couldn't understand the use of ord=2 in numpy.linalg.norm. For example, what is the difference between: np.linalg.norm(np.array([[-4, -3, -2], [-1, 0, 1], [ 2, 3, 4]])) and np.linalg.norm(np.array([[-4, -3, -2], [-1, 0, 1], [ 2, 3, 4]]),2) In Numpy documentation, it is given that ord =2 means 2-norm (largest sing. value). I couldn't understand what is meant by largest singular value. Could you explain?
has title: how does numpy.linalg.norm ord=2 work?
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/q/48279061
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/63156380
has title: GCS - Read a text file from Google Cloud Storage directly into python
upvote count: 43
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/72647098
tagged with: google-cloud-storage
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/61639873
accepted answer: http://stackoverflow.com/a/48279267
has answer: http://stackoverflow.com/a/48279267
downvote count: 0
has answer: http://stackoverflow.com/a/79045793
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/68939195
possible better answer: http://stackoverflow.com/a/63156380
has body: I feel kind of stupid right now. I have been reading numerous documentations and stackoverflow questions but I can't get it right. I have a file on Google Cloud Storage. It is in a bucket 'test_bucket'. Inside this bucket there is a folder, 'temp_files_folder', which contains two files, one .txt file named 'test.txt' and one .csv file named 'test.csv'. The two files are simply because I try using both but the result is the same either way. The content in the files is hej san and I am hoping to read it into python the same way I would do on a local with textfile = open("/file_path/test.txt", 'r') times = textfile.read().splitlines() textfile.close() print(times) which gives ['hej', 'san'] I have tried using from google.cloud import storage client = storage.Client() bucket = client.get_bucket('test_bucket') blob = bucket.get_blob('temp_files_folder/test.txt') print(blob.download_as_string) but it gives the output &lt;bound method Blob.download_as_string of &lt;Blob: test_bucket, temp_files_folder/test.txt&gt;&gt; How can I get the actual string(s) in the file?
score: 43

http://stackoverflow.com/comment/83384474
type: Comment
comment on: http://stackoverflow.com/a/48201679
score: 0
type: AnswerComment
has text: Just want to point out that flush() will trigger the same write to filesystem.

http://stackoverflow.com/comment/83557452
comment on: http://stackoverflow.com/q/48286164
type: Comment
score: 0
has text: Edited and added expected output.
type: QuestionComment

http://stackoverflow.com/comment/83552242
has text: I appreciate the try, but that doesn't run much quicker on my machine. I did use your suggestions from your other comments though!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48272993

http://stackoverflow.com/comment/83558415
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48286431
has text: Can you edit the post to include the error you're getting?
score: 0

http://stackoverflow.com/q/48272389
has comment: http://stackoverflow.com/comment/83529342
downvote count: 2
has comment: http://stackoverflow.com/comment/83529242
score: 5
has comment: http://stackoverflow.com/comment/83528677
has body: I seem to be running into a bug with Python's built-in sorted function. I can't seem to find it documented or described anywhere, but I'm also getting results that seem to be inherently impossible based on my understanding of Python so I'm hoping that someone can help, or at least point me in the right direction. To start, I've got a long list of floats (1.4m to be exact). They are all very small, and some of them are very near each other. In fact when cast to a set the length is only ~240k. My goal is simple: I need to find a cutoff, such that only n values are above this cutoff, seems simple. Here is my current code: sorted_values = sorted(all_values) top_250 = [item for item in sorted_values if item &lt; sorted_values[250]] len(top_250) # 5828 Unfortunately the data is proprietary (and quite large) so I cannot share it, but hopefully I've given enough detail above. The list is a list of all floats, all between 0 and 1, with many duplicates. I cannot for the life of me figure out what's going on here. My best guess is that the sorted comparator operates differently from a traditional &lt; in Python. Perhaps the &lt; has an implicit epsilon associated with it that I'm not aware of, but I can't find anything similar in the Python docs, so I'm really at a dead end. If anyone has even the vaguest sense of what this might be I would be tremendously grateful. Update: If I replace all_values above with list(set(all_values)) then this problem disappears and sorted performs as expected. This does not however solve my problem, nor does it explain why sorted is acting differently than documented. Based on a very large number of attempts (and failures) at reproducing this locally, this seems to happen specifically with floats at large data sizes. Update 2: Data below, and in this gist: https://gist.github.com/Slater-Victoroff/bc03fb39e07a30caf57460330d02d3f7 [4.8502882289326867e-14, 8.820403952763587e-14, 1.0250590153123516e-13, 1.6954166246183968e-13, 1.908753789966549e-13, …
has comment: http://stackoverflow.com/comment/83529045
has comment: http://stackoverflow.com/comment/83529008
has comment: http://stackoverflow.com/comment/83528759
has comment: http://stackoverflow.com/comment/83529395
upvote count: 7
has comment: http://stackoverflow.com/comment/83529679
has comment: http://stackoverflow.com/comment/83529388
has comment: http://stackoverflow.com/comment/83529161
answer count: 1
has comment: http://stackoverflow.com/comment/83529071
has comment: http://stackoverflow.com/comment/83529223
has comment: http://stackoverflow.com/comment/83529477
has comment: http://stackoverflow.com/comment/83529049
has comment: http://stackoverflow.com/comment/83565068
has comment: http://stackoverflow.com/comment/83529411
tagged with: floating-point
has comment: http://stackoverflow.com/comment/83529155
has comment: http://stackoverflow.com/comment/83528729
has comment: http://stackoverflow.com/comment/83529031
has comment: http://stackoverflow.com/comment/83528839
tagged with: sorting
has comment: http://stackoverflow.com/comment/83529555
has title: sorted() function differing from results obtained via list comprehension
has comment: http://stackoverflow.com/comment/83529263
has comment: http://stackoverflow.com/comment/83529686
has comment: http://stackoverflow.com/comment/83529312
has comment: http://stackoverflow.com/comment/83529468
favorite count: 0
has comment: http://stackoverflow.com/comment/83528859
has comment: http://stackoverflow.com/comment/83529165
has comment: http://stackoverflow.com/comment/83529479
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83529206
has comment: http://stackoverflow.com/comment/83528875
has comment: http://stackoverflow.com/comment/83528795
has comment: http://stackoverflow.com/comment/83529592
has comment: http://stackoverflow.com/comment/83528819
has comment: http://stackoverflow.com/comment/83529441
has comment: http://stackoverflow.com/comment/83529353
has comment: http://stackoverflow.com/comment/83529139
has comment: http://stackoverflow.com/comment/83529106
has comment: http://stackoverflow.com/comment/83528837
has comment: http://stackoverflow.com/comment/83529538
tagged with: python
has comment: http://stackoverflow.com/comment/83528794
has comment: http://stackoverflow.com/comment/83529424
has comment: http://stackoverflow.com/comment/83528763
has comment: http://stackoverflow.com/comment/83529038
has answer: http://stackoverflow.com/a/48272831
accepted answer: http://stackoverflow.com/a/48272831
has comment: http://stackoverflow.com/comment/83529750
has comment: http://stackoverflow.com/comment/83529124
has comment: http://stackoverflow.com/comment/83529127
has comment: http://stackoverflow.com/comment/83529526
has comment: http://stackoverflow.com/comment/83529321
has comment: http://stackoverflow.com/comment/83530139
has comment: http://stackoverflow.com/comment/83529142
has comment: http://stackoverflow.com/comment/83529765
type: Question
has comment: http://stackoverflow.com/comment/83528776
linked to: http://stackoverflow.com/q/4240050

http://stackoverflow.com/comment/83475527
comment on: http://stackoverflow.com/q/48246345
has text: There are ways to wait for the page to update, but that depends on your specific case. A quick search turns up [this SO question](https://stackoverflow.com/questions/39783190/). If you want to continue that thread of conversation, I'd suggest moving it to chat (Selenium IRC or SE chat). In the meantime, I suggested lengthening your waiting interval just for testing purposes and I'd like to see if that helps.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48287185
score: 2
has comment: http://stackoverflow.com/comment/83560344
has comment: http://stackoverflow.com/comment/83563076
answer count: 2
upvote count: 2
has body: I am trying to run my python script in cron server every minute but somehow it doesn't run. My script runs well locally. */1 * * * * python /home/ana/cronjobs/ele/transfer.py At the top of my transfer.py file I have : #!/usr/bin/python # -*- coding: utf-8 -*- Still it doesn't run. Any leads?
possible better answer: http://stackoverflow.com/a/48287253
has comment: http://stackoverflow.com/comment/83559178
has comment: http://stackoverflow.com/comment/83562457
has comment: http://stackoverflow.com/comment/83562992
downvote count: 0
has title: Cron job fails to run
has comment: http://stackoverflow.com/comment/83562384
has comment: http://stackoverflow.com/comment/83559280
favorite count: 0
has comment: http://stackoverflow.com/comment/83563015
type: Question
has comment: http://stackoverflow.com/comment/83563196
has comment: http://stackoverflow.com/comment/83559162
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48289287
has comment: http://stackoverflow.com/comment/83559183
has answer: http://stackoverflow.com/a/48289287
tagged with: cron
has comment: http://stackoverflow.com/comment/83563214
has comment: http://stackoverflow.com/comment/83563148
has comment: http://stackoverflow.com/comment/83559226
has comment: http://stackoverflow.com/comment/83559736
has comment: http://stackoverflow.com/comment/83562671
has answer: http://stackoverflow.com/a/48287253
tagged with: python
has comment: http://stackoverflow.com/comment/83563302

http://stackoverflow.com/q/48236438
accepted answer: http://stackoverflow.com/a/48236925
possible better answer: http://stackoverflow.com/a/56952423
has answer: http://stackoverflow.com/a/48236925
has answer: http://stackoverflow.com/a/56952423
tagged with: python
linked to: http://stackoverflow.com/q/44327999
answer count: 2
tagged with: pandas
score: 1
has title: merge multiple dataframe with specified suffix
downvote count: 0
upvote count: 1
has body: I implemented to merge multiple dataframe referring to this page. What I want to do is also specify the suffix for each dataframe like below. However, I get ValueError: too many values to unpack (expected 2). I understand that giving the tuple longer than 2 for suffix is causing this problem. But I have no idea how I can write code to fix this problem. Can anyone tell me how to write? def agg_df(dfList, suffix): temp=reduce(lambda left, right: pd.merge(left, right, left_index=True, right_index=True, how='outer', suffixes=suffix), dfList) return temp df=agg_df([df_cool, df_light, df_sp, df_hvac], ('_chiller', '_light', '_sp', '_hvac'))
favorite count: 0
type: Question
type: AnsweredQuestion

http://stackoverflow.com/q/48201454
upvote count: 2
possible better answer: http://stackoverflow.com/a/48201482
has comment: http://stackoverflow.com/comment/83383837
tagged with: python
has answer: http://stackoverflow.com/a/48201482
type: AnsweredQuestion
has title: Extract middle word of letter python
score: 0
answer count: 3
tagged with: pandas
downvote count: 2
has answer: http://stackoverflow.com/a/48202130
has comment: http://stackoverflow.com/comment/83383824
accepted answer: http://stackoverflow.com/a/48201483
tagged with: string
has answer: http://stackoverflow.com/a/48201483
favorite count: 0
type: Question
has body: I have pandas dataframe called df which look like this Name ------ Mike Noel Kim Anna Luke joseph joe How do i list only the name which has word 'n' or 'k' in the middle of the name. not the first letter nor the last letter. the result is namelist = [Mike, Anna, Luke]
tagged with: split

http://stackoverflow.com/comment/83568276
comment on: http://stackoverflow.com/q/48291400
has text: @MaxU I was hesitant at first, because the output isn't identical to OP's expected output, but looking at it again, probably a typo!
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48214844
answers question: http://stackoverflow.com/q/48214830
type: Answer
has body: You are only mutating the element in the loop-scope. Instead, reassign using the element index: magicians = ['harry potter', 'scamander', 'snape'] for i, magician in enumerate(magicians): magician = 'the Great ' + magician magicians[i] = magician print(magicians) Output: ['the Great harry potter', 'the Great scamander', 'the Great snape'] However, it is much shorter to use list comprehension: magicians = ['harry potter', 'scamander', 'snape'] new_magicians = ['the Great {}'.format(i) for i in magicians] Output: ['the Great harry potter', 'the Great scamander', 'the Great snape'] In the scope of the problem, a loop is not even necessary: final_data = ("the Great {}*"*len(magicians)).format(*magicians).split('*')[:-1]
upvote count: 4
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/83411594

subset
tags question: http://stackoverflow.com/q/48223205
tags question: http://stackoverflow.com/q/48273628
type: Tag
tag name: subset

http://stackoverflow.com/comment/83418882
comment on: http://stackoverflow.com/q/48217403
type: Comment
score: 0
type: QuestionComment
has text: That's less than 5 minutes once a week. Do you really need to make that faster?

http://stackoverflow.com/q/48265821
has comment: http://stackoverflow.com/comment/83515425
has answer: http://stackoverflow.com/a/48266333
has comment: http://stackoverflow.com/comment/83515585
type: Question
has comment: http://stackoverflow.com/comment/83514777
has comment: http://stackoverflow.com/comment/83515205
has comment: http://stackoverflow.com/comment/83514856
has comment: http://stackoverflow.com/comment/83514909
type: UnansweredQuestion
has title: How to read a sensor in c but then use that input in python
has comment: http://stackoverflow.com/comment/83514819
has comment: http://stackoverflow.com/comment/83515064
has comment: http://stackoverflow.com/comment/83514655
tagged with: python
has comment: http://stackoverflow.com/comment/83514703
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/83514994
has comment: http://stackoverflow.com/comment/83515272
score: 0
has comment: http://stackoverflow.com/comment/83515118
tagged with: popen
has comment: http://stackoverflow.com/comment/83515339
has body: I have a flow sensor that I have to read with c because python isn't fast enough but the rest of my code is python. What I want to do is have the c code running in the background and just have the python request a value from it every now and then. I know that popen is probably the easiest way to do this but I don't fully understand how to use it. I don't want completed code I just want a way to send text/numbers back and forth between a python and a c code. I am running raspbian on a raspberry pi zero w. Any help would be appreciated.
has comment: http://stackoverflow.com/comment/83515227
has comment: http://stackoverflow.com/comment/83514824
answer count: 1
has comment: http://stackoverflow.com/comment/83514794
has comment: http://stackoverflow.com/comment/83515026
has comment: http://stackoverflow.com/comment/83514939
has comment: http://stackoverflow.com/comment/83514842

http://stackoverflow.com/q/48319706
has body: I am calculating different levels of default in a loan book over time. I calculate default as: amount_of_money_due_to_be_paid - amount_of_money_actually_paid id amount due_date paid y/n 1 1000 2017-01-01 no 2 1000 2017-02-01 yes 3 1000 2017-03-01 no 4 1000 2017-04-01 no 5 1000 2017-05-01 yes I need to calculate this at different levels of default, i.e. 30 days_past_due, 60 days_past_due etc over a time series. As of the last day in each month, I need to know how much money was more than x days overdue. (E.g. As of June 30, how much money was more than 15 days past due) Therefore I need to divide amount_of_money_actually_paid / amount_money_due_to_be_paid_up_to_15_days_ago The resulting dataframe would have the last date of each month listed as each column header, and the rows would be the default_% at each date in the column header. Date: 2017-01-31 2017-02-29 2017-03-31 2017-04-30 2017-05-31 Default %: 100% 50% 66.67% 25% 40% In Excel, I calculate the denominator by summing the amount of money with due_date before the column header less x number of days (i.e. sum the amounts, if the due_date is before e.g. [(2017-03-31 - 15 days) = 2017-03-16] I need help in calculating this in Python. I have done the below analysis for another part of my code, and I think a small change could fix the issue. def default_days(date, outstanding_loans, days): m = (outstanding_loans['repayment_date'] &lt;= date - pd.DateOffset(days)) c = sum(m) return c dates = pd.date_range('2015-11-30',pd.to_datetime('today'), freq='M') defaultt = pd.DataFrame({'date':dates}) defaultt['15 days'] = defaultt['date'].apply(default_days, args=[repayments, 15]) The result here is that it's counting the number of rows with due_date 15 days before each specified date. I need it to sum the amounts instead of count the rows
tagged with: python
score: 2
accepted answer: http://stackoverflow.com/a/48321900
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83627724
tagged with: pandas
upvote count: 2
has comment: http://stackoverflow.com/comment/83628876
has comment: http://stackoverflow.com/comment/83625766
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83627891
has comment: http://stackoverflow.com/comment/83628538
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48321900
has title: Calculating levels of loan default over a time series
has comment: http://stackoverflow.com/comment/83624978

http://stackoverflow.com/q/48311909
downvote count: 0
has comment: http://stackoverflow.com/comment/83614710
type: UnansweredQuestion
has body: I want to schedule a python script using the python-crontab module on Windows platform. Found the following snippet to work around but having a hard time to configure. Script name cronTest.py: from crontab import CronTab file_cron = CronTab(tabfile='filename.tab') mem_cron = CronTab(tab=""" * * * * * command """) Let's say, for example, I want to print date &amp; time for ever 5 mins using the following script, named dateTime.py: import datetime with open('dateInfo.txt','a') as outFile: outFile.write('\n' + str(datetime.datetime.now())) How do I execute dateTime.py and setup the cron job for every 5mins through cronTest.py.
answer count: 1
has title: Scheduling Python script using Python CronTab on Windows 7
has answer: http://stackoverflow.com/a/48349800
favorite count: 0
has comment: http://stackoverflow.com/comment/83611015
tagged with: cron
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/83613216
has comment: http://stackoverflow.com/comment/83611863
tagged with: scheduled-tasks
type: Question
tagged with: python-3.x
score: 5
upvote count: 5

bit
tag name: bit
tags question: http://stackoverflow.com/q/48316117
type: Tag

http://stackoverflow.com/comment/90613038
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48293715
score: 0
has text: @wim Excellent! That is exactly what I was looking for. Thank you.

http://stackoverflow.com/comment/84688661
has text: @Nico, It is a very specific function I am trying to integrate (`int_f`, see the link in the comment) for a variety of values of `t` and `r`. There is only _one_ function being integrated, so I do not see why you take issue with the example. This example shows how `s` jumps around with changing `r` and `t` values due to `quad` having problems with this integrand.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48304999
type: Comment

http://stackoverflow.com/comment/83582643
has text: There are no stupid questions. Yes, the `while True` is your game loop and each iteration represents a single frame of your game. `display.flip()` tells PyGame that it's time to change to flush all the updates that have taken place to the screen. If, hypothetically, there was no notion of display flipping, you'd see the changes to the screen happen in real time which would look like flickering. As such, if you omit display flip, it'll just appear to do nothing, much like the way you are currently seeing.
score: 0
comment on: http://stackoverflow.com/a/48296026
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48191258
accepted answer of: http://stackoverflow.com/q/48190628
has body: There are a few options. As suggested in the comments, you can increase the figure size manually, making sure the width is three time bigger than the height. fig, ax = plt.subplots(figsize=(height, height*3)) If you want to use figaspect you can do the following: from matplotlib.figure import figaspect w, h = figaspect(1/3) fig, ax = plt.subplots(figsize=(w,h)) plt.show() This creates a figure which is 3 times wider than it is tall and gives: You can also change the axes aspect ratio using ax.set_aspect(). This will not change the figure size: fig, ax = plt.subplots() ax.set_aspect(1/3) plt.show() Which gives:
type: Answer
score: 7
answers question: http://stackoverflow.com/q/48190628
type: AcceptedAnswer
downvote count: 0
upvote count: 7

http://stackoverflow.com/comment/83502327
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48259515
has text: Thanks for the response, is there any way i can change the data file to some other extension and then read it and convert back to json ?

http://stackoverflow.com/comment/83408543
type: QuestionComment
comment on: http://stackoverflow.com/q/48213509
type: Comment
score: 2
has text: Not quite a dupe, but relevant: https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response

http://stackoverflow.com/comment/83478760
type: QuestionComment
score: 0
has text: Thanks for that, I've made some progress. Program now starts, however the 3D scene remains blank and the console logs the following error: `QOpenGLContext::swapBuffers() called with non-exposed window, behavior is undefined`. Any ideas ? I will edit my code to show the new version
comment on: http://stackoverflow.com/q/48238204
type: Comment

http://stackoverflow.com/comment/83443038
comment on: http://stackoverflow.com/q/48230296
type: Comment
score: 0
type: QuestionComment
has text: @user2357112 while you were typing, I've edited it. thanks.

http://stackoverflow.com/comment/83444899
type: AnswerComment
has text: Works like a charm :) Can you also add code for `matplotlib`? That would be immensely helpful.
score: 1
comment on: http://stackoverflow.com/a/48230834
type: Comment

http://stackoverflow.com/comment/83440054
score: 1
has text: @Pointy unless the functions being invoked are factory functions that return each service.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48229056

http://stackoverflow.com/a/48200476
has comment: http://stackoverflow.com/comment/83382834
type: Answer
answers question: http://stackoverflow.com/q/48200341
has comment: http://stackoverflow.com/comment/83385329
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48200341
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83420523
has comment: http://stackoverflow.com/comment/83419628
has body: You can define a function to return the value for the key you enter: def get_txt(soup, key): key_tag = soup.find('span', text=key).parent return key_tag.find_all('span')[1].text color = get_txt(soup, 'Color') print('Color: ' + color) features = get_txt(soup, 'Features') print('Features: ' + features) Output: Color: Slate, mykonos Features: Camera lens cutout, hard shell, rubberized, port cut-outs, raised edges I hope this is what you are looking for. Explanation: soup.find('span', text=key) returns the tag whose text=key. .parent returns the parent tag of the current tag. Example: When key='Color', soup.find('span', text=key).parent will return Color Slate, mykonos Now we've stored this in key_tag. Only thing left is getting the text of second , which is what the line key_tag.find_all('span')[1].text does.
has comment: http://stackoverflow.com/comment/83420762

fractals
tags question: http://stackoverflow.com/q/48306631
type: Tag
tags question: http://stackoverflow.com/q/48200406
tag name: fractals

http://stackoverflow.com/comment/83378590
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48198646
type: QuestionComment
has text: how would you write that in mate?

http://stackoverflow.com/comment/83494051
type: QuestionComment
score: 5
has text: What is tripping you up? The math, or the code?
type: Comment
comment on: http://stackoverflow.com/q/48255641

http://stackoverflow.com/comment/83549933
type: QuestionComment
has text: do you want that because you want to send the socket at any time to the process? because if that's the case `multiprocessing.Pool` isn't really what you want to use
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48281230

http://stackoverflow.com/a/59701541
has body: To be honest, writing to a spreadsheet or database might be easier I recently made a bot that does this, and uploads all messages to Google Sheets. You can check it out here. If you'd still like to make your own, this would be done with @bot.event async def on_message(message): author = str(message.author) content = str(message.content) userid = str(message.author.id) messageid = str(message.id) time = str(message.created_at) link = str(message.jump_url) channel = str(message.channel) row = [userid,author,content,time,messageid,link,channel] and then writing row to a spreadsheet or txt file for logging messages @bot.event async def on_message_edit(before, after): row = [before, after] and then writing row to a spreadsheet or txt file @bot.event async def on_message_delete(message): message = message and then writing message to message. For more info on writing messages to files, Python Input/Output docs for txt files Python JSON docs for JSON files GSpread documentation for Google Sheets SQLite Documentation for Database Files
answers question: http://stackoverflow.com/q/48247250
score: 0
type: Answer

python-sphinx
tags question: http://stackoverflow.com/q/48201226
tag name: python-sphinx
tags question: http://stackoverflow.com/q/48209841
tags question: http://stackoverflow.com/q/48321017
type: Tag
tags question: http://stackoverflow.com/q/48311159

http://stackoverflow.com/comment/83468330
type: Comment
type: AnswerComment
score: 0
has text: @t.m.adam @7stud Oh my god, I just found what was causing the problem. The problem had nothing to do with the number of requests I was sending but with the way constructed the for loop: `for domain in domains: for queue in queues:` so basically the code was applying 10k queues to each domain (instead of applying one queue per domain), by consequence this made the computer go insane. all I had to do is replace that piece of code with `for domain,queue in zip(domains,queues):`.I also added `sleep(0.02)` to give a more time to the comp. Now it works great. Thank you very much for your help.
comment on: http://stackoverflow.com/a/48240500

http://stackoverflow.com/q/48259724
upvote count: 4
has comment: http://stackoverflow.com/comment/83503571
has comment: http://stackoverflow.com/comment/83503633
possible better answer: http://stackoverflow.com/a/52856508
has comment: http://stackoverflow.com/comment/83506435
has answer: http://stackoverflow.com/a/49593925
has comment: http://stackoverflow.com/comment/83504330
downvote count: 0
tagged with: contour
has comment: http://stackoverflow.com/comment/83503679
has answer: http://stackoverflow.com/a/52856508
has answer: http://stackoverflow.com/a/52908975
answer count: 5
has answer: http://stackoverflow.com/a/48263593
has comment: http://stackoverflow.com/comment/83502481
score: 4
favorite count: 0
type: Question
tagged with: opencv
type: AnsweredQuestion
has body: As suggested by @Silencer, I used the code he posted here to draw contours around the numbers in my image. At some point, working with numbers like 0,6,8,9 I saw that their inside contours (the circles) are being filled as well. How can I prevent this ? Is there a min/max area of action to set for cv2.drawContours() so I can exclude the inner area ? I tried to pass cv2.RETR_EXTERNAL but with this parameter only the whole external area is considered. The code is this (again, thanks Silencer. Was searching for this for months..): import numpy as np import cv2 im = cv2.imread('imgs\\2.png') imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(imgray, 127, 255, 0) image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) #contours.sort(key=lambda x: int(x.split('.')[0])) for i, cnts in enumerate(contours): ## this contour is a 3D numpy array cnt = contours[i] res = cv2.drawContours(im, [cnt], 0, (255, 0, 0), 1) cv2.imwrite("contours.png", res) ''' ## Method 1: crop the region x,y,w,h = cv2.boundingRect(cnt) croped = res[y:y+h, x:x+w] cv2.imwrite("cnts\\croped{}.png".format(i), croped) ''' ## Method 2: draw on blank # get the 0-indexed coords offset = cnt.min(axis=0) cnt = cnt - cnt.min(axis=0) max_xy = cnt.max(axis=0) + 1 w, h = max_xy[0][0], max_xy[0][1] # draw on blank canvas = np.ones((h, w, 3), np.uint8) * 255 cv2.drawContours(canvas, [cnt], -1, (0, 0, 0), -1) #if h &gt; 15 and w &lt; 60: cv2.imwrite("cnts\\canvas{}.png".format(i), canvas) The main image on which I am working.. Thanks UPDATE I implemented Fiver answer below and this is the result: import cv2 import numpy as np img = cv2.imread('img.png') img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) img_v = img_hsv[:, :, 2] ret, thresh = cv2.threshold(~img_v, 127, 255, 0) image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for i, c in enumerate(contours): tmp_img = np.zeros(img_v.shape, dtype=np.uint8) res = cv2.d…
has comment: http://stackoverflow.com/comment/83504258
accepted answer: http://stackoverflow.com/a/48263593
has comment: http://stackoverflow.com/comment/83502192
has title: cv2.drawContours() - unfill circles inside characters (Python, OpenCV)
linked to: http://stackoverflow.com/q/48244328
has comment: http://stackoverflow.com/comment/83502267
tagged with: python
has answer: http://stackoverflow.com/a/48291914

http://stackoverflow.com/q/48293456
has title: Fastest way to pull data from a WebSocket
has answer: http://stackoverflow.com/a/51989382
score: 2
answer count: 2
tagged with: websocket
favorite count: 0
type: Question
tagged with: performance
has body: The problem I face is that I'm trying to pull a high frequency of data in small packets from a single WebSocket to then push it through to my AWS Kinesis Steam for processing. I am using Python v3.6. At the moment I am using pythons synchronous web socket library websocket-client and I am having no problem pulling and pushing to my Stream. Would I be better of to use the WebSockets library for asynchronous sockets? I'm concerned that the blocking in the loop structure of WebSocket request may be a bottleneck. while True: session = boto3.Session(aws_key, aws_secretkey) kinesis = session.client('kinesis', region_name='us-east-1') conn = ws.create_connection(url, sslopt={"cert_reqs": ssl.CERT_NONE}) count = 0 data = [] try: while True: msg = json.dumps(json.loads(conn.recv())['data']) data.append({'Data':msg, 'PartitionKey':'trade'}) count += 1 if count == 100: kinesis.put_records(StreamName = 'Binance_Stream', Records = data) count = 0 data = [] print('100 msg posted') except (ws.WebSocketConnectionClosedException, SQLAlchemyError) as e: print('Connection Error: ' + e)
upvote count: 2
type: UnansweredQuestion
tagged with: sockets
tagged with: io
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51936793

http://stackoverflow.com/comment/83363536
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48188468
has text: Sorry @Nurgle, this didn't work. After executing the python code `python app.py | tee output.txt.` it didn't go through
type: Comment

http://stackoverflow.com/a/48242094
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48241888
has body: Sounds like you are working in a virtual environment, yet your Django dependency is installed globally. Check which Python packages are installed globally and uninstall Django (you probably don't need it globally). Then install it into your virtual environment. Now the freeze command should output Django as well. General note: Most packages should be installed into your project virtual environment. There are only few packages where it makes sense to install them globally (eg aws management tools).
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48241888
upvote count: 1

http://stackoverflow.com/q/48296708
tagged with: python
linked to: http://stackoverflow.com/q/42620601
has body: I tried to create a 2D plot using QGraphicsItem, I was successful in doing that but when I drag the QGraphicsItem there is a delay and the view is distorted. Searching for a solution, I came across this QGraphicsItem paint delay. I applied the mouseMoveEvent to my QGraphicsView but it did not resolve the problem. Could someone tell me what is causing the problem and how can I fix it? Here is my code: from PyQt4 import QtGui, QtCore import sys import numpy as np class MyGraphicsItem(QtGui.QGraphicsItem): def __init__(self,dataX,dataY): super(MyGraphicsItem,self).__init__() self.Xval = dataX self.Yval = dataY self.Xvalmin = np.min(self.Xval) self.Xvalmax = np.max(self.Xval) self.Yvalmin = np.min(self.Yval) self.Yvalmax = np.max(self.Yval) self.rect = QtCore.QRectF(0,0,100,2) self.points = [] self._picture = None def paint(self, QPainter, QStyleOptionGraphicsItem, QWidget_widget=None): if self._picture is None: self._picture = QtGui.QPicture() QPainter.begin(self._picture) startPoint = QtCore.QPointF(0, 0) cubicPath = QtGui.QPainterPath() cubicPath.moveTo(startPoint) for i in range(len(self.points) - 2): points_ = self.points[i:i+3] cubicPath.cubicTo(*points_) QPainter.setPen(QtGui.QPen(QtCore.Qt.red)) QPainter.drawLine(0,10,100,10) QPainter.drawLine(0,-10,0,10) QPainter.setPen(QtGui.QPen(QtCore.Qt.black)) QPainter.drawPath(cubicPath) QPainter.end() else: self._picture.play(QPainter) def boundingRect(self): return self.rect class mygraphicsview(QtGui.QGraphicsView): def __init__(self): super(mygraphicsview,self).__init__() def mouseMoveEvent(self, event): QtGui.QGraphicsView.mouseMoveEvent(self,event) if self.scene().selectedItems(): self.update() class Mainwindow(QtGui.QMainWindow): def __init__(self): super(Mainwindow,self).__init__() self.main_widget = QtGui.QWidget() self.vl = QtGui.QVBoxLayout() self.scene = QtGui.QGraphicsScene() self.view = mygraphicsview() self.Xval = np.linspace(0,100,1000) self.Yval = np.sin(self.Xval) self.painter = QtGui.QPainter() self.sty…
tagged with: qgraphicsscene
has title: QGraphics Item Creates a delay in painting
score: 0
answer count: 1
type: Question
tagged with: qgraphicsview
tagged with: qgraphicsitem
has answer: http://stackoverflow.com/a/48298973
type: UnansweredQuestion
tagged with: pyqt4

http://stackoverflow.com/q/48260756
has answer: http://stackoverflow.com/a/48297750
has comment: http://stackoverflow.com/comment/83818115
downvote count: 2
upvote count: 1
has title: Basic Python function in azure notebook
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83505325
has body: Morning folks, so I've been learning python recently to get into programming and whatnot, and I've hit a bump when learning functions. I'm using the azure notebook IDE and when I try to run this code: say_cheese(): print("Say cheese, kids!") print("Cheese!") say_cheese() It's not working and I don't understand why. There's no syntax error, it just doesn't get an output.
type: UnansweredQuestion
tagged with: azure
has comment: http://stackoverflow.com/comment/83846156
has comment: http://stackoverflow.com/comment/83907907
has answer: http://stackoverflow.com/a/48261315
tagged with: python
score: -1
answer count: 2

http://stackoverflow.com/comment/83569678
type: QuestionComment
comment on: http://stackoverflow.com/q/48292152
has text: Try this code: `with open('f_bf_'+str(i)+'/my_pbs', 'w') as f: f.write(content_pbs)`
score: 0
type: Comment

http://stackoverflow.com/comment/83385790
comment on: http://stackoverflow.com/a/48202138
type: Comment
has text: `iteritems`, and this is a standard method on dictionaries in python2.7 that is equivalent to `items` in python 3
type: AnswerComment
score: 0

http://stackoverflow.com/a/48255471
score: -7
answers question: http://stackoverflow.com/q/48255244
has body: You could create a set containing the cyrillic letters and just check each character of the string: cyrillic_letters = {....} # fill it with the cyrillic letters def has_cyrillic(text): for c in text: if c in cyrillic_letters: return True return False
type: Answer
upvote count: 0
downvote count: 7

http://stackoverflow.com/q/48174011
has answer: http://stackoverflow.com/a/48174105
possible better answer: http://stackoverflow.com/a/48174819
has comment: http://stackoverflow.com/comment/83328453
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48174819
has body: I'm running apache2 web server on raspberry pi3 model B. I'm setting up smart home running with Pi's and Uno's. I have a php scrypt that executes python program>index.php. It has rwxrwxrwx >I'll change that late becouse i don't fully need it. And i want to real-time display print from python script. exec('sudo python3 piUno.py') Let's say that output is "Hello w" How can i import/get printed data from .py?
tagged with: raspberry-pi3
has comment: http://stackoverflow.com/comment/83328833
accepted answer: http://stackoverflow.com/a/48174105
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83328590
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83330123
has comment: http://stackoverflow.com/comment/83329711
has title: get python to print/return value on your website with php
tagged with: python
tagged with: php

http://stackoverflow.com/q/48281528
accepted answer: http://stackoverflow.com/a/48283123
has body: I have a problem to understand how asyncio works if I create a future future = asyncio.Future() then add add_done_callback(done_callback) and after that cancel the future future.cancel() the done_callback not suppose to get fired? I tried to use the loop.run_forever() but I end up with infinite loop. I have a small example code: _future_set = asyncio.Future() def done_callback(f): if f.exception(): _future_set.set_exception(f.exception) elif f.cancelled(): _future_set.cancel() else: _future_set.set_result(None) async def check_stats(future): while not future.cancelled(): print("not done") continue loop.stop() def set(future): if not _future_set.done(): future.add_done_callback(done_callback) loop = asyncio.new_event_loop() future = loop.create_future() asyncio.ensure_future(check_stats(future), loop=loop) set(future) future.cancel() loop.run_forever() # infinite print(_future_set.cancelled()) I know something is missing and maybe this is not the behavior but I will be happy for a little help here. I am using python 3.6 **update After set is fire and I bind the add_done_callback to the future when I cancel the future and the state of the future change to cancelled and done then I expect that _future_set will be cancelled too. and print(_future_set.cancelled()) will be True
upvote count: 1
has answer: http://stackoverflow.com/a/48283123
favorite count: 0
type: Question
tagged with: python-asyncio
has title: Python asyncio future add_done_callback then cancel the future
tagged with: python
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/83571178
type: AnswerComment
has text: @Daniel I suppose that would explain it. Excuse me, just a little bit awestruck.
comment on: http://stackoverflow.com/a/48291931
type: Comment
score: 0

http://stackoverflow.com/a/48192457
has comment: http://stackoverflow.com/comment/83366219
answers question: http://stackoverflow.com/q/48192290
type: AcceptedAnswer
has body: Your var is defined as a global variable. In each function when you're only reading the var you're accessing the global var, but the moment there's an assigned value to var somewhere in the function, python treats every var within the function as a local variable. Thus why your last function failed, because print(var) (the local varaible) was called before var = 8 was assigned. You can read up a bit about more in these threads: How bad is shadowing names defined in outer scopes? Python nonlocal statement The best thing to do is be explicit about your code so it's no longer confusing if you're trying to reference a local, nonlocal or global variable. In this case, assuming your intention is to keep using the global var, do this: var = 5 def func1(): print(var) func1() def func2(): global var var = 8 print(var) func2() def func3(): global var print(var) var = 8 # technically this is not necessary any more var = 8 was already assigned when func2() is called func3() The output is thus: 5 8 8 Edit: Thanks to juanpa.arrivillaga's comment - I missed your original question. How could I use a predefined global variable in a function, then define a local variable with the same name inside of the same function, without changing the value of the global variable ? ( in python of course ) The short answer is - define the local var first like you did in func2() and you're good. The longer answer though is - why would you want to do that? It creates confusion and becomes a headache to track which is when you have variables of the same name in different scope. A better approach would be name your local var to be local_var or something so it's distinctly different and easily traced.
has comment: http://stackoverflow.com/comment/83365709
score: 12
upvote count: 12
accepted answer of: http://stackoverflow.com/q/48192290
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83366271
has comment: http://stackoverflow.com/comment/83366497

http://stackoverflow.com/comment/83545290
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48280860
has text: Works fine thanks. I wrote locations manually as I see so will the program works for other computers as well ?
score: 0

http://stackoverflow.com/q/48261889
tagged with: python
tagged with: comparison
tagged with: diff
answer count: 0
score: 1
upvote count: 1
tagged with: compare
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
has body: The project I am working on involves running a compare algorithm on 2 versions of the same file and the writing the results to a single log. I am trying to use difflib.ndiff for this as I want the exact character that were changed, and unified/context diff do not give such results. ndiff returns a "Differ style delta", the bad part is that this is basically an iterator for a list of strings as far as I can see. After the comparison i would like to add line numbers and some other elements to make the comparison clearer. For example: File 1: line not in file 2 line different from file 2 File 2: line different from file 1 The output is: - line not in file 2 - line different from file 2 ? ^ + line different from file 1 ? ^ Indicating that the first line from the second file is not in the first file too, and indicating the exact character that was changed. I would like for the output to be even more explicit, something like: Line 1 from file 2 not found in file 1. - line not in file 2 Line 2 from file 2 has different characters than in file 2. - line different from file 2 ? ^ + line different from file 1 ? ^ Problem is that for this i need to somehow interpret the mess of strings that ndiff returns. Is there a way to actually get the SequenceMatcher of Differ objects back so I can read and process 1 entire difference at a time rather than 1 line of text? Also, am I going at this from the wrong angle? Is there a library to do this or something of the sort? Thank you in advance!
type: UnansweredQuestion
has title: Python difflib getting coherent data from ndiff instead of plain strings

http://stackoverflow.com/a/48201433
type: Answer
has body: General solution with a list comprehension and clever unpacking: pd.DataFrame( [[x] + b for a, *b in df.values for x in a], columns=df.columns ) col1 col2 0 a 1 1 s 1 2 d 1 3 f 1 4 x 2 5 y 2 6 q 3
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/83383958
has comment: http://stackoverflow.com/comment/83383809
downvote count: 0
answers question: http://stackoverflow.com/q/48197234
has comment: http://stackoverflow.com/comment/83383795

http://stackoverflow.com/a/48288845
has comment: http://stackoverflow.com/comment/83564734
has comment: http://stackoverflow.com/comment/83564869
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48287470
has body: I tried to export it to html and it worked normally. Where did you define your html? Did you used the Markdown textfields? Alternatives: I don't have the nbconverter, but what about exporting it to html and use another tool to convert it to a pdf? Use markdown language, it provides tables. Link: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet Consider upgrading your notebook

http://stackoverflow.com/a/48299999
downvote count: 0
upvote count: 1
has body: You can use extract with regex: df = df.T pat = df.index.str.extract('(^S\d,\d)', expand=False) print (pat) Index(['S1,0', 'S1,0', 'S1,0', 'S1,1', 'S1,1', 'S1,1', 'S2,0', 'S2,0', 'S2,1', 'S2,1'], dtype='object') df = df.groupby(pat).agg(['mean','std']) .T .swaplevel(0,1) .sort_index() .rename({'mean':'m','std':'s'}) print (df) S1,0 S1,1 S2,0 S2,1 m 0 2.333333 2.333333 2.500000 2.000000 1 2.000000 0.666667 0.500000 2.500000 2 2.000000 1.666667 0.500000 3.000000 s 0 2.081666 1.154701 0.707107 2.828427 1 2.000000 0.577350 0.707107 2.121320 2 1.732051 1.527525 0.707107 0.000000 Another solution without transposing, but concat is necessary: pat = df.columns.str.extract('(^S\d,\d)', expand=False) g = df.groupby(pat, axis=1) df = pd.concat([g.mean(), g.std()], keys=('m','s')) print (df) S1,0 S1,1 S2,0 S2,1 m 0 2.333333 2.333333 2.500000 2.000000 1 2.000000 0.666667 0.500000 2.500000 2 2.000000 1.666667 0.500000 3.000000 s 0 2.081666 1.154701 0.707107 2.828427 1 2.000000 0.577350 0.707107 2.121320 2 1.732051 1.527525 0.707107 0.000000
accepted answer of: http://stackoverflow.com/q/48299874
has comment: http://stackoverflow.com/comment/83584695
answers question: http://stackoverflow.com/q/48299874
has comment: http://stackoverflow.com/comment/83584756
type: Answer
has comment: http://stackoverflow.com/comment/83584799
has comment: http://stackoverflow.com/comment/83584671
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/62918843
score: 0
has comment: http://stackoverflow.com/comment/111266370
type: Answer
answers question: http://stackoverflow.com/q/48228755
has body: def binary_search(arr, val, start, end): if start == end: #折半到最后start和end可能会相等，递归退出条件之一 if arr[start] &gt; val: return start else: return start+1 if start + 1 == end: #折半到最后start和end相差1，递归退出条件之一 return start+1 mid = (start+end)//2 if arr[mid] &lt; val: return binary_search(arr,val,mid, end) elif arr[mid] &gt; val: return binary_search(arr, val, start, mid) else: return mid #折半遇到mid值与val相等，递归退出条件之一 def insertion_sort(arr:list): for i in range(1, len(arr)): if arr[i] &lt;= arr[0]: index = 0 elif arr[i] &gt;= arr[i-1]: continue else: index = binary_search(arr[0:i],arr[i],0, i-1) arr = arr[:index]+ [arr[i]] + arr[index:i] + arr[i+1:] return arr arr = [30,20,80,40,50,10,60,70,90] insertion_sort(arr)

http://stackoverflow.com/comment/83528742
type: QuestionComment
comment on: http://stackoverflow.com/q/48272475
has text: *Why is a function named?* Do you think there is an answer to that? the most likely thing is that you like it, the name of a function does not have to have any basis, it would be best if you write an email to the numpy developers asking them because they are the only ones who know the reason.
score: 0
type: Comment

http://stackoverflow.com/q/48326454
type: AnsweredQuestion
answer count: 2
downvote count: 0
has title: Why tensorflow random_normal function gives different outputs with a fixed seed value
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/48326576
tagged with: tensorflow
favorite count: 0
type: Question
has body: I set fixed a seed value and run the session using following line of codes. with tf.Session() as sess: matrix = tf.random_normal([2,2], mean=1, stddev=1, seed=1) print(matrix.eval()) print(matrix.eval()) print(matrix.eval()) print(sess.run(matrix)) print(sess.run(matrix)) print(sess.run(matrix)) print(sess.run(matrix)) But the code gave me the output like this, [[1.2818339 3.3878284] [3.2804048 0.691338 ]] [[0.84588486 1.3642604 ] [1.6235023 0.96976113]] [[2.3133767 2.4734092] [1.6430309 0.7378005]] [[ 1.8944461 0.39336425] [ 0.1861412 -0.01721728]] [[-0.6642921 2.3849297 ] [-0.06870818 -0.1625154 ]] [[ 1.0668459 0.45170426] [ 2.4276698 -0.24925494]] [[1.8668368 1.3444978 ] [1.5144594 0.31290668]] I expect to print exact values because i fixed the seed value. Why does it print out a different values? Thanks
possible better answer: http://stackoverflow.com/a/48326698
linked to: http://stackoverflow.com/q/22639587
has answer: http://stackoverflow.com/a/48326698
has answer: http://stackoverflow.com/a/48326576
tagged with: python

http://stackoverflow.com/a/62563406
has body: Delete existing migrations, drop the database and create it again(WITH THE SAME NAME), make new migrations and you're good to go
upvote count: 0
answers question: http://stackoverflow.com/q/48230518
downvote count: 1
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/110641421

http://stackoverflow.com/comment/83340672
score: 1
type: Comment
type: QuestionComment
has text: You'll need a capture group you can reference. `re.sub(r'(\d+)\xa0', r' \1.', i`
comment on: http://stackoverflow.com/q/48180363

http://stackoverflow.com/a/48264739
upvote count: 4
answers question: http://stackoverflow.com/q/48264698
downvote count: 0
score: 4
has body: Named arguments are not supported in C. All arguments must be passed in the correct order.
type: Answer

http://stackoverflow.com/q/48259567
type: Question
has title: How to configure Python syslog logging in local system?
has comment: http://stackoverflow.com/comment/83501957
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83502283
tagged with: python
tagged with: syslog
tagged with: logging
score: 0
answer count: 0
has body: I have configured my Python logger to write logs to syslog using the SysLogHandler. In SysLogHandler configuration, when I set the address as '/dev/log', both application and access logs are written to var/log/syslog file. Now, for testing on my local system instead of a remote log server, using the below netcat command I open up a UDP port where the logs should be written nc -l -u 10003 I have also updated the address in SysLogHandler as ('localhost', 10003), but when I start my application, only the application logs are written and the access logs are not written. I have two different loggers for application logs and access logs and I have set the same SysLogHandler configuration for both loggers. Is there some other configuration that needs to be done and I am missing it? Here's the configuration json for the application and access loggers "cherrypy_access": { "level": "INFO", "class": "logging.handlers.SysLogHandler", "address": [ "localhost", 10003 ], "facility": "auth", "formatter": "jsonacc" }, "cherrypy_error": { "level": "INFO", "class": "logging.handlers.SysLogHandler", "address": [ "localhost", 10003 ], "facility": "auth", "formatter": "jsonapp" }
has comment: http://stackoverflow.com/comment/83502568
has comment: http://stackoverflow.com/comment/83503859

http://stackoverflow.com/a/48276832
answers question: http://stackoverflow.com/q/48273099
has comment: http://stackoverflow.com/comment/83567219
has body: I think your problem has to do with the date format of your data. If you provide a format string to to_datetime(), you should be all set. df = pd.read_csv('MatplotLibTSManipulation.csv') df.Date = pd.to_datetime(df.Date, format='%d-%m-%Y %H:%M:%S') ax = df.set_index('Date').plot()
type: Answer
accepted answer of: http://stackoverflow.com/q/48273099
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48236081
tagged with: turtle-graphics
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48236113
linked to: http://stackoverflow.com/q/40050438
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/83455067
has answer: http://stackoverflow.com/a/48236166
has comment: http://stackoverflow.com/comment/83454912
answer count: 3
has title: How to get multiple conditionals to execute at the same time?
has answer: http://stackoverflow.com/a/48236221
upvote count: 0
has comment: http://stackoverflow.com/comment/83456477
has comment: http://stackoverflow.com/comment/83455116
downvote count: 3
has comment: http://stackoverflow.com/comment/83455283
favorite count: 0
type: Question
has body: I decided to try to do a turtle project to learn the random commands. My question is in this code: pos = 360 while a.ycor()&lt;pos: a.forward(randint(1,5)) while b.ycor()&lt;pos: b.forward(randint(1,5)) while c.ycor()&lt;pos: c.forward(randint(1,5)) while d.ycor()&lt;pos: d.forward(randint(1,5)) while e.ycor()&lt;pos: e.forward(randint(1,5)) how can I get all the conditionals to execute at the same time to start the race (all turtles take off at the same time)?

http://stackoverflow.com/comment/111591162
type: QuestionComment
has text: you can consider taking a look at this tool or contribute to the project since you share the same goal: https://github.com/nidhaloff/deep_translator
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48226763

http://stackoverflow.com/comment/83528558
has text: `Timer` only runs once (after 2 seconds in your case), as per the documentation.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48271001

http://stackoverflow.com/q/48178086
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48178123
answer count: 2
tagged with: arrays
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83336371
favorite count: 0
tagged with: tuples
possible better answer: http://stackoverflow.com/a/48178633
type: Question
has body: I have an array of coordinates as follows: [array([[ 72.57218373, 247.1759997 ]]), array([[ 262.51505688, 158.68137977]]), array([[ 244.53157113, 100.05665591]]), array([[ 245.30108919, 88.97536043]]), array([[ 43.60839312, 82.11394031]]), array([[ 260.62555476, 161.252084 ]]), array([[ 234.46830867, 269.07508699]]), array([[ 284.51718016, 142.55126301]]), array([[ 195.30252058, 84.7559498 ]]), array([[ 141.08621668, 276.6625877 ]]), array([[ 294.18468717, 131.91470926]]), array([[ 35.46840935, 51.14890688]]), array([[ 36.15758189, 131.19703618]]), array([[ 175.95018737, 216.52553084]]), array([[ 62.99149427, 217.7800738 ]]), array([[ 245.81708339, 10.06949286]]), array([[ 137.31450413, 145.10778886]]), array([[ 197.76975618, 75.96150192]]), array([[ 17.87096457, 120.88350573]]), array([[ 262.89229921, 287.40287273]]), array([[ 177.51716203, 101.5694418 ]]), array([[ 97.76530613, 190.06919232]]), array([[ 229.31904186, 97.92874288]])] I want to convert this into points so that my final list should be of the form [(72.57218373, 247.1759997), (262.51505688, 158.68137977), ( 244.53157113, 100.05665591), (245.30108919, 88.97536043), (43.60839312, 82.11394031), (260.62555476, 161.252084), ...] Can someone please give me a help to get this in Python? Thanks,
has answer: http://stackoverflow.com/a/48178633
has title: list of numpy arrays to list of co-ordinate points conversion
has answer: http://stackoverflow.com/a/48178123
tagged with: python
tagged with: numpy
has comment: http://stackoverflow.com/comment/83336381
tagged with: python-3.x

http://stackoverflow.com/q/48180718
has title: 'int' object is not subscriptable (scraping tables from website)
has comment: http://stackoverflow.com/comment/83350361
tagged with: pandas
has comment: http://stackoverflow.com/comment/83341592
has answer: http://stackoverflow.com/a/48180991
score: 2
accepted answer: http://stackoverflow.com/a/48180991
type: AnsweredQuestion
has body: I am painfully new to coding... I just learned how to use the terminal approximately one week ago if that gives you any idea of how n00bish I am. I need to learn how to scrape data from websites so I am practicing on websites that I am familiar with, and I'm trying to create a csv file that shows the data from this url: http://phish.net/song. I essentially modified code from this site (https://chihacknight.org/blog/2014/11/26/an-intro-to-web-scraping-with-python.html) and I'm trying to use it. from bs4 import BeautifulSoup import requests import pandas as pd url = "http://phish.net/song?" r = requests.get(url) data = r.text soup = BeautifulSoup(data, "lxml") table = soup.find('table') rows = table.find('tr') data = { 'song': [], 'original_artist': [], 'times': [], 'debut': [], 'last': [], 'gap': [] } for row in rows: cols = row.find('td') data['song'].append(cols[0].get_text())) data['original_artist'].append(cols[1].get_text()) data['times'].append(cols[2].get_text()) data['debut'].append(cols[3].get_text()) data['last'].append(cols[4].get_text()) data['gap'].append(cols[5].get_text()) phishData = pd.DataFrame(data) phishData.to_csv("PhishData.csv") I receive the following error: Traceback (most recent call last): File "phishnet.py", line 20, in &lt;module&gt; data['song'].append(str(cols[0].get_text())) TypeError: 'int' object is not subscriptable Which object is the one that's not subscriptable? And how do I fix this problem? Thanks in advance for your help and please tell me if this is not an appropriate use of this forum.
downvote count: 0
has comment: http://stackoverflow.com/comment/83341405
answer count: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: typeerror
type: Question
upvote count: 2
tagged with: python

pyyaml
tags question: http://stackoverflow.com/q/48234119
type: Tag
tag name: pyyaml

http://stackoverflow.com/a/48325613
score: 0
has comment: http://stackoverflow.com/comment/83651766
has body: placeholder is just an empty variable in tensorflow, to which you can feed numpy values. Now, what you are trying to do does not make sense. You can not get value out of an empty variable. If you want to standardize your tensor, why convert it to numpy var first? You can directly do this using tensorflow. The following taken from this stackoverflow ans def get_median(v): v = tf.reshape(v, [-1]) m = v.get_shape()[0]//2 return tf.nn.top_k(v, m).values[m-1] Now, you can implement your function as def standardize(x): med0 = get_median(x) mad0 = get_median(tf.abs(x - med0)) x1 = (x - med0)/(mad0 + eps) return x1
type: Answer
answers question: http://stackoverflow.com/q/48325147

http://stackoverflow.com/comment/83618960
comment on: http://stackoverflow.com/q/48316794
type: Comment
has text: Try https://stackoverflow.com/questions/23692950/how-do-you-suppress-output-in-ipython-notebook
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83771294
type: QuestionComment
has text: I followed what "wwii" suggested and it worked. Thanks, all! @MadPhysicist Sorry about that. Will keep that in mind henceforth.
type: Comment
comment on: http://stackoverflow.com/q/48256956
score: 0

multiline
tags question: http://stackoverflow.com/q/48190801
type: Tag
tag name: multiline

http://stackoverflow.com/a/48227647
has comment: http://stackoverflow.com/comment/83444371
type: Answer
has comment: http://stackoverflow.com/comment/83444422
score: 0
answers question: http://stackoverflow.com/q/48227571
has body: I normally use JYthon. Making use of Java from within Jython applications is about as seamless as using external Jython modules within a Jython script. Here is a simple example: from java.lang import Math Math.max(4, 7) Math.pow(10,5) from java.lang import System as javasystem javasystem.out.println("Hello") Hello

http://stackoverflow.com/comment/83532333
score: 2
has text: FWIW: The networkx package is entirely written in Python, so generally if you write your own method well, it won't be much different from the networkx version (though I strongly recommend using the networkx version when it exists for usability and better confidence that it's right). igraph has more of the background written in C.
comment on: http://stackoverflow.com/q/48274278
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48305298
has comment: http://stackoverflow.com/comment/83595687
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83595588
has comment: http://stackoverflow.com/comment/83595750
type: AnsweredQuestion
upvote count: 0
has body: How to check if part of the string is '\'. I'm having trouble since \ is a special symbol. In other languages this could be checked with something like s[i]=='\', but I am having no luck with Python so far. Edit:Oh my bad, I meant \, don't know how this slipped up, sorry, edited now.
answer count: 1
tagged with: string
downvote count: 1
has title: How to check if string element in i'th place in string is '\'?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48305392
has answer: http://stackoverflow.com/a/48305392
has comment: http://stackoverflow.com/comment/83595581

http://stackoverflow.com/comment/83502970
type: QuestionComment
type: Comment
has text: I seems that it's trying to access *localhost:8080*. Is a server application running on your machine that listens on that port?
score: 0
comment on: http://stackoverflow.com/q/48259919

http://stackoverflow.com/comment/89150284
type: AnswerComment
comment on: http://stackoverflow.com/a/48277811
has text: get_host gets me the local IP rather than the virtual host configured by nginx.
type: Comment
score: 0

http://stackoverflow.com/q/48230031
score: 12
type: Question
tagged with: deconvolution
answer count: 2
has title: Tensorflow Convolution Neural Network with different sized images
upvote count: 12
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48273664
has answer: http://stackoverflow.com/a/48306714
has body: I am attempting to create a deep CNN that can classify each individual pixel in an image. I am replicating architecture from the image below taken from this paper. In the paper it is mentioned that deconvolutions are used so that any size of input is possible. This can be seen in the image below. Github Repository Currently, I have hard coded my model to accept images of size 32x32x7, but I would like to accept any size of input. What changes would I need to make to my code to accept variable sized input? x = tf.placeholder(tf.float32, shape=[None, 32*32*7]) y_ = tf.placeholder(tf.float32, shape=[None, 32*32*7, 3]) ... DeConnv1 = tf.nn.conv3d_transpose(layer1, filter = w, output_shape = [1,32,32,7,1], strides = [1,2,2,2,1], padding = 'SAME') ... final = tf.reshape(final, [1, 32*32*7]) W_final = weight_variable([32*32*7,32*32*7,3]) b_final = bias_variable([32*32*7,3]) final_conv = tf.tensordot(final, W_final, axes=[[1], [1]]) + b_final
type: AnsweredQuestion
tagged with: conv-neural-network
tagged with: deep-learning
possible better answer: http://stackoverflow.com/a/48273664
accepted answer: http://stackoverflow.com/a/48306714
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/a/48216957
has comment: http://stackoverflow.com/comment/83416806
has comment: http://stackoverflow.com/comment/83416920
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48216692
has comment: http://stackoverflow.com/comment/83416511
has comment: http://stackoverflow.com/comment/83416715
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83416517
has comment: http://stackoverflow.com/comment/83416890
accepted answer of: http://stackoverflow.com/q/48216692
has comment: http://stackoverflow.com/comment/83416638
has body: Try setting the tick_label property of each bar plot like this: bar1 = plt.bar(index, not_inducted_df_mean, bar_width, color='r', label='Not Inducted', tick_label=['W','L']) or try setting the plt.xticks() like this: plt.xticks( [0.0, 0.3, 1.0, 1.3], ('W', 'L', 'W', 'L') )

http://stackoverflow.com/q/48278354
tagged with: django
type: Question
possible better answer: http://stackoverflow.com/a/48278885
has comment: http://stackoverflow.com/comment/83540069
has comment: http://stackoverflow.com/comment/83540112
tagged with: python
has answer: http://stackoverflow.com/a/48280538
type: AnsweredQuestion
score: 0
answer count: 2
has body: So I want to create a field in my Django models.py, so that the user can select a number of years as integer (e.g. 3) and then after each new entry the words 'years' to be automatically displayed. I do not want to do this with CharField. class StudyProgramme(models.Model): period = models.IntegerField(2)
accepted answer: http://stackoverflow.com/a/48280538
has answer: http://stackoverflow.com/a/48278885
has title: I want to crate a Django field in my model to display a word after each new entry

arrays
tags question: http://stackoverflow.com/q/48251448
tags question: http://stackoverflow.com/q/48265535
tags question: http://stackoverflow.com/q/48281837
tags question: http://stackoverflow.com/q/48282748
tags question: http://stackoverflow.com/q/48310067
tags question: http://stackoverflow.com/q/48218766
tags question: http://stackoverflow.com/q/48290719
tags question: http://stackoverflow.com/q/48247522
tags question: http://stackoverflow.com/q/48250315
tag name: arrays
tags question: http://stackoverflow.com/q/48240139
tags question: http://stackoverflow.com/q/48272285
tags question: http://stackoverflow.com/q/48178213
tags question: http://stackoverflow.com/q/48221710
tags question: http://stackoverflow.com/q/48191873
type: Tag
tags question: http://stackoverflow.com/q/48215857
tags question: http://stackoverflow.com/q/48250981
tags question: http://stackoverflow.com/q/48178086
tags question: http://stackoverflow.com/q/48257156
tags question: http://stackoverflow.com/q/48202923
tags question: http://stackoverflow.com/q/48253560
tags question: http://stackoverflow.com/q/48183584
tags question: http://stackoverflow.com/q/48205806
tags question: http://stackoverflow.com/q/48256088
tags question: http://stackoverflow.com/q/48237735
tags question: http://stackoverflow.com/q/48254918
tags question: http://stackoverflow.com/q/48217127
tags question: http://stackoverflow.com/q/48245987
tags question: http://stackoverflow.com/q/48186116
tags question: http://stackoverflow.com/q/48253428
tags question: http://stackoverflow.com/q/48247021
tags question: http://stackoverflow.com/q/48266387
tags question: http://stackoverflow.com/q/48320432
tags question: http://stackoverflow.com/q/48263875
tags question: http://stackoverflow.com/q/48329635
tags question: http://stackoverflow.com/q/48242064
tags question: http://stackoverflow.com/q/48323576
tags question: http://stackoverflow.com/q/48182833
tags question: http://stackoverflow.com/q/48245175
tags question: http://stackoverflow.com/q/48199077
tags question: http://stackoverflow.com/q/48248773
tags question: http://stackoverflow.com/q/48319341
tags question: http://stackoverflow.com/q/48268317
tags question: http://stackoverflow.com/q/48330460
tags question: http://stackoverflow.com/q/48256058
tags question: http://stackoverflow.com/q/48329684
tags question: http://stackoverflow.com/q/48230230
tags question: http://stackoverflow.com/q/48293509
tags question: http://stackoverflow.com/q/48242885
tags question: http://stackoverflow.com/q/48265550
tags question: http://stackoverflow.com/q/48178884
tags question: http://stackoverflow.com/q/48244794
tags question: http://stackoverflow.com/q/48199688
tags question: http://stackoverflow.com/q/48254692
tags question: http://stackoverflow.com/q/48198153
tags question: http://stackoverflow.com/q/48293161
tags question: http://stackoverflow.com/q/48219085
tags question: http://stackoverflow.com/q/48322566
tags question: http://stackoverflow.com/q/48195845
tags question: http://stackoverflow.com/q/48221841
tags question: http://stackoverflow.com/q/48218862
tags question: http://stackoverflow.com/q/48264483
tags question: http://stackoverflow.com/q/48212186
tags question: http://stackoverflow.com/q/48209760
tags question: http://stackoverflow.com/q/48206622
tags question: http://stackoverflow.com/q/48269152
tags question: http://stackoverflow.com/q/48247606
tags question: http://stackoverflow.com/q/48246135
tags question: http://stackoverflow.com/q/48299900
tags question: http://stackoverflow.com/q/48181613
tags question: http://stackoverflow.com/q/48197173
tags question: http://stackoverflow.com/q/48302009
tags question: http://stackoverflow.com/q/48200911
tags question: http://stackoverflow.com/q/48205670
tags question: http://stackoverflow.com/q/48286142
tags question: http://stackoverflow.com/q/48191060
tags question: http://stackoverflow.com/q/48330389
tags question: http://stackoverflow.com/q/48318113
tags question: http://stackoverflow.com/q/48262526

http://stackoverflow.com/comment/83585794
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48300337
score: 0
has text: @Thaise You're welcome. You can also upvote the answer if it was helpful. Cheers.

http://stackoverflow.com/comment/83477176
comment on: http://stackoverflow.com/q/48246955
has text: To answer your last question, no, `df.columns` is a list/array, and they support random access.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83540969
has text: As suggested by @MarcinZablocki, we will need some information about what you have already achieved and a [Minimal, Complete and Verifiable example](https://stackoverflow.com/help/mcve) over which we can work.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48274659
type: Comment

http://stackoverflow.com/comment/83600316
score: 0
has text: Ah, so you have a name conflict. request vs request
comment on: http://stackoverflow.com/q/48307390
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48302876
type: Question
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/48303455
has comment: http://stackoverflow.com/comment/83590725
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83590530
answer count: 1
has comment: http://stackoverflow.com/comment/83590935
has title: dtype changes after set_value/at
has comment: http://stackoverflow.com/comment/83590465
has comment: http://stackoverflow.com/comment/83590805
has comment: http://stackoverflow.com/comment/83590379
tagged with: python
has body: I'm facing a weird issue on Pandas now, not sure if a pandas pitfall or just something I'm missing... My pd.Series is just foo False False False &gt; a.foo.dtype dtype('bool') When I use a dataframe.set_value(index, col, None), my whole Series is converted to dtype('float64') (same thing applies to a.at[index, col] = None). Now my Series is foo NaN NaN NaN Do you have any idea on how this happens and how to fix it? Thanks in advance. :) Edit: Using 0.20.1.

http://stackoverflow.com/q/48263108
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83511740
tagged with: c++
type: AnsweredQuestion
has title: Cython: Numpy array missing two first elements when obtained from reference
has comment: http://stackoverflow.com/comment/83509315
has body: This is the weirdest error, I'm trying to get a numpy array from a c++ function returning a reference to a vector, the whole wrapped using Cython. I can make it work returning a vector<int> instead of a vector<int>&, but I want to understand what is happening when working with references. Here is a way to reproduce the error: cmyclass.h #ifndef MYCLASS_H #define MYCLASS_H #include <vector> #include <string> namespace vec { class IntVector { private: std::vector<int> vec; public: IntVector(); virtual ~IntVector(); std::vector<int>& get_vec(); #return a reference ! }; } #endif cmyclass.cc #include "cmyclass.h" #include <iostream> using namespace vec; IntVector::IntVector(){ for(int i=10; i<20; ++i){ vec.push_back(i); } } IntVector::~IntVector(){ } std::vector<int>& IntVector::get_vec(){ std::vector<int> buff; buff.reserve(vec.size()); for(int i=0; i<vec.size(); ++i){ buff.push_back(vec[i]); } return buff; } myclass.pyx import numpy as np cimport numpy as np from libcpp.vector cimport vector cdef extern from "cmyclass.h" namespace "vec": cdef cppclass IntVector: IntVector() except + vector[int]& get_vec() cdef class IntVec: cdef IntVector* _thisptr def __cinit__(self): self._thisptr = new IntVector() def __dealloc__(self): del self._thisptr def __init__(self): pass def get_vec(self): cdef vector[int] buff; buff = self._thisptr.get_vec(); return np.asarray(buff) setup.py from distutils.core import setup from Cython.Build import cythonize from distutils.extension import Extension sourcefiles = ['myclass.pyx', 'cmyclass.cc'] compile_opts = ['-std=c++11'] ext=[Extension('*', sourcefiles, extra_compile_args=compile_opts, language='c++')] setup( ext_modules=cythonize(ext) ) You can compile using python setup.py build_ext --inplace Usecase >>> import myclass >>> vec = myclass.IntVec() >>> vec.get_vec() array([ 0, 0, 12, 13, 14, 15, 16, 17, 18, 19]) You can see the two first values are set to zero (they should be 10 and 11) ! The code would be working fine if we were returning…
has comment: http://stackoverflow.com/comment/83511868
answer count: 1
tagged with: cython
has comment: http://stackoverflow.com/comment/83509855
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48269554
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48269554
has comment: http://stackoverflow.com/comment/83513908
has comment: http://stackoverflow.com/comment/83511505

http://stackoverflow.com/a/48682669
has body: I have solved the problem, I rewrited the label function in bfs method, and it works well.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48313158

http://stackoverflow.com/comment/83385648
comment on: http://stackoverflow.com/a/48202359
has text: @cᴏʟᴅsᴘᴇᴇᴅ Actually, it's not the most idiomatic way, but it works well. You don't downvote just because it's not the best solution!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83613845
has text: npm install --save will keep after dependencies has been installed. your in initial stage you dont know how to install and nothing in it. so `pip freeze` only list default package like `six` `wsgi` if its django thats it..
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48314021
type: Comment

http://stackoverflow.com/q/48241459
has title: Pandas changing cell values dependent on other cell values in same row
type: Question
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/48249188
upvote count: 1
tagged with: python
downvote count: 1
favorite count: 0
score: 0
has body: I am working on a dataframe in which one of my columns needs to be updated and changed based on a set of criteria and data the other columns in the row provide. The row in question is List Price Currency. If the columns before it (Price Book Name) contains Amer, I want the List Price Currency to be updated to USD List. If the price book doesn't say Amer, I want the Currency to be updated to Intl USD. Otherwise, if the Price Book name contains GBP, I just want to change that to UK list, and EUR to Euro List. I tried writing a small for loop to go through each List Price Currency and update it based on what the Price Book Name says, but it isn't actually doing anything to the cells in the column. Any help or guidance would be greatly appreciated! for column in datagrouped['List Price Currency']: if 'List Price Currency' == "USD": if 'Price Book Name'.str.contains("Amer"): 'List Price Currency' == "US List" else: 'List Price Currency' == "Intl USD" if "List Price Currency" == "GBP": "List Price Currency" == "UK List" if "List Price Currency" == "EUR": "List Pricy Currency" == "Euro List"
tagged with: pandas
tagged with: dataframe

http://stackoverflow.com/comment/83622465
score: 0
type: AnswerComment
has text: I have changed the image to show a better example. Can the response card method work too?
comment on: http://stackoverflow.com/a/48314965
type: Comment

http://stackoverflow.com/q/48313993
accepted answer: http://stackoverflow.com/a/48318223
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48318223
tagged with: algorithm
upvote count: 0
tagged with: python
score: -1
downvote count: 1
has comment: http://stackoverflow.com/comment/83618997
has title: uniform cost search algorithm with python
tagged with: search
type: AnsweredQuestion
has body: Consider a state space where the start state is 2 and each state k has three successors: numbers 2k, 2k+1, 2k+2. The cost from state k to each respective child is k, ground(k/2), k+2. I would like to implement a uniform-cost-search algorithm with python. The goal state is number 85.
answer count: 1
has comment: http://stackoverflow.com/comment/83645152

http://stackoverflow.com/q/48263802
has answer: http://stackoverflow.com/a/48264852
tagged with: shapely
score: 1
answer count: 1
has body: I have a map.geojson file that contains the regional boundaries of a various cities. How can I calculate the region of a point given by (latitude, longitude)?
tagged with: geojson
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48264852
has title: Finding location using .geojson file using python
tagged with: python
linked to: http://stackoverflow.com/q/42753745
type: AnsweredQuestion
upvote count: 2
linked to: http://stackoverflow.com/q/30457089

http://stackoverflow.com/comment/83479416
has text: @vinodbhandary, can you post a small reproducible data set as text/CSV/Python code so we could copy and paste it?
score: 0
comment on: http://stackoverflow.com/a/48248460
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48237875
has answer: http://stackoverflow.com/a/48246780
tagged with: sim900
accepted answer: http://stackoverflow.com/a/48246780
favorite count: 0
type: Question
has body: I have a Sim900 from Sainsmart. I have a working serial connection from my Raspberry Pi to Sim900. I can write commands, receive responses, and even query data such as my phone number from the Sim Card. My Sim Card is an AT&amp;T card. I cannot make Sim900 find a network and attempt to connect. Supposedly, it is supposed to do it on its own, but I have not seen that either. The only two things I can think of are that either the firmware is wrong, or the chip is not getting enough power. The firmware (from AT+CGMR) is Revision:1137B06SIM900M64_ST_ENHANCE. This appears to be the latest firmware that you can get from Simcom's Site. As for power, I am pretty sure the power is sufficient as I bought a charger usb cable and adapter in which the adapter that came with the cable promised to support 2 amps. I stripped the cable and gave it a 3 amp supply of power. The chip also doesn't randomly reset when I try connecting it. I can set settings that get lost on power loss, but they only disappear when I unplug the chip to reset the settings. The below output is from my latest test to try to understand why I cannot send SMS. ---------------------------------------------------------------------------------------- Command: "b'AT\r\n\r\n'" Response: "AT OK " ---------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------- Command: "b'AT+CMEE=2\r\n'" Response: "AT+CMEE=2 OK " ---------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------- Command: "b'AT+CFUN?\r\n'" Response: "AT+CFUN? +CFUN: 1 OK " ---------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------- Command: "b'AT+CREG=2\r\n'" Response: "AT+CREG=2 OK " -------------------------------…
has comment: http://stackoverflow.com/comment/83464369
linked to: http://stackoverflow.com/q/1210934
tagged with: network-programming
upvote count: 1
tagged with: at-command
linked to: http://stackoverflow.com/q/46062323
tagged with: python
has comment: http://stackoverflow.com/comment/83465613
has comment: http://stackoverflow.com/comment/83464116
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83686216
has comment: http://stackoverflow.com/comment/83458554
has title: Sim900 Won't Find Networks
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83466025
has comment: http://stackoverflow.com/comment/83465229

http://stackoverflow.com/a/48203608
upvote count: 1
has body: Modify your apply a bit, to slice with respect to len(x['name']) - def f(x): return x['name'][:len(x['name']) - x['Length_to_drop']] df.apply(f, 1) 0 a 1 b 2 c dtype: object
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48203449
accepted answer of: http://stackoverflow.com/q/48203449
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83559688
type: QuestionComment
comment on: http://stackoverflow.com/q/48286543
score: 0
has text: It's a class method on `datetime.datetime`, not an instance method on `int`. Hence the *"classmethod"* in the docs. Take a look at the examples of another class method just above.
type: Comment

http://stackoverflow.com/comment/83562982
type: QuestionComment
score: 5
has text: Avoid using `list` as a variable name, it is normally a Python function.
type: Comment
comment on: http://stackoverflow.com/q/48288998

http://stackoverflow.com/q/48220098
has answer: http://stackoverflow.com/a/48221847
linked to: http://stackoverflow.com/q/6501121
answer count: 1
downvote count: 3
has body: I tried to make it only ask "do you want to continue" 3 times but it doesn't seem to work, it just kept on running. How do I fix this? It is a chat-response program which the computer askes one question and the user response. def choice(): prompts = [feeling, homesick, miss] random.choice(prompts)() for item in range(3): choice() This is the code I have written for it. but it does not work. import random name = input("What is your name? ") def restart(): restart=input('do you want to continue? ') if restart=='yes': choice() else: print("ok, see you later!") exit() def feeling(): response = input("How are you feeling right now {name}?".format(name=name)) if response == "tired": tired = ['I wish I can make you feel better.','I hope school is not making you feel stressed.','You deserve the right to relax.'] print(random.choice(tired)) restart() else: print("Sorry, I don't understand what you mean by "+response+".") exit() def homesick(): response = input("Do you miss your home? ") if response == "yes": yes=["Don't worry, you will be home soon......",'I am protecting your family and loved ones, trust me on this.',"Your kingdoms has been waiting for a long time, they'd forgiven your mistakes"] print(random.choice(yes)) restart() else: print("Sorry, I don't understand what you mean by "+response+".") exit() def miss(): response = input("Who do you miss?") if response == "my mom": print("Mom will be in town soon") restart() else: print("Sorry, I don't understand what you mean by "+response+".") exit() def choice(): prompts = [feeling, homesick, miss] random.choice(prompts)() for item in range(3): choice()
favorite count: 0
type: Question
score: -2
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83423227
has title: run the code multiple times in python 3.6
accepted answer: http://stackoverflow.com/a/48221847
type: AnsweredQuestion

http://stackoverflow.com/a/48319507
answers question: http://stackoverflow.com/q/48188940
upvote count: 7
downvote count: 1
has body: I wouldn't invest time in such an effort. These are some reasons: For simple functions (blur, erode, dilate) Halcon and OpenCV have different implementations of the same function and probably you will have slightly different outputs (one may round up and the other round down, for example). A complex program that runs properly in Halcon may fail in OpenCV for these small differences (a butterfly effect). Probably there are complex functions (pattern matching algorithms, deep learning), that exist in one environment and don't exist in the other. OpenCV users typically don't have Halcon IDE. I like OpenCV because it is open source and free, I won't consider using Halcon IDE because it is not. Moreover OpenCV has many functions and it improves very fast (I don't know Halcon). If Halcon was much better than OpenCV (more popular, faster, cross platform, with all OpenCV functions implemented in Halcon) and my project had the money, I would use Halcon IDE for development and I would use it in production as well (and completely ignore OpenCV). In either case, I wouldn't use a tool that converts one to the other. It is like writing the Linux kernel with Visual Studio, maybe someone does it, but I guess it is not the majority. If I had to spend time in an open source project, I would write a better OpenCV interface (as Vladimir Perković suggests). There are some efforts in that direction (probably there is something else if you search): Interactive Visual Debugging: https://docs.opencv.org/3.3.0/d7/dcf/tutorial_cvv_introduction.html I haven't tried that, but I have written and used similar tools in the past and is usually enough. Debug images in Visual Studio: https://docs.opencv.org/2.4/doc/tutorials/introduction/windows_visual_studio_image_watch/windows_visual_studio_image_watch.html What I really want to see some day is a visual programming language editor, where you drag and drop boxes and connect them (like in a flowchart). Something similar to LabVIEW, VPL, but open sour…
type: Answer
accepted answer of: http://stackoverflow.com/q/48188940
type: AcceptedAnswer
score: 6

http://stackoverflow.com/a/48209944
type: Answer
has body: First create Series with set_index and then Series.to_json: j = df.set_index('a')['b'].to_json() print (j) {"P1":7950,"P2":1274,"P3":6160} For file: df.set_index('a')['b'].to_json(filename)
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48209914
score: 3
accepted answer of: http://stackoverflow.com/q/48209914

http://stackoverflow.com/a/48233915
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/104345215
type: AcceptedAnswer
has body: Don't write each row as a separate call to json.dumps(). Collect all the rows into a list, and dump that all at once. To convert the string fields to integers, call int() on those entries in the dict. import json import csv with csvfile_ind = open("test.csv",'r'): reader_ind = csv.DictReader(csvfile_ind) rows = [] for row in reader_ind: row["RRC_attempts"] = int(row["RRC_attempts"]) row["rrc_succ_rate"] = int(row["rrc_succ_rate"]) rows.append(row) with json_file_ind = open("test_json.json", 'w'): json.dump(rows, json_file_ind, sort_keys=False, indent=4, separators=(',', ': '))
answers question: http://stackoverflow.com/q/48233433
type: Answer
accepted answer of: http://stackoverflow.com/q/48233433

http://stackoverflow.com/comment/135189414
has text: Approach #1 is great performance-wise, but it takes into consideration all non-ascii characters (e.g Chinese, Hindi) instead of only considering Cyrillic.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/61792465

http://stackoverflow.com/comment/83519614
score: 0
type: Comment
has text: Thanks a lot. This is exactly what we need.
type: AnswerComment
comment on: http://stackoverflow.com/a/48254431

http://stackoverflow.com/a/48256811
has comment: http://stackoverflow.com/comment/83496493
type: Answer
has body: os.makedirs() is the correct function, but is has no parameter exist_ok in Python 2. Instead use os.path.exists() like: if not os.path.exists(path_to_make): os.makedirs(path_to_make) Be aware that this does not exactly match the bahavior of the exist_ok flag in Python3. Closer to matching that would be something like: if os.path.exists(path_to_make): if not os.path.isdir(path_to_make): raise OSError("Cannot create a file when that file already exists: " "'{}'".format(path_to_make)) else: os.makedirs(path_to_make)
upvote count: 4
has comment: http://stackoverflow.com/comment/83496263
has comment: http://stackoverflow.com/comment/83496281
has comment: http://stackoverflow.com/comment/83499551
has comment: http://stackoverflow.com/comment/83496477
answers question: http://stackoverflow.com/q/48256779
has comment: http://stackoverflow.com/comment/83496272
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/83496462
accepted answer of: http://stackoverflow.com/q/48256779
score: 3

http://stackoverflow.com/q/48312376
has comment: http://stackoverflow.com/comment/83610677
has title: Export list of values into csv?
has body: I am using Python 2.x on Win7. My question is: I got a list of numbers: angle = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and I would like to export the numbers to a csv file. So the csv should look like: 0 | 1 | 2 |...| 10 | But so far what I got in csv file is: [0 | 1 | 2 |...| 10] | My code is: angle = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ldsvp = open("C:\Controlled NP\\" + "LDS1.csv", 'ab') with open('LDS1.csv', 'wb') as output: ldsvp.write('Angle' + ',' + str(angle)) ldsvp.write('\n') So...any advice to remove the [ and ] from the csv file?
type: Question
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/83610666
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48312665
has comment: http://stackoverflow.com/comment/83610566
linked to: http://stackoverflow.com/q/11178061
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83610636
upvote count: 2
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/83610582
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/13207697

javascript
tags question: http://stackoverflow.com/q/48325400
tags question: http://stackoverflow.com/q/48187696
tags question: http://stackoverflow.com/q/48323434
tags question: http://stackoverflow.com/q/48249705
tags question: http://stackoverflow.com/q/48309523
tags question: http://stackoverflow.com/q/48292443
tags question: http://stackoverflow.com/q/48235825
tags question: http://stackoverflow.com/q/48275290
tags question: http://stackoverflow.com/q/48288276
tags question: http://stackoverflow.com/q/48203171
tags question: http://stackoverflow.com/q/48195813
tags question: http://stackoverflow.com/q/48202737
tags question: http://stackoverflow.com/q/48249963
tag name: javascript
tags question: http://stackoverflow.com/q/48214192
tags question: http://stackoverflow.com/q/48304872
tags question: http://stackoverflow.com/q/48285458
tags question: http://stackoverflow.com/q/48282893
tags question: http://stackoverflow.com/q/48269945
tags question: http://stackoverflow.com/q/48179772
tags question: http://stackoverflow.com/q/48181988
tags question: http://stackoverflow.com/q/48224530
tags question: http://stackoverflow.com/q/48293879
tags question: http://stackoverflow.com/q/48189413
tags question: http://stackoverflow.com/q/48228110
tags question: http://stackoverflow.com/q/48226109
tags question: http://stackoverflow.com/q/48232641
tags question: http://stackoverflow.com/q/48228241
tags question: http://stackoverflow.com/q/48188060
tags question: http://stackoverflow.com/q/48229056
tags question: http://stackoverflow.com/q/48267084
tags question: http://stackoverflow.com/q/48205315
tags question: http://stackoverflow.com/q/48248502
tags question: http://stackoverflow.com/q/48192535
type: Tag
tags question: http://stackoverflow.com/q/48311151
tags question: http://stackoverflow.com/q/48206402
tags question: http://stackoverflow.com/q/48204925
tags question: http://stackoverflow.com/q/48273815
tags question: http://stackoverflow.com/q/48232072
tags question: http://stackoverflow.com/q/48190809

http://stackoverflow.com/comment/83617702
type: AnswerComment
has text: As in your original code. This is just showing the first element in the results. `formatted_address = data['results'][0]['formatted_address']` If you want to print all results you should simply add a for loop to iterate over the results.
comment on: http://stackoverflow.com/a/48240162
score: 0
type: Comment

http://stackoverflow.com/q/48282476
score: -4
has answer: http://stackoverflow.com/a/48284304
has body: I have 2 time stamps in the format YYYYMMDDHHMMSS. d1=20180110141907 d2=20180110141907 I want a shell script which find out the difference between 2 above dates and give the output as "4days 22hrs 56min 04sec".
tagged with: python
downvote count: 4
has comment: http://stackoverflow.com/comment/83548667
upvote count: 0
answer count: 2
tagged with: shell
has title: Difference of two time stamp in proper format
tagged with: unix
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48283110
type: UnansweredQuestion

http://stackoverflow.com/comment/83378274
type: Comment
has text: Thanks very much ,and one more doubt ,why we need to inherit str class ??
comment on: http://stackoverflow.com/a/48193816
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83566638
score: 0
type: Comment
has text: See also https://stackoverflow.com/questions/42011070/on-windows-running-import-tensorflow-generates-no-module-named-pywrap-tenso.
type: QuestionComment
comment on: http://stackoverflow.com/q/48290565

http://stackoverflow.com/comment/83453329
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48235018
has text: Thanks. My final code actually didn't have print within that loop. So what you're implying is that I should split this code into two processes, with one of those processes being cached. Isn't that 'for y in range(1,x):' the longest step, as it needs to loop around each time 1/3 - 3/3 , all the way to 1/100,000,000 - 100,000,000 - 100,000,000?

http://stackoverflow.com/comment/83491184
comment on: http://stackoverflow.com/a/48253662
score: 0
has text: I would add `BatchNormalization` and then try `batch_size` from set `[16, 32, 64, 128]`. It's high data dependent issue.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83559354
comment on: http://stackoverflow.com/q/48287223
has text: Your log output seems strange. The first three lines are `HIJ`, but your code says that `I` should be followed by `N`.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/83366135
comment on: http://stackoverflow.com/a/48181008
has text: Yeah. I have installed pip and Neo4j on my mac. I could use browser to login to http://localhost:7474/db/data/ . However, I still could not connect to Neo4j by py2neo....
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48312541
has title: How to select the the row with the same name using .loc
has comment: http://stackoverflow.com/comment/83633655
tagged with: python
accepted answer: http://stackoverflow.com/a/48329629
has body: I am trying to use indexing to pull data from a panda dataframe. I ran into an issue I do not know how to solve. The name of two of my rows are named the exact same way, but each row has it's own data. Below is my line of code and it can be seen that I put a row named basic in twice (because they have different dataframes), but each one has its own value: i_s = i_s.loc'Revenue','Cost of Revenue', 'Gross profit', 'Operating expenses', 'Total operating expenses', 'Operating income', 'Net income', 'Earnings per share', 'Basic', 'Weighted average shares outstanding', 'Basic', 'EBITDA' When I try to index using the code above, the dataframe with the row labeled basic comes up four times (two dataframes in total). It selects each of the rows named basic and puts both dataframes where I call out basic in my .loc : Revenue 0.0 1.059400e+10 9.789000e+09 Cost of Revenue NaN NaN NaN Gross profit 2.0 6.420000e+09 5.691000e+09 Operating expenses 3.0 4.989000e+09 4.924000e+09 Total operating expenses 3.0 4.989000e+09 4.924000e+09 Operating income 8.0 1.431000e+09 7.670000e+08 Net income 14.0 7.370000e+08 2.890000e+08 Earnings per share 16.0 NaN NaN Basic 17.0 1.400000e+00 6.200000e-01 Basic 20.0 5.254150e+08 5.145740e+08 Weighted average shares outstanding 19.0 NaN NaN Basic 17.0 1.400000e+00 6.200000e-01 Basic 20.0 5.254150e+08 5.145740e+08 EBITDA 22.0 1.838000e+09 1.150000e+09 For example: A B C foo 0 10 foo 1 11 foo 1 12 foo 1 13 foo 1 14 I would like to use .loc to call out the column 'A' by its label 'foo', however if I use df.loc['foo'], it will pull all 3. I would like the output to only show some of them rather than all of them, like below: A B C foo 1 12 foo 1 14 Does anyone know how to solve this problem? How do I select a row with the same name as another row using .loc?
has answer: http://stackoverflow.com/a/48329629
score: 0
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/83613900
possible better answer: http://stackoverflow.com/a/48312891
has answer: http://stackoverflow.com/a/48312891
has comment: http://stackoverflow.com/comment/83644987
type: Question
tagged with: indexing
type: AnsweredQuestion

http://stackoverflow.com/a/48265667
score: 4
answers question: http://stackoverflow.com/q/48264471
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83518046
has body: Robot supports a variable number of arguments by having the last item in [Arguments] be a list variable. For example: *** Keywords *** A keyword [Arguments] @{args} ${count}= get length ${args} log you passed in ${count} arguments :FOR ${arg} IN @{args} \ log argument: ${arg} [return] ${count} *** Test cases *** Example ${result}= A keyword arg1 arg2 arg3 should be equal as numbers ${result} 3 ${result}= A keyword arg1 arg2 arg3 arg4 arg5 should be equal as numbers ${result} 5
has comment: http://stackoverflow.com/comment/83517059
type: Answer
accepted answer of: http://stackoverflow.com/q/48264471
upvote count: 4

http://stackoverflow.com/a/48314174
answers question: http://stackoverflow.com/q/48314002
score: 2
has comment: http://stackoverflow.com/comment/83652908
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83651137
has body: Instead of creating a comparator function, create a key function: mylist.sort(key=lambda i: (i.key == CRITICAL_VALUE, i.key, i.name)) This makes it clear (to me at least) that you first sort by i.key == CRITICAL_VALUE, then by i.key, and finally by i.name.
type: Answer
accepted answer of: http://stackoverflow.com/q/48314002
upvote count: 2

http://stackoverflow.com/comment/83414503
has text: We define the answers to the questions we ask the user as num1,num2 and operation before we even ask them. We set those answers to "None". Then for each time before we ask the question, we check to see if the answer is still None, or if it has changed to a suitable value.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48216086

http://stackoverflow.com/comment/83506430
comment on: http://stackoverflow.com/a/48261838
type: AnswerComment
has text: But Its summing up for years. I want to sum up against dates and then divide the resulting dataframe for years
score: 0
type: Comment

http://stackoverflow.com/comment/83589135
score: 0
type: Comment
has text: The question was closed as a dupe, and I've addressed the specifics of their question** in a comment. Or else, I could have posted the answer myself :/
type: AnswerComment
comment on: http://stackoverflow.com/a/48302083

http://stackoverflow.com/comment/83642453
type: Comment
comment on: http://stackoverflow.com/a/48323986
score: 0
type: AnswerComment
has text: Adding "?WSDL" throws an error but "Requests" works fine. Thank you very much for the solution.

http://stackoverflow.com/q/48239036
answer count: 0
tagged with: iteration
has body: I am very simply trying to refer to the value of the previous item when using the enumerate function in Python. I don't know the syntax and cannot find it online. Help much appreciated. Thanks. #if the close price is &gt; line_price, and the previous is &lt; line_price, then increment broken_line_count mylist = [6000,6000,6000,6200,6200] line_price = 6100 broken_line_count = 0 for i, x in enumerate(mylist): if x&gt;line_price and [i-1](x)&lt;line_price: broken_line_count +=1 print(broken_line_count) Obviously [i-1](x) is incorrect, this is just illustrative of what i'm trying to achieve.
duplicate of: http://stackoverflow.com/q/5434891
type: Question
has title: How do I refer to the value of the previous item when using enumerate
has comment: http://stackoverflow.com/comment/83460524
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83460367
has comment: http://stackoverflow.com/comment/83460336
tagged with: python-3.x
linked to: http://stackoverflow.com/q/5764782
linked to: http://stackoverflow.com/q/5434891
score: 0

http://stackoverflow.com/q/48284350
has body: What is wrong with this code? I'm trying to get 11 as a result. def operation(a,b): return a + b def calculate(a, b, operation): print("Parameter a=" + str(a) + ", b=" + str(b) + ", operation=" + str(operation)) b = operation(a, b) return b calculate(5,6, operation)
upvote count: 0
has title: python calling function calculate
has answer: http://stackoverflow.com/a/48284787
tagged with: function
has comment: http://stackoverflow.com/comment/83552695
downvote count: 3
score: -3
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/83552694
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83552697
tagged with: python

http://stackoverflow.com/comment/83604080
has text: I moved the variable declaration under 'for' block but script still does not go further. it does open the file for reading, prints the first line from 'for' block and that's it.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48307114
type: Comment

http://stackoverflow.com/comment/83607223
has text: @Darkonaut I believe it is returning, but I have not confirmed that yet. For now I just turned them into independent tests, which is not very DRY but did the job till I can debug this further. Appreciate your input.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48292332

http://stackoverflow.com/a/48329311
answers question: http://stackoverflow.com/q/48329257
has body: you can add the value as a tuple or a list like this: my_dict = { 'key1' : [str1, num1], 'key2' : [str2, num2], 'key3' : [str2, num2] } This would be the list way to do it. You could access your values with the corresponding indexes. my_dict['key1'][0] would be the string and my_dict['key1'][1] would be the number. Good luck!
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/83454600
has text: I believe modelstep.ckpt and model.ckpt are the same?
score: 0
comment on: http://stackoverflow.com/q/48233684
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48262487
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48262314
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48262314
has body: Let's test this out. def foo(): print('In foo') return range(5) Now, if I call foo in the head of a for loop (for _ in foo()), it should print In foo as many times as it is called/evaluated. So, for _ in foo(): pass In foo And is called just once. Meaning it was evaluated only once.
type: Answer
upvote count: 2

http://stackoverflow.com/q/48280456
has title: Pandas groupby: different indexes returned
has comment: http://stackoverflow.com/comment/83546444
tagged with: python
has comment: http://stackoverflow.com/comment/83545247
possible better answer: http://stackoverflow.com/a/48282033
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/48282033
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/83544464
tagged with: grouping
downvote count: 0
has body: Versions: * Pandas 0.21.0 * Python 2.7.12 I see this strange behaviour in Pandas: according to the dataframe and the sort, groupby returns different results: import pandas as pd from datetime import datetime df1 = pd.DataFrame({'dtime': [datetime(2017,1,1,1,5), datetime(2017,1,1,1,20)], 'val1': [11, None], 'val2': [None, 31] }) df2 = pd.DataFrame({'dtime': [datetime(2017,1,1,1,5), datetime(2017,1,1,1,20)], 'val1': [11, None], 'val2': [31, None] }) df1b = df1.melt("dtime").dropna().set_index("dtime") df2b = df2.melt("dtime").dropna().set_index("dtime") r1a = df1b.groupby(pd.Grouper(freq="1h")).value.apply(lambda x: x.sort_values(ascending=True)) r1b = df1b.groupby(pd.Grouper(freq="1h")).value.apply(lambda x: x.sort_values(ascending=False)) r2a = df2b.groupby(pd.Grouper(freq="1h")).value.apply(lambda x: x.sort_values(ascending=True)) r2b = df2b.groupby(pd.Grouper(freq="1h")).value.apply(lambda x: x.sort_values(ascending=False)) print "\n--- df1 ascending sort ---------------\n", r1a print "\n--- df1 descending sort SHOULD IT ALWAYS BE LIKE THIS? --------------\n", r1b print "\n--- df2 ascending sort ---------------\n", r2a print "\n--- df2 descending sort --------------\n", r2b return --- df1 ascending sort --------------- dtime 2017-01-01 01:05:00 11.0 2017-01-01 01:20:00 31.0 Name: value, dtype: float64 --- df1 descending sort SHOULD IT ALWAYS BE LIKE THIS? -------------- dtime dtime 2017-01-01 01:00:00 2017-01-01 01:20:00 31.0 2017-01-01 01:05:00 11.0 Name: value, dtype: float64 --- df2 ascending sort --------------- dtime 2017-01-01 01:05:00 11.0 2017-01-01 01:05:00 31.0 Name: value, dtype: float64 --- df2 descending sort -------------- dtime 2017-01-01 01:05:00 31.0 2017-01-01 01:05:00 11.0 Name: value, dtype: float64 Why df1 descending sort returns the reference time for grouping (2017-01-01 01:00:00), while it is missing in the other groups? I would expect that all grouping return a reference time as multi-index, without exception. I created an issue at github …
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48281270
type: Question
has answer: http://stackoverflow.com/a/48281270
has comment: http://stackoverflow.com/comment/83544815

http://stackoverflow.com/comment/83620145
comment on: http://stackoverflow.com/q/48317302
type: QuestionComment
type: Comment
score: 0
has text: That code is not indented correctly; proper indentation is _vital_ in Python. It looks like your `__int__` method should actually be named `__init__`.

http://stackoverflow.com/q/48328758
tagged with: python-3.x
score: 2
upvote count: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48328852
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48328852
has body: I'm trying to read some log files using Pandas, where the columns are delimited by whitespace, and some columns consist of single quoted strings with whitespace (e.g. 'string '). I am having a hard time reading these files with read_csv. For example (using some dummy data): import pandas as pd from io import StringIO data = StringIO("""\ 1 2 'asdf ' 3 4 5 'asdfg ' 4 """) columns = ['a','b','c','d'] df = pd.read_csv(data, delim_whitespace=True, names=columns) For the first row, this results in columns 1, 2, 'asdf, ', 3, where I would prefer to have it as 1, 2, asdf, 3. The behavior makes total sense, but I can't find a way to make read_csv parse such files "correctly" (as I want it). Is this at all possible?
has comment: http://stackoverflow.com/comment/83643070
tagged with: pandas
has title: Complex delimite columns in Pandas read_csv
tagged with: python

http://stackoverflow.com/q/48283887
answer count: 0
has body: It works fine in 1.11 but for some reason is not working in 2.0. I'm not sure what the issue is. Here is the fields.py file from django-recurrence from django.db.models import fields from django.utils.six import string_types import recurrence from recurrence import forms from recurrence.compat import Creator try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], [ "^recurrence\.fields\.RecurrenceField", ]) except ImportError: pass # Do not use SubfieldBase meta class because is removed in Django 1.10 class RecurrenceField(fields.Field): """Field that stores a `recurrence.base.Recurrence` to the database.""" def __init__(self, include_dtstart=True, **kwargs): self.include_dtstart = include_dtstart super(RecurrenceField, self).__init__(**kwargs) def get_internal_type(self): return 'TextField' def to_python(self, value): if value is None or isinstance(value, recurrence.Recurrence): return value value = super(RecurrenceField, self).to_python(value) or u'' return recurrence.deserialize(value, self.include_dtstart) def from_db_value(self, value, *args, **kwargs): return self.to_python(value) def get_prep_value(self, value): if not isinstance(value, string_types): value = recurrence.serialize(value) return value def contribute_to_class(self, cls, *args, **kwargs): super(RecurrenceField, self).contribute_to_class(cls, *args, **kwargs) setattr(cls, self.name, Creator(self)) def value_to_string(self, obj): return self.get_prep_value(self._get_val_from_obj(obj)) def formfield(self, **kwargs): defaults = { 'form_class': forms.RecurrenceField, 'widget': forms.RecurrenceWidget, } defaults.update(kwargs) return super(RecurrenceField, self).formfield(**defaults)
tagged with: django-forms
favorite count: 0
type: Question
tagged with: python-3.x
score: 5
has title: django-recurrence is displaying a text field in admin instead of the proper field in django 2.0
type: UnansweredQuestion
upvote count: 5
downvote count: 0
tagged with: django
tagged with: django-models
tagged with: python

http://stackoverflow.com/q/48188940
has title: Migrate Halcon code to OpenCV
has comment: http://stackoverflow.com/comment/83358974
has comment: http://stackoverflow.com/comment/83394896
tagged with: halcon
has comment: http://stackoverflow.com/comment/83359242
has answer: http://stackoverflow.com/a/48305091
favorite count: 0
type: Question
tagged with: opencv
has body: I am developing a solution using a comercial computer vision software called Halcon. I am thinking on migrating or convert my solution to OpenCV in Python. I will like to start developing my other computer vision solution in Halcon because the IDE is incredible, and them generate a script to migrate them to OpenCV. Does anyone know any library for this task? I will like to start developing an open source SDK to convert Halcon to OpenCV. I and thinking to start developing all internal function from Halcon to Python. Any advice?
has answer: http://stackoverflow.com/a/48319507
downvote count: 3
accepted answer: http://stackoverflow.com/a/48319507
tagged with: python
tagged with: computer-vision
type: AnsweredQuestion
upvote count: 3
score: 0
has answer: http://stackoverflow.com/a/48302888
has comment: http://stackoverflow.com/comment/83361105
possible better answer: http://stackoverflow.com/a/48302888
answer count: 3
has comment: http://stackoverflow.com/comment/83359872

http://stackoverflow.com/comment/83582198
type: Comment
comment on: http://stackoverflow.com/a/48298386
type: AnswerComment
score: 0
has text: Works like a charm. I was hoping that there was a way of using one of the "known" functions, but this approach makes sense and is intuitive enough. The second "for" isn't needed though. Thank you @vineeth560

http://stackoverflow.com/q/48177417
type: Question
upvote count: 2
has title: Django get unique manytomany
tagged with: django
tagged with: django-models
tagged with: python
score: 2
type: AnsweredQuestion
has body: class Word(Model): word = CharField() categories = ManyToManyField('Category') class Category(Model): name = CharField() What is the best way to fetch all unique list of categories? For example, if I have apple -&gt; General, Garden pear -&gt; General, Garden computer -&gt; IT I want to get the following list of lists (General, Garden) (IT, ) I need PostgreSQL solution.
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48178411
has answer: http://stackoverflow.com/a/48178411
favorite count: 0

http://stackoverflow.com/comment/83616690
type: QuestionComment
has text: And depending on what you want, you want to replace the QMovie, you do not want to add a new QLabel. What is your goal, use addWidget() or change the GIF?
score: 0
comment on: http://stackoverflow.com/q/48315501
type: Comment

http://stackoverflow.com/a/48284417
accepted answer of: http://stackoverflow.com/q/48284153
score: 0
answers question: http://stackoverflow.com/q/48284153
type: AcceptedAnswer
has body: you can use ( stream ) sockets for this, sockets are low-level network connections : https://docs.python.org/2/howto/sockets.html https://docs.python.org/3/library/asyncio-stream.html http://www.informit.com/articles/article.aspx?p=686162&amp;seqNum=4 ( rudimentary ) https://codereview.stackexchange.com/questions/169398/python-video-streaming-server-and-client ( ready source code example )
type: Answer

http://stackoverflow.com/comment/83592462
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48303793
type: Comment
has text: The delimiter doesn't matter here? Docs say it's only for path strings

http://stackoverflow.com/comment/83346662
has text: can you set 'Content-Type': 'application/json' in headers and try again?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48180789

http://stackoverflow.com/q/48215948
has title: Python display milliseconds in formatted string using `time.strftime`
possible better answer: http://stackoverflow.com/a/69619203
linked to: http://stackoverflow.com/q/7588511
has answer: http://stackoverflow.com/a/69619203
type: AnsweredQuestion
answer count: 3
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
score: 9
has comment: http://stackoverflow.com/comment/101272560
has comment: http://stackoverflow.com/comment/138020040
upvote count: 9
tagged with: string-formatting
accepted answer: http://stackoverflow.com/a/48216051
has body: I am trying to format milliseconds to formatted string preserving the milliseconds part. Here's my code: import time time.strftime('%Y-%m-%d %H:%M:%S:%f', time.gmtime(1515694048121/1000.0)) where 1515694048121 is a time in milliseconds. It returns me: 2018-01-11 18:07:28:f As we can see, the millisecond portion of time is not returned. What is correct format to include millisecond portion of time? Is '%Y-%m-%d %H:%M:%S:%f' not correct ?
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/48216051
has answer: http://stackoverflow.com/a/48216094

http://stackoverflow.com/comment/83335331
type: AnswerComment
has text: You're welcome :) seems I got it this time, right? :) If you have performance issues, let me know. As I wrote, this is a simple solution and there may be better ways of doing it.
comment on: http://stackoverflow.com/a/48175963
type: Comment
score: 0

http://stackoverflow.com/q/48287989
tagged with: python
answer count: 4
has body: Hi I have been working on a music bot for Discord which is a VOIP app gamers use. On here you can sent a presence to show what game you're playing and so on. In this case I want to show just some text that has been requested. Here it says on discord.py documentation this is how you would add it. This is an example how I have added it but once the bot is online this doesn't show and I have updated to the lastest discord.py version v0.16.6. If anyone could help me where I'm going wrong here id appreciate it. Thanks async def change_status(self): await self.bot.change_presence(game=discord.Game(name="Test"))` and in the full code import asyncio import discord from discord.ext import commands from .utils import checks if not discord.opus.is_loaded(): # the 'opus' library here is opus.dll on windows # or libopus.so on linux in the current directory # you should replace this with the location the # opus library is located in and with the proper filename. # note that on windows this DLL is automatically provided for you discord.opus.load_opus('opus') def __init__(self, bot): self.bot = bot class VoiceEntry: def __init__(self, message, player): self.requester = message.author self.channel = message.channel self.player = player def __str__(self): fmt = ' {0.title} uploaded by {0.uploader} and requested by {1.display_name}' duration = self.player.duration if duration: fmt = fmt + ' [length: {0[0]}m {0[1]}s]'.format(divmod(duration, 60)) return fmt.format(self.player, self.requester) class VoiceState: def __init__(self, bot): self.current = None self.voice = None self.bot = bot self.play_next_song = asyncio.Event() self.songs = asyncio.Queue() self.skip_votes = set() # a set of user_ids that voted self.audio_player = self.bot.loop.create_task(self.audio_player_task()) def is_playing(self): if self.voice is None or self.current is None: return False player = self.current.player return not player.is_done() @property def player(self): return self.current.player def skip(self): se…
score: 0
has answer: http://stackoverflow.com/a/65061540
has title: Changing presence discord status
has answer: http://stackoverflow.com/a/54171396
type: Question
has answer: http://stackoverflow.com/a/48461054
tagged with: python-3.x
tagged with: discord.py
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53574296

http://stackoverflow.com/comment/83568624
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48280450
type: Comment
has text: @jp_data_analysis No worries, go for what works best for you.

http://stackoverflow.com/a/48289503
has body: You're reading the file. Change the 'r' in fx = open(dest_url, 'r') to 'w'. fx = open(dest_url, 'w') As a side note you really should be using a with statement. with will make the file object close the connection once the code leaves the the with's scope. This way you don't have to worry about closing the connection. def download_data(csv_url): response = request.urlopen(csv_url) with open('data.csv', 'w') as f: f.write(str(response.read())) Though really there isn't any need to save the file at all if you're just going to read it and display the contents on the screen. Just have download_data return csv_str. Finally take a look at the builtin csv module. It makes life easy. import csv from io import StringIO import requests def download_data(csv_url): return csv.reader( StringIO( requests.get(csv_url) .text ), delimiter=',' ) for row in download_data('https://people.sc.fsu.edu/~jburkardt/data/csv/addresses.csv'): print("| {} |".format(str(' | '.join(row)))) # Prints: # # | John | Doe | 120 jefferson st. | Riverside | NJ | 08075 | # | Jack | McGinnis | 220 hobo Av. | Phila | PA | 09119 | # | John "Da Man" | Repici | 120 Jefferson St. | Riverside | NJ | 08075 | # | Stephen | Tyler | 7452 Terrace "At the Plaza" road | SomeTown | SD | 91234 | # | | Blankman | | SomeTown | SD | 00298 | # | Joan "the bone", Anne | Jet | 9th, at Terrace plc | Desert City | CO | 00123 |
answers question: http://stackoverflow.com/q/48289273
score: 0
type: Answer

http://stackoverflow.com/q/48326859
upvote count: 1
tagged with: psycopg2
favorite count: 0
type: Question
tagged with: postgresql
has title: Reading huge data using server side cursors with conditions in python
has body: I have a huge table (~ 0.8 billion) and I need to fetch data based on some segment condition. Data: d_id month_id sec average Class 89 201701 S 5.98 A 73 201703 N 7.63 B 31 201708 F 6.38 P 11 201709 K 6.38 P I have two lists: monthList = [201701,201702,201703] so the sql query is : sql_query = str("""select * from dbo.table_name where month_id IN monthList;""") Now I want to hold this data in server side cursor and from that fetch a subset based on a classList curs = cnxn.cursor('Class') classList = ['A','B','P'] while True: records = curs.fetchmany(int(1e3)) if not records: break for record in records: # here I want to use the classList to subset the data , something like df = pd.DataFrame() df.append(curs.fetchmany([cursor['Class'] == classList])) # And once all the records of each Class has been read create csv df.to_csv("ClassList.csv") So for the data given above: There will be 3 csv generated: 1. ClassA.csv d_id month_id sec average Class 31 201708 F 6.38 P 11 201709 K 6.38 P All data is in PostgreSQL which I am calling using psycopg2 Can someone please help me regarding: 1. Is this even possible to do with server side cursors. 2. I basically need to create a combined csv of each Class from all the data based also on month_id given as a list.
accepted answer: http://stackoverflow.com/a/48334009
tagged with: python
has answer: http://stackoverflow.com/a/48334009
tagged with: cursor
has comment: http://stackoverflow.com/comment/83641137
type: AnsweredQuestion
score: 1
tagged with: bigdata
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/83542872
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48278296
has text: @RajaSimon I just posted what the beginning of `__init__.py` looks like. Is that the only difference between mine and yours? Also, thanks for answering. Is there a way for us to confront our scripts here on stackoverflow?

http://stackoverflow.com/q/48209088
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48209508
has body: I am working on automating aws management plane security. Their api returns something like below. Here is what I am trying to implement How do I get a list of dictionaries from the Content key above? or What data structure I should use so that I can use/read the values of keys efficiently? P.S. The SO is warning me to ask a question that is clear and well formulated as this question is getting downvotes. I believe this is because I posted an image which is not clear at first glance. I request you all to click on image to see readable image. If I would have posted a data instead of image, formatting would have become worst and I would have lost too much of time formatting it.
has comment: http://stackoverflow.com/comment/83399083
favorite count: 0
has comment: http://stackoverflow.com/comment/83399294
type: Question
accepted answer: http://stackoverflow.com/a/48209552
answer count: 2
downvote count: 4
has answer: http://stackoverflow.com/a/48209552
upvote count: 0
has answer: http://stackoverflow.com/a/48209508
score: -4
has comment: http://stackoverflow.com/comment/83399053
tagged with: python
has title: python : Converting string of keys followed by values into dictionary
tagged with: boto3
tagged with: amazon-web-services

http://stackoverflow.com/comment/83612201
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48312529
has text: Possible duplicate of [Pandas convert a column of list to dummies](https://stackoverflow.com/questions/29034928/pandas-convert-a-column-of-list-to-dummies)

http://stackoverflow.com/q/48241779
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has title: Writing tweets to a JSON file using tweepy automatically adds a blank line on my PC and makes the file unreadable in Python
tagged with: tweepy
score: 0
answer count: 1
type: Question
tagged with: python-3.x
has body: My code produces many tweets in a JSON file. Each tweet is inside a { }. However, between 2 tweets in {...} and {...} there's a blank line getting produced. That makes the file unreadable in Python. However, that extra blank line between the Tweets isn't produced on an Ubuntu PC for the same code. I'll attach both of my codes below. import tweepy import json from tweepy import OAuthHandler consumer_key = 'luCMgoolgODpFH9rxcvLbRqYt' consumer_secret = 'lW9fERVDfcgoq3aqVDYpbUNGkKUUFquwpQYrLvlaXzeekpvkgZ' access_token = '750950262098059268-riOExqjYPhUTJAe4OHW9F7aYfK2ljuQ' access_secret = 'GE4K0zqwyBi50k5Ma3xFSP44zYd1HiM5ncL1gGaDscu5K' auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) api = tweepy.API(auth) from tweepy import Stream from tweepy.streaming import StreamListener class MyListener(StreamListener): def on_data(self, data): try: with open('new.json', 'a') as f: f.write(data) return True except BaseException as e: print("Error on_data: %s" % str(e)) return True def on_error(self, status): print(status) return True twitter_stream = Stream(auth, MyListener()) twitter_stream.filter(track=['#CHELEI']) Code to read JSON: fname = 'python.json' with open(fname, 'r') as f: count_all = Counter() for line in f: tweet = json.loads(line) # Create a list with all the terms terms_all = [term for term in preprocess(tweet['text'])] # Update the counter count_all.update(terms_all) # Print the first 5 most frequent words print(count_all.most_common(5))
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48241797
tagged with: windows

http://stackoverflow.com/q/48202396
tagged with: python
upvote count: 2
has body: I had written code (basically the same as the python code under synchronous here) before to transcribe a 10s wav file i made. Just today it stopped working and i get this error: Traceback (most recent call last): File "/home/ishan/Google_Cloudspeech_on_pepper/cloudspeechtest.py", line 35, in &lt;module&gt; response = client.recognize(config, audio) File "/usr/local/lib/python2.7/dist-packages/google/cloud/gapic/speech/v1/speech_client.py", line 201, in recognize return self._recognize(request, options) File "/usr/local/lib/python2.7/dist-packages/google/gax/api_callable.py", line 452, in inner return api_caller(api_call, this_settings, request) File "/usr/local/lib/python2.7/dist-packages/google/gax/api_callable.py", line 438, in base_caller return api_call(*args) File "/usr/local/lib/python2.7/dist-packages/google/gax/api_callable.py", line 376, in inner return a_func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/google/gax/retry.py", line 127, in inner ' classified as transient', exception) google.gax.errors.RetryError: RetryError(Exception occurred in retry method that was not classified as transient, caused by &lt;_Rendezvous of RPC that terminated with (StatusCode.RESOURCE_EXHAUSTED, Quota exceeded.)&gt;) Here is the code: import io from os import path # Imports the Google Cloud client library from google.cloud import speech # from google.cloud import datastore #dont need this from google.cloud.speech import enums from google.cloud.speech import types #client = datastore.Client() GOOGLE_APPLICATION_CREDENTIALS = path.join( path.dirname(__file__), 'ishan_sr.json') # Instantiates a client client = speech.SpeechClient() # The name of the audio file to transcribe file_name = path.join( path.dirname(__file__), 'Fish.wav') # Loads the audio into memory with io.open(file_name, 'rb') as audio_file: content = audio_file.read() audio = types.RecognitionAudio(content=content) config = types.RecognitionConfig( encoding=enums.RecognitionConfig.AudioEncoding.…
score: 2
answer count: 0
downvote count: 0
tagged with: api
type: UnansweredQuestion
has title: Google speech API developer error
tagged with: cloud
tagged with: speech
favorite count: 0
type: Question

http://stackoverflow.com/a/75460378
downvote count: 1
type: Answer
has body: Python has multiple other ways to start new processes. Threading would most likely be the easiest here. #task queue and comm pipes import threading tasks = Queue() parent_pipe, child_pipe = Pipe() def handle_queue_execution(tasks, pipe): logging.info("starting task queue handler") while True: if pipe.recv(): logging.debug("preparing to get task from queue") task = tasks.get() args = tasks.get() logging.debug("executing task %s(%s)", get_fn_name(task), clean_args(args)) task(args) logging.debug("task %s(%s) executed successfully", get_fn_name(task), clean_args(args)) T1 = threading.Thread(target=handle_que_execution, args=(tasks, child_pipe,)) if __name__ == '__main__': T1.start()
has comment: http://stackoverflow.com/comment/133141811
has comment: http://stackoverflow.com/comment/133204164
has comment: http://stackoverflow.com/comment/133142589
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/48200675

http://stackoverflow.com/comment/83598487
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48303788
score: 0
has text: I have a probability dictionary ready,so switching to that would just take me a few minutes. However I'm smelling a "doesnt sum to one" error. Would your normalization code work for that aswell? Or is it exclusive to a Counter with integer values?

http://stackoverflow.com/q/48214286
has comment: http://stackoverflow.com/comment/83410493
has title: Python: Deleting Customer Accounts from Bank System
has answer: http://stackoverflow.com/a/48214484
type: Question
score: 0
has body: Already asked this question and I had a very negative response so I'll forewarn you that I am extremely new to Python and programming as a whole so I don't quite understand most terminology but I'll try anyway I have to insert a method of deleting a customer account from the customers_list, both stored within bank_system I shall put a code sample of bank_system here. The customers_list is found at the top and the method to delete accounts is found near the bottom. from customer import Customer from admin import Admin from account import Account class BankSystem(object): def __init__(self): self.customers_list = [] self.admins_list = [] self.load_bank_data() def load_bank_data(self): #CUSTOMER LIST customer_1 = Customer("Adam", "1234", ["14", "Wilcot Street", "Bath", "B5 5RT"]) account_no = 1234 account_1 = Account(5000.00, account_no) customer_1.open_account(account_1) self.customers_list.append(customer_1) customer_2 = Customer("David", "password", ["60", "Holborn Via-duct", "London", "EC1A 2FD"]) account_no+=1 account_2 = Account(3200.00, account_no) customer_2.open_account(account_2) self.customers_list.append(customer_2) customer_3 = Customer("Alice", "MoonLight", ["5", "Cardigan Street", "Birmingham", "B4 7BD"]) account_no+=1 account_3 = Account(18000.00, account_no) customer_3.open_account(account_3) self.customers_list.append(customer_3) customer_4 = Customer("Ali", "150A", ["44", "Churchill Way West", "Basingstoke", "RG21 6YR"]) account_no+=1 account_4 = Account(18000.00, account_no) customer_4.open_account(account_4) self.customers_list.append(customer_4) customer_5 = Customer("Thomas", "15A", ["4", "Churchill West", "Stoke", "ST21 6YR"]) account_no+=1 account_5 = Account(0, account_no) customer_5.open_account(account_5) self.customers_list.append(customer_5) #ADMIN LIST admin_1 = Admin("Julian", "1441", True, ["12", "London Road", "Birmingham", "B95 7TT"]) self.admins_list.append(admin_1) admin_2 = Admin("Eva", "2222", False, ["47", "Mars Street", "Newcast…
tagged with: python
has comment: http://stackoverflow.com/comment/83410525
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/83421753
score: 0
has text: They do the same: `A[0] = ...` will replace the first item in `A` with a new reference.
type: QuestionComment
comment on: http://stackoverflow.com/q/48219116
type: Comment

http://stackoverflow.com/a/48270870
answers question: http://stackoverflow.com/q/48268506
score: 10
type: Answer
has body: Thanks to Bryan Oakley's guidance, I have revised the selectItem callback to: def selectItem(self, event): curItem = self.tree.item(self.tree.focus()) col = self.tree.identify_column(event.x) print ('curItem = ', curItem) print ('col = ', col) if col == '#0': cell_value = curItem['text'] elif col == '#1': cell_value = curItem['values'][0] elif col == '#2': cell_value = curItem['values'][1] elif col == '#3': cell_value = curItem['values'][2] print ('cell_value = ', cell_value) It gave me what I wanted. Hope this script will help any other asking the same question.
accepted answer of: http://stackoverflow.com/q/48268506
type: AcceptedAnswer
downvote count: 0
upvote count: 10

http://stackoverflow.com/comment/83333537
type: Comment
type: QuestionComment
score: 0
has text: If can send me any documentation to read more about the regex please I will be very congratulate with your.
comment on: http://stackoverflow.com/q/48176794

http://stackoverflow.com/a/48276865
upvote count: 2
score: 2
downvote count: 0
has body: Completely changed solution(s): Values of column Promo was changed with 2 and 3. For count consecutives all values use compare by ne (!=) by shifted column with cumsum for groups. Then use groupby by this groups and count by cumcount and add 1 for count from 1: df['Running_Total'] = (df.groupby(df['Promo'].ne(df['Promo'].shift()).cumsum()) .cumcount() .add(1)) print (df) Id Date Promo Running_Total 0 19 2015-07-09 0 1 1 18 2015-07-10 0 2 2 17 2015-07-11 0 3 3 16 2015-07-13 2 1 4 15 2015-07-14 2 2 5 14 2015-07-15 2 3 6 13 2015-07-16 1 1 7 12 2015-07-17 1 2 8 11 2015-07-18 0 1 9 10 2015-07-20 0 2 10 9 2015-07-21 0 3 11 8 2015-07-22 0 4 12 7 2015-07-23 3 1 13 6 2015-07-24 3 2 14 5 2015-07-25 3 3 15 4 2015-07-27 1 1 16 3 2015-07-28 1 2 17 2 2015-07-29 1 3 18 1 2015-07-30 1 4 19 0 2015-07-31 1 5 But if need replace rows with 0 in Promo column multiple column by boolean mask - comparing df['Promo'].ne(0) - it multiple by 0 all 0 rows and all another by 1: df['Running_Total'] = df.groupby(df['Promo'].ne(df['Promo'].shift()).cumsum()) .cumcount() .add(1) .mul(df['Promo'].ne(0)) print (df) 0 19 2015-07-09 0 0 1 18 2015-07-10 0 0 2 17 2015-07-11 0 0 3 16 2015-07-13 2 1 4 15 2015-07-14 2 2 5 14 2015-07-15 2 3 6 13 2015-07-16 1 1 7 12 2015-07-17 1 2 8 11 2015-07-18 0 0 9 10 2015-07-20 0 0 10 9 2015-07-21 0 0 11 8 2015-07-22 0 0 12 7 2015-07-23 3 1 13 6 2015-07-24 3 2 14 5 2015-07-25 3 3 15 4 2015-07-27 1 1 16 3 2015-07-28 1 2 17 2 2015-07-29 1 3 18 1 2015-07-30 1 4 19 0 2015-07-31 1 5 Detail: print (df['Promo'].ne(df['Promo'].shift()).cumsum()) 0 1 1 1 2 1 3 2 4 2 5 2 6 3 7 3 8 4 9 4 10 4 11 4 12 5 13 5 14 5 15 6 16 6 17 6 18 6 19 6 Name: Promo, dtype: int32
type: Answer
has comment: http://stackoverflow.com/comment/83537746
answers question: http://stackoverflow.com/q/48276812

http://stackoverflow.com/comment/83420672
has text: Furthermore, you demand code of users: "I want code", sounds selfish, regardless of your intent.
comment on: http://stackoverflow.com/q/48219191
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83609189
comment on: http://stackoverflow.com/q/48310413
has text: do you get error message when you run in console/terminal/cmd.exe ?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/48285248
has answer: http://stackoverflow.com/a/48285624
tagged with: numpy
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/11144513
has title: Improve performance of combined for blocks with numpy
answer count: 1
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: performance
accepted answer: http://stackoverflow.com/a/48285624
has body: I have the rather simple function func1() defined below, mainly composed of two for blocks. It works perfectly for small N values, but being that the for blocks are combined it grows very quickly to the point of taking minutes when N&gt;1000. How can I use numpy broadcasting to improve the performance of this function? import numpy as np import time as t def func1(A_triang, B_triang): aa = [] for i, A_tr in enumerate(A_triang): for j, B_tr in enumerate(B_triang): # Absolute value of differences. abs_diff = abs(np.array(A_tr) - np.array(B_tr)) # Store the sum of the differences and the indexes aa.append([sum(abs_diff), i, j]) return aa # Generate random data with the proper format N = 500 A_triang = np.random.uniform(0., 20., (N, 3)) A_triang[:, 0] = np.ones(N) B_triang = np.random.uniform(0., 20., (N, 3)) B_triang[:, 0] = np.ones(N) # Call function. s = t.clock() aa = func1(A_triang, B_triang) print(t.clock() - s)
linked to: http://stackoverflow.com/q/46135070
tagged with: python

http://stackoverflow.com/q/48269201
answer count: 2
has title: How do I make Turtle to wait for a pressed key
downvote count: 0
accepted answer: http://stackoverflow.com/a/48275375
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: turtle-graphics
linked to: http://stackoverflow.com/q/37447069
tagged with: python-turtle
has body: My group and I created a board game that runs on Turtle. We are having difficulties to make the game run without the need for the IDE console. We want to use onkeypress to run our game so the user will not have to leave the game window. #import turtle from turtle import * from random import * from time import * #drawing board game def boardgame(size): """Draw a square by drawing a line and turning through 90 degrees 4 times""" pendown() color("black", "blue") begin_fill() for _ in range(4): forward(size) right(90) end_fill() penup() #numbering each tile def number(): """Draw the tile number for each tile""" # I tried to compress this part of the code, but a lot of bugs occured, so I decided to kep the big lines because it is way more simple goto(-300, 80) x = 0 x += 1 write(x) forward(square_size) x += 1 write(x) forward(square_size) x += 1 write(x) forward(square_size) x += 1 write(x) forward(square_size) x += 1 write(x) forward(square_size) goto(-300, -70) x += 5 write(x) forward(square_size) x -= 1 write(x) forward(square_size) x -= 1 write(x) forward(square_size) x -= 1 write(x) forward(square_size) x -= 1 write(x) forward(square_size) goto(-300, -220) x += 5 write(x) forward(square_size) x += 1 write(x) forward(square_size) x += 1 write(x) forward(square_size) x += 1 write(x) forward(square_size) x += 1 write(x) forward(square_size) #assingning tile order def order(cmd): """Whites the order of the tile at the canter of the tile""" write(cmd,align="center", font=("Arial", 24, "normal")) #drawing dice number def dice_draw(number): """Write the dice number""" undo() goto(450,75) N = randint(1,4) sleep(1) write(N,align="center", font=("Arial", 40, "normal")) sleep(0.2) undo() write(N+2,align="center", font=("Arial", 40, "normal")) sleep(0.2) undo() write(number,align="center", font=("Arial", 40, "normal")) sleep(1) #starting the interface square_size = 150 penup() hideturtle() speed(0) #writing title def title(): sleep(1) goto(0, 260) write("Turtle Racer",align="ce…
has answer: http://stackoverflow.com/a/73589209
has answer: http://stackoverflow.com/a/48275375
possible better answer: http://stackoverflow.com/a/73589209
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/q/48263901
has comment: http://stackoverflow.com/comment/83511010
has body: As a fact when creating a topic in kafka it is possible to set the replication factor however I was using a KafkaProducer (the kafka api for python pip install kafka) I thought I could do producer.send(...,replication-factor=3)but then there was no option for me to do that. Now I have only one option left is to directly create a shell script to connect to kafka to create a topic but then if the feature of python kafka is so lackluster why would I continue using it. So is there a way to set a replication factor when I am going to produce a kafka topic.
has title: Python KafkaProducer cannot set replication factor
tagged with: apache-kafka
type: AnsweredQuestion
tagged with: kafka-producer-api
score: 0
accepted answer: http://stackoverflow.com/a/48264104
answer count: 1
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/48264104

http://stackoverflow.com/q/48210424
has body: I've been working on a slack bot following Tutorial1 and Tutorial2 using python slackclient. I need to create a bot that can chat with several people a the same time but in a private chat, not in a groupal channel. I've tried running the bot's code several times changing the channel and it works, but I want to do it all in the same script. Here is my code: from slackclient import SlackClient Token = 'xoxb-xxxxxxxxxxx.....' usr= 'XXXXXXXX' chat = 'XXXXXXXX' sc = SlackClient(Token) # c is just to exit the loop c=0 # Initialize the bot and send a message sc.api_call('chat.postMessage', as_user='true:', channel=chat, text='Bot is working, if you want me to sleep, just send the message \"end\"') while c&lt;1: # Get the whole conversation hist = sc.api_call('im.history', channel=chat) m=hist.get('messages') # Get the last message last_message = m[0] # Find who sent it who = last_message.get('user') # If the user sent the message, then find a keyword and reply something if who==usr: answer=last_message.get('text') if 'hi' in answer: sc.api_call('chat.postMessage', as_user='true:', channel=chat, text='Hello!:smiley: can I help you?') elif 'no' in answer: sc.api_call('chat.postMessage', as_user='true:', channel=chat, text='Ok, let me know if you need something') elif 'yes' in answer: sc.api_call('chat.postMessage', as_user='true:', channel=chat, text='What can I do for you?') elif 'end' in answer: c=2
type: UnansweredQuestion
score: 1
tagged with: python
has title: How to message several people with a slack bot without a channel?
linked to: http://stackoverflow.com/q/47917744
linked to: http://stackoverflow.com/q/47753834
has comment: http://stackoverflow.com/comment/83402023
tagged with: bots
has answer: http://stackoverflow.com/a/48212916
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: slack-api
type: Question

http://stackoverflow.com/q/48181666
tagged with: nuke
downvote count: 1
has body: I am relatively new to python still, and I have been trying to write some simple things do nuke overrides for my work style. One of them being a remove node. import nuke def removeOverride(): nuke.thisNode()["operation"].setValue("keep") nuke.thisNode()["channels"].setValue("rgb") ##Adds end lined commands to run when node is created by the user. nuke.addOnUserCreate(removeOverride, nodeClass = "remove") The above code is my attempt to change the values in the operations knob to keep instead of the nuke default of remove. As in my work flow I find it easier to just tell it which channels I want I want to keep.
has answer: http://stackoverflow.com/a/50052283
possible better answer: http://stackoverflow.com/a/50052283
favorite count: 0
has comment: http://stackoverflow.com/comment/83373588
type: Question
has comment: http://stackoverflow.com/comment/83367849
accepted answer: http://stackoverflow.com/a/48194396
has comment: http://stackoverflow.com/comment/83368265
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83373730
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48194396
has title: Setting default value of a drop down menu in nuke with python
answer count: 2

http://stackoverflow.com/comment/83441067
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48215909
has text: I am asking for an approach to design a generic model

http://stackoverflow.com/q/48188681
has comment: http://stackoverflow.com/comment/83357725
has comment: http://stackoverflow.com/comment/83357267
tagged with: python
has comment: http://stackoverflow.com/comment/83357492
has comment: http://stackoverflow.com/comment/83372093
has body: I'm trying to use openpyxl in this code import sys from openpyxl import * excel_file = sys.argv[1] work_folder = sys.argv[2] sheet_name = sys.argv[3] file_full = work_folder + "\\"+ sheet_name + '.txt' wb = load_workbook(excel_file) ws = wb.get_sheet_by_name(sheet_name) delimiter = "," with open((file_full), encoding="UTF-8") as file: for line in file: sheet.append(line.split(delimiter)) wb.Save() The problem is that I'm getting the error line 2, in &lt;module&gt; from openpyxl import * ImportError: No module named openpyxl I thought that openpyxl was not installed propely but when I tried to install it, it said requeirement already satisfied.
score: 0
has title: Using openpyxl in python 2.7
has comment: http://stackoverflow.com/comment/83368039
answer count: 0
has comment: http://stackoverflow.com/comment/83357370
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/83371267
has comment: http://stackoverflow.com/comment/83357911
has comment: http://stackoverflow.com/comment/83368333
type: Question
has comment: http://stackoverflow.com/comment/83358107
type: UnansweredQuestion

http://stackoverflow.com/comment/83374145
score: 0
has text: Can I have 5-10 rows of your input? That would help.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48196510

http://stackoverflow.com/comment/83434558
type: AnswerComment
has text: I admit I like the answer supplied by @MrLeeh above better. It's cleaner and more direct. And the eval method is more error prone as you have discovered.
comment on: http://stackoverflow.com/a/48226387
type: Comment
score: 0

http://stackoverflow.com/q/48225744
upvote count: 3
downvote count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48226016
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
score: 3
has answer: http://stackoverflow.com/a/48226016
tagged with: python
has title: matplotlib.pyplot: how to include custom legends when plotting dataframes?
type: AnsweredQuestion
has body: I am plotting two dataframes in the same chart: the USDEUR exchange rate and the 3-day moving average. df.plot(ax=ax, linewidth=1) rolling_mean.plot(ax=ax, linewidth=1) Both dataframes are labelled "Value" so I would like to customize that: I tried passing the label option but that didn't work, as it seems that this option is exclusive to matplotlib.axes.Axes.plot and not to pandas.DataFrame.plot. So I tried using axes instead, and passing each label: ax.plot(df, linewidth=1, label='FRED/DEXUSEU') ax.plot(rolling_mean, linewidth=1, label='3-day SMA') However now the legend is not showing up at all unless I explicitly call ax.legend() afterwards. Is it possible to plot the dataframes while passing custom labels without the need of an additional explicit call?

http://stackoverflow.com/q/48328468
downvote count: 0
upvote count: 1
tagged with: python
tagged with: replace
has title: How to make some pandas column values default to another value in a different column, but same row?
type: AnsweredQuestion
tagged with: pandas
score: 1
has body: I have a sample DataFrame that looks like this: ID Product UPC Units Sold no link cereal 3463 12 2211 cereal 2211 13 2211 cereal 8900 11 2211 cereal 6754 14 no link cereal 9012 13 3340 cereal 3340 12 3340 cereal 5436 15 The 'ID' column identifies similar products into one product family ID. The ID is created by the first UPC number of that family. 'No link' identifies products that are the only member of their family. What I want is set the 'no link' values to default to the UPC number. This is what I want my output to look like: ID Product UPC Units Sold 3463 cereal 3463 12 2211 cereal 2211 13 2211 cereal 8900 11 2211 cereal 6754 14 9012 cereal 9012 13 3340 cereal 3340 12 3340 cereal 5436 15 This is what I have so far: for row in product_families: if product_families.loc['Product Family Number'] == 'no link':
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48328594
has answer: http://stackoverflow.com/a/48328594
favorite count: 0
possible better answer: http://stackoverflow.com/a/48329772
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48329772

http://stackoverflow.com/a/48238248
has body: I don't know anything about pycharm. But you should try increasing the DPI of the figure (and avoid relying on the pyplot API's state machine): from matplotlib import pyplot fig = pyplot.figure(dpi=120) ax = fig.add_subplot(1, 1, 1) ax.plot([1, 2, 3], [3, 1, 2], 'ko') Explicitly creating the figure will give you much more control in the long run. Note the the display DPI of the figure isn't necessarily the resolution it will be saved at: fig.savefig('test.png', dpi=600, bbox_inches='tight')
answers question: http://stackoverflow.com/q/48238192
type: Answer
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48238192

pyglet
tags question: http://stackoverflow.com/q/48177496
tags question: http://stackoverflow.com/q/48235641
type: Tag
tags question: http://stackoverflow.com/q/48253823
tags question: http://stackoverflow.com/q/48197626
tags question: http://stackoverflow.com/q/48271706
tag name: pyglet

http://stackoverflow.com/comment/83477111
has text: @cᴏʟᴅsᴘᴇᴇᴅ Great! Can you leave that as an answer? Can you perhaps elaborate in your answer, why `at` is to prefer over `iloc` as in my example? Would there ever be a scenario in which `df.columns[-1]` is slow? Thanks!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48246955

http://stackoverflow.com/comment/83489153
score: 3
type: QuestionComment
comment on: http://stackoverflow.com/q/48253225
has text: There doesn't seem to be any point in making Utilities a class. Python is not Java.
type: Comment

http://stackoverflow.com/a/48334723
has comment: http://stackoverflow.com/comment/85991764
has comment: http://stackoverflow.com/comment/86035925
has comment: http://stackoverflow.com/comment/85951886
score: 0
has body: Yes. If you simply use the default processing, None is treated as a string, which isn't what is expected here. Instead, do something like the following: import oracledb conn = oracledb.connect("user/pw@host/service") cursor = conn.cursor() var = cursor.var(conn.gettype("TEST_TYPE")) cursor.callproc("python_test", [1, var])
accepted answer of: http://stackoverflow.com/q/48319632
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48319632
has comment: http://stackoverflow.com/comment/86022107
type: Answer
has comment: http://stackoverflow.com/comment/91098199

http://stackoverflow.com/q/48231637
score: 1
answer count: 1
has title: Print statement creates an unwanted newline
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: newline
accepted answer: http://stackoverflow.com/a/48231697
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48231697
has comment: http://stackoverflow.com/comment/83445659
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83445662
has body: I am trying to go through a long list of words, and print both the lowercase word and the uppercase word (default) to the screen in the same line. Here is my code: for word in word_list: print("Here is: {0} and {1}".format(word.lower(), word)) However, this has the output (showcasing only two words): Here is: word1 and WORD1 Here is: word2 and WORD2 I have not been able to get rid of the newline between word1 and WORD1. It does not appear to happen for the last word I try and print. Any ideas as to why, and how to overcome this?

http://stackoverflow.com/q/48191484
tagged with: orm
tagged with: annotations
tagged with: django
has answer: http://stackoverflow.com/a/48191878
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48191878
score: 3
has comment: http://stackoverflow.com/comment/83363521
tagged with: python
has body: I need to annotate something that has to be named 'id' that is the same as the primary key of the table 'id'. The final output should be an array of dictionaries. I know that I can annotate with another name like 'id_for_tree' and then after using values() to make the dictionaries and change the key in a loop. Something like: item_list = MyTable.objects.annotate(id_for_tree=Concat(F('id'), F('Code'), output_field=CharField())).values('Name', 'id_for_tree') for any_item in item_list: any_item['id'] = any_item.pop('id_for_tree') It's clear that this solution does not have a good performance. How can I get rid of the "The annotation 'id' conflicts with a field on the model" exception by discarding the previous 'id' and annotate a new 'id'?
type: AnsweredQuestion
upvote count: 3
has title: Python Django: Annotating a same name with a database field
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/83642002
has text: Can you please explain it in parts (if you have time)?
comment on: http://stackoverflow.com/a/48328100
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83491126
has text: Found some partial hints [through this link](https://tonysyu.github.io/line-color-cycling.html#.WlvI-VQ-dE4), which discusses how to control line color cycling, but I have not figured out yet how to solve my full question.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48253810
type: QuestionComment

http://stackoverflow.com/comment/83525802
comment on: http://stackoverflow.com/q/48271001
type: Comment
has text: Should `function_to_run_in_background` run only once (with a delay of 2 seconds) or once every 2 seconds?
type: QuestionComment
score: 2

http://stackoverflow.com/q/48176514
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/48176573
tagged with: python
tagged with: numpy
has title: Use original file name to save image
type: AnsweredQuestion
score: 0
has body: I want to save image with original file name for example if original file name is hero so the processed image name should be hero_Zero.png. I dont know how to pass file name in def run(dirs, img): Below code is correct and modified. def run(dirs, img, file_): for (x, y) in labels: component = uf.find(labels[(x, y)]) labels[(x, y)] = component if labels[(x, y)]==0: Zero[y][x]=int(255) count=count+1 if count&lt;=43: continue elif count&gt;43: Zeroth = Image.fromarray(Zero) Zeroth.save(os.path.join(dirs, file_+'Zero.png'), 'png') return (labels, output_img) def main(): path='E:/Dataset/1/' for root, dirs, files in sorted(os.walk(path)): for file_ in files: #print (dirs) # print (files) full_file_path = os.path.join(root, file_) img = Image.open(full_file_path) (labels, output_img) = run(root, img, file_[:-4])
answer count: 1
tagged with: os.walk
accepted answer: http://stackoverflow.com/a/48176573
type: Question

http://stackoverflow.com/q/48241169
tagged with: installation
has answer: http://stackoverflow.com/a/48241543
type: UnansweredQuestion
downvote count: 2
answer count: 1
tagged with: pip
linked to: http://stackoverflow.com/q/8548030
upvote count: 1
has body: I am trying to install PIL. I have tried going through the settings and do it that way. When that didn't work, I tried to do it through the terminal. I got an error message: C:\Users\Chris\Desktop\Paul's stuff\Paul\CpmpProject\venv\Scripts\python.exe" "C:/Users/Chris/Desktop/Paul's stuff/Paul/CpmpProject/Game.py" File "C:/Users/Chris/Desktop/Paul's stuff/Paul/CpmpProject/Game.py", line 3 pip install PIL ^ SyntaxError: invalid syntax` I have no idea how to install PIL now and am hoping someone can help me. I am working with python 3 and have updated pip and set up tools.
favorite count: 0
tagged with: python-imaging-library
duplicate of: http://stackoverflow.com/q/8548030
has title: Issue with installing PIL
has comment: http://stackoverflow.com/comment/83464984
tagged with: python
has comment: http://stackoverflow.com/comment/83464676
score: -1
has comment: http://stackoverflow.com/comment/83464675
type: Question

http://stackoverflow.com/a/48254964
has comment: http://stackoverflow.com/comment/83494184
accepted answer of: http://stackoverflow.com/q/48254890
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83493131
answers question: http://stackoverflow.com/q/48254890
has body: You can either write: from lib.imdb import IMDb ia = IMDb() or: from lib import imdb ia = imdb.IMDb() But importing IMDb and then calling imdb.IMDb() does not work. One other point to mention: If your testlib.py resides above the lib foder, then you need to add a __init__.py file within lib for your import to work. The file can be completely empty. Update: This packages uses import statement that are not relative to the package folder, but to an arbitrary folder in sys.path. An illustration of this is the exact line that causes the error: # imdb.__init__.py imdb._logging This works only if the packages resides in a folder that is part of sys.path, so either in the same path as the script that does the from imdb import IMDb statement or in the python dist-package path (simplified explanation). This and all equivalent imports could be replaced by # imdb.__init__.py from . import _logging In which case the import is relative to the module, so there is no need for the imdbpy package to reside in a directory in sys.path. The consequence for us now is that we cannot simply put imdb in a sub-folder, we need to either put it in a folder from sys.path or add the folder it resides in to sys.path. So, the options are: install the package move the imdb folder up into the current folder write: import sys sys.path.insert(0, 'absolute/path/to/lib') before the import statement. In any of the above cases you will be able to do: from imdb import IMDb ia = IMDb()
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/83493041
upvote count: 2

http://stackoverflow.com/comment/83420951
comment on: http://stackoverflow.com/a/48219354
has text: no it's not, but you did start of your answer with that, and spent enough time discussing it to make me think you found it to be significant.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48212007
has comment: http://stackoverflow.com/comment/83405722
has comment: http://stackoverflow.com/comment/83407156
has comment: http://stackoverflow.com/comment/83405784
score: 1
type: Answer
has body: There are many ways to accomplish this task. One solution is to not specify the subject when creating the student. Instead, you would create the student object and then add subjects to it. For example: student = Student(name="John Smith") for subject_name in ("Math", "Science", "Literature"): student.add_subject(subject_name) That gives you a new student who has three subjects. The add_subject method might look something like this: class Student(object): def __init__(self, name, age, gender): ... self.subjects = {} ... def add_subject(self, name): self.subjects[name] = Subject(name) To assign grades you would do something like this, perhaps student.add_grade("Math", "A") student.add_grade("Science", "B") student.add_grade("Literature", "C") add_grade would then take the grade name, look up the subject object from self.subjects, and call a method on that subject object to add the grade. For example: def add_grade(self, subject_name, grade): subject = self.subjects[subject_name] subject.add_grade(grade) Your class Subject could be something very simple: class Subject(self): def __init__(self, name): self.name = name self.grade = None def add_grade(self, grade): self.grade = grade Note: the above assumes you want a single grade per subject. If you want multiple grades, you can change self.grade to be self.grades and have it be a list.
has comment: http://stackoverflow.com/comment/83406018
has comment: http://stackoverflow.com/comment/83405351
has comment: http://stackoverflow.com/comment/83405830
has comment: http://stackoverflow.com/comment/83405452
has comment: http://stackoverflow.com/comment/83405883
has comment: http://stackoverflow.com/comment/83406600
answers question: http://stackoverflow.com/q/48211816
has comment: http://stackoverflow.com/comment/83406159
downvote count: 0
has comment: http://stackoverflow.com/comment/83406658
upvote count: 1

http://stackoverflow.com/q/48314206
answer count: 1
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/48314603
has title: How can I get specific xml tags using BeautifulSoup in python 3.5?
tagged with: python
has comment: http://stackoverflow.com/comment/83614792
tagged with: http://stackoverflow.com/tag/xml
has body: Here is my Chicago XML file: route name="red"> <route name = "red"> 830 30089 95th/Dan Ryan 5 41000 30194 Cermak-Chinatown 20180117 22:41:16 20180117 22:42:16 1 0 <flags/> 41.85532 -87.63133 176 <route name="blue"> 134 30077 Forest Park 5 40570 30112 California 20180117 22:40:47 20180117 22:42:47 0 0 <flags/> 41.92528 -87.70238 122 I was able to using .find function to extract the first train number and more info with that train, but now I want to extract the tag for one train(and the date for that specific train) for the 'route = blue' paragraph... How can I do that? I have trouble with it because every tag are the same. My current code to extract the first tag goes like: train = XML.find('rn') print(train) #just a gist of the code any solutions? I am using BeautifulSoup4
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48314603

http://stackoverflow.com/a/48200043
upvote count: 1
score: 1
has body: You've changed result because after the first time sub_sets is called, result and temp both contain a copy of the same list. You add the list [i] to temp and then add the same list to result when you call result.extend(temp).
answers question: http://stackoverflow.com/q/48199899
type: Answer
has comment: http://stackoverflow.com/comment/83381887
has comment: http://stackoverflow.com/comment/83383368
downvote count: 0

http://stackoverflow.com/a/48285014
has body: This works, but feels a little hacky. I'll happily accept a better answer if one comes along. I've made this work with the addition of two additional files (and a small update to the Dockerfile): Dockerfile: FROM python:3.6.4-slim-stretch WORKDIR /srv RUN apt-get update \ &amp;&amp; apt-get install -y build-essential \ &amp;&amp; pip install uwsgi pytest COPY test_app.py test run_tests.py /srv/ CMD ['/bin/bash'] test: #!/bin/bash uwsgi --set master=true --chdir /srv --pyrun /srv/run_tests.py exit $(cat /tmp/test_results) run_tests.py: #!/usr/bin/python import re import subprocess import sys from pytest import main def write_result(retcode): path = r'/tmp/test_results' with open(path, 'w') as f: f.write(str(retcode)) def run(): sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) retcode = 1 try: retcode = main() finally: write_result(retcode) sys.exit(retcode) if __name__ == '__main__': run() The way it works is that I've copied and tweaked the pytest program into run_tests.py, where it writes out the return code of the tests to a temporary file. The tests are run via a bash script: test, that runs uwsgi, which runs the tests, then exits the script with the return code from the tests. Results now look like: $ docker build -t=test . $ docker run test /srv/test ... ============================= test session starts ============================== platform linux -- Python 3.6.4, pytest-3.3.2, py-1.5.2, pluggy-0.6.0 rootdir: /srv, inifile: collected 1 item test_app.py F [100%] =================================== FAILURES =================================== __________________________________ test_this ___________________________________ def test_this(): &gt; assert 1==0 E assert 1 == 0 test_app.py:4: AssertionError =========================== 1 failed in 0.05 seconds =========================== worker 1 buried after 0 seconds goodbye to uWSGI. $ echo $? 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48233528
type: AcceptedAnswer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48233528
upvote count: 1

http://stackoverflow.com/a/60760199
has comment: http://stackoverflow.com/comment/117815752
has comment: http://stackoverflow.com/comment/112301207
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/111366469
has comment: http://stackoverflow.com/comment/112204307
has body: from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED limit = 10 futures = set() with ThreadPoolExecutor(max_workers=1) as executor: for arg in range(10000000): if len(futures) &gt;= limit: completed, futures = wait(futures, return_when=FIRST_COMPLETED) futures.add(executor.submit(some_func, arg))
upvote count: 28
has comment: http://stackoverflow.com/comment/117785077
has comment: http://stackoverflow.com/comment/136712181
answers question: http://stackoverflow.com/q/48263704
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/124376057
accepted answer of: http://stackoverflow.com/q/48263704
score: 28

http://stackoverflow.com/q/48301044
has comment: http://stackoverflow.com/comment/83588582
type: AnsweredQuestion
has body: I'm trying to produce a Stem plot using the 'matplotlib.pyplot.stem' function. The code works but it is taking over 5 minutes to process. I have a similar code within Matlab that produces the same plot with the same input data almost instantly. Is there a way to optimize this code for speed or a better function I could be using? The arguments for the stem plot 'H' and 'plotdata' are 16384 x 1 arrays. def stemplot(): import numpy as np from scipy.fftpack import fft import matplotlib.pyplot as plt ################################################ # Code to set up the plot data N=2048 dr = 100 k = np.arange(0,N) cos = np.cos pi = np.pi w = 1-1.932617*cos(2*pi*k/(N-1))+1.286133*cos(4*pi*k/(N-1))-0.387695*cos(6*pi*k/(N-1))+0.0322227*cos(8*pi*k/(N-1)) y = np.concatenate([w, np.zeros((7*N))]) H = abs(fft(y, axis = 0)) H = np.fft.fftshift(H) H = H/max(H) H = 20*np.log10(H) H = dr+H H[H &lt; 0] = 0 # Set all negative values in dr+H to 0 plotdata = ((np.arange(1,(8*N)+1,1))-1-4*N)/8 ################################################# # Plotting Code plt.figure plt.stem(plotdata,H,markerfmt = " ") plt.axis([(-4*N)/8, (4*N)/8, 0, dr]) plt.grid() plt.ylabel('decibels') plt.xlabel('DFT bins') plt.title('Frequency response (Flat top)') plt.show() return Here is also the Matlab code for reference: N=2048; dr = 100; k=0:N-1 w = 1 - 1.932617*cos(2*pi*k/(N-1)) + 1.286133*cos(4*pi*k/(N-1)) -0.387695*cos(6*pi*k/(N-1)) +0.0322227*cos(8*pi*k/(N-1)); H = abs(fft([w zeros(1,7*N)])); H = fftshift(H); H = H/max(H); H = 20*log10(H); H = max(0,dr+H); % Sets negative numbers in dr+H to 0 figure stem(([1:(8*N)]-1-4*N)/8,H,'-'); set(findobj('Type','line'),'Marker','none','Color',[.871 .49 0]) xlim([-4*N 4*N]/8) ylim([0 dr]) set(gca,'YTickLabel','-100|-90|-80|-70|-60|-50|-40|-30|-20|-10|0') grid on ylabel('decibels') xlabel('DFT bins') title('Frequency response (Flat top)')
answer count: 2
has answer: http://stackoverflow.com/a/48302491
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83587648
favorite count: 0
possible better answer: http://stackoverflow.com/a/48302634
has title: Optimization of matplotlib stem plot
type: Question
has comment: http://stackoverflow.com/comment/83586690
has answer: http://stackoverflow.com/a/48302634
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83587047
tagged with: python
has comment: http://stackoverflow.com/comment/83588488
tagged with: plot
has comment: http://stackoverflow.com/comment/83586969
tagged with: matlab
tagged with: optimization
accepted answer: http://stackoverflow.com/a/48302491

http://stackoverflow.com/comment/83496374
comment on: http://stackoverflow.com/a/48253912
type: Comment
has text: @MaxU, no problem at all. Thanks for improving the answer!
score: 0
type: AnswerComment

regex
tags question: http://stackoverflow.com/q/48182561
tags question: http://stackoverflow.com/q/48258185
tags question: http://stackoverflow.com/q/48291735
tags question: http://stackoverflow.com/q/48243658
tags question: http://stackoverflow.com/q/48197501
tags question: http://stackoverflow.com/q/48175689
tags question: http://stackoverflow.com/q/48239128
tags question: http://stackoverflow.com/q/48323434
tags question: http://stackoverflow.com/q/48205540
tags question: http://stackoverflow.com/q/48274890
tags question: http://stackoverflow.com/q/48201121
tags question: http://stackoverflow.com/q/48313714
tags question: http://stackoverflow.com/q/48256619
tags question: http://stackoverflow.com/q/48321607
tags question: http://stackoverflow.com/q/48180458
tags question: http://stackoverflow.com/q/48179414
tags question: http://stackoverflow.com/q/48255607
tags question: http://stackoverflow.com/q/48260793
tags question: http://stackoverflow.com/q/48321616
tags question: http://stackoverflow.com/q/48253850
tags question: http://stackoverflow.com/q/48195276
tags question: http://stackoverflow.com/q/48310701
tags question: http://stackoverflow.com/q/48193148
tags question: http://stackoverflow.com/q/48326171
tags question: http://stackoverflow.com/q/48290326
tags question: http://stackoverflow.com/q/48237151
tags question: http://stackoverflow.com/q/48186483
tags question: http://stackoverflow.com/q/48312954
tags question: http://stackoverflow.com/q/48177892
tags question: http://stackoverflow.com/q/48325900
tags question: http://stackoverflow.com/q/48269215
tag name: regex
tags question: http://stackoverflow.com/q/48215884
tags question: http://stackoverflow.com/q/48236321
tags question: http://stackoverflow.com/q/48197948
tags question: http://stackoverflow.com/q/48293837
tags question: http://stackoverflow.com/q/48184487
tags question: http://stackoverflow.com/q/48175219
tags question: http://stackoverflow.com/q/48264375
tags question: http://stackoverflow.com/q/48236223
tags question: http://stackoverflow.com/q/48246403
tags question: http://stackoverflow.com/q/48288763
tags question: http://stackoverflow.com/q/48314354
tags question: http://stackoverflow.com/q/48174601
tags question: http://stackoverflow.com/q/48214863
tags question: http://stackoverflow.com/q/48299874
tags question: http://stackoverflow.com/q/48238949
tags question: http://stackoverflow.com/q/48270978
tags question: http://stackoverflow.com/q/48237283
tags question: http://stackoverflow.com/q/48208193
tags question: http://stackoverflow.com/q/48180363
tags question: http://stackoverflow.com/q/48310832
tags question: http://stackoverflow.com/q/48190477
tags question: http://stackoverflow.com/q/48304872
tags question: http://stackoverflow.com/q/48293157
tags question: http://stackoverflow.com/q/48245236
tags question: http://stackoverflow.com/q/48295798
tags question: http://stackoverflow.com/q/48258466
tags question: http://stackoverflow.com/q/48221338
tags question: http://stackoverflow.com/q/48177725
tags question: http://stackoverflow.com/q/48264580
tags question: http://stackoverflow.com/q/48230301
tags question: http://stackoverflow.com/q/48232204
tags question: http://stackoverflow.com/q/48241272
tags question: http://stackoverflow.com/q/48193118
tags question: http://stackoverflow.com/q/48233596
tags question: http://stackoverflow.com/q/48317839
tags question: http://stackoverflow.com/q/48209706
tags question: http://stackoverflow.com/q/48203126
tags question: http://stackoverflow.com/q/48272315
tags question: http://stackoverflow.com/q/48249235
tags question: http://stackoverflow.com/q/48236846
tags question: http://stackoverflow.com/q/48279284
tags question: http://stackoverflow.com/q/48201634
tags question: http://stackoverflow.com/q/48187924
tags question: http://stackoverflow.com/q/48274585
tags question: http://stackoverflow.com/q/48231397
tags question: http://stackoverflow.com/q/48284387
tags question: http://stackoverflow.com/q/48217503
tags question: http://stackoverflow.com/q/48199747

http://stackoverflow.com/q/48227667
favorite count: 0
has title: Is there something similar as gym.spaces.Box in numpy?
has answer: http://stackoverflow.com/a/48228160
score: 1
tagged with: python
type: Question
tagged with: numpy
has body: In the OpenAI gym, you can do something like this: from gym import spaces low = [1, 2, 3] high = [4, 4, 4] box = spaces.Box(np.array(low), np.array(high)) observation = np.array([2, 2, 2]) if not box.contains(observation): print("This is invalid!") It basically checks for each dimension def contains(self, obs): n = len(obs) # == len(low) == len(high) for i in range(n): if not (self.low[i] &lt;= obs[i] &lt;= self.high[i]): return False return True Does numpy come with something like the spaces.Box class as well?
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83492344
comment on: http://stackoverflow.com/a/48237299
has text: Thanks for the feedback! Here is the code I ended up using it works pretty well for this application. `for size in sizes: if size.text in [usersize]: size.click() print colored('Carted size %s'%(size.text), 'green') break continue` Sorry about the formatting, I don't know why it won't show the indents and different lines. It's basically a for loop which finds all the sizes, finds the correct size, then clicks it.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/91854714
comment on: http://stackoverflow.com/a/48638586
has text: @JeffTang This is my command and it didn't work `python /Users/cvsanbuenaventura/tensorflow/tensorflow/python/tools/freeze_graph.py --input_meta_graph=/Userstsearch/object_ding/model.ckpt-68449.meta --input_checkpoint=/Users/cvsanbuenaventura/Documents/tensorflow_fastlog/models/research/object_detection/training/model.ckpt-68449 --output_graph=/Users/cvsanbuenaventura/Documents/tensorflow_fastlog/models/research/object_detection/inference_graph/frozen_inference_graph-python.pb --output_node_names="detection_boxes, detection_scores, detection_classes, num_detections" --input_binary=true`
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83638779
comment on: http://stackoverflow.com/q/48312790
type: QuestionComment
score: 0
has text: Yes, I want it to be duplicated because the corresponding abstract information for some of them is different. Think of it as a hierarchy where sessions are the highest level and some sessions only have on abstract and some sessions have multiple. I have information about the session and information about the abstract and I want to merge them together.
type: Comment

http://stackoverflow.com/q/48329695
type: Question
has body: I'm trying to create a class which will be able to construct, and return an object which is callable at certain points of time and sending message to RabbitMQ I'm using Pika and I've tried this code but it won't initiate unless i call ioloop but i don't need one and ioloop stucks the rest of my code which is called this class. any ideas how to achieve that? import pika import ConfigurationManager import json import gc class MessageSender: def __init__(self,brokerUrl,queueName): credentials = pika.PlainCredentials('admin', 'admin') self.brokerUrl = brokerUrl self.queueName = queueName self.channel = None self.connectionParameters = pika.ConnectionParameters(host=self.brokerUrl, credentials=credentials) self.connection = pika.SelectConnection(self.connectionParameters, on_open_callback=self.onOpen, custom_ioloop=None) def onOpen(self, connection): connection.channel(self.openChannel) def openChannel(self, channel): channel.queue_declare(None, queue=self.queueName, durable=True) self.channel = channel def createMessageJson(self,commandType,searchId,senderChannel,data,runId=None, originalMessage=None): rtnDict = {} rtnDict["commandType"] = commandType rtnDict["searchId"] = searchId rtnDict["receipientChannel"] = self.queueName rtnDict["senderChannel"] = senderChannel rtnDict["data"] = data if 'executionPlanSchema' in data: rtnDict['executionPlanSchema'] = data['executionPlanSchema'] if runId != None: rtnDict["runId"] = runId if originalMessage != None: rtnDict["originalMessage"] = originalMessage return rtnDict #def sendMessage(self,msg): # tornado.ioloop.IOLoop.current().run_sync(lambda: self.send(msg)) def sendMessageAsync(self,msg): msg = json.dumps(msg) self.channel.basic_publish(exchange='', routing_key=self.queueName, body=msg) gc.collect() def sendMessage(self,msg): msg = json.dumps(msg) self.channel.basic_publish(exchange='', routing_key=self.queueName, body=msg) gc.collect()
tagged with: pika
has answer: http://stackoverflow.com/a/48356877
type: UnansweredQuestion
tagged with: python
tagged with: rabbitmq
score: 0
has title: Pika & RabbitMQ - Async Class Handler
answer count: 1

http://stackoverflow.com/a/48284955
answers question: http://stackoverflow.com/q/48284094
has body: As you mentioned in the comments you are expect temp to have the structure: [[(4, 2)], [(4, 4)], [(2, 2)], [(1, 4)], [(1, 3)], ... ] But instead it has the structure: [(4, 2), (4, 4), (2, 2), (1, 4), (1, 3), ... ] When you pop an item from temp you try to do lst = list(temp.pop()) x = lst[0][0] y = lst[0][1] when instead you should do lst = list(temp.pop()) # lst is a two item tuple x = lst[0] y = lst[1] or even better x, y = temp.pop() # this is called tuple unpacking The reason temp had the structure that it does is that was built with temp = temp+lst Since temp is a list and lst is a list containing a single tuple [(1, 3)] the result is a new list with a tuple added to the end. To create the data structure you were imagining you would have wanted temp.append(lst), but as discussed in comments you should just do: import random import product temp = list(itertools.product(range(1, 5), 2)) random.shuffle(temp)
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48284094
type: AcceptedAnswer

http://stackoverflow.com/a/49963318
has body: Running the celery tasks without apply_async allowed me to debug this issue, showing that there was a concurrency logic error in the Celery tasks. I highly recommend this method of debugging Celery tasks. Instead of: from my_code import my_task celery_params = {'key': 'value'} my_task.apply_async(queue='worker', kwargs=celery_params) I used: from my_code import my_task celery_params = {'key': 'value'} my_task(**celery_params) This allowed me to locate the concurrency issue. After I had found the bug, I converted the code back to an asynchronous method call using apply_async.
answers question: http://stackoverflow.com/q/48290256
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91916811
downvote count: 0
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48290256

http://stackoverflow.com/q/48308693
has answer: http://stackoverflow.com/a/48633605
accepted answer: http://stackoverflow.com/a/48633605
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83841387
favorite count: 0
type: Question
score: 1
has body: I'm trying to convert the Cloud Dataflow "Wordcount" python example to a templated version by modifying the pipeline options to use runtime parameters as instructed in the docs: def run(argv=None): """Main entry point; defines and runs the wordcount pipeline.""" class WordcountTemplatedOptions(PipelineOptions): @classmethod def _add_argparse_args(cls, parser): # Use add_value_provider_argument for arguments to be templatable # Use add_argument as usual for non-templatable arguments parser.add_value_provider_argument( '--input', default='gs://dataflow-samples/shakespeare/kinglear.txt', help='Path of the file to read from') parser.add_argument( '--output', required=True, help='Output file to write results to.') pipeline_options = PipelineOptions(['--output', 'some/output_path']) p = beam.Pipeline(options=pipeline_options) wordcount_options = pipeline_options.view_as(WordcountTemplatedOptions) # Read the text file[pattern] into a PCollection. etc. etc. The problem is creating and staging the template ... when executing the command, the output is: INFO:root:Starting the size estimation of the input INFO:oauth2client.transport:Attempting refresh to obtain initial access_token INFO:oauth2client.client:Refreshing access_token INFO:root:Finished the size estimation of the input at 1 files. Estimation took 0.288088083267 seconds INFO:oauth2client.transport:Attempting refresh to obtain initial access_token INFO:oauth2client.client:Refreshing access_token INFO:root:Starting finalize_write threads with num_shards: 1, batches: 1, num_threads: 1 INFO:root:Renamed 1 shards in 0.13 seconds. INFO:root:number of empty lines: 1663 INFO:root:average word length: 4 and there is no produced file under template_location (gs://[YOUR_BUCKET_NAME]/templates/mytemplate) ... I thought the command was trying to execute the dataflow from the desktop with the "default" input file, so I removed the "default" line in the --input argument, but I got this error: raise BeamIOError('Unable to get the F…
has title: Cannot generate templated dataflow in Python
tagged with: python
tagged with: google-cloud-dataflow
has comment: http://stackoverflow.com/comment/84167145
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/48184332
has comment: http://stackoverflow.com/comment/83348446
tagged with: matplotlib
downvote count: 0
accepted answer: http://stackoverflow.com/a/48184559
favorite count: 0
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/48184559
linked to: http://stackoverflow.com/q/38044866
answer count: 2
has body: I am struggling for a while with the definition of colors in a bar plot using Pandas and Matplotlib. Let us imagine that we have following dataframe: import pandas as pd pers1 = ["Jesús","lord",2] pers2 = ["Mateo","apostel",1] pers3 = ["Lucas","apostel",1] dfnames = pd.DataFrame( [pers1,pers2, pers3], columns=["name","type","importance"] ) Now, I want to create a bar plot with the importance as the numerical value, the names of the people as ticks and use the type column to assign colors. I have read other questions (for example: Define bar chart colors for Pandas/Matplotlib with defined column) but it doesn't work... So, first I have to define colors and assign them to different values: colors = {'apostel':'blue','lord':'green'} And finally use the .plot() function: dfnames.plot( x="name", y="importance", kind="bar", color = dfnames['type'].map(colors) ) Good. The only problem is that all bars are green: Why?? I don't know... I am testing it in Spyder and Jupyter... Any help? Thanks!
has comment: http://stackoverflow.com/comment/83348717
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/83349189
tagged with: plot
has comment: http://stackoverflow.com/comment/83348947
has comment: http://stackoverflow.com/comment/83348417
has title: Problems assigning color to bars in Pandas v0.20 and matplotlib
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48185266
tagged with: pandas
has answer: http://stackoverflow.com/a/48185266

http://stackoverflow.com/a/50280414
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48230706
has body: Run in shell: ipython from IPython.lib import passwd passwd() Enter the password twice and copy the 'sha1:12345' code. After that, edit jupyter config file: vi ./jupyter/jupyter_notebook_config.py ... and alter the password. c.NotebookApp.password='sha1:12345' Paste your 'sha' code and run jupyter notebook.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83486225
comment on: http://stackoverflow.com/q/48251781
has text: Strange, hot/auto reload should work with manage.py runserver
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83650150
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48330851
has text: I don't believe that is possible. Why are you trying to fit that constraint? Maybe if I know what you are trying to avoid, I can think of another workaround

http://stackoverflow.com/a/48296848
score: 5
upvote count: 5
downvote count: 0
type: Answer
has body: By default numpy arrays only store data of a single type. Since initially it contains a floating point number (10.5), the entire array is floating point. Instead of testing the data type, you need to test the value, e.g. by grades[i].is_integer().
answers question: http://stackoverflow.com/q/48296726

http://stackoverflow.com/a/48230866
has comment: http://stackoverflow.com/comment/83446398
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83444998
type: Answer
answers question: http://stackoverflow.com/q/48230646
has body: When you load the data from the csv file you are loading also the first line containing the columns name, you can easly check that looking at the first element in x_train and x_test. If that's the case you can skip the first line like this import csv x_train = list() y_train = list() with open('TRAINING_ALL.txt', encoding='utf-8') as infile: reader = csv.reader(infile, delimiter='\t') next(reader) for row in reader: x_train.append(row[0]) y_train.append(int(row[1])) x_test = list() y_test = list() with open('TEST_ALL.txt', encoding='utf-8') as infile: reader = csv.reader(infile, delimiter='\t') next(reader) for row in reader: x_test.append(row[0]) y_test.append(int(row[1]))

http://stackoverflow.com/comment/83629220
score: 1
has text: No, `mzz = float(mzz)` does _not do anything to the series_. It only changes the object that `mzz` references. Variables != Objects.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48322070

http://stackoverflow.com/comment/83369899
comment on: http://stackoverflow.com/q/48194545
score: 0
type: Comment
has text: Uh, that's not a related error. You have whitespaces. Try `df.columns = df.columns.str.strip()`
type: QuestionComment

http://stackoverflow.com/q/48268429
has comment: http://stackoverflow.com/comment/83520075
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83520071
type: UnansweredQuestion
upvote count: 0
score: -2
tagged with: python
has body: I need to keep a Python script running all the time to make constant changes to my company's Google Adwords account. However, I still need to write and run/test other Python code for other projects. What is the easy way to keep a script continuously running that does not interfere with other Python tasks? Thanks!
has title: Keep a Python script running in the background (while regularly running other Python script)
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/83520496
has comment: http://stackoverflow.com/comment/83520268
has answer: http://stackoverflow.com/a/48268775
has comment: http://stackoverflow.com/comment/83520108

http://stackoverflow.com/comment/83345396
comment on: http://stackoverflow.com/q/48181988
type: Comment
type: QuestionComment
has text: Because when i use Click element keyword , i get the error WebDriverException: Message: unknown error: Element ... is not clickable at point (1165, 410). Other element would receive the click: . so when google i see that it would work if i try it with javascript
score: 0

http://stackoverflow.com/comment/83516040
score: 1
type: Comment
has text: You used copy&paste programming without knowing what the code does. Take a step back and try to understand the code. Start with the first `while` loop.
comment on: http://stackoverflow.com/q/48266456
type: QuestionComment

http://stackoverflow.com/q/48260352
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48264267
has body: I was trying to write a function that inputs a nested tuple and returns a tuple where all the elements are backwards, including those elements in other tuples (basically mirrors it). So with this input: ((1, (2, 3)), (4, 5)) It should return: ((5, 4), ((3, 2), 1)) What I tried def mirror(t): n = 1 for i in t: if isinstance(i, tuple): mirror(i) if n == len(t): t = list(t) t = t[::-1] t = tuple(t) n += 1 return t
has answer: http://stackoverflow.com/a/48284708
score: 7
upvote count: 7
answer count: 4
favorite count: 0
type: Question
has title: Recursively mirroring a nested tuple in Python
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48260495
accepted answer: http://stackoverflow.com/a/48260589
has answer: http://stackoverflow.com/a/48260495
has answer: http://stackoverflow.com/a/48260589
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83503506
tagged with: recursion

http://stackoverflow.com/q/48328498
type: Question
has body: I am pretty new to Python and Tkinter, so I hope this question will be easy for the seniors... I have this checkerboard: I am using a grid layout management, as can be noticed below: from tkinter import * def checkerboard(can): w = can.winfo_width() h = can.winfo_height() cellwidth = w / 4 cellheight = h / 4 for row in range(4): for col in range(4): x1=col * cellwidth y1=row * cellheight x2=(col + 1) * cellwidth y2=(row + 1) * cellheight can.create_rectangle(col * cellwidth, row * cellheight, (col + 1) * cellwidth, (row + 1) * cellheight, fill='white') can.create_text(((x1+x2)/2,(y1+y2)/2),text='A') window = Tk() thecanvas = Canvas(window, width=500, height=500) thecanvas.grid(row=0, column=0) window.update_idletasks() checkerboard(thecanvas) window.mainloop() The problem is that I want to add a previous line over the checkerboard, which does not belong to the grid layout. Something like this: How can I achieve it? Thanks in advance
has comment: http://stackoverflow.com/comment/83643667
has title: Mixing two layout managers inside the same window in Python (Tkinter)
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83642674
has comment: http://stackoverflow.com/comment/83642619
tagged with: python
has comment: http://stackoverflow.com/comment/83644418
upvote count: 2
type: AnsweredQuestion
score: 2
answer count: 2
possible better answer: http://stackoverflow.com/a/48329187
downvote count: 0
has comment: http://stackoverflow.com/comment/83642596
has answer: http://stackoverflow.com/a/48329220
has answer: http://stackoverflow.com/a/48329187
tagged with: tkinter-canvas
accepted answer: http://stackoverflow.com/a/48329220
favorite count: 0

http://stackoverflow.com/comment/83398008
comment on: http://stackoverflow.com/q/48207781
type: Comment
has text: Take a look at Rakesh comment, it may be an access problem. Your user has access to the python site-packages folder why your apache user hasn't. onlyvinish asked you to execute `which python` both from apache and from the cmd to verify that they are the same.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/89140621
type: Comment
has text: Did you ever find a solution to this?
type: QuestionComment
comment on: http://stackoverflow.com/q/48238909
score: 0

http://stackoverflow.com/comment/83612214
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48312529
has text: If you have a fairly large Series, consider the answer from [Paulo Alves](https://stackoverflow.com/a/41676643/7954504) in the link above

http://stackoverflow.com/comment/83592201
has text: That'll leave the hyphen after the common part, by the way
score: 1
comment on: http://stackoverflow.com/a/48303735
type: Comment
type: AnswerComment

pygobject
type: Tag
tags question: http://stackoverflow.com/q/48218319
tag name: pygobject

http://stackoverflow.com/a/48570128
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48216075
upvote count: 1
has body: The problem is resolved now :D. What I found is that there is no module named 'filters' in skimage '0.10.1' as it has 'filter'. So, when I upgraded it using the command sudo pip install --upgrade scikit-image to version '0.13.1', it comes with the 'filters' module instead of 'filter'. The 'filters' module has all attributes of thresholding including 'local' and others as well.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48216075

http://stackoverflow.com/a/48174161
type: Answer
downvote count: 0
upvote count: 1
has body: You are not using set() on a list of tuples, you are using set() on a list of set()s. Change your brackets {} to parentheses (): pairs=list(set(map(lambda line:(line[Column.TO],line[Column.FROM]),self.DataMatrix))) For example, the following demonstrates how to find "the unique pairs generated from the map function". In [23]: self.DataMatrix = [[1,2,5],[3,4,5],[1,2,6]] In [24]: Column.TO Out[24]: 0 In [25]: Column.FROM Out[25]: 1 In [26]: pairs=list(set(map(lambda line:(line[Column.TO],line[Column.FROM]),self.DataMatrix))) In [27]: pairs Out[27]: [(1, 2), (3, 4)]
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83328311
accepted answer of: http://stackoverflow.com/q/48174013
has comment: http://stackoverflow.com/comment/83328242
answers question: http://stackoverflow.com/q/48174013
score: 1

http://stackoverflow.com/a/48192698
type: Answer
answers question: http://stackoverflow.com/q/48192290
has comment: http://stackoverflow.com/comment/83367448
has body: Here's a rule for Python Scope Resolution from this answer LEGB Rule. L, Local — Names assigned in any way within a function (def or lambda)), and not declared global in that function. E, Enclosing-function locals — Name in the local scope of any and all statically enclosing functions (def or lambda), from inner to outer. G, Global (module) — Names assigned at the top-level of a module file, or by executing a global statement in a def within the file. B, Built-in (Python) — Names preassigned in the built-in names module : open,range,SyntaxError,... So basically in your question, the scope resolution is "from inside out" and since you aren't using the global keyword, the interpreter doesn't know to look outside the local function scope to find that variable var. All the interpreter sees is that you are using a variable before declaring and defining it, thus throwing the error. Global variables are often dangerous, and so Python wants to make sure you know you want to use a global variable by forcing you to be explicit about it. See this other answer for an explanation of the global keyword Hope it helps.
score: 5
upvote count: 5
downvote count: 0

http://stackoverflow.com/q/48296270
has answer: http://stackoverflow.com/a/61016961
tagged with: python
has comment: http://stackoverflow.com/comment/83653236
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48457726
tagged with: flask
type: Question
score: 0
tagged with: flask-mongoengine
tagged with: mongoengine
has body: I am writing an API with Flask. I use a ReferenceField for the user who has written a Post. The API should return a JSON object with the data about the post and the data about the user. Flask endpoint: @app.route("/api/posts") def posts_index(): posts = Post.objects() return jsonify({ "posts": json.loads(posts.to_json()) }) Database model: class User(Document): email = EmailField(required=True, unique=True) username = StringField(max_length=50, required=True, unique=True) password = StringField(required=True) created = DateTimeField(required=True, default=datetime.datetime.now()) class Comment(EmbeddedDocument): content = StringField(max_length=5000) user = ReferenceField(User) created = DateTimeField(required=True, default=datetime.datetime.now()) class Post(Document): title = StringField(max_length=120, required=True) user = ReferenceField(User, reverse_delete_rule=CASCADE) content = StringField(max_length=5000) comments = ListField(EmbeddedDocumentField(Comment)) created = DateTimeField(required=True, default=datetime.datetime.now()) JSON response: { "posts": [ { "_id": { "$oid": "5a5efd1f9ef3161fc64cb95a" }, "comments": [], "content": "Lorem Ipsum", "created": { "$date": 1516178223018 }, "title": "Hello", "user": { "$oid": "5a5d0b9b9ef316220b6d9881" } }, { "_id": { "$oid": "5a5efd1f9ef3161fc64cb95b" }, "comments": [], "content": "Lorem Ipsum Dolor", "created": { "$date": 1516178223018 }, "title": "Hello Again", "user": { "$oid": "5a5d0b9b9ef316220b6d9881" } } ] } I'd like to get the json response, but the ReferenceField should contain the information about the user.
has comment: http://stackoverflow.com/comment/83653184
linked to: http://stackoverflow.com/q/23977951
answer count: 2
has title: MongoDB ReferenceField to JSON

http://stackoverflow.com/a/48294932
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48294789
type: Answer
accepted answer of: http://stackoverflow.com/q/48294789
has body: Load the keywords into a list then you can check the other file line-by-line, and write to outfile as you find keywords in the line. with open('/path/to/keywords.txt') as f: keywords = set(line.strip() for line in f) # assuming words are separated by line with open('/path/to/search_me.txt') as f, open('/path/to/outfile.txt', 'w') as outfile: for line in f: if any(kw in line for kw in keywords): outfile.write(line)
score: 1

http://stackoverflow.com/a/48327483
accepted answer of: http://stackoverflow.com/q/48327444
score: 2
answers question: http://stackoverflow.com/q/48327444
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83643224
has body: When you do PATH=$PATH:$HOME/bin, you're adding $HOME/bin to the end of your PATH variable (so it's the last place that is checked). If you want this python to be the priority, you need to add it to the beginning of your PATH: PATH=$HOME/bin:$PATH
downvote count: 0
has comment: http://stackoverflow.com/comment/83641231
has comment: http://stackoverflow.com/comment/83640709
type: Answer

http://stackoverflow.com/q/48216438
has comment: http://stackoverflow.com/comment/83421314
downvote count: 1
has comment: http://stackoverflow.com/comment/83458355
has comment: http://stackoverflow.com/comment/83415332
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has body: In Pycharm, I have a multiline Python command like (that I generate by a live template by the way): import matplotlib.pyplot as plt; plt.plot(A);plt.show() I do not want to have it splitted in three single lines when I execute Menu - Code - Reformat Code. The reason for this is, that I want to have a concise and compact way of printing the contents of a variable (so also @formatter:on won't be a solution) How can I avoid the split in three consecutive lines by the reformatting tool?
has comment: http://stackoverflow.com/comment/83414866
has title: Pycharm: Avoid Line Break After Semicolon When Reformatting
has comment: http://stackoverflow.com/comment/131342421
score: 2
has comment: http://stackoverflow.com/comment/83415052
upvote count: 3
has comment: http://stackoverflow.com/comment/83446895
answer count: 0
tagged with: pycharm

split
tags question: http://stackoverflow.com/q/48222810
tags question: http://stackoverflow.com/q/48176021
tag name: split
tags question: http://stackoverflow.com/q/48181992
type: Tag
tags question: http://stackoverflow.com/q/48201454
tags question: http://stackoverflow.com/q/48205775
tags question: http://stackoverflow.com/q/48260793

http://stackoverflow.com/q/48270433
answer count: 0
tagged with: flask-socketio
type: Question
has comment: http://stackoverflow.com/comment/83560764
has body: I want to confirm the user in flasks-socketio after users entry through the flasks-login but I get a message from the server flasks-socketio that users do not login or not logged in, though I have login via flasks-log in, so how to overcome this? def disconnect(): print ("Your Not Authenticated") @socketio.on("my home", namespace="/home") def on_my_home(username): if current_user.is_authenticated: users[username] = request.sid print ("Your Was Authenticated") else: disconnect() &lt;script type="text/javascript" charset="utf-8"&gt; $(document).ready(function() { var socket = io.connect("http://127.0.0.1:5000/home"); socket.on("connect", function() { var username = "{{ current_user.username }}"; socket.emit("my home", username); }); }); &lt;/script&gt;
has comment: http://stackoverflow.com/comment/83568301
has comment: http://stackoverflow.com/comment/83590012
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83556607
has title: Flask-SocketIO Authenticate
score: 0

http://stackoverflow.com/q/48188845
score: 5
has comment: http://stackoverflow.com/comment/83357790
answer count: 1
downvote count: 0
tagged with: python
tagged with: inheritance
favorite count: 0
has title: How to override class attribute two levels deep?
has comment: http://stackoverflow.com/comment/83357560
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83357541
upvote count: 5
has answer: http://stackoverflow.com/a/48188953
accepted answer: http://stackoverflow.com/a/48188953
has body: Overriding and inheritance is seeming to work differently than I expect, let me explain this situation. I have three classes: Card, Treasure, and Copper. Copper inherits from Treasure and Treasure inherits from Card. The only difference between Treasure and Card is a single method that Treasure overrides. The only difference between Treasure and Copper is an attribute that Copper overrides. The attribute that Copper overrides is originally from Card and it is an attribute that Treasure uses in its unique method. The issue that I'm running into is that when Copper's method is being called that it inherits from Treasure, it is still using Card's attribute value, not the attribute value that Copper should be overriding it with. Below is some code, any help is appreciated. Card Class: class Card: normal_full_table = 6 pile_player_rate = 10 @staticmethod def pile_setup(player_count): pass Treasure Class: from card.card import Card from math import floor class Treasure(Card): @staticmethod def pile_setup(player_count): return (floor(player_count/Card.normal_full_table) + 1) * Card.pile_player_rate Copper Class: from card.basic.card_treasure import Treasure class Copper(Treasure): pile_player_rate = 60 What I would expect to happen is when Copper.pile_setup(6) is called that the value pile_player_rate to be 60 since Copper is overriding that value but upon inspection it is still 10. Why is this? Is this because I'm saying specifically Card.pile_player_rate? How can I get Copper to use it unique value for pile_player_rate rather than the generic one in Card? Thanks.
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/48285109
type: Answer
downvote count: 3
has comment: http://stackoverflow.com/comment/83554598
answers question: http://stackoverflow.com/q/48285048
has body: Try class AClass: def __init__(self, **vars): self.var1 = vars.get('var1')
upvote count: 0
score: -3

http://stackoverflow.com/q/48226032
has comment: http://stackoverflow.com/comment/83528358
tagged with: grpc
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83530276
favorite count: 0
type: Question
has body: my data.proto likes this: syntax = "proto3"; package rpc; service Performer { rpc carryOut(Image) returns (Objects){} } message Objects{ repeated Object objects=1; } message Object{ string type=1; } and implementation like this: class Performer(data_pb2_grpc.PerformerServicer): def __init__(self): pass def carryOut(self, req, cxt): objs=Objects() obj=objs.objects.add() obj.type='Person' return objs client request always get: self.res = self.client().carryOut(self.data()) File "/usr/local/lib/python2.7/dist-packages/grpc/_channel.py", line 484, in __call__ return _end_unary_response_blocking(state, call, False, deadline) File "/usr/local/lib/python2.7/dist-packages/grpc/_channel.py", line 434, in _end_unary_response_blocking raise _Rendezvous(state, None, None, deadline) grpc._channel._Rendezvous: &lt;_Rendezvous of RPC that terminated with (StatusCode.UNKNOWN, Stream removed)&gt; and server crash with error: Segmentation fault(written dump) and it happens in a laptop with : ubuntu 16.04 python 2.7.12 grpcio==1.8.4 grpcio-tools==1.8.4
tagged with: protocol-buffers
type: UnansweredQuestion
tagged with: python
has title: Always get UNKNOWN status code for failed gRPCs to python server
answer count: 0
downvote count: 0

http://stackoverflow.com/q/48218119
type: AnsweredQuestion
answer count: 3
tagged with: amazon-s3
possible better answer: http://stackoverflow.com/a/48281667
has answer: http://stackoverflow.com/a/48293549
has answer: http://stackoverflow.com/a/48281667
score: 1
favorite count: 0
tagged with: urllib
has comment: http://stackoverflow.com/comment/83572102
type: Question
tagged with: bitbucket
accepted answer: http://stackoverflow.com/a/48293549
has body: According to the docs, it should be as simple as: data = self.http_pool.urlopen('GET', file_url, preload_content=False, retries=max_download_retries) request.add_unredirected_header(key, header) Add a header that will not be added to a redirected request. But I cannot seem to find any examples on how this can be achieved. I am using the pyupdater to download updates from bitbucket and launch the newest version of exe. I am using this library to create a script that connects to bitbucket fine, but then it later redirects to Amazon with nauthorization: Basic &lt;redacted&gt;\r\n\r\n (this is bitbucket auth) meaning I get 'HTTP/1.1 400 Bad Request\r\n'. Amazon does not support basic auth. This should be easily solvable, but I cannot find much on this issue. The solutions presented here, require Recreating each redirected request manually. This would become an ever-growing list and get tedious very quickly, if I had to do this for new file I uploaded. It also does not continue the rest of the script, but rather downloads to the same directory. As this is how Pyupdater handles the downloads this is where the issue would likely be solved. Line 366 of downloader.py: data = self.http_pool.urlopen('GET', file_url, preload_content=False, retries=max_download_retries) Any ideas on how to fix this so it no longer creates this error. Full Error (ctrl f -> 400): Python main.py DEBUG:root:Version - 2.5.1 DEBUG:pyupdater.client:PyUpdater Version 2.5.1 Current version is 1.3 {'authorization': 'Basic &lt;redacted&gt;'} DEBUG:pyupdater.client:Setting up directories... DEBUG:pyupdater.client:Downloading key file DEBUG:pyupdater.client.downloader:Url for request: https://api.bitbucket.org/2.0/repositories/ brofewfefwefewef/eee/downloads/keys.gz DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.bitbucket.org send: b'GET /2.0/repositories/ brofewfefwefewef/eee/downloads/keys.gz HTTP/1.1\r\nHost: api.bitbucket.org\r\nAccept-Encoding: identity\r\nauthorization: Basic &lt;r…
linked to: http://stackoverflow.com/q/48161651
has title: Redirect with no auth
downvote count: 0
upvote count: 1
tagged with: python
tagged with: python-requests
has answer: http://stackoverflow.com/a/48293568
has comment: http://stackoverflow.com/comment/83559866
has comment: http://stackoverflow.com/comment/83569245

http://stackoverflow.com/q/48223764
tagged with: mysql
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48225343
has comment: http://stackoverflow.com/comment/83498128
has comment: http://stackoverflow.com/comment/83440315
tagged with: pymysql
tagged with: python
has title: How can I use conditional statement in Python + MySQL?
has body: For example, I can update the data like this: sql= "UPDATE USER SET PASSWORD='+pwd+' WHERE NAME='+name+'" But now I have some data in SQL database, and I want to do this: In table A, column a, row 1 to n If I found a data of which the length is larger than 15, I will set column b = column a, and column b = '' But I think this statement will not work: sql = "UPDATE A SET b=a where len(a)&gt;15" So how can I do this kind of thing? BTW, if the condition is "the first symbol of data is Chinese symbol"? How can I use a IsChinese(str) function to update my data?
has comment: http://stackoverflow.com/comment/83554788
has comment: http://stackoverflow.com/comment/83497855
has comment: http://stackoverflow.com/comment/83429957
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48205733
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/92323764
has comment: http://stackoverflow.com/comment/91972920
answer count: 0
has comment: http://stackoverflow.com/comment/92257298
has comment: http://stackoverflow.com/comment/91972798
tagged with: distributed
downvote count: 0
tagged with: tensorflow
has body: I have got a TensorFlow cluster which is able to perform distributed training of my model. I implemented it using tf.estimator, tf.estimator.train_and_evaluate together with a configured TF_CONFIG environment variable. Though I am able to place the evaluation on an arbitrary machine using the evaluator task, the evaluation still only happens on machine. Hence, my training is very fast since it is happening on several machines, whereas the evaluation drags behind. Is it somehow possible to distribute the evaluation on multiple machines as it is done with the training? Thanks a lot for your answers.
favorite count: 0
type: Question
score: 5
upvote count: 5
has title: tf.estimator: Distributed evaluation

http://stackoverflow.com/comment/83360346
has text: Thanks, that was excellent information :-)
comment on: http://stackoverflow.com/q/48189688
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48184300
has body: I'm trying to run test cases, but I get below error. Run command : python manage.py test Type 'yes' if you would like to try deleting the test database 'test_project_management_db', or 'no' to cancel: yes Destroying old test database for alias 'default'... Traceback (most recent call last): File "manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 62, in handle failures = test_runner.run_tests(test_labels) File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/test/runner.py", line 601, in run_tests old_config = self.setup_databases() File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/test/runner.py", line 546, in setup_databases self.parallel, **kwargs File "/home/rails/Desktop/projects/envs/project_manage_env/local/lib/python2.7/site-packages/django/test/utils.py", l…
tagged with: postgresql
has answer: http://stackoverflow.com/a/76481598
tagged with: django-tests
linked to: http://stackoverflow.com/q/4088253
favorite count: 0
type: Question
score: 41
has comment: http://stackoverflow.com/comment/84000499
upvote count: 41
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49366428
has answer: http://stackoverflow.com/a/64877070
tagged with: django
has title: When I run test cases I get this error: psycopg2.OperationalError: cursor "_django_curs_140351416325888_23" does not exist
tagged with: python
has answer: http://stackoverflow.com/a/65416559
answer count: 4
has comment: http://stackoverflow.com/comment/94299880

http://stackoverflow.com/q/48249248
has answer: http://stackoverflow.com/a/48249394
score: -1
tagged with: loops
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: for-loop
has title: For loop in Python3, using variable[i-1]
answer count: 5
upvote count: 0
has answer: http://stackoverflow.com/a/48249322
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/83481053
possible better answer: http://stackoverflow.com/a/48249279
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48249422
has answer: http://stackoverflow.com/a/48249337
has answer: http://stackoverflow.com/a/48249279
has comment: http://stackoverflow.com/comment/83481483
has body: I need help, everytime i use a for loop in Python3 like: for i in range(len(sequence)): and i write: sequence[i-1] in the first loop it gets the last number of the sequence, how can i change that? example: a=(10,15,20) for i in range(len(a)): a[i]=a[i-1]+a[i] i want to get [ 10,25,35] but i get [45,25,35]
has answer: http://stackoverflow.com/a/48249422

state
tag name: state
type: Tag
tags question: http://stackoverflow.com/q/48272415

http://stackoverflow.com/comment/83361867
has text: Why are you using `csv.writer()` to write but using `file.read()` to read anyways? If you're trying to read a csv the `csv.reader()` would handle the newlines for you.
score: 0
comment on: http://stackoverflow.com/q/48190726
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48252790
has body: I want to return a data.frame object when a upload button(code is from here) is clicked within the bokeh app. Below code, ## Load library import pandas as pd from xlrd import XLRDError import io import base64 from bokeh.layouts import row, column, widgetbox, layout from bokeh.models import ColumnDataSource, CustomJS from bokeh.models.widgets import Button, Div, TextInput, DataTable, TableColumn, Panel, Tabs from bokeh.io import curdoc from bokeh.plotting import figure sheet_names_expected = ['Sheet'+str(i) for i in range(1,7)] ## Uploaded Data Handling file_source = ColumnDataSource({'file_contents':[], 'file_name':[], 'upload_message':[]}) def file_callback(attr,old,new): print('filename:', file_source.data['file_name']) #print('filename:', type(file_source.data['file_contents'][0])) raw_contents = file_source.data['file_contents'][0] prefix, b64_contents = raw_contents.split(",", 1) file_contents = base64.b64decode(b64_contents) file_io = io.BytesIO(file_contents) try: df_dict = pd.read_excel(file_io, sheet_name = sheet_names_expected) file_source.data['upload_message'] = 'Successfully loaded data' except XLRDError: file_source.data['upload_message'] = 'One or more of the sheet names are mis-spelled/missing.\n' except : file_source.data['upload_message'] = 'Error occured while uploading the file. Ensure it\'s a xlsx file' ## How to now have the 6 dataframes within `df_dict` outside the callback function for further analysis and plotting ? file_source.on_change('data', file_callback) ########################################################################### ## Upload Button Widget ########################################################################### button = Button(label="Upload Data", button_type="success") # when butotn is clicked, below code in CustomJS will be called button.callback = CustomJS(args=dict(file_source=file_source), code = """ function read_file(filename) { var reader = new FileReader(); reader.onload = load_handler; reader.onerror = error_h…
favorite count: 0
type: Question
tagged with: python
type: UnansweredQuestion
tagged with: flask
has title: Bokeh - How to return objects from EventHandler functions
has comment: http://stackoverflow.com/comment/83500650
has answer: http://stackoverflow.com/a/48259329
has comment: http://stackoverflow.com/comment/83497241
tagged with: widget
downvote count: 0
tagged with: bokeh
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/83341127
type: AnswerComment
has text: @kilojoules See the last paragraph in my just edited answer.
comment on: http://stackoverflow.com/a/48180501
type: Comment
score: 0

http://stackoverflow.com/q/48241048
has comment: http://stackoverflow.com/comment/83465256
tagged with: vectorization
has comment: http://stackoverflow.com/comment/83465952
has comment: http://stackoverflow.com/comment/83467412
has comment: http://stackoverflow.com/comment/83479365
type: AnsweredQuestion
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/48242435
has comment: http://stackoverflow.com/comment/83465454
has comment: http://stackoverflow.com/comment/83465347
favorite count: 0
has comment: http://stackoverflow.com/comment/83465309
type: Question
has body: I am working with a dataframe, consisting of a continuity column df['continuity'] and a column group df['group']. Both are binary columns. I want to add an extra column 'group_id' that gives consecutive rows of 1s the same integer value, where the first group of rows have a 1, then 2 etc. After each time where the continuity value of a row is 0, the counting should start again at 1. Since this question is rather specific, I'm not sure how to tackle this vectorized. Below an example, where the first two columns are the input and the column the output I'd like to have. continuity group group_id 1 0 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 2 1 1 2 1 1 2 1 0 0 1 0 0 1 1 3 1 1 3 0 1 1 0 0 0 1 1 1 1 1 1 1 0 0 1 0 0 1 1 2 1 1 2
has comment: http://stackoverflow.com/comment/83466373
has comment: http://stackoverflow.com/comment/83465817
accepted answer: http://stackoverflow.com/a/48242435
answer count: 1
downvote count: 0
score: 1
upvote count: 1
has title: Identifying groups with same column value and count them

artificial-intelligence
tags question: http://stackoverflow.com/q/48301802
tags question: http://stackoverflow.com/q/48197227
type: Tag
tags question: http://stackoverflow.com/q/48283911
tag name: artificial-intelligence

http://stackoverflow.com/q/48291543
tagged with: combinatorics
type: Question
tagged with: graph
has comment: http://stackoverflow.com/comment/83568872
tagged with: algorithm
has comment: http://stackoverflow.com/comment/83568247
has comment: http://stackoverflow.com/comment/83568823
has comment: http://stackoverflow.com/comment/83568380
tagged with: python
has title: Efficiently creating and storing all "valid" edge combinations of all sizes from a set of edges
tagged with: traveling-salesman
type: AnsweredQuestion
score: 1
has body: I think this is a fairly difficult question. So thank you ahead of time for any help. I have a graph I am traversing, creating different paths, one at a time. I have a set of edges I "must" use, each is stored as a tuple of (to, from). I am avoiding repeat nodes, so we only go to each "to" once, and to each "from" once. I also don't want to create a cycle in the combination. I want to create all combinations (where order matters) of edges. To be specific, I want all combinations of all valid sizes of tuples. Some examples for clarity: Valid combinations of edges: ((5,7)) ((3,9),(9,11),(21,18)) ((1,2),(2,3),(3,4),(4,5)) Invalid combinations: ((9,8),(9,6)) ((2,5),(11,3),(8,5)) ((1,2),(2,3),(3,4),(4,1)) So, one thing we can see, is that to make all combinations, we will make combinations of size 1, then of size 2, then of 3, ... 4....n Don't worry, it's not quite this insane. The amount of edges I am creating combinations with is typically not that many. But it is variable, and who knows, maybe I could end up creating some combinations of size n. So, I was thinking about using itertools to generate the combinations. I could put itertools combinations in a loop, and increment the size of the combinations of each pass. But then I realized, that it is likely that the majority of combinations will actually end up invalid, and if I use itertools I don't think I can check their validity until the entire combination has been generated. This seems incredibly inefficient. So, my thinking then went to using an adjacency list, where any edge (to, from) I want to force is stored in indices [to][from]. This allows me to iterate the adjacency list such that I avoid getting duplicate "to"s or duplicate "froms". However, I still can't conceptualize how I can actually write a function that generates all of the combinations I want through traversal of the adjacency list. Any Ideas? Note: For now, I don't mind if anyone chooses to ignore the challenge of avoiding closed cycles, ie: 1,2,3…
accepted answer: http://stackoverflow.com/a/48291825
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48291825
has comment: http://stackoverflow.com/comment/83568870
favorite count: 0

http://stackoverflow.com/q/48173746
tagged with: datetime
answer count: 1
has comment: http://stackoverflow.com/comment/83327191
type: Question
accepted answer: http://stackoverflow.com/a/48174131
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48174131
has body: I'm having some trouble with parsing a datetime string in Python 3.6. The critical code is: datetime.datetime.strptime("Jan 08, 2018 07:04 PM UTC", '%b %d, %Y %I:%M %p %Z') And the stacktrace: File "marquito.py", line 180, in start test_date = "" if test_date == "" else datetime.datetime.strptime(test_date + " UTC", "%b %d, %Y %I:%M %p %Z") File "/usr/lib/python3.6/_strptime.py", line 565, in _strptime_datetime tt, fraction = _strptime(data_string, format) File "/usr/lib/python3.6/_strptime.py", line 362, in _strptime (data_string, format)) ValueError: time data 'Jan 08, 2018 07:04 PM UTC' does not match format '%b %d, %Y %I:%M %p %Z' Do you see anything wrong with the code?
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83327382
tagged with: python
has title: Datetime parsing error, wrong format?
favorite count: 0
has comment: http://stackoverflow.com/comment/83327480
tagged with: datetime-format
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/83394986
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48206951
type: QuestionComment
has text: so like this? Q1 = Q1.lower("If you could have any pet what would it be?")input

process
tags question: http://stackoverflow.com/q/48183917
tags question: http://stackoverflow.com/q/48296603
tags question: http://stackoverflow.com/q/48282121
type: Tag
tags question: http://stackoverflow.com/q/48306228
tag name: process

http://stackoverflow.com/a/48408031
score: 3
has comment: http://stackoverflow.com/comment/83856568
has comment: http://stackoverflow.com/comment/84018950
type: Answer
has comment: http://stackoverflow.com/comment/83950304
upvote count: 3
has body: Looks like the python path is referring to a default location. So you have two options to fix this. First is to copy the Jython library inside "C:\apache-tomcat-8.5.24\webapps\jython\WEB-INF\lib\Lib". In order to copy the jython library you need to unzip the contents of jython standalone jar in to this folder. The other option is to set the python path to point to the location where the jython standalone jar is unzipped. The code looks something like this: PythonInterpreter interpreter = null; try{ Properties p = new Properties(); p.setProperty("python.path", "PATH OF JYTHON"); p.setProperty("python.home", "PATH OF JYTHON"); p.setProperty("python.prefix", "PATH OF JYTHON"); PythonInterpreter.initialize(System.getProperties(), p, new String[] {}); interpreter = new PythonInterpreter(); }catch(Exception ex){ log.error("Exception while creating python interpreter: "+ex.toString()); }
answers question: http://stackoverflow.com/q/48215944
downvote count: 0

http://stackoverflow.com/q/48217127
has title: distance based classification
tagged with: python
has comment: http://stackoverflow.com/comment/83620449
tagged with: numpy
type: AnsweredQuestion
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/83558448
tagged with: arrays
has answer: http://stackoverflow.com/a/48311163
has comment: http://stackoverflow.com/comment/83669836
accepted answer: http://stackoverflow.com/a/48311163
has comment: http://stackoverflow.com/comment/83417537
has comment: http://stackoverflow.com/comment/83669216
downvote count: 1
has comment: http://stackoverflow.com/comment/83616228
has body: I have 3 dimensional array of integers (~4000 x 6000 x 3) that I need to classify in a particular way. I'm hoping for something like a k-means clustering method, but instead of inputting the number of clusters I would like to input the maximum radius of a cluster. Said another way, given a sphere of a defined size, I would like to find the minimum number of non-empty spheres that will cover all the data and classify the points accordingly. Though I have little knowledge of the field, I have been looking into clustering algorithms for a little while and have not found one that accomplishes this. For example, given a random dataset: import numpy as np randomArray = np.random.rand(10,10,3)*500 Out[8]: array([[[ 256.68932025, 153.07151992, 196.19477623], [ 48.05542231, 346.1289173 , 327.44694932], [ 427.87340594, 197.26882283, 402.41558648], [ 192.50462233, 408.31800086, 81.66016443], [ 64.15373494, 34.96971099, 446.55362458]], [[ 376.55003794, 70.09514697, 242.08947306], [ 194.86207829, 379.90969257, 439.47043484], [ 102.99922513, 98.57769429, 415.5059223 ], [ 464.65318671, 223.60061654, 417.52758666], [ 53.68383153, 205.32517075, 299.83858164]], [[ 364.80957874, 14.26150931, 264.01568428], [ 295.75617954, 107.52678922, 87.89830525], [ 57.90617865, 409.54132373, 54.36940482], [ 217.35951975, 345.7892723 , 301.07031811], [ 295.98999071, 27.17772152, 182.58776469]], [[ 291.69513153, 466.03218019, 279.25794618], [ 179.60152364, 161.64966386, 269.34221176], [ 374.78609278, 259.18286321, 459.8037004 ], [ 458.51249648, 87.05600447, 268.12588338], [ 152.54500603, 472.36773898, 1.15894726]], [[ 35.43731854, 163.42770568, 131.77683448], [ 14.36039625, 390.33409364, 314.56443073], [ 71.47211566, 109.78613335, 345.57021076], [ 74.62340632, 328.51303903, 341.97344285], [ 205.02121677, 235.71812371, 32.91252756]]]) and a maximum radius R = 35 I would like to output a 2D array of the same height and width, with labels that represent the sphere each point in the 3D array was classifi…
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48310655
has comment: http://stackoverflow.com/comment/83417310
possible better answer: http://stackoverflow.com/a/48310655
has comment: http://stackoverflow.com/comment/83608374
has comment: http://stackoverflow.com/comment/83669307
has comment: http://stackoverflow.com/comment/83417467
has comment: http://stackoverflow.com/comment/83607889
upvote count: 6
has comment: http://stackoverflow.com/comment/83416491

pydrive
tags question: http://stackoverflow.com/q/48259164
tag name: pydrive
type: Tag

http://stackoverflow.com/comment/83502916
score: 0
type: Comment
type: QuestionComment
has text: Most of the columns you are using seem to be an "after-effect" of being viewed.
comment on: http://stackoverflow.com/q/48257144

http://stackoverflow.com/comment/83523788
score: 0
has text: sorry, disregard the comment, for some reason I thought this was drf related. Have you checked - https://stackoverflow.com/questions/38077600/django-createview-how-do-i-call-form-class-init
type: QuestionComment
comment on: http://stackoverflow.com/q/48269809
type: Comment

http://stackoverflow.com/q/48276444
has comment: http://stackoverflow.com/comment/83536454
has comment: http://stackoverflow.com/comment/83536464
downvote count: 0
has title: Django - CSS File Not Loading In Production (Debug: False)
tagged with: django
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49398021
has comment: http://stackoverflow.com/comment/116920564
has body: Current error (Debug=False) "[16/Jan/2018 15:18:42] "GET /static/style.css HTTP/1.1" 404 90" Web site loads but broken formatting because CSS file not loaded Logging: On the CMD prompt it says "[16/Jan/2018 15:49:05] "GET /beginners/ HTTP/1.1" 200 3760 [16/Jan/2018 15:49:05] "GET /static/style.css HTTP/1.1" 404 90 " I'm not sure why this isn't working: my style.css is located in my static folder, and the static folder is the same folder as manage.py When I set Debug = True, I reload the page and it works fine - my static folder is active and I get no static error: [16/Jan/2018 15:58:11] "GET /beginners/? HTTP/1.1" 200 3759 [16/Jan/2018 15:58:11] "GET /static/style.css HTTP/1.1" 200 5014 Please help!! STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
has comment: http://stackoverflow.com/comment/83536156
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/5836674
tagged with: server
answer count: 3
accepted answer: http://stackoverflow.com/a/48276684
has answer: http://stackoverflow.com/a/55276624
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/48276684
duplicate of: http://stackoverflow.com/q/5836674
type: Question
possible better answer: http://stackoverflow.com/a/55276624
linked to: http://stackoverflow.com/q/19289925

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/48237875
tags question: http://stackoverflow.com/q/48318266
tags question: http://stackoverflow.com/q/48306528
tags question: http://stackoverflow.com/q/48321963
tags question: http://stackoverflow.com/q/48185522
tags question: http://stackoverflow.com/q/48279205
tags question: http://stackoverflow.com/q/48308202
tags question: http://stackoverflow.com/q/48181014
tags question: http://stackoverflow.com/q/48285092
type: Tag
tags question: http://stackoverflow.com/q/48181950
tags question: http://stackoverflow.com/q/48178002
tags question: http://stackoverflow.com/q/48230377
tags question: http://stackoverflow.com/q/48244782
tags question: http://stackoverflow.com/q/48243494

http://stackoverflow.com/comment/83442669
type: QuestionComment
comment on: http://stackoverflow.com/q/48230149
has text: _I have a form that I want to display_ You do? Where is it? This code contains no form definition at all.
score: 1
type: Comment

http://stackoverflow.com/q/48212394
favorite count: 0
has comment: http://stackoverflow.com/comment/83429332
has answer: http://stackoverflow.com/a/69271310
score: 1
has comment: http://stackoverflow.com/comment/83406894
tagged with: hdf5
has body: Good evening, I am trying to store a dictionary with strings and numbers in an hdf5 file, but not successfully. I have already stored some datasets with numpy but only with numbers!I have made a research but I can't find a tutorial or something like this. Thank you very much for your time in advance
has title: How to store a dictionary with strings and numbers in a hdf5 file?
type: Question
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/a/48271837
accepted answer of: http://stackoverflow.com/q/48271646
answers question: http://stackoverflow.com/q/48271646
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
has body: Using dict as the example dictionary to insert to: &gt;&gt;&gt; dict={"x":{"foo":"some_values"},"y":["name_two","name_two"]} &gt;&gt;&gt; dict {'x': {'foo': 'some_values'}, 'y': ['name_two', 'name_two']} &gt;&gt;&gt; dict['x']={**dict['x'],**{y['e']:x['c'] for x,y in zip(first_list,second_list)}} &gt;&gt;&gt; dict {'x': {'foo': 'some_values', 'name_two': '[53, 94, 58]', 'name_three': '[81, 43, 38]'}, 'y': ['name_two', 'name_two']} In this example, the number lists are left as strings - you can see in another solution an option for converting these strings to integer lists.
type: Answer

http://stackoverflow.com/q/48207469
tagged with: python
has title: How to start the browsermob-proxy?
tagged with: proxy
score: 0
answer count: 0
tagged with: selenium
has body: I am trying to run the browsermob-proxy as explained here. I closed the repository, changed into the directoty /browsermob-proxy-2.1.4/bin and run the following command: ./browsermob-proxy --use-littleproxy false -port 8080 and also ./browsermob-proxy -port 8080 In both cases I get the following error: Running BrowserMob Proxy using legacy implementation. [INFO 2018-01-11T13:44:30,243 net.lightbody.bmp.proxy.Main] (main) Starting BrowserMob Proxy version 2.1.4 [INFO 2018-01-11T13:44:30,265 org.eclipse.jetty.util.log] (main) jetty-7.x.y-SNAPSHOT [INFO 2018-01-11T13:44:30,288 org.eclipse.jetty.util.log] (main) started o.e.j.s.ServletContextHandler{/,null} [WARN 2018-01-11T13:44:30,386 org.eclipse.jetty.util.log] (main) FAILED SelectChannelConnector@0.0.0.0:8080: java.net.BindException: Address already in use [WARN 2018-01-11T13:44:30,386 org.eclipse.jetty.util.log] (main) FAILED org.eclipse.jetty.server.Server@4b41e4dd: java.net.BindException: Address already in use [ERROR 2018-01-11T13:44:30,387 net.lightbody.bmp.proxy.Main] (main) Failed to start Jetty server. Aborting. java.net.BindException: Address already in use at sun.nio.ch.Net.bind0(Native Method) ~[?:1.8.0_151] at sun.nio.ch.Net.bind(Net.java:433) ~[?:1.8.0_151] at sun.nio.ch.Net.bind(Net.java:425) ~[?:1.8.0_151] at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223) ~[?:1.8.0_151] at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74) ~[?:1.8.0_151] at org.eclipse.jetty.server.nio.SelectChannelConnector.open(SelectChannelConnector.java:162) ~[browsermob-dist-2.1.4.jar:?] at org.eclipse.jetty.server.AbstractConnector.doStart(AbstractConnector.java:356) ~[browsermob-dist-2.1.4.jar:?] at org.eclipse.jetty.server.nio.SelectChannelConnector.doStart(SelectChannelConnector.java:240) ~[browsermob-dist-2.1.4.jar:?] at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:55) ~[browsermob-dist-2.1.4.jar:?] at org.eclipse.jetty.server.Server.doStart(Server.j…
tagged with: browsermob-proxy
has comment: http://stackoverflow.com/comment/83396516
type: Question
has comment: http://stackoverflow.com/comment/83396487
type: UnansweredQuestion

http://stackoverflow.com/q/48253225
has comment: http://stackoverflow.com/comment/83488960
has comment: http://stackoverflow.com/comment/83489581
has comment: http://stackoverflow.com/comment/83489110
has comment: http://stackoverflow.com/comment/83489029
score: 0
upvote count: 2
downvote count: 2
answer count: 1
has body: I have this code: from datetime import datetime today = datetime.now().strftime('%y-%m-%d') class PrintMessage(): def __init__(self,msg): self.msg = msg self.print_message() util = Utilities() #Class adds date to self.msg util.msg_with_time() def print_message(self): #print default msg print(self.msg) class Utilities(): def msg_with_time(msg): print(msg + ' on ' + today) if __name__ == '__main__': inst = PrintMessage("My message") And it gives me the following error: print(msg + ' on ' + today) TypeError: unsupported operand type(s) for +: 'Utilities' and 'str I tried using int(today) in case it was that type of a mismatch, but still get the error. When i remove "+ ' on ' + today", the msg prints, but without the date of course. Also, in the tutorial I'm following, it seems this exact code works. The tutorial uses python 3.1 while i'm using python 3.6, if it matters. Edit: The default string prints, but the error gets thrown. Am using Eclipse workspace, btw. I finally figured it out. The issue was, as i sortof had a hunch of, that i forgot to pass 'msg' to util.msg_with_time(), i.e so it becomes util.msg_with_time(msg).
favorite count: 0
type: Question
has title: TypeError: unsupported operand type(s) for +: object and str, python
tagged with: typeerror
has comment: http://stackoverflow.com/comment/83489153
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48253269
has comment: http://stackoverflow.com/comment/83497771
tagged with: python

http://stackoverflow.com/a/48329061
type: AcceptedAnswer
has body: You can use multiple conditions in a filter method. import datetime toll_obj = Toll.objects.filter(driver__profile__invoice_number=(invoice_number), form_date__lte=datetime.datetime.today().date())
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48327906
type: Answer
answers question: http://stackoverflow.com/q/48327906

http://stackoverflow.com/comment/84233415
type: Comment
has text: Hope this helps. https://github.com/luckydonald/shairport-decoder https://github.com/idubnori/shairport-sync-trackinfo-reader
comment on: http://stackoverflow.com/a/48293724
score: 0
type: AnswerComment

http://stackoverflow.com/a/48283758
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/83552540
upvote count: 1
downvote count: 1
has body: I find the answer of @Gábor Fekete quite good. Here is a continuation of his approach: myList = ["paper", "Plastic", "aluminum", "PAPer", "tin", "glass", "tin", "PAPER", "Polypropylene Plastic"] def is_already_in(value, used_elements): low = value.lower() if low in used_elements: return True used_elements.add(low) return False used_elements = set() print([ e for e in myList if not is_already_in(e, used_elements) ])
answers question: http://stackoverflow.com/q/48283295
has comment: http://stackoverflow.com/comment/83551963

http://stackoverflow.com/comment/83443474
type: Comment
score: 0
type: AnswerComment
has text: .thank you so much. i did it earlier.there was alignment issue .
comment on: http://stackoverflow.com/a/48217191

http://stackoverflow.com/comment/83543443
type: AnswerComment
comment on: http://stackoverflow.com/a/48279709
score: 1
type: Comment
has text: @suganthi Because there is no need to be an instance of a `Tk`, as there's no widget created yet at the time `winf = winfo_Toplevel()` is run. Even if there was, that's not how the method works anyway, it needs an object of the created widget to be attached as the object to the method as in `self.winfo_toplevel()` in the last code in the Original Post.

http://stackoverflow.com/comment/83472096
has text: @f5r5e5d they're strings
type: QuestionComment
comment on: http://stackoverflow.com/q/48244632
score: 0
type: Comment

http://stackoverflow.com/q/48189736
tagged with: datetime
tagged with: rename
tagged with: python
has comment: http://stackoverflow.com/comment/83359772
has title: Renaming and Moving Files
type: AnsweredQuestion
tagged with: python-2.7
has body: I have spent considerable time on my below code but I just can't get it to work and I'm hoping someone can offer me some advice. #Example Code import os, datetime source = "U://Working_Files" nameList=["U://Working_Files".format(x) for x in ['Property','Ownership','Sold','Lease']] def Rename_and_move_files(): for name in nameList: path=os.path.expanduser(os.path.join("~",name)) dirList=os.listdir(path) for filename in dirList: filePath=os.path.join(path,filename) modified_time=os.path.getmtime(name) modified_date=datetime.date.fromtimestamp(modified_time) correct_format=modified_date.strftime('%Y%m%d') if os.path.isfile(filePath): new_name = correct_format + '_' + filename destPath=os.path.join(path, "superseded", new_name) print destPath os.rename(filePath, new_name) Rename_and_move_files() In each folder (Property for example) I have a superseded folder. My end goal is to rename each file that is in each directory to prefix the date (e.g. 2018010_Property_Export.dfb) and then move it to the superseded folder. Property-&gt; Property_Export.dfb Property_Export.xls Property_Export.shp Supserdeded (This is a folder) I am not sure how to rename each file in each folder and then move it to the superseded folder. At the moment I think I'm trying to rename the filepath instead of the individual file names.
has answer: http://stackoverflow.com/a/48190109
upvote count: 3
score: 1
has answer: http://stackoverflow.com/a/48189938
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83359945
possible better answer: http://stackoverflow.com/a/48190109
answer count: 2
accepted answer: http://stackoverflow.com/a/48189938
downvote count: 2

http://stackoverflow.com/comment/83374985
type: AnswerComment
comment on: http://stackoverflow.com/a/48196947
type: Comment
has text: He wants to toggle between fullscreen and not. Taking out the else statement would surely break the toggle.
score: 0

http://stackoverflow.com/a/48324458
accepted answer of: http://stackoverflow.com/q/48324239
upvote count: 3
score: 3
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48324239
type: Answer
has comment: http://stackoverflow.com/comment/83634724
has body: I think it's because your second line would require an offset parameter maybe? i.e. your guassianfunc can make an upside down bell-curve provided it's below the x-axis. For example: y = np.array((3, 2, 1, 2, 3))-4 ax2.plot(x, y, color='black') ax2.plot(x, fitdata(x, y), linewidth=2, label='Fit') Try adding in a 4th param like this def fitdata(x, y): mean = sum(x * y) / sum(y) sigma = np.sqrt(sum(y * (x - mean) ** 2) / sum(y)) def guassianfunc(xVar, a, b, c, d): return a * exp(-(xVar - b) ** 2 / (2 * c ** 2)) + d popt, _ = scipy.optimize.curve_fit(guassianfunc, x, y, p0=[max(y), mean, sigma,0]) return guassianfunc(x, *popt) This also reduces your error significantly.

http://stackoverflow.com/a/48277655
answers question: http://stackoverflow.com/q/48277521
score: 0
upvote count: 1
has body: join does wait for thread to complete, but subprocess.Popen() not. try using subprocess.call() instead. see more here: Python popen command. Wait until the command is finished
downvote count: 1
type: Answer

http://stackoverflow.com/comment/83332890
has text: Are you looking for constant length of list? Is it always 3 elements in the past (C, B, A)?
score: 0
comment on: http://stackoverflow.com/q/48176462
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48203931
score: 0
has comment: http://stackoverflow.com/comment/83391281
has comment: http://stackoverflow.com/comment/83390037
answer count: 1
has title: csv file written using python , is empty when opened in linux
has answer: http://stackoverflow.com/a/48204765
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83389901
has comment: http://stackoverflow.com/comment/83389184
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/83388998
tagged with: python
has body: i have copied the values from list to csv file like there are 2 lists say list1 =['a','b','c','d','e','f','g','h','i','j','k','l','m','n'] list2 = ['1','2','3','4','5','6','7','8','9','10','11','12','13'] and i am writting the 2 lists to csv file using the below code import csv from itertools import izip with open('output1.csv', 'wb') as f: writer = csv.writer(f) writer.writerows(izip(list1, list2)) when i open output1.csv in linux after executing the above thing , it is empty but when i print it , using print(open("output1.csv").read()) in python script is printing the contents of the csv file propery can you please let me know why the file is empty when i opened it in linux
has comment: http://stackoverflow.com/comment/83390197
tagged with: python-2.7

http://stackoverflow.com/comment/83335066
type: QuestionComment
has text: This is a marked improvement in your question quality. Well done, keep it up.
comment on: http://stackoverflow.com/q/48177371
score: 1
type: Comment

http://stackoverflow.com/q/48183318
upvote count: 4
favorite count: 0
type: Question
tagged with: python-3.x
has title: python unittest - wrong test count
answer count: 1
has answer: http://stackoverflow.com/a/57592596
tagged with: unit-testing
type: AnsweredQuestion
score: 3
has body: I'm writing a testing environment for a MOOC, and I have the following unit-test class, which examines the output of a method called search. The idea is to iterate over several inputs (in this case there are 2) using subTest. Here's my code: import unittest import sys from io import StringIO import ex1 import ex1sol class Ex1TestCase(unittest.TestCase): def setUp(self): self.orig_stdout = sys.stdout self.test_lst = [4, 7, 2, 3, 1] self.nums_to_search = [7, 8] def tearDown(self): sys.stdout = self.orig_stdout def test_1(self): for n in self.nums_to_search: with self.subTest(n=n): # get test output new_stdout = StringIO() sys.stdout = new_stdout ex1.search(self.test_lst, n) test_output =new_stdout.getvalue().strip() # get solution output new_stdout = StringIO() sys.stdout = new_stdout ex1sol.search(self.test_lst, n) sol_output = new_stdout.getvalue().strip() # compare self.assertEqual(test_output, sol_output) if __name__ == '__main__': unittest.main() Here's what's weird - I have 2 test-cases (which I run using a for loop inside the test_1 method. However, on the one hand my console output is: Ran 1 test in 0.001s OK Process finished with exit code 0 On the other hand, pycharm claims that I passed 3 tests: I can figure that the output is because eventually I run only a single test method, but I can't explain the 3-tests issue. My questions: What's the explanation of the behavior described above? How can I make my unittest-program to display the results for 2 tests (not 1 or 3)?
downvote count: 1
accepted answer: http://stackoverflow.com/a/57592596
tagged with: python-unittest
tagged with: python

doctest
type: Tag
tags question: http://stackoverflow.com/q/48218897
tag name: doctest
tags question: http://stackoverflow.com/q/48279161

http://stackoverflow.com/q/48326162
has title: Grab data from password protected ASP website using Python's requests
has answer: http://stackoverflow.com/a/48336858
type: AnsweredQuestion
has body: I'm trying to get the whole content of a password-protected ASP site using Python's requests. The programmer of the ASP Site told me that using PowerShell he is able to get the data using the following script: $c = $host.UI.PromptForCredential('Your Credentials', 'Enter Credentials','','') $r = Invoke-WebRequest 'https://server.com/app/login.aspx' -SessionVariable my_session $form = $r.Forms[0] $form.fields['xUsername']=$c.UserName $form.fields['xPassword']=$c.GetNetworkCredential().Password $r = Invoke-WebRequest -Uri ("https://server.com/app/login.aspx?ReturnUrl=%2Fapp%2FgetData.aspx%3Ftype%3DGETDATA%26id%3D123") -WebSession $my_session -Method POST -Body $form.Fields I'm trying to achieve this using python's requests library, but does not seems to work properly. Instead of getting the data, I get the HTML code you'll normally see when trying to access without password. import getpass import requests requests.packages.urllib3.disable_warnings() import re from bs4 import BeautifulSoup user="my_username" password=getpass.getpass() data = {"xUsername":user, "xPassword": password} with requests.Session() as s: page = s.get('https://server.com/app/login.aspx',verify=False).content soup = BeautifulSoup(page) data["___VIEWSTATE"] = soup.select_one("#__VIEWSTATE")["value"] data["__VIEWSTATEGENERATOR"] = soup.select_one("#__VIEWSTATEGENERATOR")["value"] s.post('https://server.com/app/login.aspx', data=data) open_page = s.post( "https://server.com/app/login.aspx?ReturnUrl=/app/getData.aspx?type=GETDATA&amp;id=123") What am I doing wrong?
score: 1
answer count: 1
upvote count: 1
tagged with: python-requests
tagged with: asp.net
favorite count: 0
type: Question
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83638266
accepted answer: http://stackoverflow.com/a/48336858

http://stackoverflow.com/q/48186571
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48186603
accepted answer: http://stackoverflow.com/a/48186603
possible better answer: http://stackoverflow.com/a/48186818
tagged with: python
has title: tkinter concatenate entry name from string
has answer: http://stackoverflow.com/a/48186818
has body: I have three entries like this: e1 = Entry(master, state="readonly") e2 = Entry(master, state="readonly") e3 = Entry(master, state="readonly") Is there any way to use a variable or string to define name of the Entry like: x=int(1) e+str(x) = Entry(master, state="readonly")
has comment: http://stackoverflow.com/comment/83363229
upvote count: 2
type: AnsweredQuestion
score: 0
answer count: 2
downvote count: 2
tagged with: tkinter
linked to: http://stackoverflow.com/q/5036700

http://stackoverflow.com/comment/83683490
type: QuestionComment
comment on: http://stackoverflow.com/q/48328938
has text: @jonrsharpe : That reads like there are no side effects to be expected, at least from the python core.
type: Comment
score: 0

http://stackoverflow.com/q/48323378
score: 1
tagged with: python
has title: ImportError: scipy/spatial/ckdtree.so
has answer: http://stackoverflow.com/a/48443351
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83638705
tagged with: scipy
favorite count: 0
tagged with: libstdc++
type: Question
linked to: http://stackoverflow.com/q/16605623
has comment: http://stackoverflow.com/comment/83634357
tagged with: anaconda
has body: I'm using Anaconda2 v5.0.1 on LinuxMint 17.3 Rosa. When I tried to import scipy.stats I got this error: ImportError: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `CXXABI_1.3.9' not found (required by /home/dolf/anaconda2/lib/python2.7/site-packages/scipy/sparse/_sparsetools.so Then I tried this solution: sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt-get update sudo apt-get upgrade But now I get this error: ImportError: /home/dolf/anaconda2/lib/python2.7/site-packages/scipy/spatial/ckdtree.so: symbol _ZTINSt8ios_base7failureB5cxx11E, version GLIBCXX_3.4.21 not defined in file libstdc++.so.6 with link time reference I don't understand the error message, and cannot find anything useful online. How can I fix this?

http://stackoverflow.com/comment/83335002
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48177422
has text: What does ~df do?

bdd
tags question: http://stackoverflow.com/q/48195796
tag name: bdd
type: Tag

http://stackoverflow.com/comment/83455042
score: 0
type: AnswerComment
has text: Google "git clone branch". It would tell you to type `git clone -b pybind11 https://github.com/supervacuus/dlib.git`
type: Comment
comment on: http://stackoverflow.com/a/48235816

http://stackoverflow.com/q/48266752
favorite count: 0
type: Question
tagged with: qt
type: UnansweredQuestion
has title: PyQt5 adds only one widget to centralWidget
tagged with: python
tagged with: sudoku
has answer: http://stackoverflow.com/a/48268065
has body: this is my very first post on stackoverflow. To this day stackoverflow has been a very huge help for me improving my python skills. But I'm having this problem, that PyQt adds only one widget to the centralWidget instead of the 9x9 matrix I need for Sudoku. In another version - which worked - I used two classes to create the MainWindow and the Widgets seperatly. But now I want to achieve it in only one class. link1: how it looks link2: how it should look import sys from selenium import webdriver from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class mainwindow(QMainWindow, QWidget): def __init__(self, parent = None): super(mainwindow, self).__init__(parent = parent) self.title = 'SUDOKU SOLVER' self.initUI() def initUI(self): self.setWindowTitle(self.title) # add menubar menubar = self.menuBar() # add drop down items exitAct = QAction('&amp;Exit', self) exitAct.setShortcut('Ctrl+Q') exitAct.setStatusTip('Exit Application') exitAct.triggered.connect(qApp.quit) newAct = QAction('New', self) newAct.setShortcut('Ctrl+N') newAct.setStatusTip('New Sudoku') newAct.triggered.connect(GameLogic.clearFields) rulesAct = QAction('Rules', self) rulesAct.setShortcut('Ctrl+R') rulesAct.setStatusTip('Sudoku Rules') rulesAct.triggered.connect(GameLogic.sudokuRules) # add menubar entries fileMenu = menubar.addMenu('&amp;File') fileMenu.addAction(newAct) fileMenu.addAction(exitAct) helpMenu = menubar.addMenu('&amp;Help') helpMenu.addAction(rulesAct) # call gridlayout function l = self.gridLayout() self.setCentralWidget(l) self.show() def gridLayout(self): layout = QGridLayout() solve = QPushButton('Solve', self) solve.clicked.connect(GameLogic.solveSudoku) solve.setFixedSize(60, 30) mainwindow.fields = {} # validate user input onlyInt = QIntValidator(1, 9, self) # this is the part that doesnt work... for x in range(9): for y in range(9): # keep a reference to the buttons mainwindow.fields[(x, y)] = QLineEdit(self) mainwindow.fields[(x, y)].setMaxLength…
answer count: 2
downvote count: 0
tagged with: pyqt5
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48266916

http://stackoverflow.com/a/48177931
has comment: http://stackoverflow.com/comment/83336042
accepted answer of: http://stackoverflow.com/q/48177847
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/48177847
upvote count: 5
type: Answer
has body: In bash, single quotes and double quotes mean different things. From Difference between single and double quotes in Bash Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. Whereas for double quotes: The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion). So your ".*" is getting expanded before being passed diff. Try switching the quotes bashCommand = "diff -x '.*' -r " + source + ' ' + target EDIT Popen doesn't normally use a shell to execute your command (unless you pass shell=True) so you don't need actually need to escape the pattern at all: &gt;&gt;&gt; subprocess.Popen(['diff', '-x', "'.*'", '-r', 'a', 'b']) &lt;subprocess.Popen object at 0x10c53cb50&gt; &gt;&gt;&gt; Only in a: .dot &gt;&gt;&gt; subprocess.Popen(['diff', '-x', '.*', '-r', 'a', 'b']) &lt;subprocess.Popen object at 0x10c53cb10&gt;
score: 4
has comment: http://stackoverflow.com/comment/83336111

http://stackoverflow.com/a/48459619
answers question: http://stackoverflow.com/q/48211303
has body: From the API: SGVector&lt;float64_t&gt; CMulticlassLabels::get_labels() (inherited from CDenseLabels) In your case: labels_predict.get_labels(), which will give you a numpy array.
type: Answer
score: 0

http://stackoverflow.com/a/55958098
downvote count: 0
type: Answer
upvote count: 3
score: 3
has body: You need to explicitly add {{ form.media }} so it looks like {{ form.media }}
answers question: http://stackoverflow.com/q/48317281

http://stackoverflow.com/q/48232055
has answer: http://stackoverflow.com/a/48325093
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48325093
tagged with: python
upvote count: 4
score: 4
has title: SQLAlchemy and pandas producing an error (engine.table_names return empty list)
type: AnsweredQuestion
has body: I have a code which looks like the following: from sqlalchemy import create_engine import pandas as pd # load the CSV df = pd.Series() df['raw'] = pd.read_csv('./data/Iris.csv',index_col='Id') # Connect to the mysql, and use database "datasets" engine = create_engine('mysql://root:root@127.0.0.1') engine.execute("USE Datasets") # select new db # Write data table_name = 'IRIS' df['raw'].to_sql(table_name, engine, if_exists='append', index=False) The data is correctly inserted into the database, and can be loaded afterwards, but the command produces an error: &gt; --------------------------------------------------------------------------- AttributeError Traceback (most recent call &gt; last) &lt;ipython-input-6-cfb9b0f5c930&gt; in &lt;module&gt;() &gt; 1 table_name = 'IRIS' &gt; 2 &gt; ----&gt; 3 df['raw'].to_sql(table_name, engine, if_exists='append', index=False) &gt; &gt; ~/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py in &gt; to_sql(self, name, con, flavor, schema, if_exists, index, index_label, &gt; chunksize, dtype) 1360 sql.to_sql(self, name, con, &gt; flavor=flavor, schema=schema, 1361 &gt; if_exists=if_exists, index=index, index_label=index_label, &gt; -&gt; 1362 chunksize=chunksize, dtype=dtype) 1363 1364 def to_pickle(self, path, compression='infer'): &gt; &gt; ~/anaconda3/lib/python3.6/site-packages/pandas/io/sql.py in &gt; to_sql(frame, name, con, flavor, schema, if_exists, index, &gt; index_label, chunksize, dtype) &gt; 469 pandas_sql.to_sql(frame, name, if_exists=if_exists, index=index, &gt; 470 index_label=index_label, schema=schema, &gt; --&gt; 471 chunksize=chunksize, dtype=dtype) &gt; 472 &gt; 473 &gt; &gt; ~/anaconda3/lib/python3.6/site-packages/pandas/io/sql.py in &gt; to_sql(self, frame, name, if_exists, index, index_label, schema, &gt; chunksize, dtype) 1157 table_names = &gt; engine.table_names( 1158 schema=schema or &gt; self.meta.schema, &gt; -&gt; 1159 connection=conn, 1160 ) 1161 if name not in table_names: &gt; &gt; ~/anacon…
downvote count: 0
tagged with: sql

http://stackoverflow.com/q/48286520
has comment: http://stackoverflow.com/comment/83558248
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83557891
type: UnansweredQuestion
has body: I'm relatively new to Python programming. I've run into a problem where a variable that I have defined as global isn't updating inside a definition. I (despite my best effort) can't wrap my head around what could be wrong. Here is the code: import math import numpy as np arraySize = 10 arrayPrecision = 0.1 array = [] x = 0 f_x = x def arrayMaker(): global x global f_x for n in np.arange(-arraySize/2, 0, arrayPrecision): x = n array.append(f_x) for n in np.arange(0, (arraySize/2)+0.1, arrayPrecision): x = n array.append(f_x) print(array) arrayMaker() When I run this code, it prints an array filled with zeroes, and the expression f_x returns 0. Any help would be appreciated.
has comment: http://stackoverflow.com/comment/83557920
tagged with: python
has comment: http://stackoverflow.com/comment/83557821
has comment: http://stackoverflow.com/comment/83567585
has answer: http://stackoverflow.com/a/48286834
score: 0
has comment: http://stackoverflow.com/comment/83558258
answer count: 1
has title: Python global variable not updating inside definition

http://stackoverflow.com/comment/83607414
type: Comment
comment on: http://stackoverflow.com/a/48293440
score: 0
type: AnswerComment
has text: Thanks for your response. I'm still having trouble. I can successfully load my csv into pandas and manipulate it, but I'm really struggling with how to then take my dataframe, turn it back into a csv, and then put that file into a new bucket. Could you lend any clarity on how I can accomplish that?

http://stackoverflow.com/comment/83477207
score: 0
type: AnswerComment
type: Comment
has text: Ok, I just took your example event and test it in my AWS Lambda and is working for me. BTW I'm using python 3 (and I didn't do the replace stuff). Can you send me a print of your event (not using the json.dumps that you were doing, pure print(event))
comment on: http://stackoverflow.com/a/48244447

http://stackoverflow.com/q/48238394
tagged with: pandas
has comment: http://stackoverflow.com/comment/83459157
has title: can't import pandas Python
favorite count: 0
type: Question
has body: I want to import Pandas in Python termination, but it won't take the next step unless I press CTRL C to stop the process. If I press the CTRL C after a little while (about 2 seconds), the pandas will be imported successfully. If the time is too short, it will show the keyboard interrupt exception. It looks like Pandas does import but something goes wrong after that. I have to press CTRL C to import Pandas, and that's too awful. Can anyone tell me how to solve this problem? Any suggestion will be helpful, thanks!
has answer: http://stackoverflow.com/a/48239981
type: UnansweredQuestion
answer count: 1
upvote count: 1
tagged with: python
downvote count: 1
score: 0

http://stackoverflow.com/a/48489579
accepted answer of: http://stackoverflow.com/q/48324044
score: 0
has body: The thing that was causing such a strange bug was my log files permissions. I have the following in my settings.py: if not DEBUG: WORKER_HANDLERS = {} for app in PROJECT_APPS: WORKER_HANDLERS['file_{0}'.format(app)] = { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/var/log/app/{0}.log'.format(app), } LOGGING['handlers'].update(WORKER_HANDLERS) While installing my DEBIAN package in postinst script, i was calling collectstatic command from root, which created all of my log files owned by root. That's why celery failed to run: actually there was an error starting my app. Yet strange thing is that manage.py check was saying everything was ok. Be careful with file permissions on log files.
type: Answer
answers question: http://stackoverflow.com/q/48324044
type: AcceptedAnswer

http://stackoverflow.com/tag/r
tags question: http://stackoverflow.com/q/48327727
tags question: http://stackoverflow.com/q/48310468
tags question: http://stackoverflow.com/q/48303022
tags question: http://stackoverflow.com/q/48253554
type: Tag
tags question: http://stackoverflow.com/q/48243028
tags question: http://stackoverflow.com/q/48289643
tags question: http://stackoverflow.com/q/48270742
tags question: http://stackoverflow.com/q/48252114
tags question: http://stackoverflow.com/q/48324831
tags question: http://stackoverflow.com/q/48313664
tags question: http://stackoverflow.com/q/48249008
tags question: http://stackoverflow.com/q/48280753
tags question: http://stackoverflow.com/q/48250722
tag name: r
tags question: http://stackoverflow.com/q/48265360

http://stackoverflow.com/a/48221188
has body: You can limit the Article.prices collection to a subset of all prices by using an explicit join() combined with contains_eager() option, as is explained in "Using contains_eager() to load a custom-filtered collection result": return Article.query.\ join(Article.prices).\ filter_by(active=True, location_id=location_id).\ options(db.contains_eager(Article.prices).load_only("price")).\ all() filter_by() extracts its keyword arguments from either the primary entity of the Query, or the target entity of the last join, which is ArticlePrice in this case. Using load_only() allows you to limit the set of attributes to load from ArticlePrice. The SQL produced is pretty much identical to your original, save for the primary keys of ArticlePrice – you're using an ORM after all: SELECT article_price.article_id AS article_price_article_id, article_price.location_id AS article_price_location_id, article_price.price AS article_price_price, article.id AS article_id, article.title AS article_title, article.description AS article_description, article.image AS article_image, article.brand AS article_brand, article.category_id AS article_category_id FROM article JOIN article_price ON article.id = article_price.article_id WHERE article_price.active = 1 AND article_price.location_id = ? To rename and unpack the collection of prices to a scalar pass the attribute= keyword argument to field constructor: article = namespace.model('Article', { 'id': fields.Integer, 'title': fields.String, 'description': fields.String, 'image': fields.String, 'brand': fields.String, 'price': fields.Float(attribute=lambda a: a.prices[0].price), 'category_id': fields.Integer })
has comment: http://stackoverflow.com/comment/83425969
has comment: http://stackoverflow.com/comment/83426193
upvote count: 3
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48219143
answers question: http://stackoverflow.com/q/48219143
score: 3
type: Answer

http://stackoverflow.com/comment/83626291
comment on: http://stackoverflow.com/q/48320483
type: Comment
type: QuestionComment
has text: As long as you don't expect a **massive** amount of records (500k+) - I'd recommend to keep it simple and just clear the file and write everything on each dump.
score: 1

http://stackoverflow.com/q/48234889
has body: Format of data given below: a = [[0.65, 1148.59, 752.789], [0.65, 46.70, 30.5], ...] I need to add 3rd position values , there are many values though. My solution: total_values = [] for b in a: total_values.append(b[2]) # Now find sum(total_values). I know this not a good practice. Is there any better way to get the total directly with out taking then into another list.
score: 0
duplicate of: http://stackoverflow.com/q/15352457
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48234922
tagged with: nested
has title: Better way to add values in a certain position of a nested list?
has answer: http://stackoverflow.com/a/48234928
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48234918
linked to: http://stackoverflow.com/q/15352457
tagged with: list
has comment: http://stackoverflow.com/comment/83452724
answer count: 3

http://stackoverflow.com/comment/83648065
type: Comment
type: QuestionComment
has text: Your explanation of the problem is very hard to understand. What do you mean by "caged in the namespace"? What is "object 'family tree'"?
comment on: http://stackoverflow.com/q/48330721
score: 0

http://stackoverflow.com/q/48286199
type: AnsweredQuestion
tagged with: python-2.7
tagged with: pandas
has answer: http://stackoverflow.com/a/48286570
accepted answer: http://stackoverflow.com/a/48286570
score: 1
tagged with: dataframe
tagged with: python
type: Question
downvote count: 0
has body: Say I have the following data frame: ID Brick Vinyl Stone 1 Yes No No 2 No Yes No 3 No No Yes 4 Yes Yes No 5 No No No How would I create a new column based on the names of these columns so that I ended up with the following? ID Brick Vinyl Stone Type 1 Yes No No Brick 2 No Yes No Vinyl 3 No No Yes Stone 4 Yes Yes No Multiple 5 No No No Other Note that IDs 4 and 5 are either 'Yes' for multiple columns or are all 'No'. The response I have recorded in 'Type' for those two entries doesn't have to be 'Multiple' or 'Other' specifically - if there is a default way of recording the desired information that will work just as well. Thank you!
upvote count: 1
answer count: 1
has title: How do I create one column based on the names of multiple other columns in python?
favorite count: 0

http://stackoverflow.com/comment/83337055
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48178424
type: Comment
has text: Python uses `[]` to index collections. Have you tried it?

http://stackoverflow.com/comment/83587889
comment on: http://stackoverflow.com/a/48301631
score: 3
type: Comment
has text: @ThomasKühn Yes, especially since Python supports negative indexing
type: AnswerComment

heatmap
tags question: http://stackoverflow.com/q/48235729
tags question: http://stackoverflow.com/q/48213443
tag name: heatmap
type: Tag

http://stackoverflow.com/comment/83506527
score: 1
has text: Then first try standardizing the data and then use LinearRegression or DecisionTreeRegressor. In LinearRegression, the `coef_` will give you the feature importance. In DecisionTreeRegressor use `feature_importances_` attribute. Also posting this on [Cross-Validated](https://stats.stackexchange.com) may help more.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48257144

http://stackoverflow.com/comment/83515825
has text: @alex: Also, I think you're not extracting a rectangle but instead a *cuboid*
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48266265
type: QuestionComment

http://stackoverflow.com/q/48196188
favorite count: 0
has body: New programmer with pandas here. I'm working on separating rows withing a pandas dataframe into new dataframes. I have a dataframe that looks something like this: In [1]: print (df) first_name email organization 0 Brad brad@gmail.com org1 1 Jared jared@gmail.com org2 2 Daniel daniel@gmail.com org3 3 Michael michael@gmail.com org1 4 Jaime jaime@gmail.com org2 What I want to do is go through each row in the dataframe, identify which organization the row belongs to (eg. Brad belongs to org1, Daniel belongs to org3), and then I want to write that row into a new dataframe. In this case, I'd want to have 3 new dataframes, each of which would look like the following: Org1: In [3]: print (org1) first_name email organization 0 Brad brad@gmail.com org1 1 Michael michael@gmail.com org1 Org2: In [4]: print (org2) first_name email organization 0 Jared jared@gmail.com org2 1 Jaime jaime@gmail.com org2 Org3: In [3]: print (org3) first_name email organization 0 Daniel daniel@gmail.com org3 How would I create a loop that iterates through each row in my original dataframe, identify the dataframe to write to through the value in a specific column, and then actually writes it to the dataframe? The first time that the loops encounters the value, I would want it to create a brand new dataframe. After that, any subsequent rows with the same value should get added to it-- not create a new one entirely. Any help (and wisdom for understanding how loops work in regards to dataframes) would be greatly appreciated.
type: Question
linked to: http://stackoverflow.com/q/46124699
tagged with: python
duplicate of: http://stackoverflow.com/q/46124699
has answer: http://stackoverflow.com/a/48196235
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: pandas
has title: Write rows into new dataframes
answer count: 1
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48196235

http://stackoverflow.com/comment/83643881
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48327367
has text: My bad, didn't pay attention to function's name... But saw clearly that one returned value `> 0.42524395175128987` was mentioned.

http://stackoverflow.com/comment/83493189
has text: @dahrens I want django do this when something changes.
comment on: http://stackoverflow.com/q/48254782
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48296615
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48296532
has body: You can do this: for key in d2: d1.pop(key, None)
type: Answer
has comment: http://stackoverflow.com/comment/83584905
downvote count: 0

http://stackoverflow.com/q/48262191
type: Question
upvote count: 2
tagged with: wtforms
has title: creating custom widget with flask wtforms
type: UnansweredQuestion
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/57263692
score: 2
downvote count: 0
has body: I am strugling to find resources that explain how to create custom widget with wtforms. I want to display a list of toggle buttons. So far I ve been able to create a list of checkboxes with SelectMultipleFields: class PrecisionForm(FlaskForm): phone_number = StringField('Phone number', [validators.Length(min=4, max=25)]) contact_emails = SelectMultipleField( 'Contact emails', [at_least_one], choices=[], option_widget=widgets.CheckboxInput(), widget=widgets.ListWidget(prefix_label=False) ) but now I want to modify my widget.CheckBoxInput() with my custom widget looking like : &lt;label class='switch'&gt; &lt;input type='checkbox'&gt;&lt;span class='slider round'&gt;&lt;/span&gt;&lt;/label&gt; I would be very grateful if someone could explain step by step how to do that. --UPDATE-- I found a way to achieve what I wanted to do but it seems pretty bad : class ToggleButtonWidget(object): def __call__(self, field): html = '&lt;label class="switch"&gt;&lt;input type="checkbox" id={} name={} value={}&gt;&lt;span class="slider round"&gt;&lt;/span&gt;&lt;/label&gt;'.format(field.id, field.name, field.label.__dict__['text']) return HTMLString(html) especially this part : field.label.__dict__['text'] that I use to set the value of my checkbox (the field object from wtforms has no attribute value). Is there a better way ?
answer count: 1
favorite count: 0

http://stackoverflow.com/q/48222754
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48229254
answer count: 2
has body: I'm automating an application with the Robot Framework (Python 2.7). I use the xpath to locate the objects. I have seen that the xpath of the objects is different when I change the language application. For example: ES // * [@ id = "dnn_ctr489_ViewINT_Cupones_ibtnAdd"] FR // * [@ id = "dnn_ctr644_ViewINT_Cupones_ibtnAdd"] EN // * [@ id = "dnn_ctr583_ViewINT_Cupones_ibtnAdd"] This forces me to redo the Test Case because the xpath is different. Is it possible to use a regular expression to form the xpath? How can I avoid having to redo the test cases for each different language? Thank you. Marta
has title: Regular expression to create xpath with Robot Framework
type: Question
has answer: http://stackoverflow.com/a/48229254
tagged with: robotframework
has answer: http://stackoverflow.com/a/48223778
possible better answer: http://stackoverflow.com/a/48223778
tagged with: python
tagged with: xpath

http://stackoverflow.com/comment/83415811
comment on: http://stackoverflow.com/q/48216856
score: 0
type: QuestionComment
type: Comment
has text: Well, `BAR` is a variable that is in the class scope, which is sort of a special case in Python. Check out [this answer](https://stackoverflow.com/a/23471004/5014455)

http://stackoverflow.com/comment/87941853
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48309092
has text: @j_4321 : I am using Python 3.6.1 on Windows7

http://stackoverflow.com/q/48269152
has answer: http://stackoverflow.com/a/48269436
score: 0
answer count: 2
tagged with: arrays
tagged with: bigdata
type: UnansweredQuestion
type: Question
has body: Let's say I have '3 deep' list of lists len(list) --&gt; 500 len(list[0]) --&gt; 25 len(list[0][0]) --&gt; 100 and I wanted to convert into a numpy array with the shape of (500, 25, 100). What would be the most efficient way of going about this computationally? assuming the list is very very large.
tagged with: python
has answer: http://stackoverflow.com/a/48269210
has comment: http://stackoverflow.com/comment/83521467
has title: Easily converting List of lists to numpy Multidim array for big data
tagged with: numpy

http://stackoverflow.com/comment/104493725
comment on: http://stackoverflow.com/a/48204108
score: 2
type: AnswerComment
has text: Just to note that this is only for admin.site.urls. Everything else (such as wagtail and your own application urls) requires include(xxx) still.
type: Comment

http://stackoverflow.com/comment/83482008
comment on: http://stackoverflow.com/q/48249734
type: Comment
type: QuestionComment
has text: @WillemVanOnsem I think OP has multiple list and he want to keep only unique elements.
score: 0

http://stackoverflow.com/comment/83470802
comment on: http://stackoverflow.com/q/48243658
type: QuestionComment
type: Comment
has text: @kaloon, post the final expected result
score: 0

http://stackoverflow.com/q/48286217
linked to: http://stackoverflow.com/q/46947288
score: 12
upvote count: 12
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/71826243
has title: Simplest lambda function to copy a file from one s3 bucket to another
tagged with: amazon-web-services
tagged with: aws-lambda
favorite count: 0
has answer: http://stackoverflow.com/a/56301941
type: Question
has answer: http://stackoverflow.com/a/76779036
has comment: http://stackoverflow.com/comment/115184918
has comment: http://stackoverflow.com/comment/83559209
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/83557097
has answer: http://stackoverflow.com/a/60448910
tagged with: python
has comment: http://stackoverflow.com/comment/83557180
answer count: 6
has body: I'm a total noob to working with AWS. I am trying to get a pretty simple and basic operation to work. What I want to do is, upon a file being uploaded to one s3 bucket, I want that upload to trigger a Lambda function that will copy that file to another bucket. I went to the AWS management console, created an s3 bucket on the us-west2 server called "test-bucket-3x1" to use as my "source" bucket and another called "test-bucket-3x2" as my 'destination' bucket. I did not change or modify any settings when creating these buckets. In the Lambda console, I created an s3 trigger for the 'test-bucket-3x1', changed 'event type' to "ObjectCreatedByPut", and didn't change any other settings. This is my actual lamda_function code: import boto3 import json s3 = boto3.resource('s3') def lambda_handler(event, context): bucket = s3.Bucket('test-bucket-3x1') dest_bucket = s3.Bucket('test-bucket-3x2') print(bucket) print(dest_bucket) for obj in bucket.objects(): dest_key = obj.key print(dest_key) s3.Object(dest_bucket.name, dest_key).copy_from(CopySource = {'Bucket': obj.bucket_name, 'Key': obj.key}) When I test this function with the basic "HelloWorld" test available from the AWS Lambda Console, I receive this" { "errorMessage": "'s3.Bucket.objectsCollectionManager' object is not callable", "errorType": "TypeError", "stackTrace": [ [ "/var/task/lambda_function.py", 12, "lambda_handler", "for obj in bucket.objects():" ] ] } What changes do I need to make to my code in order to, upon uploading a file to test-bucket-3x1, a lambda function is triggered and the file is copied to test-bucket-3x2? Thanks for your time.
has answer: http://stackoverflow.com/a/74716581
has answer: http://stackoverflow.com/a/65895249

http://stackoverflow.com/a/48259109
has body: The following technique is not limited to use with filter and can be applied far more generally. Setup I'll use @cᴏʟᴅsᴘᴇᴇᴅ setup Let df be: d1 d2 abc 0 5 1 8 1 13 8 6 2 9 4 7 3 9 16 15 4 1 20 9 Inplace update Use pd.DataFrame.update update will take the argument dataframe and alter the calling dataframe where index and column values match the argument. df.update(df.filter(regex='d.*') / 3) df d1 d2 abc 0 1.666667 0.333333 8 1 4.333333 2.666667 6 2 3.000000 1.333333 7 3 3.000000 5.333333 15 4 0.333333 6.666667 9 Inline copy Use pd.DataFrame.assign I use the double splat ** to unpack the argument dataframe into a dictionary where column names are keys and the series that are the columns are the values. This matches the required signature for assign and overwrites those columns in the copy that is produced. In short, this is a copy of the calling dataframe with the columns overwritten appropriately. df.assign(**df.filter(regex='d.*').div(3)) d1 d2 abc 0 1.666667 0.333333 8 1 4.333333 2.666667 6 2 3.000000 1.333333 7 3 3.000000 5.333333 15 4 0.333333 6.666667 9
has comment: http://stackoverflow.com/comment/83529529
type: AcceptedAnswer
upvote count: 15
has comment: http://stackoverflow.com/comment/83500882
accepted answer of: http://stackoverflow.com/q/48258466
type: Answer
answers question: http://stackoverflow.com/q/48258466
score: 15
downvote count: 0
has comment: http://stackoverflow.com/comment/83500830

http://stackoverflow.com/comment/83599554
comment on: http://stackoverflow.com/q/48306865
type: Comment
type: QuestionComment
score: 0
has text: Hi. thank you guys for your awnser. Sorry for my unclear question.

http://stackoverflow.com/q/48312589
type: Question
has comment: http://stackoverflow.com/comment/83626068
has body: I need to pass a json object as input to an API which will give me back a json in return. The usual way I access an API using requests is response=requests.get('url',auth=uauth,headers=headers).json() This will give me the json output from the API. Here, I pass the parameters dynamically in the url. I just need to pass a JSON input here so that I can get a response for that particular input.
type: UnansweredQuestion
has title: Pass a json input to API using requests
tagged with: python-requests
score: 0
tagged with: http://stackoverflow.com/tag/json
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48312709

http://stackoverflow.com/q/48236790
has answer: http://stackoverflow.com/a/48236818
has body: fieldnames =['quote', 'author'] myFile = open('quotes.csv', 'a') file = ('quotes.csv') quoteNum = int(input("How many qoutes do you want to enter: ")) fileEmpty = os.stat(file).st_size == 0 with myFile: writer = csv.DictWriter(myFile, fieldnames=fieldnames) if fileEmpty: writer.writeheader() for entry in range(1,quoteNum + 1 ): authur_name = input("Enter the Authors name:") quoteValue = input("Enter the Qoute by "+authur_name + " here: " ) writer.writerow({'author': authur_name, 'quote': quoteValue})
tagged with: python
downvote count: 6
type: AnsweredQuestion
upvote count: 0
answer count: 2
has title: i don't know why this code is writing empty rows on my csv file when using a PC but not on a Mac
accepted answer: http://stackoverflow.com/a/48236818
has comment: http://stackoverflow.com/comment/83456209
score: -6
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83456497
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83456237
has answer: http://stackoverflow.com/a/48236843
possible better answer: http://stackoverflow.com/a/48236843

http://stackoverflow.com/q/48257994
tagged with: urllib
type: Question
accepted answer: http://stackoverflow.com/a/48258054
answer count: 2
tagged with: download
has body: Situation: The file to be downloaded is a large file (>100MB). It takes quite some time, especially with slow internet connection. Problem: However, I just need the file header (the first 512 bytes), which will decide if the whole file needs to be downloaded or not. Question: Is there a way to do download only the first 512 bytes of a file? Additional information: Currently the download is done using urllib.urlretrieve in Python2.7
has answer: http://stackoverflow.com/a/48258054
has title: How to Download only the first x bytes of data Python
has comment: http://stackoverflow.com/comment/83498511
has comment: http://stackoverflow.com/comment/83498636
downvote count: 0
linked to: http://stackoverflow.com/q/23602412
score: 6
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/83498702
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83498536
has answer: http://stackoverflow.com/a/48258200
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83498613
possible better answer: http://stackoverflow.com/a/48258200
favorite count: 0
tagged with: urlretrieve

http://stackoverflow.com/a/48259943
upvote count: 1
answers question: http://stackoverflow.com/q/48259396
score: 1
type: Answer
has body: Try this: np.array(list(train_x)).shape answer would be (43907, 120) if list has equal length elements inside it. otherwise, it will be: (43907,)
downvote count: 0

http://stackoverflow.com/comment/83571322
has text: @ChristianDean Done.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48293104

http://stackoverflow.com/comment/83596848
score: 0
type: AnswerComment
has text: TypeError: bad operand type for unary ~: 'Index'
comment on: http://stackoverflow.com/a/48305848
type: Comment

http://stackoverflow.com/comment/83582223
type: Comment
type: QuestionComment
has text: And `Mj_rank[Mj_rank.index.duplicated(keep=False)]` mo rows?
score: 2
comment on: http://stackoverflow.com/q/48298628

http://stackoverflow.com/a/48317271
upvote count: 1
answers question: http://stackoverflow.com/q/48317054
accepted answer of: http://stackoverflow.com/q/48317054
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: The two thresholds are swapped if the low threshold is higher. OpenCV is open source, so you can look at the source code: if (low_thresh &gt; high_thresh) std::swap(low_thresh, high_thresh);

http://stackoverflow.com/q/48246307
type: Question
has comment: http://stackoverflow.com/comment/83475292
upvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83475310
accepted answer: http://stackoverflow.com/a/48246330
has title: Python: return dont work
tagged with: factorial
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48246330
has comment: http://stackoverflow.com/comment/83475255
has comment: http://stackoverflow.com/comment/83475387
answer count: 1
has comment: http://stackoverflow.com/comment/83475412
has body: I write this code and I have a problem with return. def factorial(n): if n == 0: return 1 else: recurse = factorial(n - 1) result = n * recurse return result factorial(3) When I run it I have that output: Process finished with exit code 0 And thats it all but when i try it with print i have someting extra: code: def factorial(n): if n == 0: print ("1") else: recurse = factorial(n - 1) result = n * recurse print(result) factorial(3) Output: Traceback (most recent call last): 1 Traceback (most recent call last): File "C:/Users/Ptr/Desktop/python/Python_w/brbd/rek.py", line 16, in &lt;module&gt; factorial(3) File "C:/Users/Ptr/Desktop/python/Python_w/brbd/rek.py", line 13, in factorial recurse = factorial(n - 1) File "C:/Users/Ptr/Desktop/python/Python_w/brbd/rek.py", line 13, in factorial recurse = factorial(n - 1) File "C:/Users/Ptr/Desktop/python/Python_w/brbd/rek.py", line 14, in factorial result = n * recurse TypeError: unsupported operand type(s) for *: 'int' and 'NoneType' Process finished with exit code 1 My question is - why when I try run that with return I don't see anything and what about second code with print? Maybe my question or issues is stupid, but humans learn from their mistakes
downvote count: 1
score: -1
favorite count: 0

http://stackoverflow.com/q/48321159
score: -4
answer count: 1
has comment: http://stackoverflow.com/comment/83627485
downvote count: 4
has body: Problem with "from models import Category, Product"... def ProductList(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html', { 'category': category, 'categories': categories, 'products': products })
has title: from models import Category, Product
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48321201
upvote count: 0
has comment: http://stackoverflow.com/comment/83627499
tagged with: django
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/48284235
type: Answer
has body: if sys.argv[0] == 'build': kw = {'setup_requires': [req1, req2, …]} else: kw = {} setup( …, **kw ) Another approach to try is override build command with a custom cmdclass: from setuptools.command.build import build as _build class build(_build): def run(self): subprocess.call(["pip", "install", req1, req2…]) _build.run(self) setup( …, cmdclass={'build': build}, ) and avoid setup_requires at all.
downvote count: 0
has comment: http://stackoverflow.com/comment/83581124
upvote count: 1
answers question: http://stackoverflow.com/q/48283503
score: 1
has comment: http://stackoverflow.com/comment/83574793

http://stackoverflow.com/q/48290758
type: AnsweredQuestion
score: 3
upvote count: 3
has body: I can first obtain the DFT matrix of a given size, say n by import numpy as np n = 64 D = np.fft.fft(np.eye(n)) The FFT is of course just a quick algorithm for applying D to a vector: x = np.random.randn(n) ft1 = np.dot(D,x) print( np.abs(ft1 - fft.fft(x)).max() ) # prints near double precision roundoff The 2D FFT can be obtained by applying D to both the rows and columns of a matrix: x = np.random.randn(n,n) ft2 = np.dot(x, D.T) # Apply D to rows. ft2 = np.dot(D, ft2) # Apply D to cols. print( np.abs(ft2 - fft.fft2(x)).max() ) # near machine round off again How do I compute this analogously for the 3 dimensional Discrete Fourier Transform? I.e., x = np.random.randn(n,n,n) ft3 = # dot operations using D and x print( np.abs(ft3 - fft.fftn(x)).max() ) # prints near zero Essentially, I think I need to apply D to each column vector in the volume, then each row vector in the volume, and finally each "depth vector". But I'm not sure how to do this using dot.
tagged with: python
has answer: http://stackoverflow.com/a/48290839
has title: Apply DFT matrix along each axis of 3D array in NumPy?
favorite count: 0
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48290839
answer count: 1
downvote count: 0

http://stackoverflow.com/a/48183638
has body: I find usefull to work with the pathlib module. I create Path objects on top of my scripts (or in a dedicated file) like this: from pathlib import Path path_1 = Path(r'C:\Users\User\Documents\Python3\ml-100k\ml-100k') # absolute path path_2 = Path.cwd() # current working directory Then this is helpfull for the rest of your scripts. You can use these objects like so: user = pd.read_csv(path_2.joinpath('u.users'), sep = '|', names = ['User ID', 'Age','Gender', 'Occupation','Zip Code'])
score: 1
answers question: http://stackoverflow.com/q/48179932
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/48330016
has comment: http://stackoverflow.com/comment/83646185
favorite count: 0
has body: Long story short, I already have the things that I need to display (for a qlineedit) in a list. But there are some additional information that I need to display in the auto-complete box, that messes up the QCompleter since I use its setModel method to update what it displays (so the additional information that I put into the setModel method messes with the completion rule of the QCompleter) So I need a QCompleter-like display underneath a QLineEdit. Is there anyway I can make that happen? #The method TopProducts(text) -&gt; returns a list of strings with the format #"manufacturer - model number - description" (picks three products based on the given text) #in __init__ somewhere: self.nameEdit = QLineEdit() self.completer = QCompleter() self.nameEdit.setCompleter(self.completer) self.nameEdit.textEdited.connect(self.suggest) self.model = QStringListModel() def suggest(self,text): stringList = TopProducts(text) self.model.setStringList(stringList) self.completer.setModel(self.model)
type: Question
has comment: http://stackoverflow.com/comment/83646244
has comment: http://stackoverflow.com/comment/83648256
accepted answer: http://stackoverflow.com/a/48331185
has comment: http://stackoverflow.com/comment/83646430
tagged with: pyqt4
has answer: http://stackoverflow.com/a/48331185
tagged with: python
has comment: http://stackoverflow.com/comment/83646401
has title: Possible to have a QCompleter-like appearance without using a QCompleter?
has comment: http://stackoverflow.com/comment/83646039
has comment: http://stackoverflow.com/comment/83646511
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83646519
tagged with: pyqt
score: 1
tagged with: qcompleter
answer count: 1
has comment: http://stackoverflow.com/comment/83645882
tagged with: pyqt5
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83415209
comment on: http://stackoverflow.com/q/48216358
type: Comment
has text: this answer might help https://stackoverflow.com/a/46237943/4132383
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83507082
has text: @ChuckSchuldiner consider the function `foo(x): return 2*x`. Why would you expect a line that just contained `foo(x)` to be useful? The input parameter is not mutated and you don't use the result.
score: 0
comment on: http://stackoverflow.com/q/48262059
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83559597
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48286958
score: 0
has text: ok the issue is when I remove a site image from a record it seems, site_details_files added

http://stackoverflow.com/comment/83480413
has text: It is slower by the way. I was hoping getting the actual indexes may work faster than boolean indexing (it does in some cases) but it it not the case here.
type: Comment
comment on: http://stackoverflow.com/a/48248854
type: AnswerComment
score: 0

http://stackoverflow.com/q/48280759
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83546742
has comment: http://stackoverflow.com/comment/83546268
has comment: http://stackoverflow.com/comment/83546113
tagged with: python
has body: I made a script for reading a grammar book of Georgian verbs in English. It visualizes correctly the Georgian and English characters from the text on the screen however when it stores the information in a list, the Georgian characters assume a different representation. See an example below. Note tha t I am using Python release 2.7. Print on computer screen and corresponding to the exact content in the text 10.1. Conjugation of transitive verbs 10.1.1. წერს – he/she writes I სერია Stored on a list [['10.1.', 'Conjugation', 'of', 'transitive', 'verbs'], [], ['10.1.1.', '\xe1\x83\xac\xe1\x83\x94\xe1\x83\xa0\xe1\x83\xa1', '\xe2\x80\x93', 'he/she', 'writes'], [], ['I', '\xe1\x83\xa1\xe1\x83\x94\xe1\x83\xa0\xe1\x83\x98\xe1\x83\x90'], [], []] The Georgian characters are now represents by strings containing characters like '\xe1\xac'. Please can you help me to handle Georgian alphabet? Thanks.
has comment: http://stackoverflow.com/comment/83544991
has comment: http://stackoverflow.com/comment/83546222
has comment: http://stackoverflow.com/comment/83546459
has title: Reading a text written in different language scripts (Western, Georgian)
tagged with: text
score: 0
has comment: http://stackoverflow.com/comment/83546626
has comment: http://stackoverflow.com/comment/83546080
has comment: http://stackoverflow.com/comment/83546333
has comment: http://stackoverflow.com/comment/83546657
tagged with: character

http://stackoverflow.com/comment/83638898
type: AnswerComment
score: 0
type: Comment
has text: Thanks a lot, that's exactly what I wanted!
comment on: http://stackoverflow.com/a/48324979

http://stackoverflow.com/q/48222566
tagged with: python
favorite count: 0
type: Question
has title: How can I impute the NA in a dataframe with values randomly selected from a specified normal distribution
accepted answer: http://stackoverflow.com/a/48222938
upvote count: 2
has answer: http://stackoverflow.com/a/48222938
downvote count: 0
tagged with: imputation
has body: How can I impute the NA in a dataframe with values randomly selected from a specified normal distribution. The dataframe df is defined as follows: A B C D 1 3 NA 4 NA 2 3.4 2.3 4.1 NA 3 2.3 0.1 0.2 6.3 4 3.1 4.5 2.1 0.2 5 4.1 2.5 NA 2.4 I want to fill the NA with the values randomly select from a generated normal distribution and the values are different. The mean the normal distribution is the 1% quantile of the values of the given dataframe. The standard deviation is the median SD of the rows in dataframe. My code is as follows: import pandas as pd import numpy as np df = pd.read_csv('try.txt',sep="\t") df.index = df['type'] del df['type'] sigma = median(df.std(axis=1)) mu = df.quantile(0.01) # mean and standard deviation df = df.fillna(np.random.normal(mu, sigma, 1)) The mean is incorrect and the df can not fill with the simulated array. How can I complete the work. Thank you.
type: AnsweredQuestion
score: 2
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/83546405
type: QuestionComment
comment on: http://stackoverflow.com/q/48280629
has text: (in the graph that I posted, the paths never intersect, but touch the surface tangentially. anyway, the problem persists even when I lift the surface by ZZ=YY**2+10
score: 0
type: Comment

http://stackoverflow.com/q/48251704
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83486999
tagged with: nlp
has comment: http://stackoverflow.com/comment/83487678
has body: I'm trying to create an algorithm that could transform sentences to questions. This is the code: def sentence_to_question(arg): hverbs = ["is", "have", "had", "was", "could", "would", "will", "do", "did", "should", "shall", "can", "are"] words = arg.split(" ") zen_sim = (0, "", "") for hverb in hverbs: for word in words: similarity = SequenceMatcher(None, word, hverb).ratio()*100 if similarity > zen_sim[0]: zen_sim = (similarity, hverb, word) if zen_sim[0] < 30: raise ValueError("unable to create question.") else: words.remove(zen_sim[2]) words = " ".join(words)[0].lower() + " ".join(words)[1:] question = "{0} {1}?".format(zen_sim[1].capitalize(), words) return question Explanation: there is a prepared list of helping verbs, each word of the sentence is compared to the helping verb. The word that has highest similarity helping verb, will be chosen. difflib.SequenceMatcher's Ratcliff/Obershep pattern recognition algorithm is used to compare similarity of two strings. Although if the similarity percentage is less than 30%, I believe that there exists very low probability that user can misspell the helping verb by this much, and high probability that helping verb is not existent in the question, thus the question is not recognized. Finally, chosen helping verb is placed in the beginning of string. (I know the "algorithm" requires much more optimization). Testing on examples: >>> sentence_to_question("Euclid was a prominent mathematician") 'Was euclid a prominent mathematician?' >>> sentence_to_question("Euclid waz a prominent mathematician") # does work with small typos 'Was euclid a prominent mathematician?' >>> sentence_to_question("The company name, logo and slogan are vital elements of the house style of a company and important elements of corporate design") 'Are the company name, logo and slogan vital elements of the house style of a company and important elements of corporate design?' Now as we know, multiple questions can be generated from a single sentence, but…
has comment: http://stackoverflow.com/comment/83485883
has title: Creating questions from sentences
tagged with: pattern-recognition
has comment: http://stackoverflow.com/comment/83487439
downvote count: 0
has comment: http://stackoverflow.com/comment/83485945
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83487621
type: Question
tagged with: algorithm
answer count: 0
tagged with: python

http://stackoverflow.com/comment/83413503
score: 0
type: Comment
has text: No noticeable performance difference. However, this is still useful for folk on spark <1.6 because of union all. See here: https://stackoverflow.com/questions/38650568/spark-1-5-2-org-apache-spark-sql-analysisexception-unresolved-operator-union
type: AnswerComment
comment on: http://stackoverflow.com/a/48196865

http://stackoverflow.com/comment/83559728
has text: Regardless, this line: `prediction = dict.fromkeys(files.keys(),[])` is completely useless, since you overwrite those keys immediately afterwards in the for-loop, never once using the `list` you put in them originally...
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48287289

http://stackoverflow.com/q/48225786
answer count: 2
score: 1
has comment: http://stackoverflow.com/comment/83434281
has answer: http://stackoverflow.com/a/48289248
has body: This is my view: class FilteredReclamationListView(FilterView, SingleTableView): table_class = ReclamationTable model = ReclamationMainModel template_name = 'reclamation_table/index.html' filterset_class = ReclamationFilter table_pagination = { 'per_page': 50 } def get_table_data(self): return self.object_list def get_queryset(self): return self.model.objects.filter(archive=False).order_by('-id') Is it possible to remember the URL parameter in this case? How? I would like to have a situation that the user goes to another view and when he is back he will see his last query/filter. I read about sessions and request.GET.urlencode(), but I can't apply that in my view.
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83434450
tagged with: django-tables2
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48226428
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/83433263
tagged with: python
tagged with: django-filter
has title: Remember URL parameters in django-tables2 with django-filter

http://stackoverflow.com/a/48327835
has body: I think you are confusing sample_weights and class_weights. Checking the docs a bit we can see the differences between them: sample_weights is used to provide a weight for each training sample. That means that you should pass a 1D array with the same number of elements as your training samples (indicating the weight for each of those samples). In case you are using temporal data you may instead pass a 2D array, enabling you to give weight to each timestep of each sample. class_weights is used to provide a weight or bias for each output class. This means you should pass a weight for each class that you are trying to classify. Furthermore, this parameter expects a dictionary to be passed to it (not an array, that is why you got that error). For example consider this situation: class_weight = {0 : 1. , 1: 50.} In this case (a binary classification problem) you are giving 50 times as much weight (or "relevance") to your samples of class 1 compared to class 0. This way you can compensate for imbalanced datasets. Here is another useful post explaining more about this and other options to consider when dealing with imbalanced datasets. If I train for more epochs, val_loss keeps dropping, but I get worse results. Probably you are over-fitting, and something that may be contributing to that is the imbalanced classes your dataset has, as you correctly suspected. Compensating the class weights should help mitigate this, however there may still be other factors that can cause over-fitting that escape the scope of this question/answer (so make sure to watch out for those after solving this question). Judging by your post, seems to me that what you need is to use class_weight to balance your dataset for training, for which you will need to pass a dictionary indicating the weight ratios between your 7 classes. Consider using sample_weight only if you want to give each sample a custom weight for consideration. If you want a more detailed comparison between those two consider checki…
has comment: http://stackoverflow.com/comment/107739334
has comment: http://stackoverflow.com/comment/107738751
has comment: http://stackoverflow.com/comment/91480873
has comment: http://stackoverflow.com/comment/91510913
upvote count: 27
answers question: http://stackoverflow.com/q/48315094
has comment: http://stackoverflow.com/comment/107739041
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/107738608
has comment: http://stackoverflow.com/comment/91511033
has comment: http://stackoverflow.com/comment/83648986
score: 27
has comment: http://stackoverflow.com/comment/107738284
has comment: http://stackoverflow.com/comment/91480926
has comment: http://stackoverflow.com/comment/107739182

http://stackoverflow.com/a/48255723
has body: why not just use choice? import random names = ['Sam', 'Paul', 'Mark', 'Simon', 'Sean', 'Samantha', 'Ellen'] random_name = random.choice(names) print(random_name)
type: Answer
upvote count: 3
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/48255710

http://stackoverflow.com/a/48286958
accepted answer of: http://stackoverflow.com/q/48286606
type: Answer
has body: You need to pass request.FILES to the form when uploading files. form = FileForm(request.POST, request.FILES, instance=item_data) Make sure that you set enctype="multipart/form-data" in the template as well. See the docs on file uploads for more info. However, these changes won't solve your error, since it is coming from a different view site_detail_files. It looks as if you are using file.site_image.url in the template without checking file.site_image first. You should add an extra if block: {% for file in photos %} ... {% if file.site_image %} ... &lt;a class="image-float-left" id="" href="{% signed_url file.site_image.url %}" target="_blank"&gt; ... {% endif %} {% endfor %}
answers question: http://stackoverflow.com/q/48286606
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83559597

http://stackoverflow.com/q/48191060
accepted answer: http://stackoverflow.com/a/48191338
type: Question
tagged with: indexing
tagged with: python
has comment: http://stackoverflow.com/comment/83362652
has answer: http://stackoverflow.com/a/48191558
possible better answer: http://stackoverflow.com/a/48191558
has answer: http://stackoverflow.com/a/48191338
has title: NumPy Fancy Indexing - Crop different ROIs from different channels
upvote count: 4
tagged with: numpy
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/83362511
has body: Let assume, we have following numpy 4D array (3x1x4x4): import numpy as np n, c, h, w = 3, 1, 4, 4 data = np.arange(n * c * h * w).reshape(n, c, h, w) &gt;&gt;&gt; array([[[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]], [[[16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31]]], [[[32, 33, 34, 35], [36, 37, 38, 39], [40, 41, 42, 43], [44, 45, 46, 47]]]]) Now I want to crop each of the n subarray on a different location with a same size: size = 2 locations = np.array([ [0, 1], [1, 1], [0, 2] ]) The slow way to do this is the following: crops = np.stack([d[:, y:y+size, x:x+size] for d, (y,x) in zip(data, locations)]) &gt;&gt;&gt; array([[[[ 1, 2], [ 5, 6]]], [[[21, 22], [25, 26]]], [[[34, 35], [38, 39]]]]) Now im looking for a way to achieve this with the numpy's fancy indexing. I have already spent hours to figure out, how to solve this problem. Am I overlooking a simple way to solve this? Are there some numpy indexing experts out there, who can help me?
linked to: http://stackoverflow.com/q/47411872
tagged with: arrays
downvote count: 0
score: 4
favorite count: 0

http://stackoverflow.com/q/48243829
has comment: http://stackoverflow.com/comment/83470665
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83470522
has comment: http://stackoverflow.com/comment/83470452
has body: I have imported a class module and inside that class module I have another class module but when I try to access that I get the error as AttributeError: 'class_name1' object has no attribute 'function_name2_1' Example code for detail: main.py from FOLDER import File_name1 as a b = a.class_name1('aa') EDITED, The full code is like this File_name1.py class class_name1: def __init__(self, name) self.varname = name if (name == 'aa') from FOLDER.File_name2 import class_name2 print('a') if (name == 'bb') from FOLDER.File_name3 import class_name3 File_name2.py class class_name2: def __init__(self, name) self.varname = name def function_name2_1(self): print('Something') When I run main.py program I get output a as expected. But if I add the line b.function_name2_1() ie. main.py from FOLDER import File_name1 as a b = a.class_name1('aa') b.function_name2_1() I get the above error. File "C:/Users/Karthik/Desktop/PROGRAMMING/Testing/main.py", line 3, in b.function_name2_1() AttributeError: 'class_name1' object has no attribute 'function_name2_1' I don't know how to resolve this. Could anyone please help me?
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/83470204
has comment: http://stackoverflow.com/comment/83470893
has comment: http://stackoverflow.com/comment/83470229
has title: In python, how to access a function of an imported class inside an imported class as it gives attribute error?
type: Question

http://stackoverflow.com/q/48275591
has answer: http://stackoverflow.com/a/48417569
has answer: http://stackoverflow.com/a/76099282
type: Question
type: UnansweredQuestion
has title: Dlib library - How to change parameters of correlation tracker on Python
tagged with: python
tagged with: c++
tagged with: dlib
score: 0
answer count: 2
has body: I am using Dlib library (originally written using C++), correlation tracker to track multiple vehicles on Python and it is working fine. Then I wanted to increase the accuracy of the system and there was an article saying this can be done by changing the parameter "filter_size" of the correlation tracker. So my question is how can I change the "filter_size" parameter which is defined on C++ code from the Python code? Thank you very much.

http://stackoverflow.com/a/48256425
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48253554
has body: If we need to use . way then str() is equivalent to __str__() &gt;&gt;&gt; "In year " + today.year.__str__() + " I should learn more Python" # 'In year 2018 I should learn more Python'
downvote count: 0

http://stackoverflow.com/comment/83591824
type: QuestionComment
has text: Have you tried what the answer in that question suggests? The title of that question makes it seem like it's a Pycharm error when it is not
score: 1
comment on: http://stackoverflow.com/q/48302622
type: Comment

http://stackoverflow.com/comment/83516574
has text: @hspandher, I don't think OP is trying to parse arguments, they're trying to pass arguments to a different process.
comment on: http://stackoverflow.com/q/48266705
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48215220
tagged with: tornado
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48215282
accepted answer: http://stackoverflow.com/a/48215282
downvote count: 0
upvote count: 1
answer count: 1
favorite count: 0
tagged with: decorator
has title: Python, Tornado: gen.coroutine decorator breaks try-catch in another decorator
has body: I have a class with plenty static methods with Tornado coroutine decorator. And I want to add another decorator, to catch exceptions and write them to a file: # my decorator def lifesaver(func): def silenceit(*args, **kwargs): try: return func(*args, **kwargs) except Exception as ex: # collect info and format it res = ' ... ' # writelog(res) print(res) return None return silenceit However, it doesn't work with gen.coroutine decorator: class SomeClass: # This doesn't work! # I tried to pass decorators in different orders, # but got no result. @staticmethod @lifesaver @gen.coroutine @lifesaver def dosomething1(): raise Exception("Test error!") # My decorator works well # if it is used without gen.coroutine. @staticmethod @gen.coroutine def dosomething2(): SomeClass.dosomething3() @staticmethod @lifesaver def dosomething3(): raise Exception("Test error!") I understand, that Tornado uses raise Return(...) approach which is probably based on Exceptions, and maybe it somehow blocks try-catches of other decorators... So, how can I used my decorator to handle Exceptions with Tornado coroutines? The answer Thanks to Martijn Pieters, I got this code working: def lifesaver(func): def silenceit(*args, **kwargs): try: return func(*args, **kwargs) except (gen.Return, StopIteration): raise except Exception as ex: # collect info and format it res = ' ... ' # writelog(res) print(res) raise gen.Return(b"") return silenceit So, I only needed to specify Tornado Return. I tried to add @gen.coroutine decorator to silenceit function and use yield in it, but this leads to Future objects of Future objects and some other strange unpredictable behaviour.
type: Question
tagged with: exception
score: 1
tagged with: python

http://stackoverflow.com/comment/83338739
has text: Thanks for your kind reply. The result is the same as I had in my question.
type: AnswerComment
comment on: http://stackoverflow.com/a/48179113
score: 0
type: Comment

http://stackoverflow.com/comment/83396664
score: 0
comment on: http://stackoverflow.com/q/48206553
type: Comment
has text: url(r'^orders/create/', views.create_order, name='create_order'), the create_order function lives in core, i'm importing it in administrator views
type: QuestionComment

http://stackoverflow.com/q/48255710
possible better answer: http://stackoverflow.com/a/48255723
score: 3
accepted answer: http://stackoverflow.com/a/48255716
tagged with: random
has comment: http://stackoverflow.com/comment/83494360
has answer: http://stackoverflow.com/a/48255716
has comment: http://stackoverflow.com/comment/83494234
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/48255723
upvote count: 3
has title: Select a random element from an array
downvote count: 0
tagged with: python
has body: I am trying to select a random element from my array. However, sometimes I am getting an index out of bounds error, even though I accounted for the array starting at 0 by adding 1 to the maximum value of the index. from random import randint names = ['Sam', 'Paul', 'Mark', 'Simon', 'Sean', 'Samantha', 'Ellen'] random_name = names[randint(0, len(array)+1)] print(random_name) I only get an index out of bounds error sometimes?
type: AnsweredQuestion

http://stackoverflow.com/comment/83440516
type: AnswerComment
has text: If you can't convert the string to a float, then `get()` is clearly not returning a number, (that's why I put in the bit about error-checking.) You need to figure out why.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48229096

http://stackoverflow.com/comment/83372513
type: QuestionComment
score: 2
has text: Happy Coding. SO is about fixing _your_ Code - not implementing your ideas. Please go over [how to ask](https://stackoverflow.com/help/how-to-ask) and [on-topic](https://stackoverflow.com/help/on-topic) again and if you have questions provide your code as [mvce](https://stackoverflow.com/help/mcve) For questions about panda, start with providing your dataframe including testdata _and_ show your expected & gotten results. Try to solve it yourself first.
comment on: http://stackoverflow.com/q/48195758
type: Comment

http://stackoverflow.com/comment/83489032
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48253266
type: AnswerComment
has text: it should be `a+` if you want to append new lines , `w+` **Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.** For further reading https://stackoverflow.com/a/23566951/8150371

http://stackoverflow.com/comment/83353582
has text: Thank yu for this hint: this solved ineed the problem of response being 404. Now i get a correct response 200. I still can not login though. The response is the same page as the login page.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48186576

http://stackoverflow.com/comment/83561868
has text: Remove `splitlines`?
score: 0
comment on: http://stackoverflow.com/q/48288374
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83488397
score: 2
type: Comment
comment on: http://stackoverflow.com/q/48252891
has text: `argparse.py` in your SAT directory seems to be interfering with the actual argparse module.
type: QuestionComment

http://stackoverflow.com/q/48300985
tagged with: neural-network
tagged with: tensorflow
tagged with: tensorflow-datasets
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48301540
score: 3
has body: I am new to TensorFlow. I looked for examples on implementation of multi layer perceptron using tensorflow, but i am getting examples only on MNIST image data sets, apart from MNIST can i able to build the Neural Network model using same optimization and cost functions and train the data which is in number format,Means, Can I train my own number dataset using tensorflow. Is there any example for training the new dataset?.
has answer: http://stackoverflow.com/a/48301540
tagged with: perceptron
has title: TensorFlow: Implementing Single layer perceptron / Multi layer perceptron using own data set
tagged with: python
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/48317655
upvote count: 3
has answer: http://stackoverflow.com/a/48317655
downvote count: 0

http://stackoverflow.com/comment/83629508
score: 0
comment on: http://stackoverflow.com/q/48322071
has text: Have you at least tried to research about how to list files in a directory?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48265397
has answer: http://stackoverflow.com/a/48276290
accepted answer: http://stackoverflow.com/a/48276290
answer count: 1
has comment: http://stackoverflow.com/comment/83514785
score: 4
has comment: http://stackoverflow.com/comment/83514383
favorite count: 0
type: Question
type: AnsweredQuestion
upvote count: 5
has comment: http://stackoverflow.com/comment/83514368
has comment: http://stackoverflow.com/comment/83514356
has title: multiple filters on a single aggregation in elasticsearch
downvote count: 1
tagged with: elasticsearch
has comment: http://stackoverflow.com/comment/83514675
tagged with: python
has comment: http://stackoverflow.com/comment/83516566
tagged with: elasticsearch-aggregation
has body: I am using elasticsearch on python client. I would like to filter on multiples field on the same aggregation bucket. First, let's inject some data curl -XPUT 'localhost:9200/data/document/1' -d '{ "facet1": ["a1","b1"], "facet2":["b2"],"facet3":["a3", "c3"] }' curl -XPUT 'localhost:9200/data/document/2' -d '{ "facet1": ["a1","c1"], "facet2":["b2", "c2"],"facet3":["a3", "c3"] }' curl -XPUT 'localhost:9200/data/document/3' -d '{ "facet1": ["a1"], "facet2":["b2"],"facet3":["c3"] }' Then let's query it ! {'_source': ['facet1', 'facet2', 'facet3'], 'aggregations': {'all_products': {'aggregations': {'facet1_aggregation': {'aggregations': {'filtered_facet1': {'terms': {'field': 'facet1'}}}, 'filter': [{'terms': {'facet2': ['a2 ' 'b2']}}, {'terms': {'facet3': ['a3', 'b3' 'c3']}}]}}, 'facet2_aggregation': {'aggregations': {'filtered_facet2': {'terms': {'field': 'facet2'}}}, 'filter': [{'terms': {'facet1': ['a1' 'b1']}}, {'terms': {'facet3': ['a3', 'b3' 'c3']}}]}, 'global': {}}}, 'query': {'bool': {'filter': [{'terms': {'facet1': ['a1']}}, {'terms': {'facet2': ['a2', 'b2']}}]}, 'must': {'match_all': {}}}, 'size': 10000} When I run this query, I get a parse error TransportError(400, 'parsing_exception', 'Expected [START_OBJECT] under [filter], but got a [START_ARRAY] in [facet1_aggregation]')

http://stackoverflow.com/comment/83512681
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48264580
has text: @mata well, you are right, this is not what I want. If I change it to ^(@[a-zA-Z0-9.]+\b) then it catches just first line. Any idea how to catch it anywhere?
type: Comment

http://stackoverflow.com/a/64367023
type: Answer
answers question: http://stackoverflow.com/q/48193316
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/116759583
has body: For Python requests module, this is bad: requests.post(url, data=nested_dict) Good: requests.post(url, json=nested_dict) Note: nested_dict does not need to be stringified. Just pass it in as dictionary.

firebase
tags question: http://stackoverflow.com/q/48302669
tags question: http://stackoverflow.com/q/48181580
tags question: http://stackoverflow.com/q/48291682
tags question: http://stackoverflow.com/q/48241016
tags question: http://stackoverflow.com/q/48264536
type: Tag
tag name: firebase
tags question: http://stackoverflow.com/q/48272023

http://stackoverflow.com/comment/83621950
comment on: http://stackoverflow.com/q/48318101
score: 1
has text: wouldn't this line `con = get_object_or_404(Course, slug=slug)` only retrieve one object? Have you tried something like `Course.objects.filter(slug=slug).all()`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83639925
comment on: http://stackoverflow.com/q/48327085
type: Comment
has text: Does [`numpy.matmul(A,B)`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.matmul.htm) succeed? Or `eye(3) @ eye(3)`? I don't know the answer off-hand, but either of those might help narrow it down. Also, what version of `numpy`? You need [at least v1.10](https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.ndarray.html) (search for `@`)
type: QuestionComment
score: 2

http://stackoverflow.com/q/48291036
has comment: http://stackoverflow.com/comment/83567195
tagged with: python
has comment: http://stackoverflow.com/comment/83567438
has comment: http://stackoverflow.com/comment/83568322
has comment: http://stackoverflow.com/comment/83567566
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83567607
has comment: http://stackoverflow.com/comment/83567978
has comment: http://stackoverflow.com/comment/83567812
answer count: 1
has comment: http://stackoverflow.com/comment/83568681
has comment: http://stackoverflow.com/comment/83568299
has title: Quickly compute the convolution product of two Probability Density Functions
has comment: http://stackoverflow.com/comment/83567500
has comment: http://stackoverflow.com/comment/83567601
has comment: http://stackoverflow.com/comment/83576204
tagged with: scipy
has body: Suppose I have the probability density function on some sufficiently large range with small enough inter-spacing. I now would like to compute the convolution product of these two probability density functions as efficient as possible, at the moment I have the following function: def convolve_PDF(PDF1, PDF2, delta): conv_PDF = np.empty(len(PDF1)) for n in range(len(conv_PDF)): conv_PDF[n] = np.trapz(PDF1[0:(n+1)] * PDF2[n::-1], dx = delta) return conv_PDF delta = 0.001 s_range = np.arange(0,100,delta) PDF1 = scipy.stats.expon(scale = 100).cdf(s_range) PDF2 = scipy.stats.gamma(a = 1).cdf(s_range) PDF_convol = convolve_PDF(PDF1, PDF2, delta) here delta is the interspacing. As you can probably tell, this code is very slow and I was wondering how I can speed this up?
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83567771
has comment: http://stackoverflow.com/comment/83567326
accepted answer: http://stackoverflow.com/a/48296565
tagged with: convolution
has answer: http://stackoverflow.com/a/48296565

http://stackoverflow.com/q/48298807
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Comparing 2 CSV files using python with different rows
tagged with: python-2.7
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83584275
has comment: http://stackoverflow.com/comment/83582400
answer count: 1
tagged with: file
has answer: http://stackoverflow.com/a/48300201
favorite count: 0
has body: I have two csv file say one.csv and two.csv. Format of file is One.csv: ID1 , att 1 , att 2 for two.csv ID2, att2, att1 Now i want to print ID1 ,ID 2 ,att1, att2 wherever att1 and att2 are same. I've written this code but it prints only one such case But there are a lot more cases like this import csv path1 ="/home/vishver/Desktop/" file1 =open(path1 +"one.csv","r") file2 =open(path1 +"two.csv","r") reader1 =csv.reader(file1) reader2 =csv.reader(file2) count =0 for line1 in reader1: for line2 in reader2: if line1[1] == line2[2] or line1[2] == line2[1]: t=line2[0],line1[0],line1[1],line1[2] print(t) count+=1 print count
type: Question
has comment: http://stackoverflow.com/comment/83582552
has comment: http://stackoverflow.com/comment/83582744
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83583722

http://stackoverflow.com/q/48241548
score: 3
tagged with: http://stackoverflow.com/tag/html
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48241557
has title: Django Error - TemplateSyntaxError at / Could not parse the remainder: '['userType']' from '['userType']'
upvote count: 4
favorite count: 0
type: Question
has body: {% if 'is_logged_in' in request.session %} {% if request.session['userType'] == 0 %} {% include 'headersuccess.html' %} {% else %}dfgh {% endif %} This is my code. I am checking two conditions But I am getting the above error . Can anybody please help me to solve the same? My views.py is @csrf_exempt def index(request): if('is_logged_in' in request.session): id = request.session['authToken']; return render(request,"index.html",{'uid':id}); else: return render(request,"index.html",{}); views.py(server) This is my server code and in request.session userType is present @csrf_exempt def login_user(request): user = None try: #user = models.user.objects.get(Q(user_name=request.POST['key'])|Q(contact__email=request.POST['key']))#|Q(contact__phone=request.POST['key'])) user = models.user.objects.get(Q(user_name=request.POST['key'])|Q(email=request.POST['key']))#|Q(contact__phone=request.POST['key'])) pswd = pass_enc(request.POST['password'],user.token) if user.password == pswd: #create signed auth token data = { 'uid' : user.uid, 'userType' : user.userType, 'is_agent' : user.is_agent, 'is_new' : user.is_new, 'is_admin' : user.userType == 8, 'created_at':time.time() } signedToken = create_crypt_header(data) session = None try: session = models.session.objects.get(user=user) session.activeSession += 1 session.save() except Exception as e: session = models.session( user=user, activeSession=1 ) session.save() #handel weblogin ajax_token = create_crypt_header({'val':1,'at':time.time()}) request.session['authToken'] = signedToken request.session['v'] = 1 request.session['ajax_token'] = ajax_token request.session['is_logged_in'] = True return JsonResponse({'authentication' : True,'authToken':signedToken,"userType":user.userType,'session_mask':session.sessionId,'is_new':user.is_new}) else: return JsonResponse({'authentication' : False}) except Exception as e: return JsonResponse({'authentication': False}) This is my code. I am checking two conditions But I am getting the above erro…
type: UnansweredQuestion
answer count: 1
tagged with: django

http://stackoverflow.com/a/48328448
type: AcceptedAnswer
has body: Try this. It will get you there: from bs4 import BeautifulSoup import requests req = requests.get("https://education.maharashtra.gov.in/saral/27230500360") soup = BeautifulSoup(req.text,"lxml") for item in soup.select("#logo"): data = ' '.join(item.text.split()) item_dict = {data.split(" ")[-1]:' '.join(data.split(" ")[:-1])} print(item_dict) Output: {'(27230500360)': 'BHARATI VIDYAMANDIR HINDI NIGHT HIGH SCHOOL AND JR COLLEGE'}
type: Answer
accepted answer of: http://stackoverflow.com/q/48325562
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48325562

http://stackoverflow.com/comment/86598207
comment on: http://stackoverflow.com/a/49781577
has text: Why not put the code for the ProcessPoolExecutor in the doctest string so it runs it as a test? Or is there some other use case?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48234742
has comment: http://stackoverflow.com/comment/83452083
type: Answer
has comment: http://stackoverflow.com/comment/83452399
answers question: http://stackoverflow.com/q/48234609
downvote count: 0
upvote count: 1
has body: I would quit using the global vars, you tend to hide them by declaring the same named vars locally, presuming you set a global but its just the local one. I have retructured some of your code so it should work without global variables: import random def word_gen(): """Returns a ramdom choice word form a fixed list""" return random.choice(["hello", "test", "never"]) def guesser(): """Returns an input from the user - ask for 1 letter""" return input("give a letter...") def guess_compare(): """Main game loop for "guess my word character by character". Gets a random word. Asks for letters until the correct one is given. Prints out status messages regarding correctness of guesses. Stops when all characters were guessed correctly.""" game_word = word_gen() soFar = "" # for status-message, text correctly guessed so far for ch in game_word: # check for every character in word while(guesser() != ch): # guess until char is correct print("wrong") else: # finally, one more ch solved... soFar += ch print("you guessed correctly: " + soFar) print("you solved it!") # finished guess_compare() # start the game Using no globals might seem tougher, but it eleminates one source of error. If you still want them, you need to declare that you want to use the global in your funcion: Some funcs with global variables: def myFunc(): global myVar # declare that we use the global here myVar += 20 # modifying the global one here print (myVar) def myOtherFunc(): myVar = "something" # this is just local , not the global one print (myVar) myVar = 25 print ("myVar: ", myVar) myFunc() print ("after myFunc: ", myVar) myOtherFunc() print ("after myOtherFunc: ", myVar) Output: myVar: 25 45 after myFunc: 45 something after myOtherFunc: 45
score: 1

deconvolution
type: Tag
tag name: deconvolution
tags question: http://stackoverflow.com/q/48230031

http://stackoverflow.com/comment/83460881
score: 0
comment on: http://stackoverflow.com/a/48219223
type: Comment
has text: Yes, i did use a context processor function getting the data in the db, now i can use it around thr diferents area of the web site! That was the solution! Thanks a lot for guiding me to the knowledge!!! Cheers!
type: AnswerComment

http://stackoverflow.com/comment/83522963
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48269694
has text: Typo on line 10: the string should be hard level solved.
type: Comment

http://stackoverflow.com/comment/83650332
comment on: http://stackoverflow.com/q/48329092
has text: :/ I have vtk 8.0 but cant seem to load in vtkDICOMReader, I will look further into it
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48310814
has comment: http://stackoverflow.com/comment/83607408
tagged with: pandas-groupby
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/83607396
answer count: 1
downvote count: 0
upvote count: 1
has title: Create new column in pandas dataframe that merges specific column names and corresponding values
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48310855
has answer: http://stackoverflow.com/a/48310855
tagged with: python
has body: I have a dataframe that looks like the following: Colm1 ColmX Colm2 0 1 2 3 1 4 5 6 I need a new one as follows: Colm1 ColmX Colm2 Colm3 0 1 2 3 Colm1_1_Colm2_3 1 4 5 6 Colm1_4_Colm2_6 The merged value in Colm3 is constructed as an underscore separated list of pair of a specific list of columns, in this case, [Colm1, Colm2] How do I go about doing this? I have a list of column names that I need to merge as above, to start off with. Thank you!
type: AnsweredQuestion

http://stackoverflow.com/comment/103929912
type: Comment
comment on: http://stackoverflow.com/a/54356223
score: 2
type: AnswerComment
has text: This looks like it could have run time performance impacts since sorting seems to be left to the server and the not the database.

http://stackoverflow.com/comment/83568731
type: QuestionComment
has text: @Olivier not necessarily, per "Both lists have different size"
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48291699

http://stackoverflow.com/comment/83499658
type: Comment
comment on: http://stackoverflow.com/q/48257280
type: QuestionComment
has text: the point is to not use _iter_ and build everything from scratch.
score: 0

http://stackoverflow.com/q/48300979
has answer: http://stackoverflow.com/a/48326247
has comment: http://stackoverflow.com/comment/83594636
has title: Optimize a non linear function in python
tagged with: python
has body: I have a function in python which looks like this: import numpy as np def fun(Gp,Ra,Mr,Pot,Sp,Mc,Keep): if(Keep==True): return(Pot*np.tanh((Gp+Ra+Mr+ Mc)*Sp )) Assuming the following data: import pandas as pd dt_org = pd.DataFrame({"RA": [0.5, 0.8, 0.9], "MR": [0.97, 0.95, 0.99], "POT": [0.25, 0.12, 0.05], "SP": [0.25, 0.12, 0.15], "MC": [50, 75, 100], "COUNTRY": ["GB", "IR", "GR"] }) I have in total 100 GP and i want to allocate all of them properly in order to maximize the objective_function: under the restriction that all the 3 elements are positive According to this post the scipy.optimize would be the way to go, but i am confused in order how to write the problem down Update: my try from scipy.optimize import minimize y = {'A': {'RA': 0.5, 'MR': 0.97, 'POT': 0.25, 'SP': 0.25, 'MC': MC_1, 'keep': True}, 'B': {'RA': 0.8, 'MR': 0.95, 'POT': 0.12, 'SP': 0.12, 'MC': MC_2, 'keep': True}, 'C': {'RA': 0.9, 'MR': 0.99, 'POT': 0.05, 'SP': 0.15, 'MC': MC_3, 'keep': True}} def objective_function(x): return( -(fun(x[0], Ra=y['A']['RA'], Mr=y['A']['MR'], Pot=y['A']['POT'], Sp=y['A']['SP'], Mc=y['A']['MC'], Keep=y['A']['keep']) + fun(x[1], Ra=y['B']['RA'], Mr=y['B']['MR'], Pot=y['B']['POT'], Sp=y['B']['SP'], Mc=y['B']['MC'], Keep=y['B']['keep']) + fun(x[2], Ra=y['C']['RA'], Mr=y['C']['MR'], Pot=y['C']['POT'], Sp=y['C']['SP'], Mc=y['C']['MC'], Keep=y['C']['keep'])) ) cons = ({'type': 'ineq', 'fun': lambda x: x[0] + x[1] + x[2] - 100}) bnds = ((0, None), (0, None), (0, None)) minimize(objective_function, x0=[1,1,1], args=y, method='SLSQP', bounds=bnds, constraints=cons) The problem now is that i get the error ValueError: Objective function must return a scalar, whereas the output of the fun function is a scalar UPDATE 2 (after @Cleb comment) So now i changed the function in: def objective_function(x,y): temp = -(fun(x[0], Ra=y['A']['RA'], Mr=y['A']['MR'], Pot=y['A']['POT'], Sp=y['A']['SP'], Mc=y['A']['MC'], Keep=y['A']['keep']) + fun(x[1], Ra=y['B']['RA'], Mr=y['B']['MR'], Pot=…
has comment: http://stackoverflow.com/comment/83634743
tagged with: optimization
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/83590479
has comment: http://stackoverflow.com/comment/83636710
tagged with: numpy
linked to: http://stackoverflow.com/q/43309877
has comment: http://stackoverflow.com/comment/83636568
has comment: http://stackoverflow.com/comment/83634299
answer count: 1
has comment: http://stackoverflow.com/comment/83637109
has comment: http://stackoverflow.com/comment/83602139
has comment: http://stackoverflow.com/comment/83638062
downvote count: 1
tagged with: scipy
favorite count: 0
has comment: http://stackoverflow.com/comment/83633835
tagged with: python-3.x
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/48326247
has comment: http://stackoverflow.com/comment/83595076

http://stackoverflow.com/comment/83495050
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48256088
type: Comment
has text: Please check what you wrote for your first criteria. It doesn't make sense to me. Indices 3 and 4 are 12 and 14 for both arrays. Also, what does "Every second value in the Cartesian product must be smaller than the value before it." mean exactly? 15 is not smaller than 13 in the example you gave.

kubernetes
tags question: http://stackoverflow.com/q/48290256
type: Tag
tags question: http://stackoverflow.com/q/48319496
tags question: http://stackoverflow.com/q/48310468
tag name: kubernetes

http://stackoverflow.com/comment/83567601
score: 0
has text: @PaulPanzer I can consider using `full`, but I would rather not as I need to convolute iteratively (around 100 times), so if I use `full`, I'm afraid my size will blow up?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48291036

http://stackoverflow.com/comment/83388760
comment on: http://stackoverflow.com/q/48203834
type: QuestionComment
has text: What is your desire output
score: 0
type: Comment

http://stackoverflow.com/a/48338969
type: AcceptedAnswer
has body: At last, I get my solution: class TokenSerializer(serializers.ModelSerializer): """ Serializer for Token model. """ user = UserInfoSerializer(many=False, read_only=True) # this is add by myself. class Meta: model = TokenModel fields = ('key', 'user') # there I add the `user` field ( this is my need data ). In the project settings.py, add the TOKEN_SERIALIZER like bellow: REST_AUTH_SERIALIZERS = { ... 'TOKEN_SERIALIZER': 'Project.path.to.TokenSerializer', } Now I get my need data:
score: 16
answers question: http://stackoverflow.com/q/48314694
downvote count: 1
upvote count: 17
accepted answer of: http://stackoverflow.com/q/48314694
type: Answer

http://stackoverflow.com/comment/83600653
has text: Why would you do both `resample` and `asfreq`? Normally you'd do one or the other. `resample` is a deferred action so (like groupby) and needs to be followed by something like max or min -- something that tells resample how to aggregate the data -- not asfreq, which is essentially redundant here. Pandas behavior seems like what I'd expect here, unless I'm missunderstanding.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48298628
score: 0

matplotlib
tags question: http://stackoverflow.com/q/48240021
tags question: http://stackoverflow.com/q/48194193
tags question: http://stackoverflow.com/q/48200406
tags question: http://stackoverflow.com/q/48320804
tags question: http://stackoverflow.com/q/48204702
tags question: http://stackoverflow.com/q/48191134
tags question: http://stackoverflow.com/q/48266772
tags question: http://stackoverflow.com/q/48312151
tags question: http://stackoverflow.com/q/48180594
tags question: http://stackoverflow.com/q/48260014
tags question: http://stackoverflow.com/q/48273099
tags question: http://stackoverflow.com/q/48208222
tags question: http://stackoverflow.com/q/48244609
tags question: http://stackoverflow.com/q/48199545
tags question: http://stackoverflow.com/q/48238471
tags question: http://stackoverflow.com/q/48256413
tags question: http://stackoverflow.com/q/48302284
tags question: http://stackoverflow.com/q/48330505
tags question: http://stackoverflow.com/q/48300718
tags question: http://stackoverflow.com/q/48253978
tags question: http://stackoverflow.com/q/48188615
tags question: http://stackoverflow.com/q/48240792
tags question: http://stackoverflow.com/q/48232385
tags question: http://stackoverflow.com/q/48187228
tags question: http://stackoverflow.com/q/48231500
tags question: http://stackoverflow.com/q/48173975
tags question: http://stackoverflow.com/q/48259542
tags question: http://stackoverflow.com/q/48257352
tags question: http://stackoverflow.com/q/48282768
tags question: http://stackoverflow.com/q/48226295
tags question: http://stackoverflow.com/q/48177074
tags question: http://stackoverflow.com/q/48295581
tags question: http://stackoverflow.com/q/48281836
tags question: http://stackoverflow.com/q/48211424
tags question: http://stackoverflow.com/q/48198334
tags question: http://stackoverflow.com/q/48323164
tags question: http://stackoverflow.com/q/48243870
tags question: http://stackoverflow.com/q/48235880
tags question: http://stackoverflow.com/q/48235729
tags question: http://stackoverflow.com/q/48250225
tags question: http://stackoverflow.com/q/48220730
tags question: http://stackoverflow.com/q/48225888
tags question: http://stackoverflow.com/q/48270534
tags question: http://stackoverflow.com/q/48271838
tags question: http://stackoverflow.com/q/48179498
tags question: http://stackoverflow.com/q/48228470
tags question: http://stackoverflow.com/q/48249521
tags question: http://stackoverflow.com/q/48218590
tags question: http://stackoverflow.com/q/48283125
tags question: http://stackoverflow.com/q/48218912
tags question: http://stackoverflow.com/q/48262442
tags question: http://stackoverflow.com/q/48310820
tags question: http://stackoverflow.com/q/48187280
tags question: http://stackoverflow.com/q/48275425
tags question: http://stackoverflow.com/q/48194542
tags question: http://stackoverflow.com/q/48258994
tags question: http://stackoverflow.com/q/48284548
tags question: http://stackoverflow.com/q/48322071
tags question: http://stackoverflow.com/q/48238192
tags question: http://stackoverflow.com/q/48292990
tags question: http://stackoverflow.com/q/48328481
tags question: http://stackoverflow.com/q/48272437
tags question: http://stackoverflow.com/q/48190614
tags question: http://stackoverflow.com/q/48273065
tags question: http://stackoverflow.com/q/48211348
tags question: http://stackoverflow.com/q/48284453
tags question: http://stackoverflow.com/q/48294332
tags question: http://stackoverflow.com/q/48206605
tags question: http://stackoverflow.com/q/48190628
tags question: http://stackoverflow.com/q/48322741
tag name: matplotlib
tags question: http://stackoverflow.com/q/48269859
tags question: http://stackoverflow.com/q/48267427
tags question: http://stackoverflow.com/q/48289129
tags question: http://stackoverflow.com/q/48236622
tags question: http://stackoverflow.com/q/48243983
tags question: http://stackoverflow.com/q/48264085
tags question: http://stackoverflow.com/q/48305004
tags question: http://stackoverflow.com/q/48225021
tags question: http://stackoverflow.com/q/48320175

http://stackoverflow.com/a/48228113
upvote count: 1
has comment: http://stackoverflow.com/comment/83438152
has comment: http://stackoverflow.com/comment/83438190
has comment: http://stackoverflow.com/comment/83438662
has comment: http://stackoverflow.com/comment/83438022
type: Answer
has comment: http://stackoverflow.com/comment/83438261
has body: class Polynomial: def __init__(self, coeficents, degrees=None): if degrees = None: self.degree = list(reversed(range(len(coeficents)))) else: self.degree = degrees self.coeficents = coeficents def __call__(self, x): print(self.coeficents) print(self.degree) return sum([self.coeficents[i]*x**self.degree[i] for i in range(len(self.coeficents))]) p = Polynomial([1,2,4],[10,2,0]) print(p(2)) This will compute the polynomial x^10 + 2x^2 + 4 at x = 2. It should be very clear how to use with your example.
score: 1
has comment: http://stackoverflow.com/comment/83438036
answers question: http://stackoverflow.com/q/48227710
downvote count: 0
has comment: http://stackoverflow.com/comment/83438074

http://stackoverflow.com/comment/112301207
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/60760199
has text: @NedBatchelder true, tnx, fixed
type: Comment

http://stackoverflow.com/a/48269064
has body: Based on the documentation, tf.argmax() takes an input, and an axis, among other parameters. If your label has shape [1,1], what do you expect to get from an argmax across axis 1? There is only one entry. Most likely, you want to compare the label to the argmaxed result. So: ... image, label = ... # label: Tensor("..", shape=(1, 1), dtype=int32) logits = model(image) # logits: Tensor("..", shape=(1, 10), dtype=float32) predic = tf.nn.softmax(logits) arg_log = tf.argmax(logits, 1) ... pre, lbl, a_log, a_lbl = sess.run([predic, label, arg_log, arg_lbl]) cor_pre = tf.equal(arg_log, tf.cast(label, tf.int64))
type: Answer
accepted answer of: http://stackoverflow.com/q/48268918
answers question: http://stackoverflow.com/q/48268918
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/48272283
type: Answer
has body: Use lt, and you can specify an axis. df.lt(s, axis=0) 1 2 3 1 True False False 2 True True True 3 False False False The axis is 1 by default, and using the overloaded operator &lt; doesn't give you as much flexibility that way. As DYZ mentioned in a comment, having the axis default to 1 here is an exception, because it usually defaults to 0 (in other functions such as apply and transform). If the series and dataframe indexes don't align nicely, you can still get around that by comparing s.values instead. df.lt(s.values, axis=0) 1 2 3 1 True False False 2 True True True 3 False False False
has comment: http://stackoverflow.com/comment/83528348
score: 8
upvote count: 8
answers question: http://stackoverflow.com/q/48272201
downvote count: 0

http://stackoverflow.com/a/48192859
score: 0
has body: I'd do it this way: In [25]: df[df.groupby('Sort_Key')['Status'] .transform(lambda x: not x.tail(1).between(30,39).any())] Out[25]: Admit Claim_no Discharge Sort_Key Status 0 678678 40000 456435 100000003 12 4 8989 42000 34557 100000034 30 5 67867 50000 6867456 100000034 18 6 89697 42000 345435 100000034 19
answers question: http://stackoverflow.com/q/48192028
type: Answer

http://stackoverflow.com/a/48329017
score: 2
type: Answer
answers question: http://stackoverflow.com/q/48327085
has body: As far as I can tell, it turns out to have been an issue with having the right version of numpy, per cxw's comment. I have updated numpy, and everything seems to be working fine now.
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/68679081
score: 0
answers question: http://stackoverflow.com/q/48312983
type: Answer
has body: if -env is the environment that need pass to the image, you should call : docker run -it -e ENVXX=aa -e ENVYY=bb ImageNameOfTest if -env is the param that need pass to your test exe, call : docker run -it ImageNameOfTest test -env xxx -env yyy

http://stackoverflow.com/comment/83958652
has text: @FlorentB. I've added debug in my repo and it is not of any help. It's like it just skips over it. I find it strange how the script runs except for pyupdater. Puzzling..
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48179088

http://stackoverflow.com/comment/83530710
type: Comment
comment on: http://stackoverflow.com/q/48273473
score: 0
type: QuestionComment
has text: so, what is the question?

http://stackoverflow.com/a/71832689
type: Answer
has body: I found venv-run which should do what you ask: pip install venv-run venv-run cmd args
upvote count: 4
answers question: http://stackoverflow.com/q/48174599
downvote count: 1
score: 3

http://stackoverflow.com/a/48180885
score: 2
upvote count: 2
downvote count: 0
has body: You can achieve it by implementing a simple tag-stripper. def strip_tags(html, invalid_tags): soup = BeautifulSoup(html) for tag in soup.findAll(True): if tag.name in invalid_tags: s = "" for c in tag.contents: if not isinstance(c, NavigableString): c = strip_tags(unicode(c), invalid_tags) s += unicode(c) tag.replaceWith(s) return soup html = " Love, Hate, and Happinessy " invalid_tags = ['b', 'i', 'u'] print strip_tags(html, invalid_tags) The result is: Love, Hate, and Happiness
type: Answer
answers question: http://stackoverflow.com/q/48180690

http://stackoverflow.com/a/48254579
downvote count: 0
answers question: http://stackoverflow.com/q/48254555
has body: You can use groupby on (Datetime, Col4) + count here. df = df.groupby([df.index, df.Col4]).Col4.count().reset_index(level=1, name='ColB') Or, df = df.groupby([df.index, df.Col4]).size().reset_index(level=1) Next, set the column names: df.columns = ['ColA', 'ColB'] df ColA ColB Datetime 2016-11-01 Durham 2 2016-11-02 Ips 1 2016-11-02 New 1 2016-11-03 Durham 1
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/48254555
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/48198021
score: 34
has title: Filter pandas dataframe with specific column names in python
accepted answer: http://stackoverflow.com/a/48198034
favorite count: 0
has answer: http://stackoverflow.com/a/73304939
type: Question
type: AnsweredQuestion
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48198051
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/78547303
has answer: http://stackoverflow.com/a/48198051
answer count: 4
has body: I have a pandas dataframe and a list as follows mylist = ['nnn', 'mmm', 'yyy'] mydata = xxx yyy zzz nnn ddd mmm 0 0 10 5 5 5 5 1 1 9 2 3 4 4 2 2 8 8 7 9 0 Now, I want to get only the columns mentioned in mylist and save it as a csv file. i.e. yyy nnn mmm 0 10 5 5 1 9 3 4 2 8 7 0 My current code is as follows. mydata = pd.read_csv( input_file, header=0) for item in mylist: mydata_new = mydata[item] print(mydata_new) mydata_new.to_csv(file_name) It seems to me that my new dataframe produces wrong results.Where I am making it wrong? Please help me!
has comment: http://stackoverflow.com/comment/138483702
upvote count: 34
has answer: http://stackoverflow.com/a/48198034
downvote count: 0

http://stackoverflow.com/q/48312957
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/83630368
upvote count: 1
tagged with: string
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48313071
has title: Include the result of a function in a Python string
has body: Trying to work through some beginners Python code. I need to provide a string that given 3 numbers a, b, and c, states The average is: XX. How do I incorporate sum(a,b,c) / len(a,b,c) into the output string?
tagged with: python
has comment: http://stackoverflow.com/comment/83611831
tagged with: average
tagged with: python-3.x
score: 0

http://stackoverflow.com/comment/83394011
type: Comment
comment on: http://stackoverflow.com/q/48206383
type: QuestionComment
has text: Possible duplicate of [limit choices with dropdown in flask-admin](https://stackoverflow.com/questions/32106940/limit-choices-with-dropdown-in-flask-admin)
score: 0

http://stackoverflow.com/a/71895326
answers question: http://stackoverflow.com/q/48254689
has body: Using PyCharm 2021.3.3 (Community Edition) built March 16. 2022: There are two columns of buttons on the left of the console the bottom left one says "New Console" on hover. Pressing it gives a new console (duh) with no user variables.
score: 0
type: Answer

http://stackoverflow.com/comment/83629357
has text: Can you elaborate on the interrupt pin. Is this held open for input and capture changes in the state ?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48316117
type: Comment

http://stackoverflow.com/q/48264917
tagged with: web-crawler
has comment: http://stackoverflow.com/comment/83513563
score: 0
has comment: http://stackoverflow.com/comment/83512974
answer count: 0
tagged with: web-scraping
tagged with: beautifulsoup
type: Question
has body: How can I make a search query using bs4 and urllib which find a search field and puts the value to fields and press submit (another url having token). I have tried this but this didn't seem to even login. import bs4 as bs from urllib import request from urllib import parse # print(soup.text) values ={'username': '1234567890', 'password': 'mypassw'} post_arg = parse.urlencode(values).encode('utf-8') url = 'http://site24.way2sms.com/content/index.html?' sauce = request.urlopen(url, post_arg) soup = bs.BeautifulSoup(sauce, "lxml") #print(sauce) for i in soup.find_all('input', attrs={'id':'username'}): print(i) #put values to input fields #grab token, I can't find any csrf token. #visit the desired webpage
has title: Making a search query using bs4 and urllib
has comment: http://stackoverflow.com/comment/83513198
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83602371
has text: Try to install `zlib-devel` as explained here: https://serverfault.com/questions/608781/is-there-a-way-to-install-pip-and-zlib-devel-on-rhel-5-7-without-red-hat-entitle .
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48210675
type: Comment

http://stackoverflow.com/comment/83434881
comment on: http://stackoverflow.com/a/48222850
has text: Thanks for taking the time to help out @Jonas Byström. I tried your solution. Unfortunately, I am not getting the desired result. I have updated by question with this information too for reference if it helps as I am not sure how to provide a dataframe output in the comment section.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83357187
comment on: http://stackoverflow.com/a/48188419
type: Comment
has text: Is that available for *windows* users?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83644901
score: 0
comment on: http://stackoverflow.com/q/48313111
type: QuestionComment
has text: http://py-component-controller.readthedocs.io/en/latest/controller.html#get-browser-console-logs
type: Comment

http://stackoverflow.com/q/48305611
tagged with: classification
has answer: http://stackoverflow.com/a/63579513
possible better answer: http://stackoverflow.com/a/63579513
has comment: http://stackoverflow.com/comment/83601611
tagged with: decision-tree
tagged with: python
accepted answer: http://stackoverflow.com/a/48327031
linked to: http://stackoverflow.com/q/16505670
has comment: http://stackoverflow.com/comment/83596672
type: AnsweredQuestion
score: 0
has body: I want to retrieve the path each instance takes in decision tree or RandomForest. for instance, I need such an output: # 1 1 3 4 8 NA NA # 2 1 2 5 7 11 NA # 3 1 3 4 9 10 13 # 4 1 3 4 8 NA NA # etc It means that instance #1 passes the path from node 1, 3, 4 and ended in terminal node 8 and so forth. It is obvious that the path length of some instances is shorter than others. I used decision_path but it gives a sparse matrix which I can not understand and find such a path. Even I cannot read the output. It is the sample code for Iris database: from sklearn.datasets import load_iris iris = load_iris() import numpy as np ytrain = iris.target xtrain = iris.data from sklearn.tree import DecisionTreeClassifier dtree = DecisionTreeClassifier() fitted_tree = dtree.fit(X=xtrain,y=ytrain) predictiontree = dtree.predict(xtrain) fitted_tree.decision_path(xtrain) The output is this: &lt;150x17 sparse matrix of type '&lt;class 'numpy.int64'&gt;' with 560 stored elements in Compressed Sparse Row format&gt; Please help me make the matrix such as the one I mentioned at the top. I have no idea how to handle sparse matrix.
has comment: http://stackoverflow.com/comment/83596638
has comment: http://stackoverflow.com/comment/83601137
has answer: http://stackoverflow.com/a/48327031
has title: using decision_path in Decision Tree in Python
has comment: http://stackoverflow.com/comment/83600944
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83601567

http://stackoverflow.com/comment/83386270
type: QuestionComment
score: 0
has text: Dear @JKC sorry for above comment. my comment is longer than the above one. but the internet connection messed up that's why it looks a little dumb. no offense sorry.
type: Comment
comment on: http://stackoverflow.com/q/48201898

http://stackoverflow.com/a/48287703
downvote count: 0
score: 2
has comment: http://stackoverflow.com/comment/83560944
has comment: http://stackoverflow.com/comment/83561289
type: Answer
has body: If you are running this script from an EC2 instance, attach an IAM role to the instance. The IAM role should contain the following policy (in addition to what you already have). { "Version": "2012-10-17", "Statement": [ { "Sid": "statement1", "Effect": "Allow", "Action": ["s3:PutObject"], "Resource": "arn:aws:s3:::examplebucket/*" } ] } If you are not running this script in an EC2 instance, you need to use the access and secret keys.
has comment: http://stackoverflow.com/comment/83561064
has comment: http://stackoverflow.com/comment/83561551
has comment: http://stackoverflow.com/comment/83561239
answers question: http://stackoverflow.com/q/48286141
upvote count: 2

http://stackoverflow.com/a/48276282
has comment: http://stackoverflow.com/comment/92684809
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/92700319
has body: I would suggest not to use normalize in sklearn as it does not deal with NaNs. You can simply use below code to normalize your data. df['col']=(df['col']-df['col'].min())/(df['col'].max()-df['col'].min()) Above method ignores NaNs while noramlizing the data
downvote count: 0
answers question: http://stackoverflow.com/q/48275733
has comment: http://stackoverflow.com/comment/92673342
type: Answer

http://stackoverflow.com/comment/83642774
score: 0
type: Comment
type: QuestionComment
has text: The other answers related to this question are not what I want. Those answers weren't help for me.
comment on: http://stackoverflow.com/q/48328110

http://stackoverflow.com/a/48231135
score: 0
answers question: http://stackoverflow.com/q/48228215
upvote count: 1
has body: This function should do what you want: def import_force(name): needs_reload = name in sys.modules module = importlib.import_module(name) if needs_reload: module = importlib.reload(module) return module # Usage example: os = import_force('os') An alternative approach is to write your own import hooks, which I won't describe. However please note that this is an anti-pattern and I would discourage the practice of reloading modules at every import. If this is for debugging purposes, then I would suggest using one of the many auto-reloader solutions available online: they watch your Python files for changes, and when you make modifications they automatically re-import the modules. The reasons why your function didn't work are two: The import keyword does not resolve variables, so import m does not mean "import the module which name is in the variable m", but rather it means "import the module named m". importlib.reload wants a module object, not a module name.
has comment: http://stackoverflow.com/comment/83444751
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/83444684
has comment: http://stackoverflow.com/comment/83444550

http://stackoverflow.com/a/48265741
downvote count: 0
type: Answer
has body: the module PDFWriter is in xtopdf PDFWriter - a core class of the xtopdf toolkit - can now be used with a Python context manager, a.k.a. the Python with statement. ( http://code.activestate.com/recipes/578790-use-pdfwriter-with-context-manager-support/ ) how to install xtopdf is in https://bitbucket.org/vasudevram/xtopdf : Installation and usage: To install the files, first make sure that you have downloaded and installed all the prerequisities mentioned above, including setup steps such as adding needed directories to your PYTHONPATH. Then, copy all the files in xtopdf.zip into a directory which is on your PYTHONPATH. To use any of the Python programs, run the .py file as: python filename.py This will give a usage message about the correct usage and arguments expected. To run the shell script(s), do the same as above. Developers can look at the source code for further information. an alternative is to use pdfdocument to create the pdf, it can be installed using pip ( https://pypi.python.org/pypi/pdfdocument ) parse the data from the json data ( How can I parse GeoJSON with Python, Parse JSON in Python ) and print it as pdf using pdfdocument ( https://pypi.python.org/pypi/pdfdocument ) import json data = json.loads(datastring) from io import BytesIO from pdfdocument.document import PDFDocument def say_hello(): f = BytesIO() pdf = PDFDocument(f) pdf.init_report() pdf.h1('Hello World') pdf.p('Creating PDFs made easy.') pdf.generate() return f.getvalue()
answers question: http://stackoverflow.com/q/48262492
score: 5
upvote count: 5

http://stackoverflow.com/a/48283281
has comment: http://stackoverflow.com/comment/83550491
score: 1
upvote count: 1
has body: Yes that is possible, kinda, using Funcanimation and encapsulating your data inside func. import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation arr1 = np.random.rand(300,3,4) arr2 = np.random.rand(200,5,6) fig, (ax1, ax2) = plt.subplots(1,2) img1 = ax1.imshow(arr1[0]) img2 = ax2.imshow(arr2[0]) # set relative display rates r1 = 2 r2 = 3 def animate(ii): if ii % r1: img1.set_data(arr1[ii/r1]) if ii % r2: img2.set_data(arr2[ii/r2]) return img1, img2 ani = animation.FuncAnimation(fig, func=animate, frames=np.arange(0, 600)) plt.show()
downvote count: 0
has comment: http://stackoverflow.com/comment/83551524
has comment: http://stackoverflow.com/comment/83551757
type: Answer
answers question: http://stackoverflow.com/q/48282768

http://stackoverflow.com/comment/83588229
has text: @cᴏʟᴅsᴘᴇᴇᴅ literally speaking, doing this with a decorator still counts as "inside the function" ;)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48301581

design-patterns
tags question: http://stackoverflow.com/q/48303370
tag name: design-patterns
tags question: http://stackoverflow.com/q/48296986
type: Tag

http://stackoverflow.com/comment/89238195
has text: I'd like to override the messages for the codes 'too_few_forms' and 'too_many_forms' as well. Relevant part is [here](https://github.com/django/django/blob/16ee53d7bb01819859c78a88e3fc93eda985f71a/django/forms/formsets.py#L345).
comment on: http://stackoverflow.com/q/48312057
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48224916
favorite count: 0
type: AnsweredQuestion
has title: Join Single level table to a multi level table in Python
upvote count: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48228612
accepted answer: http://stackoverflow.com/a/48228612
has body: I have df1 which is multi level table with expenses -it looks like this ( a &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 60 &nbsp;&nbsp; EUR 10 &nbsp;&nbsp; AUD 20 &nbsp;&nbsp;&nbsp;USD 30 b &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 65 &nbsp;&nbsp;&nbsp; EUR 40 &nbsp;&nbsp;&nbsp; GBP 10 &nbsp;&nbsp;&nbsp; HKD 15 both of them are done using this script t_sub=pd.concat([ t.assign( **{x: '' for x in ['Client'][i:]} ).groupby(list(['Client'])).sum() for i in range(1,2) ]).sort_index() and then i have Another table which is with the Money of each person - df2 a - 100 b - 200 I want to Append the second table to the first one but it has to match the level of the client total only e.g. a &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 60 100 &nbsp;&nbsp;&nbsp; EUR 10 - &nbsp;&nbsp;&nbsp; AUD 20 - &nbsp;&nbsp;&nbsp; USD 30 - b &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp; 65 200 &nbsp;&nbsp;&nbsp; EUR 40 - &nbsp;&nbsp;&nbsp; GBP 10 - &nbsp;&nbsp;&nbsp; HKD 15 -
type: Question
tagged with: pandas
score: 1
tagged with: python
tagged with: merge
tagged with: append

http://stackoverflow.com/comment/83605664
type: AnswerComment
has text: I only forgot to specify that this was for odoo 9 I'll put an edit. Thank you for your constructive observation. Although, it could be a little bit delicate to migrate the database from the 9th version to later ones due to the changes that have been made.
comment on: http://stackoverflow.com/a/48305450
type: Comment
score: 0

http://stackoverflow.com/comment/83532132
has text: https://pandas.pydata.org/pandas-docs/stable/advanced.html
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48274259
type: QuestionComment

http://stackoverflow.com/a/48313531
accepted answer of: http://stackoverflow.com/q/48311159
downvote count: 0
answers question: http://stackoverflow.com/q/48311159
type: Answer
has comment: http://stackoverflow.com/comment/83662142
has body: As you have found through your research of the authoritative source and elsewhere, there is no definitive indentation specification, except a minimum of 2 spaces for option lists, and a minimum of 3 spaces for footnotes. See the specification on indentation for reStructuredText. That said, there are some recommendations. Choose a style and keep it consistent for your documentation. IDEs often complain about incorrect indentation, like for docstrings in Python, so using 4 spaces can avoid those warnings. IDEs can be set to indent to 4 spaces for code, so why not keep it the same for documentation? See my bonus tip about indenting for numbered lists.
type: AcceptedAnswer
score: 19
upvote count: 19

http://stackoverflow.com/comment/83584587
score: 2
comment on: http://stackoverflow.com/q/48300027
type: Comment
type: QuestionComment
has text: Any attempts from your side?

http://stackoverflow.com/comment/83623208
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48318892
has text: `plot_surface` requires 2D arrays as input, not 1D lists.

http://stackoverflow.com/comment/83378185
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48198410
type: Comment
has text: `self.country` might access an awful lot of things ... not just any potential `country` "attribute"

unit-testing
tags question: http://stackoverflow.com/q/48328560
tags question: http://stackoverflow.com/q/48287018
tags question: http://stackoverflow.com/q/48227108
tags question: http://stackoverflow.com/q/48216473
tags question: http://stackoverflow.com/q/48311594
type: Tag
tags question: http://stackoverflow.com/q/48279161
tags question: http://stackoverflow.com/q/48210488
tags question: http://stackoverflow.com/q/48173887
tag name: unit-testing
tags question: http://stackoverflow.com/q/48179407
tags question: http://stackoverflow.com/q/48313888
tags question: http://stackoverflow.com/q/48307041
tags question: http://stackoverflow.com/q/48267322
tags question: http://stackoverflow.com/q/48285951
tags question: http://stackoverflow.com/q/48295296
tags question: http://stackoverflow.com/q/48292332
tags question: http://stackoverflow.com/q/48309969
tags question: http://stackoverflow.com/q/48273420
tags question: http://stackoverflow.com/q/48234672
tags question: http://stackoverflow.com/q/48290074
tags question: http://stackoverflow.com/q/48183318

http://stackoverflow.com/q/48271438
has comment: http://stackoverflow.com/comment/83526754
has comment: http://stackoverflow.com/comment/83526763
answer count: 1
has comment: http://stackoverflow.com/comment/83526931
has comment: http://stackoverflow.com/comment/83526827
type: Question
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83526843
has answer: http://stackoverflow.com/a/48271888
accepted answer: http://stackoverflow.com/a/48271888
tagged with: delay
tagged with: python
has body: What I am attempting to do is run another file (file1 process) , and while that file is running I want to check the local directory for existence of a file. If the file doesn't exist then everything keeps running and check again in 30 seconds. If the file does exist I want to print the contents to a label and stop the file1 process. My code below causes Tkinter to erase all of its labels and freezes the GUI while the after delay occurs. Where am I going wrong ? def turnOn(): global proc if proc is None: window.after(5000,file_chk) print('Starting Beacon') proc = subprocess.Popen(["python3", "/home/pi/FLBeacon/FLBeaconout.py"]) label1 = Label(window,text ="Beacon is Running") label1.configure(bg='green') label1.place(x= 350, y=10, width=150) global label2 label2 = Label(window,text = full_message) label2.configure(bg='green') label2.place(x=50, y=90, width=550) def file_chk(): filelist = ['FLBeaconRecieved.txt'] while True: list1 = [] for file in filelist: list1.append(os.path.isfile(file)) if all(list1): #all elements are true file = open("FLBeaconRecieved.txt") data = file.read() file.close() Results = Label(window, text = data) Results.place(x = 50, y = 350) print('Beacon Stopped') proc.terminate() proc = None label1 = Label(window,text = "Beacon is not running") label1.configure(bg='red') label1.place(x= 350, y=10, width=150) label2.destroy() break else: #time.sleep(30) print("there is no file") on = Button(window, borderwidth=2, text = "Start Beacon", width=15, pady=5, command = turnOn) off = Button(window, borderwidth=2, text = "Stop Beacon", width=15, pady=5, command = turnOff) on.place(x=215,y=300) off.place(x=380,y=300) def stop(): window.destroy() #Top.destroy() b = Button(window, borderwidth=2, text="Update Beacon", width=15, pady=5, command=enter) b.place(x=50,y=300) b = Button(window, borderwidth=2, text="Exit", width=12, pady=5, command = combine_funcs(turnOff, stop)) b.place(x=250,y=550) window.mainloop()
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83526779
score: 0
has title: using after() properly in Tkinter

http://stackoverflow.com/comment/83379685
type: QuestionComment
comment on: http://stackoverflow.com/q/48199188
score: 2
type: Comment
has text: Is `tags[0]` a string? Just because it can print doesn't make it so.

http://stackoverflow.com/comment/83594018
type: Comment
score: 0
type: AnswerComment
has text: Thanks for the command i did what you said But when i print logguittime it prints it like this: {u'loguittime': datetime.timedelta(0, 58981)} in phpmyadmin it stands like this: 16:23:01
comment on: http://stackoverflow.com/a/48304142

http://stackoverflow.com/comment/83492217
score: 0
comment on: http://stackoverflow.com/q/48254520
type: QuestionComment
has text: I have 8GB of RAM, so it should work. I'd like to be able to scale it up to something along the lines of K=256, is there anyway to do this? Closing everything else running will get K=20 to work, but it takes very long. Checking RAM usage shows around 7.5GB used.
type: Comment

http://stackoverflow.com/q/48174599
tagged with: python
tagged with: command-line-interface
upvote count: 42
has answer: http://stackoverflow.com/a/71832689
score: 41
has body: I have a command that only runs correctly inside a Python virtual environment I've configured (as intended). I know that I can run the command as $ cmd args once I've activated the venv. But (due to the constraints of the tool I'm using) I need to activate run (and deactivate?) in one line: something equivalent to running $ activate_somehow cmd args outside the command line. Is there a way to do this?
has answer: http://stackoverflow.com/a/66079786
has title: Is there a single line way to run a command in a Python venv?
has answer: http://stackoverflow.com/a/79005270
has answer: http://stackoverflow.com/a/48174818
tagged with: virtualenv
downvote count: 1
has answer: http://stackoverflow.com/a/73231347
favorite count: 0
type: Question
answer count: 8
has answer: http://stackoverflow.com/a/74163454
linked to: http://stackoverflow.com/q/54871891
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48174859
has answer: http://stackoverflow.com/a/72996083

http://stackoverflow.com/q/48183177
has answer: http://stackoverflow.com/a/48183327
answer count: 1
tagged with: mysql
type: Question
has body: The timestamp when storing in database its correct but while querying it back the value of time is changing. models.py aed = models.CharField(max_length=100) gbp = models.CharField(max_length=100) timestamp = models.DateTimeField(auto_now= False,auto_now_add=True) Database Stored Values 2018-01-10 13:17:05.107542+05:30 2018-01-10 13:18:01.803399+05:30 2018-01-10 13:19:01.873091+05:30 2018-01-10 13:20:04.476807+05:30 2018-01-10 13:21:01.913048+05:30 My query Values 2018-01-10 07:47:05.107542+00:00 2018-01-10 07:47:05 2018-01-10 07:49:01.873091+00:00 2018-01-10 07:49:01 2018-01-10 07:51:01.913048+00:00 2018-01-10 07:51:01 2018-01-10 07:48:01.803399+00:00 2018-01-10 07:48:01 2018-01-10 07:50:04.476807+00:00 2018-01-10 07:50:04 The Time is getting changed. My Settings.py TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True
tagged with: postgresql
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83345932
score: 0
has title: Timestamp values changing Django

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/48218263
type: Tag

http://stackoverflow.com/comment/83465266
comment on: http://stackoverflow.com/a/48238102
type: Comment
type: AnswerComment
score: 1
has text: I understand why you feel like that. Sorry if it felt really silly. But I basically started using numpy and 3d arrays slicing yesterday and was totally lost with advanced slicing vs basic slicing, so I hadn't really started playing much yet, just exploring basic concepts by asking questions here.

http://stackoverflow.com/q/48277961
score: 2
upvote count: 2
downvote count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83539572
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83540521
has body: I would like to suppress output using print from a tested function, while keeping output from the testing function, using a decorator on the testing function, in a safe manner. Essentially: script.py def func(): print("script") This module is called in: test_script.py import script @some_decorator def test_func(): print("test_script") script.func() test_func() What should some_decorator be, for test_script to print without script? I can import any library as necessary on either of the scripts, preferably from the standard library. Thanks! EDIT: I'm using importlib to import script.py, so the import line should be something like this: import importlib file_name = "script" script = importlib.import_module(file_name)
linked to: http://stackoverflow.com/q/12998908
has comment: http://stackoverflow.com/comment/83539858
type: Question
has title: Suppress Output in Tested Function
tagged with: python-unittest
tagged with: python
type: UnansweredQuestion
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/83539359

http://stackoverflow.com/comment/83547621
type: QuestionComment
comment on: http://stackoverflow.com/q/48281988
score: 0
has text: @deceze actually not
type: Comment

http://stackoverflow.com/q/48323976
has comment: http://stackoverflow.com/comment/83639632
has body: I having some issues with haystacks. when i nitialize with my model that giving me a list with type SearchQuerySet: def sqs_query(self, sqs): q = self.request.QUERY_PARAMS.get('q', '') results = sqs.filter(content=q) pdb.set_trace() sorted = sort(results) return sorted def get_queryset(self): sqs = self.sqs_query(self.sqs_models(SearchQuerySet())) return sqs (pdb) type(results) &lt;class 'haystack.query.SearchQuerySet'&gt; I can acess the position 0: (pdb) results[0] &lt;SearchResult: article.article (pk=u'5')&gt; But i can't assign: (pdb) results[0] = results[1] *** TypeError: 'SearchQuerySet' object does not support item assignment I need to modify the positions of the list to order the list. order_by() will no help me but i need to calculate my own values to compare. Every result has a title word. I will calculate Levenshtein_distance using the string q and every result will asscociate with a diferente value.
has title: How acess and modify SearchQuerySet(HayStack)?
tagged with: python
has comment: http://stackoverflow.com/comment/83633483
answer count: 0
score: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/83633254
type: Question

http://stackoverflow.com/comment/83498654
type: QuestionComment
has text: Sry , a newbie to web dev and django . I tried to setup my project as my friend's(his is working properly) even he couldnt fix the issue. Heres the link to its git could you please look into it, I am sure its something silly I might have missed out. Thanks in advance. [link](https://github.com/kewalkishang/Django_Basics)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48249068

http://stackoverflow.com/comment/83519187
has text: I recommend using Enumerated types for your directions and declaring them explicitly throughout (name not by value). from enum import Enum Should make it more readable too (if indeed another edit will be supplied)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48267969
type: QuestionComment

http://stackoverflow.com/comment/83497971
score: 0
comment on: http://stackoverflow.com/a/48257591
type: AnswerComment
type: Comment
has text: Thanks, this works. I also found a flaw in my code: if i exchange up_lim and dwn_lim then it should all work out just fine. But I learned something new with your answer.

http://stackoverflow.com/a/48291207
upvote count: 1
has body: Your code works. The window is not drawn on the screen until you call mainloop(), so printing M.filename before that point prints an empty string (the initialization value). The mainloop() blocks until the window closes, after which 3 print statements successfully print the value that the user entered into the box. You may be interested in the easygui module, which does exactly what your program does except you don't have to make it yourself.
answers question: http://stackoverflow.com/q/48291140
type: Answer
score: 1
downvote count: 0

http://stackoverflow.com/a/48180149
score: 0
has body: I'm pushing against the boundaries set forth in your question.. if you're simply wanting to do it in JavaScript, but outside the context of a browser, have you considered working in Node?
has comment: http://stackoverflow.com/comment/83340428
has comment: http://stackoverflow.com/comment/83340376
answers question: http://stackoverflow.com/q/48179772
type: Answer

http://stackoverflow.com/a/76064428
score: 1
downvote count: 0
has body: Although it has been a couple of years since this question was asked, today I ran into the same requirement. As @Nickolas mentioned, the given answers do not account for submodels. Here is a recursive function to find the total number of layers in a model, including submodels: def count_layers(model): num_layers = len(model.layers) for layer in model.layers: if isinstance(layer, tf.keras.Model): num_layers += count_layers(layer) return num_layers
answers question: http://stackoverflow.com/q/48265926
type: Answer
upvote count: 1

http://stackoverflow.com/a/48264918
answers question: http://stackoverflow.com/q/48260092
accepted answer of: http://stackoverflow.com/q/48260092
type: AcceptedAnswer
type: Answer
has body: Figured out my error going over the tutorial I was following regarding this issue.
score: 0

http://stackoverflow.com/comment/83647378
comment on: http://stackoverflow.com/a/48329937
score: 0
type: Comment
has text: @LelouchLamperouge update another method , should be faster than apply
type: AnswerComment

http://stackoverflow.com/a/48250968
has body: As soon as you use not default (not None) value for chunksize parameter pd.read_csv returns a TextFileReader iterator instead of a DataFrame. pd.read_csv() will try to read your CSV file in chunks (with specified chunk size): reader = pd.read_csv(filename, chunksize=N) for df in reader: # process df (chunk) here So when using chunksize - all chunks (except the very last one) will have the same length. Using iterator parameter you can define how much data (get_chunk(nrows)) you want to read in each iteration: In [66]: reader = pd.read_csv(fn, iterator=True) let's read first 3 rows In [67]: reader.get_chunk(3) Out[67]: a b c 0 2.229657 -1.040086 1.295774 1 0.358098 -1.080557 -0.396338 2 0.731741 -0.690453 0.126648 now we'll read next 5 rows: In [68]: reader.get_chunk(5) Out[68]: a b c 0 -0.009388 -1.549381 0.913128 1 -0.256654 -0.073549 -0.171606 2 0.849934 0.305337 2.360101 3 -1.472184 0.641512 -1.301492 4 -2.302152 0.417787 0.485958 next 7 rows: In [69]: reader.get_chunk(7) Out[69]: a b c 0 0.492314 0.603309 0.890524 1 -0.730400 0.835873 1.313114 2 1.393865 -1.115267 1.194747 3 3.038719 -0.343875 -1.410834 4 -1.510598 0.664154 -0.996762 5 -0.528211 1.269363 0.506728 6 0.043785 -0.786499 -1.073502 from docs: iterator : boolean, default False Return TextFileReader object for iteration or getting chunks with get_chunk(). chunksize : int, default None Return TextFileReader object for iteration. See the IO Tools docs for more information on iterator and chunksize.
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48250655
downvote count: 0
has comment: http://stackoverflow.com/comment/83486135

http://stackoverflow.com/q/48255567
tagged with: pyqt
has comment: http://stackoverflow.com/comment/83520925
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/83510342
has title: Sorting Q_FLAGS in Designer for a custom widget made in PyQt
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83494593
tagged with: python
tagged with: qt
has body: I'm creating some custom widgets in PyQt, that are to be used into Qt's Designer. Some of them have properties as Q_FLAGS, for example some of the QtCore.Qt.AlignmentFlag. Since I won't use the whole QtCore.Qt.Alignment flags (it's unnecessary and creates confusion), I created a QFlags class. class SomeWidget(QtWidgets.QWidget): class LabelAlignment: AlignLeft = int(QtCore.Qt.AlignLeft) AlignHCenter = int(QtCore.Qt.AlignHCenter) AlignRight = int(QtCore.Qt.AlignRight) AlignTop = int(QtCore.Qt.AlignTop) AlignVCenter = int(QtCore.Qt.AlignVCenter) AlignBottom = int(QtCore.Qt.AlignBottom) QtCore.Q_FLAGS(LabelAlignment) (Note: I'm using int() conversion as I need to do some bitwise operations and, AFAIK, a flag pyqtProperty is always read as int within Designer's property sheet; I tried to use plain flags, but the result is the same) The problem is that the flags are sorted in an unpredictable order within Designer's property editor. I suppose that it's due to the use of LabelAlignment.__dict__ to map the class's flags, thus creating an "unsorted" list of the flags (which, obviously, changes every time Designer loads the plugin interface, since python's dicts are unordered). Is there any way of ordering those flags (maybe using an OrderedDict)?
score: 0
answer count: 0

http://stackoverflow.com/comment/83541131
comment on: http://stackoverflow.com/a/48260915
has text: Thanks! Ok, I'll see what I can do
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48247490
has answer: http://stackoverflow.com/a/48249910
answer count: 5
has title: Django Rest-Framework nested serializer order
has answer: http://stackoverflow.com/a/54356223
score: 56
has answer: http://stackoverflow.com/a/55315670
downvote count: 0
tagged with: django
upvote count: 56
tagged with: python
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/60214106
accepted answer: http://stackoverflow.com/a/48249910
linked to: http://stackoverflow.com/q/44418189
type: AnsweredQuestion
tagged with: rest
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/60214106
has answer: http://stackoverflow.com/a/74204193
has body: Is there a way to order a nested serializer _set, for example order by pk or time-stamp. So basically order song_set shown in the json data below from the most recent to the latest object created, in this case by order_by('-timestamp') or order_by('-pk'). Json data { "pk": 151, "album_name": "Name", "song_set": [ { pk: 3, timestamp: '5 seconds' }, { pk: 2, timestamp: '10 seconds' }, { pk: 1, timestamp: '15 seconds' } ] } Model class Album(models.Model): album_name = models.CharField(max_length=100, blank=True) class Song(models.Model): album = models.ForeignKey('album.Album', default=1) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) Serializer class SongListSerializer(HyperlinkedModelSerializer): class Meta: model = Song fields = [ 'pk', 'timestamp' ] class AlbumSerializer(HyperlinkedModelSerializer): song_set = SongListSerializer(many=True, read_only=True) class Meta: model = Album fields = [ 'pk', 'timestamp', 'song_set' ]
has comment: http://stackoverflow.com/comment/130825549
favorite count: 0
type: Question

http://stackoverflow.com/q/48305346
has answer: http://stackoverflow.com/a/48305888
has comment: http://stackoverflow.com/comment/83595892
has comment: http://stackoverflow.com/comment/83596358
answer count: 1
linked to: http://stackoverflow.com/q/31521027
type: AnsweredQuestion
score: 0
tagged with: pandas-groupby
has comment: http://stackoverflow.com/comment/83596816
has comment: http://stackoverflow.com/comment/83597332
accepted answer: http://stackoverflow.com/a/48305888
tagged with: pandas
has title: Python Pandas groupby row data manipulation
tagged with: python
has body: I am a newbie to Python and pandas and learning the same. I have basic question for pandas dataframe related to groupby. I have a dataframe and from that I want to have some calculations as below: SH TH QH RH S1 B 10 5 S2 B 12 8 S1 B 5 8 S1 S 5 10 S1 S 3 12 And I want something like this as intermediate: SH TH QH RH S1 B 15 6 S1 S 8 10.75 S2 B 12 8 And final result as below: SH TH QH RH S1 B 7 6 S2 B 12 8 I want to know how best I can do it in python pandas way of doing it. Thanks Nand
type: Question

http://stackoverflow.com/comment/83328233
has text: Haven't you tried fetching the actual predictions from the probabilities with `tf.argmax`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48174323

http://stackoverflow.com/a/48273516
score: 0
answers question: http://stackoverflow.com/q/48272285
type: Answer
has body: Your Enumerate() function has issues: enumerate returns a tuple on every iteration. That tuple consists of the index in the iterable(list) and then the list item at that index. This means your second for statement is not iterating over each row of data in the list, but over the tuple of (index, list). You iterate through and process the entire buttons list for every iteration through the col_index loop. try this function instead: def populate(): for row_index, row_data in enumerate(easy): for col_index, cell_value in enumerate(row_data): buttons[(row_index * 9) + col_index].config(text=cell_value)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48272285

http://stackoverflow.com/q/48185580
type: Question
tagged with: tf-idf
has comment: http://stackoverflow.com/comment/83351860
has answer: http://stackoverflow.com/a/48187229
upvote count: 2
has title: TF-IDF for data filtering
accepted answer: http://stackoverflow.com/a/48187229
downvote count: 0
has comment: http://stackoverflow.com/comment/83350968
tagged with: scikit-learn
tagged with: python
has comment: http://stackoverflow.com/comment/83351100
score: 2
type: AnsweredQuestion
tagged with: tfidfvectorizer
has body: I've a list of raw document, already filtered and removed english stopwords: rawDocument = ['sport british english sports american english includes forms competitive physical activity games casual organised ...', 'disaster serious disruption occurring relatively short time functioning community society involving ...', 'government system group people governing organized community often state case broad associative definition ...', 'technology science craft greek τέχνη techne art skill cunning hand λογία logia collection techniques ...'] and I've used from sklearn.feature_extraction.text import TfidfVectorizer sklearn_tfidf = TfidfVectorizer(norm='l2', min_df=0, use_idf=True, smooth_idf=False, sublinear_tf=False) sklearn_representation = sklearn_tfidf.fit_transform(rawDocuments) But I got a &lt;4x50 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 51 stored elements in Compressed Sparse Row format&gt; and I cant interpret the result. So, am I using the right tool or have I to change the way? My goal is to get the relevant word in each document, in order to perform a cosine similarity with other words in a query document. Thank you in advance.
answer count: 1
favorite count: 0

http://stackoverflow.com/tag/zip
tags question: http://stackoverflow.com/q/48311513
tags question: http://stackoverflow.com/q/48311136
tags question: http://stackoverflow.com/q/48317221
tags question: http://stackoverflow.com/q/48238968
type: Tag
tags question: http://stackoverflow.com/q/48280153
tag name: zip
tags question: http://stackoverflow.com/q/48307878
tags question: http://stackoverflow.com/q/48175757

http://stackoverflow.com/comment/83371503
comment on: http://stackoverflow.com/q/48195226
has text: Please post `ExampleDF.info()` and `ExampleDF.iloc[-1].dtype`.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83636495
score: 1
comment on: http://stackoverflow.com/q/48325478
has text: What library are you using to send that to Excel?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83455766
type: QuestionComment
has text: Your question is really unclear, can you try rephrasing what the problem you're trying to solve is? And, at any rate, you almost certainly don't want to be using `cgi`. You probably want to look into a framework, such as `Flask` that uses jinja templating.
type: Comment
comment on: http://stackoverflow.com/q/48236529
score: 0

http://stackoverflow.com/a/69434972
score: 0
answers question: http://stackoverflow.com/q/48287404
has body: Please try to remove the semicolon after "SET NOCOUNT ON" and then run the script.
type: Answer
has comment: http://stackoverflow.com/comment/122730017

http://stackoverflow.com/q/48325601
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/48323981
tagged with: string
answer count: 1
type: Question
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48335380
tagged with: python
has answer: http://stackoverflow.com/a/48335380
has body: I have the following code from this question Df groupby set comparison: import pandas as pd wordlist = pd.read_csv('data/example.txt', sep='\r', header=None, index_col=None, names=['word']) wordlist = wordlist.drop_duplicates(keep='first') # wordlist['word'] = wordlist['word'].astype(str) wordlist['split'] = '' wordlist['anagrams'] = '' for index, row in wordlist.iterrows() : row['split'] = list(row['word']) anaglist = wordlist['anagrams'] = wordlist['word'].apply(lambda x: ''.join(sorted(list(x)))) wordlist['anagrams'] = anaglist wordlist = wordlist.drop(['split'], axis=1) wordlist = wordlist['anagrams'].drop_duplicates(keep='first') print(wordlist) print(wordlist.dtypes) Some input in my example.txt file seems to be being read as ints, particularly if the strings are of different character lengths. I can't seem to force pandas to see the data as strings using .astype(str) What's going on?
has title: Pandas keeps converting strings to int

http://stackoverflow.com/comment/83669609
has text: Oh, this method is really not implemented! Thanks for point this out! Feel free to send pull request on GitHub. New method should be very simple like [is_selected at line 1393 of common_controls.py](https://github.com/pywinauto/pywinauto/blob/master/pywinauto/controls/common_controls.py#L1393).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48315572
score: 0

http://stackoverflow.com/comment/83639940
has text: @rnso thats like a nuking a house to get rid of a spider
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48327207
score: 0

http://stackoverflow.com/q/48201634
has answer: http://stackoverflow.com/a/48202963
has title: Check empty lines in Python
favorite count: 0
type: Question
has body: I have a text file which contains multiple number of lines. I want to check a specific line (calling xyz ...) in present or not in between two line(++ start line and -- exiting line). If the line (calling xyz ...) is present then it should return the line and if line is not present then NULL value should be return. I want to store the result in to a list. Example file: ++ start line 22 15:36:53 dog, cat, monkey, rat calling xxxxx animal already added -- exiting line Above block of line should add calling xxxxx to list. ++ start line 12 12:56:34 cat, camel, cow, dog animal already added -- exiting line In above block calling xyz is missing so it should add NULL to the list Expected Output calling xxxxx NULL
has answer: http://stackoverflow.com/a/48203151
possible better answer: http://stackoverflow.com/a/48202963
tagged with: python
has comment: http://stackoverflow.com/comment/83384410
tagged with: regex
has answer: http://stackoverflow.com/a/48201895
accepted answer: http://stackoverflow.com/a/48201895
has comment: http://stackoverflow.com/comment/83384170
tagged with: text
type: AnsweredQuestion
answer count: 3
score: 1
upvote count: 3
downvote count: 2

http://stackoverflow.com/a/48278030
score: 4
answers question: http://stackoverflow.com/q/48277722
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48277722
upvote count: 4
has body: Your code should remain that way: selected_services = forms.CharField(label="Selected_services *", widget=forms.Textarea()) Defining the TextArea widget becomes a TextField and the max_length attribute is not required
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83360830
type: QuestionComment
comment on: http://stackoverflow.com/q/48189768
has text: I think there's not a defined spaces or tabs between colums.
score: 0
type: Comment

http://stackoverflow.com/comment/83340919
has text: Because n is changing, "for" may have been a poor choice, but this is the closest. Nevertheless, you shouldn't post spoilers for challenge sites. The question is https://projecteuler.net/problem=3
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48180217

http://stackoverflow.com/comment/83335906
comment on: http://stackoverflow.com/q/48177832
has text: make your batch size smaller or in your case just split your dataset into batches and use mini-batch training approach
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/132463071
comment on: http://stackoverflow.com/a/56043773
has text: what is fit_generator? No context for this comment.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48204570
downvote count: 1
has answer: http://stackoverflow.com/a/48204956
has comment: http://stackoverflow.com/comment/83390429
favorite count: 0
type: Question
has body: I'm beginner in python. I'm trying to read my database and write into json file with following format {"intents": [ {"tag": "greeting", "patterns": ["hello"], "responses": ["hello"] }, {"tag": "greeting", "patterns": ["are you fine"], "responses": ["yeah"] } ] } I've following database tag patterns responses greeting hello hello greeting are you fine yeah I've tried this code: connection = sqlite3.connect('database.db') c = connection.cursor() def writeToJSONFile(path, fileName, data): filePathNameWExt = './' + path + '/' + fileName + '.json' with open(filePathNameWExt, 'w') as fp: json.dump(data, fp) result = c.execute("SELECT * FROM reply").fetchall() data = {} data['intents'] = [{***some code here***}] writeToJSONFile('./','intents',data) I'm unable to write code for json part. Any help, suggestion are welcome
has comment: http://stackoverflow.com/comment/83390291
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83417306
type: AnsweredQuestion
has title: convert database into json with specific format in python
upvote count: 0
tagged with: http://stackoverflow.com/tag/json
answer count: 1
accepted answer: http://stackoverflow.com/a/48204956

http://stackoverflow.com/q/48212572
tagged with: module
tagged with: buildroot
type: AnsweredQuestion
has title: Add a pypi python package to buildroot
accepted answer: http://stackoverflow.com/a/48221822
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48221822
upvote count: 1
favorite count: 0
type: Question
has body: I'm trying to integrate python3-functionfs module into buildroot. I'm able to select it with make menuconfig but when I'm running make the package isn't even downloaded. The package is available here : functionfs-0.3 pypi page And the download url here : functionfs-0.3 download link There is also the github repo here : functionfs git repository I'm using Buildroot 2017.02 version. Here is my Config.in file : config BR2_PACKAGE_PYTHON3_FUNCTIONFS bool "python3-functionfs" depends on BR2_PACKAGE_PYTHON3 help Pythonic API for linux’s functionfs. functionfs is part of the usb gadget subsystem. Together with usb_gadget’s configfs integration, allows userland to declare and implement an USB device. https://pypi.python.org/pypi/functionfs And here is my .mk file : ################################################################################ # # python3-functionfs # ################################################################################ PYTHON_FUNCTIONFS_VERSION = 0.3 PYTHON_FUNCTIONFS_SOURCE = functionfs-$(PYTHON_FUNCTIONFS_VERSION).tar.gz PYTHON_FUNCTIONFS_SITE = https://pypi.python.org/packages/e3/2d/56e0d9ffe0da7c116a6724ee538375689dd59e34dbe1676edf6b66b52be4 PYTHON_FUNCTIONFS_LICENSE = GPLv3+ PYTHON_FUNCTIONFS_LICENSE_FILE = COPYING PYTHON_FUNCTIONFS_SETUP_TYPE = setuptools $(eval $(python-package)) The documentation also mentions at 17.8.3. Generating a python-package from a PyPI repository If the Python package for which you would like to create a Buildroot package is available on PyPI, you may want to use the scanpypi tool located in utils/ to automate the process. You can find the list of existing PyPI packages here. scanpypi requires Python’s setuptools package to be installed on your host. When at the root of your buildroot directory just do : utils/scanpypi foo bar -o package This will generate packages python-foo and python-bar in the package folder if they exist on https://pypi.python.org. Find the external python modules menu and insert your packa…
tagged with: linux
tagged with: package
score: 1
tagged with: python

http://stackoverflow.com/q/48265893
linked to: http://stackoverflow.com/q/2351008
has body: Can Python invoke the Java Framework? I want to know whether a Python project can invoke a Java Framework, I find a Java Framework in GitHub, whether I can use it in my Python project?
has comment: http://stackoverflow.com/comment/83514902
has answer: http://stackoverflow.com/a/48267024
tagged with: python
has comment: http://stackoverflow.com/comment/83515060
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48266588
answer count: 2
downvote count: 0
has title: Can Python invoke the Java Framework?
score: 1
upvote count: 1
tagged with: java
has comment: http://stackoverflow.com/comment/83514999
accepted answer: http://stackoverflow.com/a/48267024
has comment: http://stackoverflow.com/comment/83515037
favorite count: 0
possible better answer: http://stackoverflow.com/a/48266588
type: Question

http://stackoverflow.com/q/48280793
has comment: http://stackoverflow.com/comment/83545194
has answer: http://stackoverflow.com/a/48289233
tagged with: pandas
has title: Save loop output with list into dictionary in Python
score: 1
tagged with: dataframe
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48282345
type: Question
has comment: http://stackoverflow.com/comment/83553924
has comment: http://stackoverflow.com/comment/83552943
has comment: http://stackoverflow.com/comment/83547240
answer count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83545286
has comment: http://stackoverflow.com/comment/83545749
tagged with: python
tagged with: dictionary
has body: I have some point codes in two column and I'm looking for a path between them. For example: COL_A COL_B B1011 B1012 B1012 B1014 B1013 B2017 B1014 B1018 ... B1018 B2022 For each of them I need a path from the first untill the last (without broke). For example, for B1011 it will B1012,B1014, B1018, ...B2022. I have write a code which goes through all values and put it in the list, but in that version I need to input string of the point code. Now I need to automated it and return dictionary as an output. For example {'B1011' : ['B1012', 'B1014', 'B1018', ...'B2022'], ... } Code I have: list_for_output = [] def func_top(x,num): for i in range(len(x[x.COL_A==num])): list_for_output.append(x[x.COL_A==num]['COL_B'].iloc[i]) for i in range(len(x[x.COL_A==num])): if x[x.COL_A==list_for_output[-(i+1)]].empty == True: return else: func_top(x,list_for_output[-(i+1)]) return How to add output to dictionary in form : {COL_A:list_for_output} for each row in dataframe? Thanks. Desired output: {'B1011' : ['B1012', 'B1014', 'B1018', ...'B2022'], 'B1012': ['B1014', 'B1018', ...'B2022'], 'B1014':['B1018', ...'B2022'], 'B1013':['B2017'],... }

http://stackoverflow.com/comment/83561191
has text: Thanks!!! As suggested i added sml1=sml[0] but getting Indexerror,Can you please advice what is the issue dict1={"one":1,"two":2,"three":3} list1=[] for i in range(len(dict1)): sml =[a for a in dict1.values() if a ==min(dict1.values()) and a not in list1] key1=[k for k,v in dict1.items() if v ==min(dict1.values()) and v not in list1] sml1=sml[0] list1.append(sml1) print(sml1) print(list1)
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48287841

http://stackoverflow.com/a/48267504
has body: For you 1st question piv.columns=piv.columns.map('_'.join) piv Out[431]: out_1_y out_1_z out_2_y out_2_z label 1 3.5 1.5 13.5 15.5 2 11.5 9.5 5.5 7.5
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48265340
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48265340

http://stackoverflow.com/a/48198940
answers question: http://stackoverflow.com/q/48198885
has comment: http://stackoverflow.com/comment/83379093
type: AcceptedAnswer
downvote count: 0
has body: You can implement the groups as mixins. For example like this: user_actions.py class UserActions: def user_create(...): ... the_api.py from . import user_actions class TheApi(UserActions, ItemActions, OtherActions, ...): # common functionality goes here Then you can call the_api_instance.user_create(...) once you have an object created.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48198885
score: 1
type: Answer

http://stackoverflow.com/comment/83559980
score: 0
type: Comment
has text: I have a .txt file along with my transfer.py file in the same directory. I need the .txt file to get some output from the transfer.py file. Do u think I need to schedule the .txt file as well like I did to the .py file? @MikeTung
comment on: http://stackoverflow.com/a/48287253
type: AnswerComment

http://stackoverflow.com/a/48312845
type: Answer
score: 0
has body: I think you need Erlang Script. But I don't recommend you this. I think you should do it as Mathieu Kerjouan said. If you insist on doing what your said, please consider solution below: Start your Erlang application as a daemon. Use escript to communicate with your application by Erlang's rpc. Control the escript in your python code.
answers question: http://stackoverflow.com/q/48294028

http://stackoverflow.com/comment/83577282
comment on: http://stackoverflow.com/q/48295661
has text: I dont think so. Can you if possible make an example or point me to the link which can verify when you say "I'm quite sure RandomizedSearchCV object points to the estimator objects"
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/48300191
answers question: http://stackoverflow.com/q/48298787
has body: I solved it by adding tf.convert_to_tensor (Image) after the Image =[[[[1, 1, 1,1], [2, 2, 2,2]], [[3,3, 3, 3], [4,4, 4, 4]]]]
type: Answer
score: 0

http://stackoverflow.com/a/48199808
has comment: http://stackoverflow.com/comment/83446490
has comment: http://stackoverflow.com/comment/83380690
has comment: http://stackoverflow.com/comment/83392170
answers question: http://stackoverflow.com/q/48199688
has comment: http://stackoverflow.com/comment/83406856
type: Answer
accepted answer of: http://stackoverflow.com/q/48199688
score: 0
type: AcceptedAnswer
has body: It's hard to understand what you're trying to do, but you can first reduce redundant code like this: def calculo(items): wints = numpy.zeros(len(items), dtype=int) if items[0][0] &gt; items[0][1]: wints += [1,1,0,0,0] # players 12 else: wints += [0,0,1,1,0] # players 34 if items[1][0] &gt; items[1][1]: wints += [1,0,0,0,1] # players 15 else: wints += [0,1,1,0,0] # players 23 if items[2][0] &gt; items[2][1]: wints += [1,0,0,1,0] # players 14 else: wints += [0,1,0,0,1] # players 25 if items[3][0] &gt; items[3][1]: wints += [1,0,1,0,0] # players 13 else: wints += [0,0,0,1,1] # players 45 if items[4][0] &gt; items[4][1]: wints += [0,1,0,1,0] # players 24 else: wints += [0,0,1,0,1] # players 35 return wints There seems to be a pattern here... def one_hot_encode(players, n): arr = numpy.zeros(n + 1, dtype=int) arr[players] = 1 return arr[1:] def calculo(scores, pairings, n_players): wints = numpy.zeros(n_players, dtype=int) for (s1, s2), (p1, p2) in zip(scores, pairings): winner = p1 if s1 &gt; s2 else p2 wints += one_hot_encode(winner, n_players) return wints scores = [[118, 28], [128, 66], [26, 133], [111, 0], [57, 109]] pairings = [ [[1,2],[3,4]], [[1,5],[2,3]], [[1,4],[2,5]], [[1,3],[4,5]], [[2,4],[3,5]] ] print(calculo(scores, pairings, 5)) Outputs: [3 2 2 0 3] You can generate the pairings as you desire.
has comment: http://stackoverflow.com/comment/83393433

http://stackoverflow.com/q/48323434
tagged with: python
tagged with: regex-group
tagged with: regex
has comment: http://stackoverflow.com/comment/83632347
answer count: 2
tagged with: regex-negation
downvote count: 0
upvote count: 1
has body: assuming the following sentence: this is @sys.any and. here @names hello. and good.bye how would I find all the '.' besides the ones appearing in words that start with @? disclaimer, been playing at regex101 for over 2 hours now after reading a few answers on SO and other forums.
has title: Regex find char '.' except for words starting with @
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48323739
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48323646
tagged with: javascript

http://stackoverflow.com/comment/83418963
comment on: http://stackoverflow.com/q/48216921
has text: That's twice you've said 'further encrypt' in relation to pickle. Pickling does not encrypt in any way. If you want the pickled data to be encrypted then you pass encrypted data to pickle.dump(). Another option is to pickle.dumps() to a string, encrypt that and write it to a file. Perhaps an interesting exercise, but as mentioned don't trust real passwords to this method.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83506280
has text: Sorry, I should've listed jq as a dependency. It's so handy, I'm beginning to take it for granted. It's like sed for json. It could be replaced with an xpath xml tool, if you want.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48251635
score: 0

http://stackoverflow.com/q/48242217
has comment: http://stackoverflow.com/comment/83466878
has comment: http://stackoverflow.com/comment/83466890
has body: I have a file containing some json which I load and loop through the "servers" items and pass them to a send_alert() method (items marked "REDACTED" are not the real code/output): "servers": [ { "address": "smtp.gmail.com", "encrypted-password": "Copy and Paste from 'password' after encryption.", "login-name": false, "port": 587, "type": "email" }, { "address": "smtp.mail.yahoo.com", "encrypted-password": "&lt;REDACTED&gt;", "login-name": "&lt;REDACTED&gt;@yahoo.com", "port": 587, "type": "email" }] I expect the gmail item to be skipped because it should render False or None for the 'login-name'... so I am really just processing the yahoo item: def send_alert(self, server, message, email): print(json.dumps(server, encoding=self.encoding, sort_keys=True, indent=2)) print(type(server)) print(server["login-name"]) username = getattr(server, "login-name", None) enc_pass = getattr(server, "encrypted-password", None) address = getattr(server, "password", None) port = getattr(server, "port", None) server_type = getattr(server, "type", None) mess = message if not username: print(username) self.log.warn("incorrectly configured alert!\n:%s", json.dumps(server, encoding=self.encoding, sort_keys=True, indent=2)) return False if server_type.lower() == "email": self.send_email(username, enc_pass, address, port, mess, email) else: self.log.debug("unknown server type listed in Alerts/servers") when send_alert is called, I receive the following output: { "address": "smtp.mail.yahoo.com", "encrypted-password": &lt;REDACTED&gt;, "login-name": "&lt;REDACTED&gt;@yahoo.com", "port": 587, "type": "email" } &lt;type 'dict'&gt; &lt;REDACTED&gt;@yahoo.com None [11:35:39] [Wrapper.py/WARNING]: incorrectly configured alert! :{ "address": "smtp.mail.yahoo.com", "encrypted-password": &lt;REDACTED&gt;, "login-name": "&lt;REDACTED&gt;@yahoo.com", "port": 587, "type": "email" } I would like to use getattr, versus testing (if "login-name" in server:) or try-excepting the values. I have done this in …
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83466850
linked to: http://stackoverflow.com/q/38018475
has comment: http://stackoverflow.com/comment/83466927
type: AnsweredQuestion
score: 3
tagged with: python-2.7
upvote count: 3
has title: getattr returns a default even though attribute exists in dict keys
accepted answer: http://stackoverflow.com/a/48242355
answer count: 1
has answer: http://stackoverflow.com/a/48242355
has comment: http://stackoverflow.com/comment/83466865
has comment: http://stackoverflow.com/comment/83466916
favorite count: 0
has comment: http://stackoverflow.com/comment/83466917
type: Question
has comment: http://stackoverflow.com/comment/83466960
tagged with: python-3.x

http://stackoverflow.com/comment/83641121
type: Comment
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/48327787
has text: And you don't need `else: pass`

http://stackoverflow.com/a/48291135
answers question: http://stackoverflow.com/q/48290623
score: 0
type: Answer
has body: Why not import it as follows: from sklearn.linear_model import LinearRegression In my opinion it is much cleaner than what you did. You can then use it like that: lr = LinearRegression()

http://stackoverflow.com/comment/83560061
type: QuestionComment
has text: Use `print` statements in your script to print out paths of files/scripts you are using in your code to debug the issue.
score: 0
comment on: http://stackoverflow.com/q/48286718
type: Comment

http://stackoverflow.com/q/48176087
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83332143
tagged with: pyinstaller
has title: Can't install Pyinstaller - alternatives?
tagged with: python
has body: using Python 3.6.0, Anaconda 4.3.0 at work and can't pip install. I have a basic data entry program that I'd like to roll out, but it's unrealistic unless it's a .exe file. At a previous job, I did this with pyinstaller, but this computer is pretty locked down and I can't install much. Tried py2exe and got the "ModuleNotFoundError" and sure enough, it looks like it's not in my package library, though I'm not sure it normally is in 4.3. Do I have any other options that are realistic for a novice? I appreciate the help!
score: 0
tagged with: anaconda
answer count: 0
has comment: http://stackoverflow.com/comment/83333871
has comment: http://stackoverflow.com/comment/83332161
tagged with: py2exe
type: Question

http://stackoverflow.com/comment/83331322
has text: These arbitrary restrictions surely sound like an assignment. And what is it - exactly or at least two vowels? Text and headline say different things.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48175689

http://stackoverflow.com/a/48174402
accepted answer of: http://stackoverflow.com/q/48174361
has body: I believe that the best approach to this would be to make the following change and updated execute() with num_retries=n where n can be any integer you would like. response = service.projects().predict( name=name, body={'instances': instances} ).execute(num_retries=2)
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48174361
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48209506
type: Question
upvote count: 4
tagged with: pycharm
answer count: 5
has body: Please go easy on me, its my first days trying to use python and I already have problem with setting up enviroment. When I use IDLE with code: import pandas as pd column_names = ["a,b"] dataset = pd.read_csv('abdataset', names = column_names, index_col = False) dataset shows the whole dataset in quite good way. Whenever when I try same code on PyCharm and go RUN on the console I can only see Process finished with exit code 0 Is there any way to configure run console to show output like IDLE do?
downvote count: 0
possible better answer: http://stackoverflow.com/a/66279257
score: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48209601
has title: PyCharm shows no output from pandas
has answer: http://stackoverflow.com/a/54492527
tagged with: pandas
has answer: http://stackoverflow.com/a/48209596
tagged with: python
accepted answer: http://stackoverflow.com/a/48211182
has answer: http://stackoverflow.com/a/66279257
has answer: http://stackoverflow.com/a/48211182
favorite count: 0

http://stackoverflow.com/a/48306489
has comment: http://stackoverflow.com/comment/83602776
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48306295
has comment: http://stackoverflow.com/comment/83602819
has comment: http://stackoverflow.com/comment/83616238
score: 1
has body: I'm using this utility function to extract all text elements from PDF: from pdfminer.converter import PDFPageAggregator from pdfminer.layout import LAParams, LTTextBox, LTTextLine from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfinterp import PDFPageInterpreter, PDFResourceManager from pdfminer.pdfpage import PDFPage, PDFTextExtractionNotAllowed from pdfminer.pdfparser import PDFParser def pdf2text(stream): parser = PDFParser(stream) document = PDFDocument(parser) if not document.is_extractable: raise PDFTextExtractionNotAllowed resmgr = PDFResourceManager() laparams = LAParams() device = PDFPageAggregator(resmgr, laparams=laparams) interpreter = PDFPageInterpreter(resmgr, device) for page in PDFPage.create_pages(document): interpreter.process_page(page) for obj in device.get_result(): if isinstance(obj, (LTTextBox, LTTextLine)): yield obj.get_text() stream parameter is a file-like object (e.g. file opened for reading or an instance of io.BytesIO or such). This example basically follows official example.
type: Answer
has comment: http://stackoverflow.com/comment/83598619
has comment: http://stackoverflow.com/comment/83602155

http://stackoverflow.com/comment/83490331
comment on: http://stackoverflow.com/q/48253844
type: QuestionComment
has text: It'd be helpful if you can post the first few rows of `X_train`, before `labelencoder_X.fit_transform()` and then as it looks when passed to `onehotencoder.fit_transform()`. That might reveal what's not working with your encoding schema. (Also, consider the Pandas method `get_dummies` as an alternate option.)
score: 0
type: Comment

http://stackoverflow.com/q/48269712
accepted answer: http://stackoverflow.com/a/48270362
has answer: http://stackoverflow.com/a/48270362
tagged with: python
linked to: http://stackoverflow.com/q/41507829
tagged with: ipython
score: 6
tagged with: timeit
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83523962
has body: I am trying to the run the following code but I get a local variable 'a' referenced before assignment. a = [x for x in range(10)] b = [x for x in range(10)] %timeit a+=b The statement works without the %timeit magic. Is there something I am missing? Thank you.
has title: ipython %timeit "local variable 'a' referenced before assignment"
answer count: 1
has comment: http://stackoverflow.com/comment/83523899
upvote count: 7
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83522901

http://stackoverflow.com/comment/83568780
comment on: http://stackoverflow.com/q/48291699
has text: @Olivier fair question, but we're given no reason to think so and I don't think it's important to the answer.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48270362
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/48269712
has comment: http://stackoverflow.com/comment/83529929
accepted answer of: http://stackoverflow.com/q/48269712
type: Answer
has comment: http://stackoverflow.com/comment/83530838
has body: What do you expect it to do? Outside of the timeit it does: In [188]: a += b In [189]: a Out[189]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] I tried initializing x, and got a near infinite loop, eventually ending with a memory error In [192]: %%timeit x=a ...: x += b In [194]: len(a) Out[194]: 529076630 In other words each timeit loop concatenated another list of b values to x (and by extension a), resulting are very long loop. I suspect an individual x+=b was fast, resulting in timeit choosing to loop many times. Lets create an a fresh each loop: In [196]: %%timeit ...: a = [x for x in range(10)] ...: a += b ...: 1.91 µs ± 4.82 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) This produces the memory error as well: In [197]: %%timeit a = [x for x in range(10)] ...: a += b If I control the number of loops: In [202]: %%timeit -n 100 a = [x for x in range(10)] ...: a += b ...: ...: 208 ns ± 11 ns per loop (mean ± std. dev. of 7 runs, 100 loops each) With ns times I can see why the default loops is so large. I haven't tried timing a plain a+=... before (not even with numpy arrays), but evidently it expects some sort of local initialization for that a, either within the loop or in the initialization block. But it is important to keep in mind that the timed actions may be performed many times (the -r and -n parameters or the default values). So any in-place action might result bit changes to the global values. In this case timeit might be trying to protect us from that kind of unexpected growth, by expecting some sort of 'local' variable. Lets try the a+b, but with an assignment: In [215]: c=np.zeros(10) In [216]: a Out[216]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) In [217]: b Out[217]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [218]: %timeit c = a+b 5.33 µs ± 105 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [219]: c Out[219]: array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) Notice that the global c has not changed. The assignment…
has comment: http://stackoverflow.com/comment/83529671
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/q/48287815
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 4
answer count: 0
type: UnansweredQuestion
tagged with: python
score: 4
has title: getting values from tf.estimator.EstimatorSpec
has body: The returned EstimatorSpec Object is iterable when the PREDICT ModeKey is passed to tf.estimator.Estimator. predictions = { 'class_ids': tf.argmax(input=logits, axis=1), 'logits': logits } if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode, predictions=predictions) then, prediction_results = classifier.predict(input_fn=prediction_dataset_input) for x, each in enumerate(prediction_results): print(each) produces a line for each of the predictions like this; .... {'class_ids': 1, 'logits': array([-32976400., -30171870.], dtype=float32)} {'class_ids': 1, 'logits': array([-32958380., -30386898.], dtype=float32)} {'class_ids': 1, 'logits': array([-32940332., -30601930.], dtype=float32)} {'class_ids': 1, 'logits': array([-32922300., -30816956.], dtype=float32)} .... How could I get the TRAIN ModeKey to return something that is iterable? Ideally, I would like to print each feature value used and the computed logit at defined steps in the training. I am returning; if mode == tf.estimator.ModeKeys.TRAIN: return tf.estimator.EstimatorSpec( mode, loss=loss, predictions=predictions, train_op=train_objective) then, prediction_results = classifier.train(input_fn=lambda: dataset_input_fn( file_dataset_feed, perform_shuffle=True, repeat_count=100)) for x, each in enumerate(prediction_results): print(each) produces; TypeError: 'Estimator' object is not iterable
downvote count: 0

http://stackoverflow.com/a/48302873
downvote count: 0
upvote count: 1
has body: I think the correct syntax should be datetime.date(year, month, day) myvariable = (2008, 11, 10) var = datetime.date(myvariable[0],myvariable[1],myvariable[2]) now var has datetime object. For Further methods you can refer this link
type: Answer
answers question: http://stackoverflow.com/q/48302639
score: 1

http://stackoverflow.com/comment/83423570
comment on: http://stackoverflow.com/a/48220791
type: Comment
has text: By passing the full path into the Pillow save method.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48260418
has comment: http://stackoverflow.com/comment/83503690
downvote count: 1
tagged with: python
has title: Python can't get polyfit function to work
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83503765
has comment: http://stackoverflow.com/comment/83503781
score: 0
upvote count: 1
has body: I have an array "uniqueMonths" with 12 elements (1 to 12) and one array of 8991 values. I want to use polyfit function to these values, but I don't get any output on aa variable and no error code either. Maybe you could help me what is wrong? Code: aa = np.polyfit(uniqueMonth,values, 1)

http://stackoverflow.com/q/48249425
type: Question
has comment: http://stackoverflow.com/comment/83482548
upvote count: 2
tagged with: python-imaging-library
type: UnansweredQuestion
has body: I was trying to build Fisherfaces(https://github.com/bytefish/facerec) on my Mac(OS X 10.12.6), and I successfully built its dependencies including sklearn, numpy, scipy, matplotlib except Pillow. So I tried : pip3 install Pillow at first I failed out of some network issue, so I tried again, and at last, I get this from terminal: Installing collected packages: pillow Successfully installed pillow-5.0.0 but then I tried on terminal: TreaserdeMacBook-Pro:scripts treasersmac$ python3 Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13) [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 PIL Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'PIL' and when I use python instead of python3, still get the same question. Then I check the pip3 list: TreaserdeMacBook-Pro:scripts treasersmac$ pip3 list DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning. cycler (0.10.0) Django (2.0.1) image (1.5.17) matplotlib (2.0.0) nose (1.3.7) numpy (1.12.0) Pillow (5.0.0) pip (9.0.1) pygal (1.7.0) pyparsing (2.1.10) python-dateutil (2.6.0) pytz (2016.10) requests (2.13.0) scikit-learn (0.19.1) setuptools (36.5.0) six (1.10.0) wheel (0.30.0) seemed OK. Then I checked path: &gt;&gt;&gt; import sys &gt;&gt;&gt; print(sys.path) ['', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Users/treasersmac/Library/Python/3.6/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages'] and PIL or Pillow was in: /usr/local/lib/python3.6/site-packages but: TreaserdeMacBo…
tagged with: python
has comment: http://stackoverflow.com/comment/83495606
score: 2
answer count: 0
downvote count: 0
tagged with: pip
has comment: http://stackoverflow.com/comment/83481529
tagged with: macos
has title: Installed Pillow but still get : ModuleNotFoundError: No module named 'PIL'
favorite count: 0

http://stackoverflow.com/q/48202962
type: Question
tagged with: object-detection-api
accepted answer: http://stackoverflow.com/a/48203320
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48203320
has body: When i run export_inference_graph.py with the correct paths from the object_detection folder, or from the models/research folder like this: python export_inference_graph \ # object_detection/ (if from /research) --input_type image_tensor \ --pipeline_config_path path/to/ssd_inception_v2.config \ --trained_checkpoint_prefix path/to/model.ckpt \ --output_directory path/to/exported_model_directory then i got following error: File "object_detection/export_inference_graph.py", line 71, in &lt;module&gt; from object_detection import exporter File "/usr/local/lib/python2.7/dist-packages/tensorflow/models/research/object_detection/exporter.py", line 28, in &lt;module&gt; from object_detection.builders import model_builder File "/usr/local/lib/python2.7/dist-packages/tensorflow/models/research/object_detection/builders/model_builder.py", line 17, in &lt;module&gt; from object_detection.builders import anchor_generator_builder File "/usr/local/lib/python2.7/dist-packages/tensorflow/models/research/object_detection/builders/anchor_generator_builder.py", line 20, in &lt;module&gt; from object_detection.protos import anchor_generator_pb2 ImportError: cannot import name anchor_generator_pb2 Inside anchor_generator_builder.py it tries to import anchor_generator_pb2 but a file with this name does not exist. Additional Info: - Yes i added the libraries with: # From tensorflow/models/research/ export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim - Yes i pulled the latest tensorflow/models version Please tell me how to properly export a new Frozen Graph, i think this should be really easy, but it stops my whole work. Thank you guys in advance
type: AnsweredQuestion
has title: Error running export_inference_graph.py in Object Detection API
score: 1
answer count: 1
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/83552532
type: QuestionComment
comment on: http://stackoverflow.com/q/48272799
has text: Again, do you want XML output or parsed text output?
score: 0
type: Comment

http://stackoverflow.com/q/48272738
answer count: 0
downvote count: 0
favorite count: 0
type: Question
has title: RaspberryPi, collectd python plugin, rrd, CGP based occupancy logging/sensing (PIR & Sound)
tagged with: python
tagged with: plugins
type: UnansweredQuestion
tagged with: collectd
score: 2
upvote count: 2
has body: I've got a PIR and a sound sensor working on my Pi ZeroW. I also have a python script that opens a listening socket and handles the 'sound' or 'motion' interrupts. For each sound/motion event it increments a value which can be read over the socket connection and gets reset to zero after a successful read. I have created 2 collectd python plugins 'motion.py' and 'sound.py' and they are creating rrd data and graphs in CGP (collectd graph panel) but they are two separate plugins. What I'd really like it to have: A stacked graph showing the two variables summed together (memory usage style) A line graph showing both variables but not summed (load style) and for both to have them updating once per minute (instead of every 10 secs). What I have so far is as follows: I've defined a type 'occupation' in ~/collectd/types.db.local and in ~/cgp/inc/types.db ... occupation motion:GAUGE:0:U, sound:GAUGE:0:U motion value:GAUGE:0:U sound value:GAUGE:0:U ... In ~/cgp/plugin I have occupation.json { "occupation": { "title": "Occupancy on {{HOST}}", "vertical": "Events", "type": "stacked", "legend": { "motion": { "name": "Motion", "color": "0000f0" }, "sound": { "name": "Sound", "color": "ff00f0" } }, "legend_format": "%.1lf" } } and my occupation.py plugin is as follows: /usr/share/pi/occupation/bin/occupation.py import collectd import socket import sys server_name = 'localhost' server_port = 10000 def config_func(config): collectd.info('config called') def read_occupation(): collectd.info('read_occupation called') # Read raw value # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) global server_name global server_port server_address = (server_name, server_port) sock.connect(server_address) sock.sendall('MOVEMENT') motion = sock.recv(16) sock.sendall('SOUND') sound = sock.recv(16) sock.close() # Dispatch value to collectd val1 = collectd.Values() val1.plugin = 'occupation' val1.type = 'occupation' val1.values = [motion, sound] val1.dispatch() collectd.…

http://stackoverflow.com/a/50205632
has body: Bokeh developers have added an option to redirect the output logger directly &gt; bokeh serve --help [...] --log-level LOG-LEVEL One of: trace, debug, info, warning, error or critical --log-format LOG-FORMAT A standard Python logging format string (default: '%(asctime)s %(message)s') --log-file LOG-FILE A filename to write logs to, or None to write to the standard stream (default: None)
type: Answer
accepted answer of: http://stackoverflow.com/q/48322241
score: 1
answers question: http://stackoverflow.com/q/48322241
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83553905
has text: Try doing a dir on one of those chat objects: dir(client.chats.list()[0]) Should show you the possible attributes of the object. The message is probably in a .text attribute. Maybe it has some other useful metadata :)
score: 0
comment on: http://stackoverflow.com/q/48284617
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48273371
tagged with: python
has body: I am trying to read a csv file through python pandas.read_csv() method. If if specify delimiter="_" in the argument, I am getting an error. Appreciate your suggestions. Code: pandas.read_csv('D:/Coding/data/Sample.csv',header=None,delimiter="_") CSV data format: Company1_A_EPS5,2016-03-31,-0.31,-0.31 Error: ParserError: Error tokenizing data. C error: Expected 3 fields in line 309, saw 4
tagged with: delimiter
has comment: http://stackoverflow.com/comment/83530798
tagged with: tokenize
has comment: http://stackoverflow.com/comment/83535323
tagged with: pandas
answer count: 0
downvote count: 0
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83683133
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
score: 1
has title: Python Pandas reading csv file - Need to delimit the first data item by _
has comment: http://stackoverflow.com/comment/83530779

http://stackoverflow.com/comment/83528875
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48272389
type: QuestionComment
has text: @srig unfortunately getting the 250th unique value isn't what I need. I need the 250th value regardless of uniqueness. The duplicates aren't important in the list, but they are meaningful when it comes to using the output.

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/48214481
tags question: http://stackoverflow.com/q/48280129
type: Tag
tags question: http://stackoverflow.com/q/48306253
tags question: http://stackoverflow.com/q/48242125
tags question: http://stackoverflow.com/q/48305970
tags question: http://stackoverflow.com/q/48233175
tags question: http://stackoverflow.com/q/48257321
tags question: http://stackoverflow.com/q/48239455
tags question: http://stackoverflow.com/q/48192424
tags question: http://stackoverflow.com/q/48250995
tags question: http://stackoverflow.com/q/48302352
tags question: http://stackoverflow.com/q/48273267
tags question: http://stackoverflow.com/q/48179906
tags question: http://stackoverflow.com/q/48178475
tags question: http://stackoverflow.com/q/48193090
tags question: http://stackoverflow.com/q/48250655
tags question: http://stackoverflow.com/q/48235494
tags question: http://stackoverflow.com/q/48180777
tags question: http://stackoverflow.com/q/48229422
tags question: http://stackoverflow.com/q/48299320
tags question: http://stackoverflow.com/q/48240169
tags question: http://stackoverflow.com/q/48206402
tags question: http://stackoverflow.com/q/48218076
tags question: http://stackoverflow.com/q/48244194
tags question: http://stackoverflow.com/q/48252855
tags question: http://stackoverflow.com/q/48185449
tags question: http://stackoverflow.com/q/48288164
tag name: csv
tags question: http://stackoverflow.com/q/48190161
tags question: http://stackoverflow.com/q/48277120
tags question: http://stackoverflow.com/q/48327221
tags question: http://stackoverflow.com/q/48297173
tags question: http://stackoverflow.com/q/48179772
tags question: http://stackoverflow.com/q/48249658
tags question: http://stackoverflow.com/q/48203931
tags question: http://stackoverflow.com/q/48218134
tags question: http://stackoverflow.com/q/48205371
tags question: http://stackoverflow.com/q/48203832
tags question: http://stackoverflow.com/q/48294616
tags question: http://stackoverflow.com/q/48320483
tags question: http://stackoverflow.com/q/48309759
tags question: http://stackoverflow.com/q/48194261
tags question: http://stackoverflow.com/q/48272012
tags question: http://stackoverflow.com/q/48291093
tags question: http://stackoverflow.com/q/48270074
tags question: http://stackoverflow.com/q/48324715
tags question: http://stackoverflow.com/q/48213605
tags question: http://stackoverflow.com/q/48179035
tags question: http://stackoverflow.com/q/48268624
tags question: http://stackoverflow.com/q/48217392
tags question: http://stackoverflow.com/q/48207478
tags question: http://stackoverflow.com/q/48240345
tags question: http://stackoverflow.com/q/48210945
tags question: http://stackoverflow.com/q/48195202
tags question: http://stackoverflow.com/q/48329815
tags question: http://stackoverflow.com/q/48233433
tags question: http://stackoverflow.com/q/48252610
tags question: http://stackoverflow.com/q/48308560
tags question: http://stackoverflow.com/q/48259225
tags question: http://stackoverflow.com/q/48244857
tags question: http://stackoverflow.com/q/48197549
tags question: http://stackoverflow.com/q/48253582
tags question: http://stackoverflow.com/q/48251058
tags question: http://stackoverflow.com/q/48256408
tags question: http://stackoverflow.com/q/48187884
tags question: http://stackoverflow.com/q/48329810
tags question: http://stackoverflow.com/q/48204730
tags question: http://stackoverflow.com/q/48199811
tags question: http://stackoverflow.com/q/48285413
tags question: http://stackoverflow.com/q/48230216
tags question: http://stackoverflow.com/q/48298807
tags question: http://stackoverflow.com/q/48236378
tags question: http://stackoverflow.com/q/48214975
tags question: http://stackoverflow.com/q/48254034
tags question: http://stackoverflow.com/q/48190726
tags question: http://stackoverflow.com/q/48286420
tags question: http://stackoverflow.com/q/48273371
tags question: http://stackoverflow.com/q/48218781
tags question: http://stackoverflow.com/q/48273159

http://stackoverflow.com/comment/83366430
comment on: http://stackoverflow.com/a/48181043
type: Comment
has text: @FarazMasroor The last para explains it all together. If this answers your question, please accept this answer.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83482251
type: Comment
comment on: http://stackoverflow.com/a/48249833
has text: Thanks. I get `AttributeError: 'list' object has no attribute 'click'`.
score: 0
type: AnswerComment

http://stackoverflow.com/a/68075564
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48315785
has body: There is a pull request got pyinstaller... Actually, it is already merged into master. It adds this functionality: https://github.com/pyinstaller/pyinstaller/pull/4887 At the moment you will need to build the pyinstaller to have this, but it is feasible. I managed to do this for my project without any deep knowledge in c/c++ etc.

http://stackoverflow.com/comment/83540150
type: QuestionComment
comment on: http://stackoverflow.com/q/48275809
score: 0
type: Comment
has text: @juanpa.arrivillaga thanks. how do i convert keys to values and values to keys? this makes sense as values are unique.

http://stackoverflow.com/q/48303354
has answer: http://stackoverflow.com/a/48311477
has title: Find the intersection of two tensors. Return the sorted, unique values that are in both of the input tensors
type: AnsweredQuestion
upvote count: 3
score: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/48311477
has body: Hi Tensorflow Beginner here, I want to remove any numpy code in implementation and only use tensorflow functions. Currently I'm trying to filter out Background Bounding Boxes and boxes with a low confidence score. For that I want a index called keep that I can use to keep track of which boxes to keep: # Filter out background boxes keep = np.where(class_ids &gt; 0)[0] # Filter out low confidence boxes if config.DETECTION_MIN_CONFIDENCE: keep = np.intersect1d( keep, np.where(class_scores &gt;= config.DETECTION_MIN_CONFIDENCE)[0]) class_ids is a tensor of shape (1000,) where each entry is a number between 0 and 80 depending on the class (81 classes in total). class_scores is a tensor of shape (1000,) where each entry is a probability for the class of the corresponding bounding box. I know that np.where() is easily changed to tf.where but how can I get the same functionality as np.intersect1d() with tensorflow? Thanks for the help.
answer count: 1
tagged with: python
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/comment/83453431
has text: There is not any file problem ... it is something else @R2RT
type: QuestionComment
comment on: http://stackoverflow.com/q/48235048
score: 0
type: Comment

tuples
tags question: http://stackoverflow.com/q/48254096
tags question: http://stackoverflow.com/q/48178424
tags question: http://stackoverflow.com/q/48205443
tag name: tuples
tags question: http://stackoverflow.com/q/48227848
tags question: http://stackoverflow.com/q/48292790
tags question: http://stackoverflow.com/q/48220279
tags question: http://stackoverflow.com/q/48295381
tags question: http://stackoverflow.com/q/48176081
tags question: http://stackoverflow.com/q/48302639
tags question: http://stackoverflow.com/q/48220643
tags question: http://stackoverflow.com/q/48291861
tags question: http://stackoverflow.com/q/48311136
tags question: http://stackoverflow.com/q/48327371
tags question: http://stackoverflow.com/q/48234473
type: Tag
tags question: http://stackoverflow.com/q/48181949
tags question: http://stackoverflow.com/q/48178086

geometry
tags question: http://stackoverflow.com/q/48253800
tag name: geometry
type: Tag
tags question: http://stackoverflow.com/q/48271539

http://stackoverflow.com/q/48244076
downvote count: 0
answer count: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48245045
favorite count: 0
type: Question
tagged with: python-3.x
score: 1
tagged with: elasticsearch
tagged with: python
has body: I am unable to scan whole ElasticSearch index. ElasticSearch version: 1.7.5 I am trying to scan index but it always fail after 1000 documents fetched. res = helpers.scan(es, index="twitter", query={"query": {"match_all": {}}}, request_timeout=60) for hit in res: do_some_stuff() Traceback: WARNING:elasticsearch:GET http://example.com:9200/_search/scroll?scroll=5m [status:400 request:0.002s] WARNING:elasticsearch:DELETE http://example.com:9200/_search/scroll [status:400 request:0.001s] Traceback (most recent call last): File "/project/.env/lib/python3.5/site-packages/elasticsearch/helpers/__init__.py", line 301, in scan resp = client.scroll(scroll_id, scroll=scroll, request_timeout=request_timeout) File "/project/.env/lib/python3.5/site-packages/elasticsearch/client/utils.py", line 73, in _wrapped return func(*args, params=params, **kwargs) File "/project/.env/lib/python3.5/site-packages/elasticsearch/client/__init__.py", line 1024, in scroll params=params, body=body) File "/project/.env/lib/python3.5/site-packages/elasticsearch/transport.py", line 312, in perform_request status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout) File "/project/.env/lib/python3.5/site-packages/elasticsearch/connection/http_urllib3.py", line 128, in perform_request self._raise_error(response.status, raw_data) File "/project/.env/lib/python3.5/site-packages/elasticsearch/connection/base.py", line 125, in _raise_error raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info) elasticsearch.exceptions.RequestError: &lt;exception str() failed&gt; When I tried manually send request: POST example.com:9200/twitter/_search?scroll=1m { "size": 100, "query": { "match_all": {} } } It returned me 100 documents and scroll_id. But this scroll_id was 524 character long. Probably this can be a problem.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48245045
has title: helpers.scan() doesn't scroll - ElasticSearch

http://stackoverflow.com/comment/83627897
score: 0
comment on: http://stackoverflow.com/q/48321363
has text: i want in regular expression instead of beautifulsoup and scrapy.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83476470
has text: The `.` is a called a _wildcard_ in regex, it matches any character. The `*` that follows it indicates that the wildcard can occur any number of times (including zero times). Basically, `.*` is another way of saying "match everything", which fits your criteria. But if you take away the`.`, then you have `\d+\+*`, which now means "match a digit at least once and then match `+` any number of times. Since `44watt+btc` matches a digit at least once and then matches `+` any number of times immediately afterward (in this case, zero times - as we get a `w` instead) - you get a match.
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48236977

http://stackoverflow.com/comment/83543660
comment on: http://stackoverflow.com/q/48279801
has text: Can you post an answer describing the pseudo-code with the best algorithm you have in mind for this particular task? Seems I'll have to settle with this.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48309806
type: Question
has comment: http://stackoverflow.com/comment/83605323
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48309971
downvote count: 5
has comment: http://stackoverflow.com/comment/83605337
tagged with: python
tagged with: sorting
linked to: http://stackoverflow.com/q/48156839
has comment: http://stackoverflow.com/comment/83605628
linked to: http://stackoverflow.com/q/72899
has body: How can i do this: In: a = [{'10100': u'Z'}, {u'00101': u'C'}, {u'01100': u'B'}, {u'00111': u'T'}] Out: a = [{u'01100': u'B'}, {u'00101': u'C'}, {u'00111': u'T'}, {'10100': u'Z'}] I mean in order to value
tagged with: list
score: -5
has title: Sorting list of dicts in order of values
has comment: http://stackoverflow.com/comment/83605613
has comment: http://stackoverflow.com/comment/83605536
duplicate of: http://stackoverflow.com/q/48156839
answer count: 1
has comment: http://stackoverflow.com/comment/83605593
has comment: http://stackoverflow.com/comment/83605398
favorite count: 0

http://stackoverflow.com/comment/83410369
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48200851
type: QuestionComment
has text: @mohammedqudah thank you! I did something like this and it solved.

http://stackoverflow.com/comment/83348056
type: Comment
comment on: http://stackoverflow.com/q/48180935
type: QuestionComment
score: 0
has text: Please, *do not post code in the comments section!* Edit your post instead!!

http://stackoverflow.com/q/48330915
has body: I have a list with data points and 'identifiers' that looks like this: ['identifier', 1, 2, 3, 4, 'identifier', 10, 11, 12, 13, 'identifier', ...] I would like to write this list to a CSV file and start a new column for each identifier. e.g. for data in list: if data=='identifier': ==&gt; create a new column in the CSV file and print the subsequent data points I'm looking forward to hearing your suggestions. Cheers, -Sebastian
has answer: http://stackoverflow.com/a/48331217
has comment: http://stackoverflow.com/comment/83648006
favorite count: 0
has answer: http://stackoverflow.com/a/48331652
type: Question
has answer: http://stackoverflow.com/a/48332212
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/83648084
score: -3
has comment: http://stackoverflow.com/comment/83647773
has answer: http://stackoverflow.com/a/48336859
has comment: http://stackoverflow.com/comment/83647730
has comment: http://stackoverflow.com/comment/83648043
has comment: http://stackoverflow.com/comment/83648079
has title: write a list to CSV file and start new column if condition is met
answer count: 4
has comment: http://stackoverflow.com/comment/83647830
has comment: http://stackoverflow.com/comment/83651008
linked to: http://stackoverflow.com/q/36313605
has comment: http://stackoverflow.com/comment/83650978
has comment: http://stackoverflow.com/comment/83647752
tagged with: python
has comment: http://stackoverflow.com/comment/83647638
has comment: http://stackoverflow.com/comment/83647849
upvote count: 0
downvote count: 3

http://stackoverflow.com/q/48269688
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/83523572
type: Question
tagged with: qlabel
has answer: http://stackoverflow.com/a/54303706
tagged with: python
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/54303706
tagged with: qdialog
answer count: 2
has answer: http://stackoverflow.com/a/48269939
tagged with: pyqt
accepted answer: http://stackoverflow.com/a/48269939
has title: how to add qlabel to a QDialogButtonBox UI file
has body: I'm trying to write a QGIS plugin and display a help dialogbox with python 3 and Qt5. However, the default dialog box based on QDialogButtonBox shows only two standard buttons and no text. The .ui file has the following: <x>30</x> <y>240</y> 341 32 Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok I'm new to Qt5/pyqt. I tried to add a widget following examples: label = QLabel() label.setText("Help\n instructions: \n") self.dlg.addWidget(label) But I got an error: AttributeError: 'XXXDialog' object has no attribute 'addWidget' My question is: How can I add a QLabel or another widget (preferably with a text editor) that can display multiline text to the main area of the dialogbox. Do I have to use a different base class than QDialogButtonBox?

http://stackoverflow.com/comment/83764908
comment on: http://stackoverflow.com/q/48286927
type: Comment
type: QuestionComment
score: 0
has text: Since the OLD code runs 'clean' and the NEW code throws the message, I'd begin by determining what the difference was between the 2 sets of code. You might find that the NEW code calls a DLL or EXE which was created using Visual Foxpro. Find that out first and we might be better able to assist you.

http://stackoverflow.com/a/48287839
has comment: http://stackoverflow.com/comment/83710999
type: Answer
answers question: http://stackoverflow.com/q/48271312
upvote count: 3
score: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83709397
has body: In essence, you want to store data in a way that can be retrieved after the game has ended. This can be done by writing the relevant data/variable content to a file with either a predetermined format(JSON) or your own simple format. Either way you should be able to correctly parse the information when the game starts. How to do this: Identify the point in your code where you should open the file and write the new high score to the file. Check if a new file must be created. If so, then create it. Implement the code which will write the high score to the file. When the game starts up again you must open the file in "read-only" mode and retrieve the information. Note: Make sure you close all files that you open to prevent memory leakage. I hope that this answer helped you and if you have any further questions please feel free to post a comment below!
accepted answer of: http://stackoverflow.com/q/48271312

http://stackoverflow.com/q/48256395
has answer: http://stackoverflow.com/a/75061774
tagged with: python
answer count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83495763
tagged with: memory
has answer: http://stackoverflow.com/a/74998556
tagged with: categorical-data
has title: When should I use pandas' Categorical dtype?
tagged with: pandas
score: 20
has answer: http://stackoverflow.com/a/75186633
downvote count: 0
has body: My question concerns optimizing memory usage for pandas Series. The docs note, The memory usage of a Categorical is proportional to the number of categories plus the length of the data. In contrast, an object dtype is a constant times the length of the data. My understanding is that pandas Categorical data is effectively a mapping to unique (downcast) integers that represent categories, where the integers themselves occupy (presumably) fewer bytes than the strings that make up the object dtype. My question: is there any rule-of-thumb for when using pd.Categorical will not save memory over object? How direct is the aforementioned proportionality, and doesn't it also depend on the length of each element (string) in the Series? In the test below, pd.Categorical seems to win by a long shot. import string import matplotlib.pyplot as plt import numpy as np import pandas as pd np.random.seed(444) %matplotlib inline def mem_usage(obj, index=False, total=True, deep=True): """Memory usage of pandas Series or DataFrame.""" # Ported from https://www.dataquest.io/blog/pandas-big-data/ usg = obj.memory_usage(index=index, deep=deep) if isinstance(obj, pd.DataFrame) and total: usg = usg.sum() # Bytes to megabytes return usg / 1024 ** 2 catgrs = tuple(string.printable) lengths = np.arange(1, 10001, dtype=np.uint16) sizes = [] for length in lengths: obj = pd.Series(np.random.choice(catgrs, size=length)) cat = obj.astype('category') sizes.append((mem_usage(obj), mem_usage(cat))) sizes = np.array(sizes) fig, ax = plt.subplots() ax.plot(sizes) ax.set_ylabel('Size (MB)') ax.set_xlabel('Series length') ax.legend(['object dtype', 'category dtype']) ax.set_title('Memory usage of object vs. category dtype') Albeit, for n&lt;125, pd.Categorical is slightly larger. fig, ax = plt.subplots() ax.plot(sizes[:200]) ax.set_ylabel('Size (MB)') ax.set_xlabel('Series length') ax.legend(['object dtype', 'category dtype']) ax.set_title('Memory usage of object vs. category dtype')
has answer: http://stackoverflow.com/a/65888603
favorite count: 0
has answer: http://stackoverflow.com/a/74575498
type: Question
upvote count: 20

http://stackoverflow.com/a/48330687
has body: If you change the ip address of the flask server from the default 0.0.0.0 to your the ip address of your computer (eg 192.168.1.2) the other clients on your local network can connect. If you want to expose your app the whole of the internet you should get a host that (eg try heroku.com) that has a fixed ip assigned and is reachable from the internet.
answers question: http://stackoverflow.com/q/48330515
type: Answer
has comment: http://stackoverflow.com/comment/83647857
has comment: http://stackoverflow.com/comment/83647358
score: 0
has comment: http://stackoverflow.com/comment/83648000

http://stackoverflow.com/q/48175703
accepted answer: http://stackoverflow.com/a/48211392
upvote count: 1
tagged with: python
tagged with: local-storage
favorite count: 0
has answer: http://stackoverflow.com/a/48211392
has body: How do I click 'Allow' on this local storage chromedriver browser dialog? or completely bypass / disable it? I have tried the following methods: [TRIED METHOD 1: - Disable Chrome Notifications] chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--disable-notifications") driver = webdriver.Chrome(chrome_options=chrome_options) [TRIED METHOD 2: - Disable Chrome Extensions] chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--disable-extensions") driver = webdriver.Chrome(chrome_options=chrome_options) [TRIED METHOD 3: - Disable Chrome Notifications (Another Way)] chrome_options = webdriver.ChromeOptions() prefs = {"profile.default_content_setting_values.notifications": 2} chrome_options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome(chrome_options=chrome_options) [TRIED METHOD 4: - Accept the Dialog] driver.switch_to_alert().accept() [Possible Solutions?] Maybe I could use python to somehow call a javascript that disables localstorage after the chromedriver instance is running? You probably already gathered I am very green. As a result.. Your knowledge and wisdom would be greatly appreciated! =) My current lame working Hack is an X,Y Coordinate Mouse Click.
type: AnsweredQuestion
tagged with: alert
score: 1
has title: Python Webdriver - How do I handle or bypass the 'local storage' dialog?
tagged with: webdriver
type: Question
tagged with: selenium-chromedriver
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48199439
has answer: http://stackoverflow.com/a/48199590
type: UnansweredQuestion
score: 6
upvote count: 6
has title: use range with stepsize in yaml file
tagged with: range
tagged with: python
linked to: http://stackoverflow.com/q/3337020
downvote count: 0
tagged with: yaml
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/51053903
type: Question
has body: In a .yaml file, I want to specify a range for a certain field, e.g., something like, list_field: range(10,50,5) In the above, I intend the list_field to be "pythonic" range(10,50,5). Is there a way to achieve that?

http://stackoverflow.com/a/52872276
has comment: http://stackoverflow.com/comment/122200977
answers question: http://stackoverflow.com/q/48270385
type: Answer
downvote count: 0
has body: Locate your project's virtual environment. In my case, I am working on a Django project and my virtual environment is located on the path below: C:/Users/abc/Desktop/Virutal36/myLab/Scripts/python.exe Copy the address of your virtual environment. On VS Code, Select File > Preferences> Settings to open your User Settings (or use the Ctrl+, shortcut). Create or modify an entry for python.pythonPath with the full path to your virtual environment and you will be good to go. In my case it is: C:/Users/abc/Desktop/Virutal36/myLab01/Scripts/python.exe https://code.visualstudio.com/docs/python/environments#_manually-specify-an-interpreter
has comment: http://stackoverflow.com/comment/105055051
upvote count: 9
score: 9

http://stackoverflow.com/q/48256433
tagged with: django
tagged with: django-models
tagged with: python
has title: Speed up model property of _set in Django
has body: I have a relatively simple setup with a string of Parent->Child relationships. **Parent Child** Site BU BU CT CT Line Line WS WS Assess So each child has models.ForeignKey(Parent) The business logic is structured like a pyramid. Line's level (1-2-3) is dependent on all of it's childs WS level. A CT's level is dependent on all of it's line's level. BU's level on CTs level Site on BUs level. For example: WS1 \ WS2 - line 1 -- CT 1 -\ WS3 / / \ line 2 -/ \ CT 2 -- BU 1 -\ .. Site 1 .. CT 3 -- BU 2 -/ .. line 9 -- CT 4 -/ line 10 -/ Here's the issue: Each level has a property to set the color. Asking for the Site color (top of the pyramid) initiates 1266 queries on my development database with a minimum amount of dummy data. That is a huge amount. Does anyone know how to better model the color property? It is taking a 4+ seconds to get the site color on a production server with only a few sites, with the intent of adding many additional ones. model.py excerpt: class CT(models.Model): name = models.CharField(max_length=255, blank=False) BU = models.ForeignKey(BU, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return "{}".format(self.name) def _color(self): workstations = self.line_set.all() num_of_workstations = len(workstations) high_count = 0 for workstation in workstations: if workstation.color == "high": high_count = high_count + 1 elif workstation.color == "No Assessments completed": num_of_workstations = num_of_workstations - 1 if num_of_workstations &lt;=0: return "No Assessments completed" else: if high_count/num_of_workstations &gt; 0.1: return "high" elif high_count &gt; 0: return "medium" else: return "low" color = property(_color) class Line(models.Model): ct= models.ForeignKey(CT, null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField(max_length=255, blank=False) def __str__(self): return "{}".format(self.name) def _color(self): wts = self.wt_set.all() num_of_wts = len(wts) high_count = 0 for wt in wts: if wt.color ==…
answer count: 0
tagged with: django-queryset
score: 0
has comment: http://stackoverflow.com/comment/83501003
type: Question
tagged with: performance
has comment: http://stackoverflow.com/comment/83495552
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83495567

http://stackoverflow.com/a/48221445
upvote count: 1
type: Answer
has body: One can utilize the capability of multiple Counters to be handily summed to create some neat one-liners, but their performance can't compete with juanpa's explicit loop approach (timings for the original dict): from collections import Counter from operator import add from functools import reduce # 1 out = sum((Counter({x: v for x in k}) for k, v in d.items()), Counter()) # timeit: 16.2 # 2 out = reduce(add, (Counter({x: v for x in k}) for k, v in d.items())) # timeit: 10.8 # 3 # juanpa's approach # timeit: 3.7
score: 1
answers question: http://stackoverflow.com/q/48221317
downvote count: 0

http://stackoverflow.com/comment/83432334
comment on: http://stackoverflow.com/a/48224933
type: AnswerComment
score: 0
has text: Solutuion is same, only first step is `df1 = df1.set_index('ternary')` and last add `.reset_index()`
type: Comment

http://stackoverflow.com/q/48243522
type: AnsweredQuestion
score: 2
has title: Python - How do I get my GUI to display in Spyder
tagged with: pyqt
tagged with: spyder
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/17601896
tagged with: ipython
accepted answer: http://stackoverflow.com/a/66009290
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83469575
has answer: http://stackoverflow.com/a/66009290
upvote count: 2
has comment: http://stackoverflow.com/comment/83469487
tagged with: python
has body: I'm new to creating GUI's in Python and can't seem to get over the first hurdle. I'm using Anaconda - Spyder and I normally run all (mainly mathematical) code through this (and the IPython console?). My issue is that when I run the code below I'm expecting it to display a simple blank window but nothing happens. Is Spyder/IPython not the best way to do this or is there an issue with my code? I've tried using the command prompt by typing "python TestScript.py" whilst in the correct directory but I get an error saying 'Python is not recognised as a internal or external command'. Do I need to set up cmd to use Anaconda? import sys from PyQt5.QtWidgets import QApplication, QWidget if __name__ == '__main__': app = QApplication(sys.argv) w = QWidget() w.resize(250,150) w.move(30,30) w.setWindowTitle('Simple Window') w.show sys.exit(app.exec_())
has comment: http://stackoverflow.com/comment/83473321

http://stackoverflow.com/comment/83510003
has text: even extracting and changing the command to python manage.py loaddata municipios_geo_2013_4674.json the error is the same.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48263309
score: 0

http://stackoverflow.com/a/48192813
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83366747
has comment: http://stackoverflow.com/comment/83371518
answers question: http://stackoverflow.com/q/48192741
type: Answer
has body: PyCharm doesn't do that. Meantime, you can read a .pkl file by using code in a pretty simple way. The following approach uses pickle library. Example import pickle # read python dict back from the file pkl_file = open('myfile.pkl', 'rb') mydict2 = pickle.load(pkl_file) pkl_file.close() print mydict2 Reference: https://www.saltycrane.com/blog/2008/01/saving-python-dict-to-file-using-pickle/
accepted answer of: http://stackoverflow.com/q/48192741
score: 4
has comment: http://stackoverflow.com/comment/83441905
upvote count: 4

generator
type: Tag
tags question: http://stackoverflow.com/q/48256088
tags question: http://stackoverflow.com/q/48262059
tags question: http://stackoverflow.com/q/48219177
tags question: http://stackoverflow.com/q/48232573
tag name: generator
tags question: http://stackoverflow.com/q/48225583
tags question: http://stackoverflow.com/q/48285635
tags question: http://stackoverflow.com/q/48290519

http://stackoverflow.com/q/48255641
upvote count: 0
has comment: http://stackoverflow.com/comment/83494051
has answer: http://stackoverflow.com/a/48255751
score: -4
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/77109623
has title: Python: 2.5.1 Painting a Wall
has body: I am currently trying to solve this on python. Here's where I've got to so far: 350 square feet requires 1 gallon of paint. Assign gallons_paint with the amount of paint required for wall_area. Sample output for the given program: 250.0 square feet wall will need: 0.714285714286 gallons of paint wall_area = 250.0 gallons_paint = 0.0 gallons_paint = 0.714285714286 print(wall_area, 'square feet wall will need:') print(gallons_paint, 'gallons of paint')
answer count: 5
accepted answer: http://stackoverflow.com/a/48255713
tagged with: python
has answer: http://stackoverflow.com/a/48255713
has answer: http://stackoverflow.com/a/60021711
has comment: http://stackoverflow.com/comment/83494090
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50784913
possible better answer: http://stackoverflow.com/a/48255751
downvote count: 4
has comment: http://stackoverflow.com/comment/83494147

http://stackoverflow.com/comment/83642283
comment on: http://stackoverflow.com/q/48253244
type: Comment
type: QuestionComment
has text: just read your excel file with pandas: `df = p.read_excel(yourfilepath)` and start from there. First: READ THE DOCS
score: 0

http://stackoverflow.com/q/48196115
has answer: http://stackoverflow.com/a/48196194
has body: I have a dataframe (FinalDF) which looks like this id | Movie | Cast 0 The Dark Knight Christopher Nolan 1 The Dark Knight Christian Bale 2 Pulp Fiction Quentin Tarantino 3 Pulp Fiction John Travolta 4 Schindler’s List Steven Spielberg 5 Schindler’s List Liam Neeson and Movie names are mapped to IDs like this in movie_cast_DF id | name | uuid ------------------------- 1 | The Dark Knight | m1 2 | Pulp Fiction | m2 3 | Schindler’s List | m3 4 | Christopher Nolan | d1 5 | Christian Bale | a1 6 | Quentin Tarantino | d2 7 | John Travolta | a2 8 | Steven Spielberg | d3 9 | Liam Neeson | a3 I need to map the ids in the columns like this in FinalDF id | Movie | Cast | mid | cid ------------------------------------------------------------------ 0 The Dark Knight Christopher Nolan m1 d1 1 The Dark Knight Christian Bale m1 a1 2 Pulp Fiction Quentin Tarantino m2 d2 3 Pulp Fiction John Travolta m2 a2 4 Schindler’s List Steven Spielberg m3 d3 5 Schindler’s List Liam Neeson m3 a3 I tried using following method: def getID(x): try: return movie_cast_DF[movie_cast_DF['name'].str.contains(x.lower(), case=False)]['uuid'].values[0] except: return None FinalDF['mid'] = FinalDF['Movie'].apply(getID) FinalDF['cid'] = FinalDF['Cast'].apply(getID) FinalDF.head() Is there any efficient and faster way to do the mapping?
answer count: 1
has comment: http://stackoverflow.com/comment/83373337
type: AnsweredQuestion
has title: Pandas mapping columns from multiple dataframes
has comment: http://stackoverflow.com/comment/83375109
accepted answer: http://stackoverflow.com/a/48196194
tagged with: python
has comment: http://stackoverflow.com/comment/83373375
type: Question
score: 0
tagged with: pandas

http://stackoverflow.com/comment/83491762
comment on: http://stackoverflow.com/q/48254539
score: 0
type: Comment
has text: You could choose python version using python2 or python3 in script file. However the error seems like there is a path problem not about python version.
type: QuestionComment

http://stackoverflow.com/a/48216964
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48216907
upvote count: 2
has body: Try this list2 = [[item] for item in list1]
score: 2

http://stackoverflow.com/a/48326247
has body: There is a general issue regarding your objective function that explains why the values you obtain are very close to each other; it is discussed below. If we first look at the technical aspect, the following works fine for me: import numpy as np from scipy.optimize import minimize def func(Gp, Ra, Mr, Pot, Sp, Mc, Keep): if Keep: return Pot * np.tanh((Gp + Ra + Mr + Mc) * Sp) def objective_function(x, y): temp = -(func(x[0], Ra=y['A']['RA'], Mr=y['A']['MR'], Pot=y['A']['POT'], Sp=y['A']['SP'], Mc=y['A']['MC'], Keep=y['A']['keep']) + func(x[1], Ra=y['B']['RA'], Mr=y['B']['MR'], Pot=y['B']['POT'], Sp=y['B']['SP'], Mc=y['B']['MC'], Keep=y['B']['keep']) + func(x[2], Ra=y['C']['RA'], Mr=y['C']['MR'], Pot=y['C']['POT'], Sp=y['C']['SP'], Mc=y['C']['MC'], Keep=y['C']['keep'])) return temp y = {'A': {'RA': 0.5, 'MR': 0.97, 'POT': 0.25, 'SP': 0.25, 'MC': 50., 'keep': True}, 'B': {'RA': 0.8, 'MR': 0.95, 'POT': 0.12, 'SP': 0.12, 'MC': 75., 'keep': True}, 'C': {'RA': 0.9, 'MR': 0.99, 'POT': 0.05, 'SP': 0.15, 'MC': 100., 'keep': True}} cons = ({'type': 'ineq', 'fun': lambda x: x[0] + x[1] + x[2] - 100.}) bnds = ((0., None), (0., None), (0., None)) print(minimize(objective_function, x0=np.array([1., 1., 1.]), args=y, method='SLSQP', bounds=bnds, constraints=cons)) This will print fun: -0.4199999999991943 jac: array([ 0., 0., 0.]) message: 'Optimization terminated successfully.' nfev: 6 nit: 1 njev: 1 status: 0 success: True x: array([ 33.33333333, 33.33333333, 33.33333333]) As you can see, x nicely sums up to 100. If you now change bnds to e.g. bnds = ((40., 50), (0., None), (0., None)) then the result will be fun: -0.419999999998207 jac: array([ 0., 0., 0.]) message: 'Optimization terminated successfully.' nfev: 6 nit: 1 njev: 1 status: 0 success: True x: array([ 40., 30., 30.]) Again, the constraint is met. One can also see that the objective value is the same. That seems to be due to the fact that Mc and Gp are very large, therefore, np.tanh will always just return 1.0. That im…
has comment: http://stackoverflow.com/comment/83665766
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83665735
upvote count: 1
answers question: http://stackoverflow.com/q/48300979
has comment: http://stackoverflow.com/comment/83665496
has comment: http://stackoverflow.com/comment/83664901
score: 1
has comment: http://stackoverflow.com/comment/83665296
accepted answer of: http://stackoverflow.com/q/48300979
type: Answer
has comment: http://stackoverflow.com/comment/83660002
has comment: http://stackoverflow.com/comment/83666567

http://stackoverflow.com/q/48190614
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
duplicate of: http://stackoverflow.com/q/42056713
score: 0
answer count: 1
has body: I spent a lot of time trying to find a solution for my stupid problem but I didn't manage to do it. I'm a newbie in Python (and in plotting above all). What I would like to do is to plot a small legend for my datapoint. I have a 2-dimensional dataset with a class [0,1,2] for each entry. This is the code I wrote for plotting my dataset: plt.figure(figsize=(15,8)) plt.scatter(reduced_dataset[:,0], reduced_dataset[:,1], c=y.Gender) plt.xlabel('PC 1') plt.ylabel('PC 2') plt.legend() plt.figure() And this is my output image: So, what I want is first of all to know which class the three colours represent and to add a small legend on the top right explaining this. Edit: I add some details. My dataset, called reduced_dataset is a 2-dimensional dataset like this, obtained from a 8-dimensional dataset by the application of PCA (n_components=2): [[5.29251,-0.680271] [-10.6902,0.135495] [-0.676506,-0.0493725] [0.306184,-0.315342] [-2.73479,-0.705164]] and I have a vector that represents the classes for each row of my dataset: [0,0,1,0,2] So the class could be 1, 2 or 3, that's why I have three color for the datapoints in my plot. I would need a legend like this: Thank you.
has comment: http://stackoverflow.com/comment/83361817
has title: Python - plot legend of classified datapoints with different colors using Matplotlib
has comment: http://stackoverflow.com/comment/83363836
tagged with: plot
type: Question
has comment: http://stackoverflow.com/comment/83363153
has answer: http://stackoverflow.com/a/48190883
linked to: http://stackoverflow.com/q/42056713

http://stackoverflow.com/a/58447245
answers question: http://stackoverflow.com/q/48234473
upvote count: 1
score: -7
has comment: http://stackoverflow.com/comment/119266278
downvote count: 8
type: Answer
has body: Either use dict.setdefault() if the key is not added yet to dictionary : dict.setdefault(key,[]).append(value) or use, if you already have the keys set up: dict[key].append(value) source: stackoverflow answers

http://stackoverflow.com/comment/83603641
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48308586
has text: dumb question here... how do i do that?
type: Comment

http://stackoverflow.com/a/48178666
type: AcceptedAnswer
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48178204
type: Answer
has body: Another approach could be to create a test runner for Django as described at https://pytest-django.readthedocs.io/en/latest/faq.html#how-can-i-use-manage-py-test-with-pytest-django
answers question: http://stackoverflow.com/q/48178204
score: 2

http://stackoverflow.com/comment/83478265
type: Comment
has text: I ran your example as is, with the single record you provided and it worked. Used Spark 2.2.1. Could this be sensitive to your data? If so, you may need to post some more records for us to replicate.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48243877

http://stackoverflow.com/q/48259396
has comment: http://stackoverflow.com/comment/83501540
has comment: http://stackoverflow.com/comment/83502249
answer count: 2
has comment: http://stackoverflow.com/comment/83501550
has comment: http://stackoverflow.com/comment/83502528
has answer: http://stackoverflow.com/a/48259943
downvote count: 0
upvote count: 1
tagged with: python
has title: python converting nested list to array shape (x,y)
has comment: http://stackoverflow.com/comment/83501735
favorite count: 0
accepted answer: http://stackoverflow.com/a/48260062
has comment: http://stackoverflow.com/comment/83501507
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83501966
has comment: http://stackoverflow.com/comment/83501784
possible better answer: http://stackoverflow.com/a/48259943
has answer: http://stackoverflow.com/a/48260062
score: 1
has comment: http://stackoverflow.com/comment/83501925
has body: Here is the info on the data: len(train_x) 43907 len(train_x[0]) 120 At this moment, the result of train_x.shape and train_x[0].shape = AttributeError: 'list' object has no attribute 'shape' How can I convert the list to array, so that train_x.shape = (43907, 120) Thanks a lot! I have tried some method: y = np.array([np.array(xi) for xi in train_x]) y.shape (43907,) y = np.asarray(train_x) y.shape (43907,) train_x ..., list([0.5079, 0.53121, 0.48361, 0.43715, 0.23894, 0.40985, 0.37101, 0.52262, 0.3558, 0.32028, 0.07165, 0.22726, 0.1828, 0.33434, 0.22724, 0.58681, 0.60266, 0.54746, 0.54243, 0.27596, 0.48267, 0.44198, 0.61634, 0.40842, 0.36773, 0.08, 0.25968, 0.20736, 0.4081, 0.26364, 0.43949, 0.40627, 0.34249, 0.41082, 0.29823, 0.41726, 0.3349, 0.40235, 0.36406, 0.32254, 0.1037, 0.28708, 0.24023, 0.37453, 0.28247, 0.6889, 0.64081, 0.5699, 0.69185, 0.59155, 0.65528, 0.57795, 0.64536, 0.60209, 0.58496, 0.29947, 0.62166, 0.52717, 0.6641, 0.56016, 0.44234, 0.50816, 0.51885, 0.4832, 0.18316, 0.4146, 0.33292, 0.50479, 0.31084, 0.28013, 0.06714, 0.26984, 0.12609, 0.33334, 0.17912, 0.53691, 0.60331, 0.61581, 0.59752, 0.24429, 0.50457, 0.40295, 0.59399, 0.38408, 0.34765, 0.09223, 0.35618, 0.17109, 0.42679, 0.23766, 0.41467, 0.3831, 0.36008, 0.43135, 0.24159, 0.40538, 0.31992, 0.37393, 0.34129, 0.29538, 0.09859, 0.32734, 0.17516, 0.36731, 0.23401, 0.63889, 0.60933, 0.59681, 0.67709, 0.43071, 0.61608, 0.52587, 0.58346, 0.54974, 0.49239, 0.20944, 0.56235, 0.33494, 0.58968, 0.42295]), list([0.44562, 0.4337, 0.44278, 0.3224, 0.20899, 0.32632, 0.29239, 0.41387, 0.32087, 0.30168, 0.08165, 0.22109, 0.17525, 0.26691, 0.20498, 0.54586, 0.55545, 0.54536, 0.41838, 0.25996, 0.4172, 0.37677, 0.5596, 0.39001, 0.37804, 0.11458, 0.28325, 0.21854, 0.33375, 0.25278, 0.3771, 0.3383, 0.30371, 0.31716, 0.29712, 0.3303, 0.27284, 0.3175, 0.33599, 0.32316, 0.17167, 0.30562, 0.27194, 0.31794, 0.29298, 0.6748, 0.64904, 0.63219, 0.65454, 0.60501, 0.61411, 0.56783, 0.63976, 0.61265, 0.62258, 0.50435, 0.6…
linked to: http://stackoverflow.com/q/10346336
has comment: http://stackoverflow.com/comment/83501831
has comment: http://stackoverflow.com/comment/83501478
has comment: http://stackoverflow.com/comment/83502381
type: Question

http://stackoverflow.com/q/48198153
tagged with: python
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/48213088
tagged with: arrays
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83379749
accepted answer: http://stackoverflow.com/a/48198763
has answer: http://stackoverflow.com/a/48213088
has answer: http://stackoverflow.com/a/48198763
type: AnsweredQuestion
has title: Pandas percentage change to a n value before
has body: Hello I have a pandas column with n values 2018-01-03 01:30:00 14873.46 2018-01-03 01:45:00 14848.01 2018-01-03 02:00:00 14888.90 2018-01-03 02:15:00 14834.59 2018-01-03 02:30:00 14895.08 2018-01-03 02:45:00 15049.98 2018-01-03 03:00:00 15041.00 2018-01-03 03:15:00 15198.00 I want to get arrays of the percent change related to the first value of n sets. For example, I choose a set of three, 2018-01-03 01:30:00 14873.46 2018-01-03 01:45:00 14848.01 2018-01-03 02:00:00 14888.90 2018-01-03 01:45:00 14848.01 2018-01-03 02:00:00 14888.90 2018-01-03 02:15:00 14834.59 For this sets I want to be returned #This is percentage change between all values of the set and the first value of the same set ex (14848.01 and 14873.46) and (14888.90 and 14873.46), [-0.17,0.10] [0.27,-0.09] How can I get it donne using pandas
tagged with: data-analysis
linked to: http://stackoverflow.com/q/4923617
tagged with: pandas
score: 1

http://stackoverflow.com/comment/83394245
score: 0
comment on: http://stackoverflow.com/q/48205495
type: Comment
type: QuestionComment
has text: You could start the two applications on diffrent ports (just add `port = 5001` to the `app.run` call to start the app at port 5001 instead of 5000)

min
type: Tag
tags question: http://stackoverflow.com/q/48247958
tag name: min

http://stackoverflow.com/a/48255642
has comment: http://stackoverflow.com/comment/83494288
answers question: http://stackoverflow.com/q/48255607
type: Answer
has comment: http://stackoverflow.com/comment/83494224
accepted answer of: http://stackoverflow.com/q/48255607
has body: I do not believe you need regular expressions to check for existence in the string. Instead, use in and re to split the string: import re creategarbageterms = {'tim_tam' : ['tim_tam','yummy_tim_tam', 'berry_tim_tam'], 'pudding': ['pudding', 'chocolate_pudding', 'biscuits', 'tiramusu'], 'ice_cream': ['ice_cream', 'vanilla_ice_cream']} s = ['wow_yummy_tim_tam', 'melted_tim_tam, berry_tim_tam', 'cherry_berry_tim_tam', 'wow_tam', 'wow_m', 'wow_ti', 'Wow_tim_t'] for c in s: truthy = any(any(i in c for i in b) for a, b in creategarbageterms.items()) if truthy: print("Yes") else: print("no") Output: Yes Yes Yes no no no no
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83494138

http://stackoverflow.com/comment/123745945
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48310939
type: Comment
has text: @CMCDragonkai the `--forked` option now moved to `pytest-forked`. you can use `xdist` with `--boxed` to get the same effect, or move to `pytest-forked`

http://stackoverflow.com/a/48329718
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48329109
has body: The equivalent for pudb appears to be to instantiate Debugger from pudb.debugger. For example: import pudb.debugger import sys def example_keyword(): ... pudb.debugger.Debugger(stdout=sys.__stdout__).set_trace() ...
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/48329109

http://stackoverflow.com/q/48245734
has body: I have a situation where a python file is dynamically loaded with the importlib module. I then catch ImportError to detect if the file does not exist. However this catches any importerrors indirectly caused by the import too. E.g. # file a.py import importlib try: importlib.load_module("b") except ImportError: print("it seems b.py does not exist!") # oops! it actually does, it just also raised an ImportError! # file b.py import nonexistantmoduletocauserror I would like to be able to tell the difference between an ImportError caused from my importlib.load_module and and caused by the process of executing the imported module itself.
tagged with: python-import
possible better answer: http://stackoverflow.com/a/48245792
tagged with: python
accepted answer: http://stackoverflow.com/a/48245875
has answer: http://stackoverflow.com/a/48245792
has answer: http://stackoverflow.com/a/48245875
type: AnsweredQuestion
answer count: 2
score: 1
downvote count: 0
tagged with: error-handling
upvote count: 1
has title: Only Catch Importerrors Caused Directly by Import
favorite count: 0
type: Question

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/48202930
tags question: http://stackoverflow.com/q/48174702
tags question: http://stackoverflow.com/q/48244071
tags question: http://stackoverflow.com/q/48235431
tags question: http://stackoverflow.com/q/48324771
tags question: http://stackoverflow.com/q/48175809
tags question: http://stackoverflow.com/q/48235486
tags question: http://stackoverflow.com/q/48303969
tags question: http://stackoverflow.com/q/48180789
tags question: http://stackoverflow.com/q/48217170
tags question: http://stackoverflow.com/q/48328012
tags question: http://stackoverflow.com/q/48204570
tags question: http://stackoverflow.com/q/48183073
tags question: http://stackoverflow.com/q/48243425
tags question: http://stackoverflow.com/q/48191218
tags question: http://stackoverflow.com/q/48181747
tags question: http://stackoverflow.com/q/48241779
tag name: json
tags question: http://stackoverflow.com/q/48244172
tags question: http://stackoverflow.com/q/48310067
tags question: http://stackoverflow.com/q/48239455
tags question: http://stackoverflow.com/q/48196080
tags question: http://stackoverflow.com/q/48177085
tags question: http://stackoverflow.com/q/48222763
tags question: http://stackoverflow.com/q/48247490
tags question: http://stackoverflow.com/q/48262492
tags question: http://stackoverflow.com/q/48254782
tags question: http://stackoverflow.com/q/48198810
tags question: http://stackoverflow.com/q/48275771
tags question: http://stackoverflow.com/q/48206785
tags question: http://stackoverflow.com/q/48237143
tags question: http://stackoverflow.com/q/48243569
tags question: http://stackoverflow.com/q/48282893
tags question: http://stackoverflow.com/q/48311628
tags question: http://stackoverflow.com/q/48227871
tags question: http://stackoverflow.com/q/48273802
tags question: http://stackoverflow.com/q/48324118
tags question: http://stackoverflow.com/q/48286609
tags question: http://stackoverflow.com/q/48177934
tags question: http://stackoverflow.com/q/48308356
tags question: http://stackoverflow.com/q/48302110
tags question: http://stackoverflow.com/q/48256921
tags question: http://stackoverflow.com/q/48275809
tags question: http://stackoverflow.com/q/48280813
tags question: http://stackoverflow.com/q/48268038
tags question: http://stackoverflow.com/q/48228783
tags question: http://stackoverflow.com/q/48329730
tags question: http://stackoverflow.com/q/48233405
tags question: http://stackoverflow.com/q/48326015
tags question: http://stackoverflow.com/q/48194775
tags question: http://stackoverflow.com/q/48313101
type: Tag
tags question: http://stackoverflow.com/q/48327661
tags question: http://stackoverflow.com/q/48215487
tags question: http://stackoverflow.com/q/48176310
tags question: http://stackoverflow.com/q/48189684
tags question: http://stackoverflow.com/q/48312589
tags question: http://stackoverflow.com/q/48205315
tags question: http://stackoverflow.com/q/48294492
tags question: http://stackoverflow.com/q/48271353
tags question: http://stackoverflow.com/q/48187790
tags question: http://stackoverflow.com/q/48193502
tags question: http://stackoverflow.com/q/48233433
tags question: http://stackoverflow.com/q/48227090
tags question: http://stackoverflow.com/q/48318624
tags question: http://stackoverflow.com/q/48237860
tags question: http://stackoverflow.com/q/48228150
tags question: http://stackoverflow.com/q/48245677
tags question: http://stackoverflow.com/q/48252914
tags question: http://stackoverflow.com/q/48259515
tags question: http://stackoverflow.com/q/48252967
tags question: http://stackoverflow.com/q/48208637
tags question: http://stackoverflow.com/q/48236087
tags question: http://stackoverflow.com/q/48259296
tags question: http://stackoverflow.com/q/48175348
tags question: http://stackoverflow.com/q/48213328
tags question: http://stackoverflow.com/q/48183707
tags question: http://stackoverflow.com/q/48280807
tags question: http://stackoverflow.com/q/48176411
tags question: http://stackoverflow.com/q/48232152

http://stackoverflow.com/comment/83487445
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48218869
has text: Please provide a [MVCE](https://stackoverflow.com/help/mcve), e.g. [this appears to work fine](https://gist.github.com/RazerM/275ab484e33e7832ded42346a5d55e5f)

http://stackoverflow.com/q/48190161
type: UnansweredQuestion
answer count: 1
has title: python 3 my csv isn't formatting right
tagged with: python
has comment: http://stackoverflow.com/comment/83362294
has body: im trying to pull data from another python script into my python script that allow the data to be downloaded and make the data into a csv which is in a table format but when i pull it out it comes disorderly im not sure why here is the csv puller script to get the data into csv import psutil import sys import os import inspect import socket from gevent.pywsgi import WSGIServer from time import gmtime, strftime from threading import Thread from flask import Flask, render_template, session, app, request, redirect, url_for, send_file, send_from_directory from flask_cors import CORS, cross_origin from time import sleep import requests import data import tank import csv APP_ROOT = os.path.dirname(os.path.abspath('__file__')) def funcScript(): from data import tankOBJ as tank for tank in data.tankOBJ: printtofile(tank['id'] + ',' + tank['name'] + ',' + tank['density'] + ',' + tank['tempature'] + ',' + tank['product'] + ',' + tank['timestamp'] + ',' + tank['water']) with open(os.path.join(os.path.join(APP_ROOT, '/csv tester/motherwell.csv')),'r',newline='') as output_file: writer = csv.Dictwriter(output_file, fieldnames=fieldnames, delimiter = '\t') csv_writer.writeheader() for line in csv_reader: writer.writerow(row) print ('%s, %s,' %('hello','world')) return 'Hello World!' here is the data im trying to pull tankOBJ = [] """ Data Entries id - Tank id name - Tank Name product - Product id state - Scan state (Options:Y|N) shape - Tank Shape pos_x - Map Posistion X pos_y - Map Posistion Y datum - Tank Datum max_work - Tank maximum working level min_work - offset_bottom - offset_volume - offset_level - roof_density - roof_weight - roof_start - roof_end - shell_insulated - shell_cte - shell_temperature':tank[19], shell_capacity':tank[20], shell_molecular':tank[21], shell_pressure':tank[22], shell_gtemp':tank[23], dimension_a':tank[24], dimension_b':tank[25], dimension_c':tank[26], knee_third':tank[28], knee_second':tank[29], knee_first':tank[30], suction_third':tank[31], suct…
tagged with: http://stackoverflow.com/tag/csv
type: Question
has answer: http://stackoverflow.com/a/48190846
score: 0

http://stackoverflow.com/q/48304405
type: Question
upvote count: 2
score: 2
downvote count: 0
tagged with: sympy
has body: I have derived a formula that I want to recursively subsitute later. As an example: f = Function("f") expr=f(x,y).diff(x) + f(x,y).diff(x).diff(x) expr.subs(f(x,y).diff(x),f(x,y+1)) This gives me f(x, y + 1) + Derivative(f(x, y + 1), x) But what I want is f(x,y+1) + f(x,y+2) How do I do this in a nice way?
tagged with: symbolic-math
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48307495
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48307495
has title: Recursive substitution of formulas in sympy
tagged with: python

http://stackoverflow.com/a/48318003
score: 2
type: Answer
has body: import collections x=[11,12,21,34,35,36] lists = collections.defaultdict(list) for i in x: lower = (i//10) * 10 upper = lower + 10 lists[(lower, upper)].append[i] Now your lists variable is a dictionary that maps (min, max) pairs to a list of values in that range: &gt;&gt;&gt; lists[(10, 20)] [11, 12] Of course you don't need both the lower and upper bounds in the key - you could store them just by lower bound since you know how wide the ranges are: import collections x=[11,12,21,34,35,36] lists = collections.defaultdict(list) for i in x: lower = (i//10) * 10 lists[lower].append[i]
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48317882

http://stackoverflow.com/a/48178416
downvote count: 0
score: 2
has comment: http://stackoverflow.com/comment/83368010
answers question: http://stackoverflow.com/q/48177085
type: Answer
accepted answer of: http://stackoverflow.com/q/48177085
has body: The problem lies somewhere inside is_zipfile. Although it is stayed that "filename may be a file or file-like object" (13.5.1. ZipFile Objects: zipfile.is_zipfile), it fails with the seek error. A possible solution is to close the file and reopen it just to check: zf.close() with open(data["fileName"] + '.epub','r') as f: if zipfile.is_zipfile(f) is True: print("ZIP file is valid.") I also found that that check is extremely basic and will return True even if you manually damage some bytes. It takes some effort to actually make it fail. Interestingly, the apparent more thorough zipfile.ZipFile.testzip function needs that zf again – but it also fails if called before zf.close(). And there is no zf.flush() ... Luckily, checking the created ePub file with zip after running the script reveals it contains no errors: ~/Documents $ zip -T IdealogicalEcho.epub test of IdealogicalEcho.epub OK (which does not tell you, by the way, that it is a valid epub. (It is not.))
has comment: http://stackoverflow.com/comment/83417290
upvote count: 2
has comment: http://stackoverflow.com/comment/83367638
type: AcceptedAnswer

http://stackoverflow.com/comment/83474509
comment on: http://stackoverflow.com/q/48239941
score: 0
type: Comment
type: QuestionComment
has text: @TamirKfir it's being hosted on the same django server.. would it be better to host it on a different node.js server?

http://stackoverflow.com/comment/83436581
comment on: http://stackoverflow.com/a/48227221
type: AnswerComment
score: 0
has text: @Lxndr could you please explain what is `a`?
type: Comment

http://stackoverflow.com/q/48271543
tagged with: django
type: AnsweredQuestion
tagged with: typeerror
has answer: http://stackoverflow.com/a/48271630
possible better answer: http://stackoverflow.com/a/48271630
has answer: http://stackoverflow.com/a/48272155
upvote count: 1
score: 1
tagged with: django-urls
tagged with: python
favorite count: 0
has body: I know it looks like a simple problem but I'm still too new for sorting it out myself, so : learning_log/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', 'learning_logs.urls',name_space='learning_logs'), ] Previously I had the following error so I've removed the include function ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. learing_logs/urls.py """Defines URL patterns for learning_logs.""" from django.conf.urls import url from . import views urlpatterns=[ #Homepage url(r'^$',views.index,name='index'), ] views.py from django.shortcuts import render #Create your views here. def index(request): """The home page for Learning Log""" return render(request,'learning_logs/index.html') I'm using Django 2.0 and Python 3.6.1 Could you please advise why I'm getting TypeError with name_space arg, is that related to Django version, many thanks in advance.
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48272155
downvote count: 0
has title: TypeError: url() got an unexpected keyword argument 'name_space'

http://stackoverflow.com/comment/128307719
score: 1
has text: Despite setting random_state, we are getting different results on each run of decisiontree... What can be the cause?
comment on: http://stackoverflow.com/a/48252411
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83538021
type: Comment
type: QuestionComment
score: 2
has text: What should be printed on the first run through of the loop, when there is no previous value?
comment on: http://stackoverflow.com/q/48277271

http://stackoverflow.com/comment/83341177
type: QuestionComment
comment on: http://stackoverflow.com/q/48179112
has text: Ah i realised why. cascading down in the column there are mixed date formats. i did df2['plan start date'0.dtype()
score: 0
type: Comment

http://stackoverflow.com/comment/83491883
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48247606
score: 0
has text: no. because in Numpy, slicing is just a view to the data (aka pointers), but when I copy I do a real memcpy, doubling the memory. All other functions work over the data itself, not on copies.

http://stackoverflow.com/a/48307594
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48307479
has body: Your merge_sort function returns the sorted list but at both locations you call it you discard the result. You need to assign the result (bind it to a name) so that you can pass those results to merge: if len(list_sort) &gt;= 2: x= len(list_sort) / 2 part_a = list_sort[:x] part_b = list_sort[x:] print part_a , part_b sorted_part_a = merge_sort(part_a) sorted_part_b = merge_sort(part_b) return merge(sorted_part_a, sorted_part_b)

http://stackoverflow.com/comment/83338862
type: Comment
type: QuestionComment
has text: Do you know what the purpose of the triple double quotes is?
score: 0
comment on: http://stackoverflow.com/q/48179010

http://stackoverflow.com/q/48265583
has answer: http://stackoverflow.com/a/48283153
possible better answer: http://stackoverflow.com/a/48283153
has comment: http://stackoverflow.com/comment/83662513
has answer: http://stackoverflow.com/a/65181685
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48277838
has comment: http://stackoverflow.com/comment/83887386
has title: Shutdown for socketserver based Python 3 server hangs
tagged with: python
has comment: http://stackoverflow.com/comment/84026021
tagged with: gevent
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/48458088
has body: I am working on a "simple" server using a threaded SocketServer in Python 3. I am going through a lot of trouble implementing shutdown for this. The code below I found on the internet and shutdown works initially but stops working after sending a few commands from the client via telnet. Some investigation tells me it hangs in threading._shutdown... threading._wait_for_tstate_lock but so far this does not ring a bell. My research tells me that there are ~42 different solutions, frameworks, etc. on how to do this in different python versions. So far I could not find a working approach for python3. E.g. I love telnetsrv (https://pypi.python.org/pypi/telnetsrv/0.4) for python 2.7 (it uses greenlets from gevent) but this one does not work for python 3. So if there is a more pythonic, std lib approach or something that works reliably I would love to hear about it! My bet currently is with socketserver but I could not figure out yet how to deal with the hanging server. I removed all the log statements and most functionality so I can post this minimal server which exposes the issue: # -*- coding: utf-8 -*- import socketserver import threading SERVER = None def shutdown_cmd(request): global SERVER request.send(bytes('server shutdown requested\n', 'utf-8')) request.close() SERVER.shutdown() print('after shutdown!!') #SERVER.server_close() class service(socketserver.BaseRequestHandler): def handle(self): while True: try: msg = str(self.request.recv(1024).strip(), 'utf-8') if msg == 'shutdown': shutdown_cmd(msg, self.request) else: self.request.send(bytes("You said '{}'\n".format(msg), "utf-8")) except Exception as e: pass class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): pass def run(): global SERVER SERVER = ThreadedTCPServer(('', 1520), service) server_thread = threading.Thread(target=SERVER.serve_forever) server_thread.daemon = True server_thread.start() input("Press enter to shutdown") SERVER.shutdown() if __name__ == '__main__': run() It would …
has comment: http://stackoverflow.com/comment/83833653
accepted answer: http://stackoverflow.com/a/48458088
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83525148
downvote count: 0
has comment: http://stackoverflow.com/comment/83833733
has comment: http://stackoverflow.com/comment/83664188
has comment: http://stackoverflow.com/comment/83535430
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/83833576
has comment: http://stackoverflow.com/comment/83833522
has comment: http://stackoverflow.com/comment/83746390
has comment: http://stackoverflow.com/comment/83765052
tagged with: socketserver

http://stackoverflow.com/a/48362710
has comment: http://stackoverflow.com/comment/83816198
has comment: http://stackoverflow.com/comment/83767662
type: Answer
answers question: http://stackoverflow.com/q/48312790
has comment: http://stackoverflow.com/comment/83767997
has comment: http://stackoverflow.com/comment/83768790
has comment: http://stackoverflow.com/comment/83771451
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: To generate your final output table I used the following code: final_df = pd.merge(df_details, df'Session_ID', 'Session_Title', 'Sponsors', 'Type', left_on = ['Session_ID'], right_on = ['Session_ID'], how = 'outer')
accepted answer of: http://stackoverflow.com/q/48312790

http://stackoverflow.com/a/48214081
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48211609
has body: If your intention is to have a very accurate page view count yes, you'd have to persist it in the datastore and you'd have to address the risk of exceeding the max entity group writing rate of ~1/sec. The typical approach in this case is Sharding counters. However if you're OK with potentially missing a few views now and then (which IMHO could be perfectly acceptable) you could use a different strategy, using memcache where you'd store a counter and a timestamp, which you can tune to be much more relaxed in terms of datastore operations. On every page view you'd invoke a transactional function (to prevent corrupting the datastore counter value) which would: increment the memcache counter value (or set it to 1 if missing or invalid) check the memcache timestamp value and, if valid and "recent enough" (tunable) it'd just return, otherwise continue update the memcache timestamp with the current time (to prevent, together with the next step, a race condition with the same function invoked for another concurrent request) add the memcache counter value to the datastore counter value and save the datastore counter; if this transaction fails it means some other concurrent request is doing it already, nothing to do (the function would end at this point) reset the memcache counter to zero optional, not needed if you don't expect long enough inactivity periods during which you risk losing a significant amount of views accumulated in the memory counter which can dissapear at any time - enqueue a delayed task (or a deferred one, if you prefer to use the deferred library) which would also invoke this same transactional function, except in that run: it won't increment the memcache counter value it won't enqueue another delayed task I'd pick the task delay value equal with the "recent enough" one. By tuning the "recent enough" value you control how often you update the datastore counter value. When you want to display the number of views you'd just read the datastore value and the …

http://stackoverflow.com/q/48269063
has title: How to remove a comma in an output
upvote count: 1
has answer: http://stackoverflow.com/a/48269108
has answer: http://stackoverflow.com/a/48269113
has comment: http://stackoverflow.com/comment/83521376
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48269177
has comment: http://stackoverflow.com/comment/83521531
downvote count: 2
linked to: http://stackoverflow.com/q/9452108
tagged with: python-3.5
answer count: 5
type: UnansweredQuestion
tagged with: python
score: -1
has body: def calculate_average(): mylist = [] for i in range (10): input = int(input("Enter an integer: ")) mylist.append(integer) avg = sum(numbers) / len(numbers) aboveavg = ([x for x in numbers if x &gt; average]) print("\nThe average is:", avg) print("Numbers greater than average:") print(str(aboveavg).strip('[]')) I get an output for the very last line where it has a comma. For example Numbers greater than average: 14, 15 Instead of: 14 15 How to go about fixing the code? Do I use join? (something I haven't learned about in class yet)
has answer: http://stackoverflow.com/a/48269120
has answer: http://stackoverflow.com/a/48269117

http://stackoverflow.com/comment/83413374
type: Comment
type: QuestionComment
has text: Based on your sample JSON, I'm afraid I don't understand the problem enough. Is that the JSON you send to Lex, or what you're expecting to receive from Lex? As far as I know it doesn't match either of Lex's `Input Event` or `Response` JSON structures. Check this out for details: https://docs.aws.amazon.com/lex/latest/dg/lambda-input-response-format.html
comment on: http://stackoverflow.com/q/48207257
score: 0

http://stackoverflow.com/comment/83370863
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48194944
has text: Thank you Imran and Evan! I just couldn't come up with the correct terms to search for no matter how I tried!!!

http://stackoverflow.com/a/69009724
score: 2
upvote count: 2
downvote count: 0
has body: Currently zooming in with adaptive resolution is not supported. Your best option is to use a different tool for that. To cancel the sciview: settings -> Tools -> python scientific -> untick "show plots in tool window" view -> untick "scientific mode".
answers question: http://stackoverflow.com/q/48238192
type: Answer

http://stackoverflow.com/comment/83411545
comment on: http://stackoverflow.com/q/48213988
score: 0
type: Comment
type: QuestionComment
has text: @bivoauc0 Can you look at my edit? The open stock functions is that one, out of the module

http://stackoverflow.com/q/48232385
tagged with: data-visualization
has title: How to get the same bin widths for variable bin ranges in a histogram using Python?
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/83447261
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48232699
downvote count: 0
answer count: 1
tagged with: histogram
has body: I am trying to create a histogram with a custom bin range. However, as you can see in the histogram below, the bin widths are not a constant size. Ideally, I want something like this. The spacing between bins doesn't really matter, I just want each bin/column to be the same width: The code I used to generate the first histogram is this: plt.figure() weights = np.ones_like(data)/float(len(data)) plt.hist(data, bins=[0, 1.0, 3.0, 5.0, 10.0, 25.0, 90.0], weights=weights)
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83447097
accepted answer: http://stackoverflow.com/a/48232699
upvote count: 2

http://stackoverflow.com/comment/83661668
type: Comment
comment on: http://stackoverflow.com/a/48318574
type: AnswerComment
has text: wait, so the post is actually like a search ? eg: posting userId will get back the information of the userId given ?
score: 0

oauth-1.0a
tag name: oauth-1.0a
type: Tag
tags question: http://stackoverflow.com/q/48327742

http://stackoverflow.com/comment/83436477
has text: Do you need to do it with MSER? I think this can be easier with `cv2.findCountours()`
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48227215

http://stackoverflow.com/q/48315405
downvote count: 1
favorite count: 0
score: -1
type: Question
upvote count: 0
type: UnansweredQuestion
tagged with: python
has body: What I need is how do I merge all these excel month wise . For example All July files must in one excel file in July.xls , ALl september files should be in one excel file which is september.xls etc How do I do this can any body help and also if these files exceeds the range of excels then divide it into two excel files july_1 ,july_2. I have multiple Excel files which are as follows This are the input excel files July_1_2017_00_23_59.xls July_2_2017_00_23_59.xls July_3_2017_00_23_59.xls July_4_2017_00_23_59.xls July_5_2017_00_23_59.xls August_1_2017_00_23_59.xls August_2_2017_00_23_59.xls August_3_2017_00_23_59.xls August_4_2017_00_23_59.xls August_5_2017_00_23_59.xls september_1_2017_00_23_59.xls september_2_2017_00_23_59.xls Please help me do this in python.
has comment: http://stackoverflow.com/comment/83616326
tagged with: excel
has title: Combining multiple Excel files in one excel in python
has comment: http://stackoverflow.com/comment/83616185
has answer: http://stackoverflow.com/a/48315775
has comment: http://stackoverflow.com/comment/83616723
answer count: 1

http://stackoverflow.com/comment/83462409
type: QuestionComment
has text: Take a look here : https://stackoverflow.com/questions/31811253/execute-python-script-from-php/31811462#31811462
comment on: http://stackoverflow.com/q/48240058
score: 0
type: Comment

http://stackoverflow.com/comment/83480127
comment on: http://stackoverflow.com/q/48248450
type: Comment
type: QuestionComment
score: 0
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/163136/discussion-between-vinod-bhandary-and-maxu).

http://stackoverflow.com/q/48236866
has comment: http://stackoverflow.com/comment/83456400
tagged with: sklearn-pandas
type: Question
has answer: http://stackoverflow.com/a/48238875
possible better answer: http://stackoverflow.com/a/48238875
answer count: 2
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83456965
has comment: http://stackoverflow.com/comment/83456803
has comment: http://stackoverflow.com/comment/83456987
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/48236956
accepted answer: http://stackoverflow.com/a/48236956
has comment: http://stackoverflow.com/comment/83456767
favorite count: 0
has comment: http://stackoverflow.com/comment/83456358
type: AnsweredQuestion
tagged with: theano
has comment: http://stackoverflow.com/comment/83463188
tagged with: pandas
has title: StandardScaler Doesn't Scale Properly
score: 1
has body: I am trying to use StandardScaler to scale the features of a neural network. Lets say then neural network has these features: 1.0 2.0 3.0 4.0 5.0 6.0 4.0 11.0 12.0 etc ... When I apply StandardScaler to the whole thing (all rows) I get the following result for the first row: ['-0.920854068785', '-0.88080603151', '-0.571888559111'] When I try to apply the StandardScaler to the first row only (matrix consisting of just the first row) I get completelly different result. ['0.0', '0.0', '0.0'] Obviosly the neural network won't work this way, because the rows are not the same. Is there any way to use Standard scaller in a way so I get the same results each time, for the same input(line)? Here is the code and the output: from sklearn.preprocessing import StandardScaler import numpy as np sc = StandardScaler() #defining the (big) matrix AR = np.array([[1.0,2.0,3.0],[4.0,5.0,6.0],[4.0,11.0,12.0],[42.0,131.0,1121.0],[41.0,111.0,121.0]]) AR = sc.fit_transform(AR) print "fited data from big array:" m=0 for row in AR: m = m + 1 if m==1:print [str(m) for m in row] #defining the (small) matrix AR1 = np.array([[1.0,2.0,3.0]]) AR1 = sc.fit_transform(AR1) print "fited data from small array" for row in AR1: print [str(m) for m in row] The output is: fited data from big array: ['-0.920854068785', '-0.88080603151', '-0.571888559111'] fited data from small array ['0.0', '0.0', '0.0']
tagged with: python
has comment: http://stackoverflow.com/comment/83456438

http://stackoverflow.com/q/48285915
has title: Creating list of lists in c++
has comment: http://stackoverflow.com/comment/83556650
has comment: http://stackoverflow.com/comment/83558680
has answer: http://stackoverflow.com/a/48285968
duplicate of: http://stackoverflow.com/q/9694838
has comment: http://stackoverflow.com/comment/83556411
tagged with: python
has comment: http://stackoverflow.com/comment/83556370
has comment: http://stackoverflow.com/comment/83556466
downvote count: 1
has comment: http://stackoverflow.com/comment/83559309
linked to: http://stackoverflow.com/q/9694838
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48286183
possible better answer: http://stackoverflow.com/a/48285961
has body: In C++, what is the recommended way of creating a list of a certain size, where each element of the list is a list of 3 elements? Analogy To clarify, the analogy in Python for what I'm trying to do would go as follows: Simplest: n = 10 ls = [[0,0,0] for i in range(n)] Already initialised as well and I can access elements (e.g. ls[0][0]) and even modify them (ls[0][0]=2), perfect! or using numpy import numpy as np n = 10 #number of elements ls = np.empty((n,0)).tolist() and then to each element (here a list), we'd append our 3 values. Basic attempt Now I understand in C++, one starting difference would be to specifically define the type of variables the inner-lists are supposed to contain. But vector is not a variable type in c++ right? As in something along the lines of: int n = 4; vector&lt;vector&gt; ls(4); for(int i=0; i&lt;n; i++) { ls[i] = {0,0,0}; } would be wrong. Moreover, if I try instead vector&lt;int&gt; ls; then I cannot assign lists to each element. Question: Is there a way to make htis work using vector in C++? Alternatively, are there simpler ways of going about this?
tagged with: list
answer count: 3
has comment: http://stackoverflow.com/comment/83557215
has comment: http://stackoverflow.com/comment/83556331
has answer: http://stackoverflow.com/a/48285961
has comment: http://stackoverflow.com/comment/83556529
has comment: http://stackoverflow.com/comment/83557131
favorite count: 0
type: Question
upvote count: 4
tagged with: c++
has comment: http://stackoverflow.com/comment/83556327
tagged with: vector
accepted answer: http://stackoverflow.com/a/48285968

http://stackoverflow.com/q/48213605
score: -1
has answer: http://stackoverflow.com/a/48213713
has title: Convert csv rows into colum
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83408942
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/17037566
downvote count: 1
possible better answer: http://stackoverflow.com/a/48213781
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48213781
answer count: 2
has body: So I have a csv file that looks like this.. 1 a 2 b 3 c And I want to make it look like this.. 1 2 3 a b c I'm at a loss for how to do this with python3, anyone have any ideas? Really appreciate it
has comment: http://stackoverflow.com/comment/83408862
upvote count: 0
has comment: http://stackoverflow.com/comment/83408811
accepted answer: http://stackoverflow.com/a/48213713
tagged with: python

http://stackoverflow.com/q/48309840
has comment: http://stackoverflow.com/comment/83605502
downvote count: 0
has answer: http://stackoverflow.com/a/48309947
upvote count: 1
score: 1
linked to: http://stackoverflow.com/q/15790493
has comment: http://stackoverflow.com/comment/83605461
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/19753897
has title: Is it possible to increment/access a class variable from inside a constructor in Python?
possible better answer: http://stackoverflow.com/a/48309947
has answer: http://stackoverflow.com/a/48309881
accepted answer: http://stackoverflow.com/a/48309881
has body: I want to keep track via a counter, every time a class is instantiated. I was trying to do this by incrementing a counter defined as a class variable from inside the class' consructor ala: class Cl: cntr = 0 def __init__(self): cntr += 1 However, when I instantiate the class, I get an "UnboundLocalError: local variable 'cntr' referenced before assignement" I'm assuming this is because the constructor is treating it as a local variable. How do I reference the class variable from inside a method or constructor in Python 2.7?
has comment: http://stackoverflow.com/comment/83605482
has comment: http://stackoverflow.com/comment/83605478
tagged with: python
has comment: http://stackoverflow.com/comment/83605441
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83605513
tagged with: python-2.7
answer count: 2

http://stackoverflow.com/a/48326781
has comment: http://stackoverflow.com/comment/83639521
has comment: http://stackoverflow.com/comment/83638916
has comment: http://stackoverflow.com/comment/83639403
type: Answer
answers question: http://stackoverflow.com/q/48326551
score: 0
has comment: http://stackoverflow.com/comment/83639663
has comment: http://stackoverflow.com/comment/83639284
has body: The problem is with these lines: try: soup = getWebData(val) except: plans When getWebData(val) throws an exception, the variable soup doesn't get assigned any value. So, when you use it here soup.find_all(...), you are using a variable soup which is not yet defined. Thus the message "local variable 'soup' referenced before assignment". You can rectify this by doing something like this try: soup = getWebData(val) except: return plans Here, if an exception is thrown, the program won't reach the soup.find_all(...) statement.

http://stackoverflow.com/a/48174649
has body: If you just want the count of Bald people (!!), then use - isBaldCount = data.isBald.eq('Bald').sum() On the other hand, if you want to count every value and assign it to separate variables, then use value_counts and assign the result - c = data.isBald.value_counts() isBaldCount = c.loc['Bald'].item() notBaldCount = c.loc['Not Bald'].item()
type: Answer
upvote count: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48174608
score: 4
answers question: http://stackoverflow.com/q/48174608
downvote count: 0

http://stackoverflow.com/q/48270191
tagged with: locale
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48270239
has answer: http://stackoverflow.com/a/48270239
score: 7
has body: I have a python program (jrnl) that should print the day of the week as text in German. However, it always prints the English name. Here is the output of locale: LANG=en_US.UTF-8 LC_CTYPE="en_US.UTF-8" LC_NUMERIC=de_DE.UTF-8 LC_TIME=de_DE.UTF-8 LC_COLLATE="en_US.UTF-8" LC_MONETARY=de_DE.UTF-8 LC_MESSAGES="en_US.UTF-8" LC_PAPER=de_DE.UTF-8 LC_NAME=de_DE.UTF-8 LC_ADDRESS=de_DE.UTF-8 LC_TELEPHONE=de_DE.UTF-8 LC_MEASUREMENT=de_DE.UTF-8 LC_IDENTIFICATION=de_DE.UTF-8 LC_ALL= You can see that LC_TIME is set to de_DE.UTF-8. But when I start python this locale is not set: &gt;&gt;&gt; import locale &gt;&gt;&gt; locale.getlocale(locale.LC_TIME) (None, None) So my week day is shown in English: &gt;&gt;&gt; from time import gmtime, strftime &gt;&gt;&gt; strftime("%A, %d %b %Y %H:%M:%S +0000", gmtime()) 'Monday, 15 Jan 2018 20:22:30 +0000' What do I have to do for python to use the system locale?
downvote count: 0
answer count: 1
upvote count: 7
has title: Python does not use locale from environment
favorite count: 0
type: Question

http://stackoverflow.com/comment/83331026
has text: @piRSquared, can't believe you said that! Wish you a very happy new year btw
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48175498

http://stackoverflow.com/q/48260963
type: UnansweredQuestion
tagged with: aggregation-framework
tagged with: datetime
linked to: http://stackoverflow.com/q/12694490
tagged with: python
has comment: http://stackoverflow.com/comment/83530747
has comment: http://stackoverflow.com/comment/83505864
has comment: http://stackoverflow.com/comment/83544617
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83536770
tagged with: pymongo
has body: In the below query I'm trying to get all the records added in certain month and year by matching given month and year in timestamp but not iso. { "$match":{ "expr":{ "$and":[ { "$eq":[ { "$year":"$timestamp" }, 2016 ] }, { "$eq":[ { "$month":"$timestamp" }, 1 ] } ] } } } but above line throws "pymongo.errors.OperationFailure: unknown operator: $and" error in python script. How do i change the $and in my aggregate query to implicit AND, so that my python script runs without error. P.S : The query works fine in mongo 3.6. The error is because of the missing $ in expr, my apologies.
has comment: http://stackoverflow.com/comment/83530743
has title: MongoDB change $and from aggregate query to implicit and
type: Question
tagged with: mongodb
has comment: http://stackoverflow.com/comment/83556325
has comment: http://stackoverflow.com/comment/83506895
has comment: http://stackoverflow.com/comment/83556366

http://stackoverflow.com/a/48217191
type: Answer
has comment: http://stackoverflow.com/comment/83443474
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48186483
downvote count: 0
answers question: http://stackoverflow.com/q/48186483
has body: First of all, Python and especially multi-line strings are indent dependant. Make sure you have no preceding spaces inside the string (as they will be treated as characters) and make sure the patterns (brackets) align visually. Moreover I think you might want to have &lt;ADJ&gt;&lt;NN&gt;+ as your second pattern. + means 1 or more, whereas * means 0 or more. I hope this solves the issue. #!/usr/bin/env python import nltk PATTERN = r""" NP: {&lt;NN&gt;&lt;NN&gt;+} {&lt;ADJ&gt;&lt;NN&gt;+} """ sentence = [('the', 'DT'), ('little', 'ADJ'), ('yellow', 'ADJ'), ('shepherd', 'NN'), ('dog', 'NN'), ('barked', 'VBD'), ('at', 'IN'), ('the', 'DT'), ('silly', 'ADJ'), ('cat', 'NN')] cp = nltk.RegexpParser(PATTERN) print(cp.parse(sentence)) Result: (S the/DT little/ADJ yellow/ADJ (NP shepherd/NN dog/NN) barked/VBD at/IN the/DT (NP silly/ADJ cat/NN)) Reference: http://www.nltk.org/book/ch07.html
type: AcceptedAnswer

http://stackoverflow.com/q/48329975
type: Question
tagged with: curio
tagged with: pytest
upvote count: 3
has title: Combining py.test and trio/curio
answer count: 1
downvote count: 0
has body: I would to combine pytest and trio (or curio, if that is any easier), i.e. write my test cases as coroutine functions. This is relatively easy to achieve by declaring a custom test runner in conftest.py: @pytest.mark.tryfirst def pytest_pyfunc_call(pyfuncitem): '''If item is a coroutine function, run it under trio''' if not inspect.iscoroutinefunction(pyfuncitem.obj): return kernel = trio.Kernel() funcargs = pyfuncitem.funcargs testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames} try: kernel.run(functools.partial(pyfuncitem.obj, **testargs)) finally: kernel.run(shutdown=True) return True This allows me to write test cases like this: async def test_something(): server = MockServer() server_task = await trio.run(server.serve) try: # test the server finally: server.please_terminate() try: with trio.fail_after(30): server_task.join() except TooSlowError: server_task.cancel() But this is a lot of boilerplate. In non-async code, I would factor this out into a fixture: @pytest.yield_fixture() def mock_server(): server = MockServer() thread = threading.Thread(server.serve) thread.start() try: yield server finally: server.please_terminate() thread.join() server.server_close() def test_something(mock_server): # do the test.. Is there a way to do the same in trio, i.e. implement async fixtures? Ideally, I would just write: async def test_something(mock_server): # do the test..
tagged with: python-trio
accepted answer: http://stackoverflow.com/a/48342124
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48342124
score: 3
tagged with: python

nonetype
tags question: http://stackoverflow.com/q/48185462
type: Tag
tag name: nonetype

http://stackoverflow.com/q/48241007
has body: x1 = input('0.0') x2 = input('5.6') y1 = input('2.3') y2 = input('6.6') slope = (y2-y1 / x2-x1) print("The Slope is ") I have this write but every time I run it it returns a value of 0.0
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83464329
has title: How do I write the code in Python for this slope
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83464733
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83464309
has answer: http://stackoverflow.com/a/48241137
type: UnansweredQuestion

http://stackoverflow.com/a/48269936
score: 1
upvote count: 1
has body: As noted in the comments, your code is missing the colon at the end of each of your if and elif statements. Also, your code has extraneous colons within the first conditional test (ie. (FirstNumber%2!=0:). Also, as you mention that you are a beginner, a few suggestions on simplifying the code... or improving the readability... firstNum = int(input("Enter First Number: ")) secondNum = int(input("Enter Second Number: ")) thirdNum = int(input("Enter Third Number: ")) # In this case, we don't need the parenthesis. (Sometimes parens are # required to ensure that the logic works correctly, but in this case, # we don't.) Python short circuits, meaning it will stop the If # statement mid-way as soon as a conditional statement equivocates to False. if firstNum % 2 != 0 and firstNum &gt; secondNum and firstNum &gt; thirdNum: print 'First Number is largest odd -&gt; ' + str(firsthirdNum) elif secondNum % 2 != 0 and secondNum &gt; firstNum and secondNum &gt; thirdNum: print 'Second Number is largest odd -&gt; ' + str(secondNum) elif thirdNum % 2 != 0 and thirdNum &gt; firstNum and thirdNum &gt; secondNum: print 'Third Number is largest odd -&gt; ' + str(thirdNum) else: print 'None are odd -&gt; ' + str(firstNum), str(secondNum), str(thirdNum)
answers question: http://stackoverflow.com/q/48269790
type: Answer
downvote count: 0

http://stackoverflow.com/a/48280014
has comment: http://stackoverflow.com/comment/83544687
score: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48279640
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48279640
has comment: http://stackoverflow.com/comment/83543868
upvote count: 5
type: Answer
has body: The primary difference between PHP and Python is that PHP arrays are both associative and ordered, while in Python you can either have an ordered list or an associative dict, but not both in one data structure.* * There's OrderedDict and dict is starting to become ordered itself, but let's stick with the primitives. So fundamentally you'll need to think of different data structures. The typical way to do this is to have a list of tuples, with one tuple value representing your former index and the other value the former value: [(0, 'foo'), (1, 'bar'), ...] You can get to that from a normal list using enumerate: l = list(enumerate(my_list)) # ['foo', 'bar'] → [(0, 'foo'), (1, 'bar')] And you can sort it in the process: l = sorted(enumerate(my_list), key=lambda i: i[1]) # → [(1, 'bar'), (0, 'foo')] Here lambda i: i[1] simply sorts by the second tuple value, i.e. your former value. You can replace that with itemgetter(1) from the operator module for brevity, or adjust as necessary for your sorting condition. If you want to turn that into an associative data structure again, use OrderedDict: from collections import OrderedDict from operator import itemgetter l = OrderedDict(sorted(enumerate(my_list), key=itemgetter(1)))

http://stackoverflow.com/comment/83424991
score: 0
has text: Do you want to extract 10000,25000 then 20000,5000
comment on: http://stackoverflow.com/a/48221626
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48237860
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has body: I have read about mixins and understood that A mixin is a special kind of multiple inheritance and provide a lot of optional features for a class. Now i want to know what are JsonResponseMixin and why they are used. class JsonResponseMixin(object): def render_to_json_response(self,context,**response_kwargs): return JsonResponse(context,**response_kwargs) def get_data(self,context): return context This is the code i found in mixin.py .Can someone please expain why this is used .Are they used in serializing data?Please elaborate
upvote count: 2
type: UnansweredQuestion
tagged with: mixins
downvote count: 1
answer count: 1
tagged with: django
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48242946
has title: What is JsonResponseMixin? How they work with the class based views
score: 1

http://stackoverflow.com/comment/83525308
type: AnswerComment
comment on: http://stackoverflow.com/a/48266736
type: Comment
has text: Yeah that was a bad wording I guess, sorry. A single instance of `False` should also be replaced, if the pattern applies
score: 0

http://stackoverflow.com/comment/83588489
has text: Yes, I have already done it with functions, but I prefer a more DRY way
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48301493
type: Comment

http://stackoverflow.com/q/48248567
has title: How to await a select.select call in python asyncio
upvote count: 15
has answer: http://stackoverflow.com/a/48250808
answer count: 1
downvote count: 0
has body: I have a python 3.6 program where I am using the asyncio package event loops. One of my data sources comes from an api which was not build around asyncio. My connection object contains a member called _connection which is just a python socket. Right now I can use this in a select statement to tell when data is ready. async def run(self): while True: if select.select([self._q._connection], [], [])[0]: msg = self._q.receive() print(msg) What I would really like is... async def run(self): while True: if await select.select([self._q._connection], [], [])[0]: msg = self._q.receive() print(msg) I know there is a sock_recv function in the asyncio event loop however I need the api to do the actual reading and decoding. I tried this but it would just fall through the await which I guess makes sense since I said 0 bytes. async def run(self): while True: print('A') await asyncio.get_event_loop().sock_recv(self._q._connection, 0) print('B') msg = self._q.receive() print(msg) The only solution I can think of for now is to add a small timeout to the select and then call asyncio.sleep while there is no data but this seems like an inefficent approach. I wish there was something like asyncio.select. Do anyone want to recommend another approach? EDIT: Right now I have come up with this. I don't like it because it adds an extra quarter second latency (probably doesn't matter much for my application but it still bugs me.) async def run(self): while True: if select.select([self._q._connection], [], [], 0)[0]: print(self._q.receive()) else: await asyncio.sleep(0.25)
favorite count: 0
accepted answer: http://stackoverflow.com/a/48250808
type: AnsweredQuestion
tagged with: python-asyncio
tagged with: sockets
tagged with: python
score: 15
type: Question

http://stackoverflow.com/a/48272993
downvote count: 0
type: Answer
has body: Doing a quick comparison between your original code and my code, here are the time differences: Your Code %%timeit # data ''' ID State perform A B C D 234 AK 75.8456 1 0 0 0 284 MN 78.6752 0 0 1 0 ''' # make dataframe dfr = pd.read_clipboard() df_a = dfr'ID', 'State', 'perform', 'A'.groupby(['ID', 'State']).corr().ix[1::2]'A'.reset_index(2).drop('level_2', axis=1) df_b = dfr'ID', 'State', 'perform', 'B'.groupby(['ID', 'State']).corr().ix[1::2]'B'.reset_index(2).drop('level_2', axis=1) df_c = dfr'ID', 'State', 'perform', 'C'.groupby(['ID', 'State']).corr().ix[1::2]'C'.reset_index(2).drop('level_2', axis=1) df_d = dfr'ID', 'State', 'perform', 'D'.groupby(['ID', 'State']).corr().ix[1::2]'D'.reset_index(2).drop('level_2', axis=1) df = df_a.merge(df_b, left_index=True, right_index=True) df = df.merge(df_c, left_index=True, right_index=True) df = df.merge(df_d, left_index=True, right_index=True) My Code %%timeit # data ''' ID State perform A B C D 234 AK 75.8456 1 0 0 0 284 MN 78.6752 0 0 1 0 ''' # make dataframe df = pd.read_clipboard() # make other dfs df_a = df.loc[:, :'A'].groupby([ 'ID', 'State' ]).corr().iloc[1::2]'A'.reset_index(2, drop = True) df_b = df.loc[:, [ 'ID', 'State', 'perform', 'B' ]].groupby([ 'ID', 'State' ]).corr().iloc[1::2]'B'.reset_index(2, drop = True) df_c = df.loc[:, [ 'ID', 'State', 'perform', 'C' ]].groupby([ 'ID', 'State' ]).corr().iloc[1::2]'C'.reset_index(2, drop = True) df_d = df.loc[:, [ 'ID', 'State', 'perform', 'D' ]].groupby([ 'ID', 'State' ]).corr().iloc[1::2]'D'.reset_index(2, drop = True) # concat them together pd.concat([df_a, df_b, df_c, df_d], axis = 1) The difference may still be negligible though. Edit Decided to try using a for loop to remove repeated code. Showed some improvement in run time: %%timeit # data ''' ID State perform A B C D 234 AK 75.8456 1 0 0 0 284 MN 78.6752 0 0 1 0 ''' # make dataframe df = pd.read_clipboard() # make list of letter columns letters = ['A', 'B', '…
score: 1
has comment: http://stackoverflow.com/comment/83552242
upvote count: 1
answers question: http://stackoverflow.com/q/48270953
has comment: http://stackoverflow.com/comment/83632771
has comment: http://stackoverflow.com/comment/83563236

http://stackoverflow.com/comment/83365526
has text: i'm getting this when debugging: contour.py:1534: UserWarning: Warning: converting a masked element to nan. self.zmax = float(z.min())
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48191593

http://stackoverflow.com/a/48233540
has comment: http://stackoverflow.com/comment/83451700
answers question: http://stackoverflow.com/q/48233041
type: Answer
has comment: http://stackoverflow.com/comment/83451038
has body: Using a for loop, you could extract year, month, and day, and convert them to integers. data = ['20170301', '20170302', '20170303', '20170304', '20170305'] yyyy_mm_dd = [] for date in data: year = int(date[:4]) month = int(date[4:6]) day = int(date[6:]) yyyy_mm_dd.append([year, month, day]) print(yyyy_mm_dd) # [[2017, 3, 1], [2017, 3, 2], [2017, 3, 3], [2017, 3, 4], [2017, 3, 5]] Use a list comprehension to extract days from yyyy_mm_dd: days = [sub[-1] for sub in yyyy_mm_dd] print(days) # [1, 2, 3, 4, 5]
downvote count: 0
score: 1
upvote count: 1

winpty
type: Tag
tag name: winpty
tags question: http://stackoverflow.com/q/48199794

http://stackoverflow.com/comment/83443011
score: 2
comment on: http://stackoverflow.com/q/48230296
type: Comment
type: QuestionComment
has text: I think it's better if you show what you have already tried so far. also it'd be good if you could show your solution for the prime numbers.

http://stackoverflow.com/comment/83526452
has text: Hmm, what numpy and matplotlib versions are you using?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48270006

http://stackoverflow.com/comment/83425911
type: QuestionComment
has text: Can you please upload an image from your scanner? You can blur out any sensitive information - we just need to get an idea for the logo's appearance/size.
score: 0
comment on: http://stackoverflow.com/q/48193843
type: Comment

http://stackoverflow.com/comment/83592000
has text: @sascha, thank your for your answer. l have another question if you don't mind. to choose the best alpha l need to do cross validation. Is there a way of how to make cross validation with SGDclassifier ? such like numpy.mean(cross_val_score(clf, data_train, train_labels, cv=5))
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48302463
score: 0

http://stackoverflow.com/q/48254629
upvote count: 0
answer count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/83491889
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83491926
tagged with: python-3.x
has body: I am trying to see how many values in a nested dictionary are &lt;= a value (rcEnterThreshold) subject to couple other simple conditions. The nested dictionary has about 10 million values and its taking about 30 seconds to do the following: numCandidateVars = sum(1 for f in reducedCosts for t in reducedCosts[f] if f!=t if reducedCosts[f][t][colGenLoopCounter] &lt;= rcEnterThreshold if t not in EdgeDict[f]) Is there a modification I can make to this to speed it up significantly? Should I scrap the use of dictionaries completely in favour of another data structure more suited? Any ideas greatly appreciated.
has answer: http://stackoverflow.com/a/48255328
possible better answer: http://stackoverflow.com/a/48255328
has answer: http://stackoverflow.com/a/48256059
accepted answer: http://stackoverflow.com/a/48256059
score: -3
has comment: http://stackoverflow.com/comment/83492196
tagged with: python
has comment: http://stackoverflow.com/comment/83492531
has comment: http://stackoverflow.com/comment/83493309
type: AnsweredQuestion
has title: Faster way to do a conditional sum from a nested dictionary?

http://stackoverflow.com/comment/83652542
has text: add a bunch of print statements and get display them
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48328486
score: 0

http://stackoverflow.com/q/48314694
tagged with: python
has comment: http://stackoverflow.com/comment/83615452
type: AnsweredQuestion
has title: After login the `rest-auth`, how to return more information?
accepted answer: http://stackoverflow.com/a/48338969
has answer: http://stackoverflow.com/a/78844685
answer count: 3
score: 14
possible better answer: http://stackoverflow.com/a/66819642
upvote count: 14
downvote count: 0
linked to: http://stackoverflow.com/q/51431768
has comment: http://stackoverflow.com/comment/83615351
has comment: http://stackoverflow.com/comment/83615485
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/78793640
has comment: http://stackoverflow.com/comment/83615155
tagged with: django-rest-auth
has answer: http://stackoverflow.com/a/48338969
has answer: http://stackoverflow.com/a/66819642
has body: I use django-rest-auth in my Django project. After login the rest-auth/login/, how to return more information? In the rest-auth/login/, when I login the user, it returns a key. I want to also return the user's information, how can I get this?
tagged with: django

http://stackoverflow.com/a/48274153
answers question: http://stackoverflow.com/q/48274129
has body: The () notation means that the data type is of tuple while the [] denotes a list. Additionally tuples use less memory and are immutable while lists are mutable.
has comment: http://stackoverflow.com/comment/83531827
type: Answer
score: 0

http://stackoverflow.com/comment/95728433
comment on: http://stackoverflow.com/a/49918848
type: Comment
has text: Ah it got fixed when I restarted my jupyter notebook kernel
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83574632
comment on: http://stackoverflow.com/q/48294965
score: 1
has text: Not really sure to understand your question, but you can use color picker (from google for example: https://www.google.fr/search?q=color+picker) to get rgb code
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48287850
score: 1
upvote count: 1
has body: For this specific case, Stefan's answer of: prediction = {file_name:ds.stt(*wav.read(directory)[::-1]) for file_name,directory in files.items()} is the most straightforward, reversing and then unpacking the results as positional arguments to ds.stt. If you have a scenario where constructing a valid slice isn't possible though (say, you need the 0th, 3rd and 4th values, or attributes spam and eggs) there are other ways to do this with a single call, while preserving the dict comprehension. All of them boil down to making a cached of the result somehow, so it can have multiple items pulled from it before it disappears: Via operator.itemgetter or operator.attrgetter: from operator import attrgetter, itemgetter # For specified indices with itemgetter (returns tuple of requested values in order specified) get1_0 = itemgetter(1, 0) prediction = {file_name:ds.stt(*get1_0(wav.read(directory))) for file_name,directory in files.items()} # For spam and eggs attributes via attrgetter in order specified: getspamandeggs = attrgetter('spam', 'eggs') prediction = {file_name:ds.stt(*getspamandeggs(wav.read(directory))) for file_name,directory in files.items()} Via nested loops in comprehension to make cached item: # Final line makes one-tuple of cached value and iterates it to give # a name for reuse prediction = {file_name:ds.stt(audio, wavelength) for file_name,directory in files.items() for wavelength, audio in (wav.read(directory),)} # Last line could be just for readval in (wav.read(directory),)} # If unpacking impractical, and then readval reused to index or look up attributes Two-liner, with a lazy generator expression to pair values, then a dict comprehension to consume it: prediction = ((file_name, wav.read(directory)) for file_name,directory in files.items()) prediction = {file_name:ds.stt(readval[1],readval[0]) for file_name, (wavelength, audio) in prediction} # Again, (wavelength, audio) could just be readval if you unpacking # impractical
has comment: http://stackoverflow.com/comment/83564042
type: Answer
has comment: http://stackoverflow.com/comment/83564856
answers question: http://stackoverflow.com/q/48287289
downvote count: 0
has comment: http://stackoverflow.com/comment/83560746

http://stackoverflow.com/comment/83387413
type: Comment
comment on: http://stackoverflow.com/q/48203126
score: 0
has text: _"I'd like to refactor it by writing a whole regex pattern instead of substituting."_ Why? Using `re.sub` is the easiest and most straightforward solution.
type: QuestionComment

typeahead
type: Tag
tag name: typeahead
tags question: http://stackoverflow.com/q/48239116

http://stackoverflow.com/comment/83603929
comment on: http://stackoverflow.com/q/48307646
score: 0
type: Comment
type: QuestionComment
has text: sounds more like an SQL question. There you would set indexes on some variables to access them faster but in pandas the index should be unique ( unique combinations) , s.t. you can identify the rows.

http://stackoverflow.com/a/48939491
downvote count: 0
type: Answer
score: 3
upvote count: 3
has body: I've been through this just now. See if this work for you: Make a new build system in Sublime Text: Tools > Build System > New Build System This will open an file "untitled.sublime-build" waiting for you to fill in. Paste the following in that file and fix the path so that it points to the python executable in your own tensorflow environment under anaconda. { "cmd": ["/Users/yourUserName/anaconda3/envs/tensorflow/bin/python3", "-u", "$file"], "file_regex": "^[ ]File \"(...?)\", line ([0-9]*)", "selector": "source.python"} } Save that file with a descriptive name like "tf_conda.sublime-build" Now build your python script using this custom build system. Choose Tools > Build System > tf_conda and Ctrl + b to build and run your script.
answers question: http://stackoverflow.com/q/48198844

http://stackoverflow.com/comment/83447754
type: AnswerComment
comment on: http://stackoverflow.com/a/48232629
has text: @JoeIddon, A) because the other two answers did; B) perhaps a list comprehension runs at Python speed, but `map` runs at **C** speed as long as the function is a built-in?
type: Comment
score: 0

http://stackoverflow.com/q/48310452
type: Question
tagged with: numpy
answer count: 0
has comment: http://stackoverflow.com/comment/83609585
downvote count: 0
has body: I'm trying to create a numpy array of strings in a C extension module. I cant tell what im doing wrong, I've tried various things at this point. My main issue is that im creating a fixed-size string type array, where the fixed size is effectively the max size but the strings are null-terminated c strings. The problem is that when I print out the array ive returned, it prints the entire fixed length rather than respecting the null terminator, ie: b'PZYJKT\x00A\x04' b'PZYJKBT\x00\x04' b'PZYJKBT\x00\x04' rather than b'PZYJKT' b'PZYJKBT' b'PZYJKBT' I set the dtype in this example = "S13". If I do the same thing in native python, everything works fine: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.array( [ 'PZYJKT', 'PZYJKBT', 'PZYJKBT' ], dtype = 'S13' ) array([b'PZYJKT', b'PZYJKBT', b'PZYJKBT'], dtype='|S13') even though internally it seems to be represented just like my string array: &gt;&gt;&gt; _.tobytes() b'PZYJKT\x00\x00\x00\x00\x00\x00\x00PZYJKBT\x00\x00\x00\x00\x00\x00PZYJKBT\x00\x00\x00\x00\x00\x00' The only thing I just noticed is that if i zero init the entire fixed string, then it seems to work similar to python. Could it be that numpy looks at the entire string for the last null-terminator? EDIT: Code im using to create the array: template&lt;size_t N&gt; PyObject * as_nparray( char * data ) { npy_intp dims[1]{ ( npy_intp ) buffer.size() }; bp::str date_type = ( "S"s + std::to_string( N ) ).c_str(); PyArray_Descr *descr; PyArray_DescrConverter( date_type.ptr(), &amp;descr ); return PyArray_NewFromDescr( &amp;PyArray_Type, descr, 1, dims, NULL, data, NPY_ARRAY_OWNDATA, NULL ); } I'll also add that I found this post which seems to imply my suspicion that numpy strings are expected to be null padded rather than null terminated: https://mail.scipy.org/pipermail/numpy-discussion/2014-July/070637.html
has title: How to properly create numpy string arrays using the NumPY C API
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83608739
favorite count: 0
upvote count: 3
score: 3
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/83606742

http://stackoverflow.com/comment/83466757
comment on: http://stackoverflow.com/q/48242168
type: QuestionComment
score: 1
type: Comment
has text: The former will take slightly longer, the latter will occupy memory even when it doesn't need to. Neither will ever be enough to matter. The latter is better because it makes it easier to change all of your messages as a group.

http://stackoverflow.com/a/48306699
has body: I believe you can do this with a combination of numpy.where and numpy.all. Using all to check for all zeros along the last dimension will give you a boolean array that is True where the null_class should be 1. I will use a (2,2,5) array for the sake of display. arr = np.random.randint(0, 2, size=(2,2,5)) null_class = np.zeros(arr.shape[:-1]) arr[0, 0] = [0, 0, 0, 0, 0] arr array([[[0, 0, 0, 0, 0], [1, 1, 1, 1, 1]], [[0, 0, 1, 0, 0], [0, 1, 1, 1, 0]]]) np.all(arr[:, :] == 0, axis=2) array([[ True, False], [False, False]], dtype=bool) np.where(np.all(arr[:, :] == 0, axis=2)) (array([0]), array([0])) null_class[np.where(np.all(arr[:, :] == 0, axis=2)] = 1 null_class array([[ 1., 0.], [ 0., 0.]])
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48304756
answers question: http://stackoverflow.com/q/48304756
type: Answer
has comment: http://stackoverflow.com/comment/83641964

http://stackoverflow.com/q/48228241
has answer: http://stackoverflow.com/a/48228316
type: Question
answer count: 1
tagged with: javascript
tagged with: python
type: AnsweredQuestion
has body: Here's the code: for eachP in arr14: print('{1} onclick="" '.format(arr14.index(eachP), eachP)) Now, this code is in working state but, I want to alter the code and do something with the onclick="" attribute. I would like to detect which link user has pressed and alerting the exact same link. The code that I was writing was this: onclick=" " Note: It's a .py file and I am using HTML, JS and Python(of course) inside it. I am having problem with the onclick event. I would highly appreciate if anyone could help solve my problem ^.^
has title: Detecting which link is clicked with pure Javascript
score: 0
tagged with: http://stackoverflow.com/tag/html
accepted answer: http://stackoverflow.com/a/48228316

http://stackoverflow.com/a/48201339
has body: You can reduce the task to merging two dictionaries into one and then use reduce and the binary merging function in order to merge your entire list of dictionaries: from functools import reduce # Python3, no import needed in Python2 def merge(d1, d2): mk = max(d1) if d1 else 0 # max key of d1 return dict(list(d1.items()) + [(mk+k, d2[k]) for k in d2]) reduce(merge, [d1, d2, d3]) # reduce dicts # {1: 'a', 2: 'k', 3: 'l', 4: 'j', 5: 'k', 6: 'j', 7: 'n', 8: 'j', 9: 'k', 10: 'j', 11: 'i', 12: 'j'}
upvote count: 2
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48201152

http://stackoverflow.com/comment/83520217
type: AnswerComment
score: 0
type: Comment
has text: Ok, if you would like, take a look at this question: https://stackoverflow.com/questions/48268522/python-performance-image-slicing-numpy
comment on: http://stackoverflow.com/a/48267073

http://stackoverflow.com/q/48304947
type: Question
has comment: http://stackoverflow.com/comment/83617060
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/48322237
has comment: http://stackoverflow.com/comment/83595032
score: 2
upvote count: 2
type: AnsweredQuestion
has title: How to format all cells in one sheet based on corresponding cell values in another sheet using XlsxWriter?
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/83596643
tagged with: xlsxwriter
answer count: 1
has body: I am exporting to Excel two pandas DataFrames using XlsxWriter, each DataFrame having a separate sheet. I would like to apply a colour format to all the cells in one sheet based on values in another sheet, they correspond one-to-one based on column names and row numbers. Example: Sheet1 A B C 1 1 3 1 2 0 4 2 Sheet2 A B C 1 a d b 2 b a a I would like to assign a colour format to all the cells in Sheet1 that have a value 'a' in Sheet2.
has comment: http://stackoverflow.com/comment/83602798
has answer: http://stackoverflow.com/a/48322237
tagged with: excel
favorite count: 0

http://stackoverflow.com/q/48192424
has comment: http://stackoverflow.com/comment/83522113
upvote count: 0
has answer: http://stackoverflow.com/a/48269413
accepted answer: http://stackoverflow.com/a/48269413
answer count: 1
has title: Python using Fuzzywuzzy to compare a csv to excel and copy data from csv file to excel based approximate data in the excel file
downvote count: 1
tagged with: excel
favorite count: 0
has body: I have the following code that will copy and paste data from a csv file to an excel file (it compares names of employees and copies the date). The only problem is that it only copies dates for exact matches (William to William, as opposed to Will to William). Is there anyway to use fuzzywuzzy to make it also copy data from approximate matches. The code is listed below. from fuzzywuzzy import fuzz from fuzzywuzzy import process import csv import openpyxl import datetime training_updates = {}; with open('from.csv') as frombook: reader = csv.DictReader(frombook) for row in reader: if int(row["ViewTotalScore"]) &gt; 70: training_updates[(row["ViewerInfo"].strip("[]").lower())] = (row["DateTime"])[:-8].rstrip() wb = openpyxl.load_workbook('to.xlsm', data_only=True, keep_vba=True) wb2 = openpyxl.load_workbook('to.xlsm', keep_vba=True) sheetcheck = wb.get_sheet_by_name(wb.get_sheet_names()[0]) sheetwrite = wb2.get_sheet_by_name(wb2.get_sheet_names()[0]) for rowNum in range(2, sheetcheck.max_row): if sheetcheck.cell(row=rowNum, column=3).value is not None: employee = str(sheetcheck.cell(row=rowNum, column=3).value).lower() if employee in training_updates: xldate = datetime.datetime.strptime(training_updates[employee], "%Y-%m-%d").strftime("%m/%d/%Y") sheetwrite.cell(row=rowNum, column=5).value = xldate print("Updated record for " + employee) wb2.save('updatedto.xlsm') I have used fuzzywuzzy extractOne to try to pull them as well and that hasn't yielded any results for fuzzy matches: import csv import openpyxl import datetime from fuzzywuzzy import fuzz from fuzzywuzzy import process training_updates = {}; # create workbook object 'wb' from 'from.xlsm' with open('from.csv') as frombook: reader = csv.DictReader(frombook) for row in reader: if int(row["ViewTotalScore"]) &gt; 70: training_updates[(row["ViewerInfo"].strip("[]").lower())] = (row["DateTime"])[:-8].rstrip() wb = openpyxl.load_workbook('to.xlsm', data_only=True, keep_vba=True) wb2 = openpyxl.load_workbook('to.xlsm',…
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: -1
type: Question

http://stackoverflow.com/comment/83571676
type: Comment
has text: What I want to achieve is that when I call the method "newElement" with the name as parameter, say "quad8", I should be able to call the constructor of the subclass "ElementQuad2D()" from the enum "elements". My current implementation in Python involves bunch of if else statements which would be problematic, if I implement many such element types. I don't want exact implementation, but something close to this.
type: QuestionComment
comment on: http://stackoverflow.com/q/48278260
score: 0

http://stackoverflow.com/q/48318624
has comment: http://stackoverflow.com/comment/83622629
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83623446
accepted answer: http://stackoverflow.com/a/48492949
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48492949
has comment: http://stackoverflow.com/comment/83623207
tagged with: http://stackoverflow.com/tag/json
has body: I need to compare to JSON objects only for the keys, but not the value. These JSON objects can be nested ones, containing dictionaries, arrays, and other objects. Please suggest me an efficient way of doing this. Again, I need to compare only if both JSON objects have same keys and same structure. Below are example JSONs First JSON { name: 'my object', description: 'it is an object', details: { it: 'has', an: 'array', with: ['a', 'few', 'elements'] } } Second JSON { name: 'updated object', description: 'it is an object!', details: { it: 'has', an: 'array', with: ['a', 'few', 'more', 'elements'] } } Above pair of JSONs, when compared should not give any difference because they have the same keys.
favorite count: 0
type: Question
downvote count: 4
has title: JSON Structural Difference
score: -3
answer count: 1

http://stackoverflow.com/comment/83365664
comment on: http://stackoverflow.com/q/48191933
score: 0
type: Comment
has text: I guess not. I always tried to keep the conda packages, but maybe it's better the other way around.
type: QuestionComment

http://stackoverflow.com/q/48190241
downvote count: 0
tagged with: usrp
score: 3
tagged with: python
favorite count: 0
type: Question
tagged with: gnuradio
has title: How can I read B210 GPS sensor while capturing data in gnuRadio
answer count: 0
has body: I am working with a B210 USRP from Ettus Research and for some reason it keeps dropping GPS lock. I would like to periodically poll the GPS lock status and save it to a file while running. The basic design was generated in gnuradio-companion where the USRP source block is tied to a File Sink block. From there, the python was modified to check the GPS lock from the GPSDO looping on self.usrp.get_mboard_sensor("gps_locked",0).to_bool() in the __init__() function. I've added the function below to the class to read GPS data so that I can access it from another process. def getGPS(self,gps_field): return self.usrp.get_mboard_sensor(gps_field,0).value When I call the above function from another process, it works the first time through but then produces the following error: Process Process-1: Traceback (most recent call last): File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap self.run() File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run self._target(*self._args, **self._kwargs) File "./experiment.py", line 291, in monitorGPS locked = tb.getGPS('gps_locked') File "./experiment.py", line 158, in getGPS return self.usrp.get_mboard_sensor(gps_field,0).value File "/usr/local/lib/python2.7/dist-packages/gnuradio/uhd/uhd_swig.py", line 3493, in get_mboard_sensor return _uhd_swig.usrp_sink_sptr_get_mboard_sensor(self, name, mboard) RuntimeError: ValueError: locked(): unable to determine GPS lock status Is it possible to access GPS information while running a data collect and if so, where am I going wrong here? -Edit- It turns out that using threading rather than multiprocessing allows me to access GPS information without error. I would still like to know if there is a better way of going about this.
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/comment/83470959
type: QuestionComment
has text: I used `requests` and found that this package loads data in two steps. First, the metadata, reads the path to the ACTUAL data (which is https://pkgstore.datahub.io/core/population/population/data/c8df6fc75bdf8cbdb0052140b7eeba7f/population.csv among others), and then reads _that_.
type: Comment
comment on: http://stackoverflow.com/q/48244071
score: 0

http://stackoverflow.com/q/48213190
has comment: http://stackoverflow.com/comment/83412564
tagged with: anaconda
has body: Hi I'm new to Anaconda and Spyder and I'm having some problems when running spyder. Firstly, when I write "spyder" in Terminal, while it starts it gives me this code: [warn] kq_init: detected broken kqueue; not using.: Undefined error: 0 [warn] kq_init: detected broken kqueue; not using.: Undefined error: 0 [warn] kq_init: detected broken kqueue; not using.: Undefined error: 0 [warn] kq_init: detected broken kqueue; not using.: Undefined error: 0 [warn] kq_init: detected broken kqueue; not using.: Undefined error: 0 [warn] kq_init: detected broken kqueue; not using.: Undefined error: 0 [warn] kq_init: detected broken kqueue; not using.: Undefined error: 0 [warn] kq_init: detected broken kqueue; not using.: Undefined error: 0 js: Not allowed to load local resource: file:///*****/*******/anaconda/lib/python3.6/site-packages/spyder/utils/help/static/css/default.css I've found that if write "export EVENT_NOKQUEUE=1" before running spyder, all the "[warn] kq_init: detected broken kqueue; not using.: Undefined error: 0" messages disappear, but I have to write it every time I want to run spyder. I haven't found any solution to the "js: Not allowed to load local resource" problem. Moreover, when I open spyder the console shows the following message: An error ocurred while starting the kernel Your Python environment or installation doesn't have the ipykernel and cloudpickle modules installed on it. Without these modules is not possible for Spyder to create a console for you. You can install them by running in a system terminal: pip install ipykernel cloudpickle or conda install ipykernel cloudpickle I've installed ipykernel and cloudpickle but it doesn't work and continues showing the message. What should I do? Can someone help me? Thank you
has comment: http://stackoverflow.com/comment/83408241
tagged with: spyder
has comment: http://stackoverflow.com/comment/83412677
has comment: http://stackoverflow.com/comment/83408042
has title: Spyder launching
score: 1
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83412604
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/q/48242320
type: Question
accepted answer: http://stackoverflow.com/a/48278102
upvote count: 5
tagged with: apache-beam
tagged with: python
tagged with: google-cloud-dataflow
has body: We are running logfile parsing jobs in google dataflow using the Python SDK. Data is spread over several 100s of daily logs, which we read via file-pattern from Cloud Storage. Data volume for all files is about 5-8 GB (gz files) with 50-80 million lines in total. loglines = p | ReadFromText('gs://logfile-location/logs*-20180101') In addition, we have a simple (small) mapping csv, that maps logfile-entries to human readable text. Has about 400 lines, 5 kb size. For Example a logfile entry with [param=testing2] should be mapped to "Customer requested 14day free product trial" in the final output. We do this in a simple beam.Map with sideinput, like so: customerActions = loglines | beam.Map(map_logentries,mappingTable) where map_logentries is the mapping function and mappingTable is said mapping table. However, this only works if we read the mapping table in native python via open() / read(). If we do the same utilising the beam pipeline via ReadFromText() and pass the resulting PCollection as side-input to the Map, like so: mappingTable = p | ReadFromText('gs://side-inputs/category-mapping.csv') customerActions = loglines | beam.Map(map_logentries,beam.pvalue.AsIter(mappingTable)) performance breaks down completely to about 2-3 items per Second. Now, my questions: Why would performance break so badly, what is wrong with passing a PCollection as side-input? If it is maybe not recommended to use PCollections as side-input, how is one supposed to build such as pipeline that needs mappings that can/should not be hard coded into the mapping function? For us, the mapping does change frequently and I need to find a way to have "normal" users provide it. The idea was to have the mapping csv available in Cloud Storage, and simply incorporate it into the Pipeline via ReadFromText(). Reading it locally involves providing the mapping to the workers, so only the tech-team can do this. I am aware that there are caching issues with side-input, but surely this should not apply to a 5…
linked to: http://stackoverflow.com/q/43958372
has answer: http://stackoverflow.com/a/48278102
has title: Google Dataflow / Apache Beam Python - Side-Input from PCollection kills performance
type: AnsweredQuestion
answer count: 2
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/83525775
has comment: http://stackoverflow.com/comment/83527783
has comment: http://stackoverflow.com/comment/83539472
possible better answer: http://stackoverflow.com/a/48245716
has answer: http://stackoverflow.com/a/48245716
has comment: http://stackoverflow.com/comment/83491186
favorite count: 0

http://stackoverflow.com/comment/83607768
type: AnswerComment
has text: Alright, I now understand. Admin is not a file, but rather a directory. Regarding the __init__.py file, am I right to understand it as this: without it, Admin will not be regarded as a package, and it will be impossible to import from, for example sites. Moreover, __init__ allows me to import functions and classes etc, thus making them easier to import in a script (making it possible to go 'admin.site' instead of 'admin.sites.site'). IF this is true, I think I've completely got it! Thank you S O much! Really. Thank you thank you thank you.
score: 0
comment on: http://stackoverflow.com/a/48310438
type: Comment

http://stackoverflow.com/a/48293650
downvote count: 0
type: Answer
has body: query_pokeapi must be returning None, which would mean that your API call is not receiving a 200 HTTP response. I'd check your URL, to make sure it's properly formed. Test it in your web browser. best practice would be to try-except your API call with an error message letting you know that your API call failed and otherwise routing the thread. Update: reread and the sub scripting issue could be in any layer of your nested object. Evaluate charizard['sprites'][0]['resource_uri'] step by step in your debugger.
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/48293582

http://stackoverflow.com/q/48294789
has title: I need to search a string in data file. but the string is written in another file
tagged with: file
accepted answer: http://stackoverflow.com/a/48294932
has body: I have key words to be search in one file let say abc.txt and in another file I have my data, def.txt. I want a code in python to find key words written in abc.txt, in def.txt and if present, print those line in a new file. Thank you. I tried writing a code but it didn't work. following is the code I write. f = open('/home/vivek/Documents/abc.txt') f1 = open('output.txt', 'a') f2 = open('/home/vivek/Documents/def.txt', 'r') # doIHaveToCopyTheLine=False for line in f.readlines(): if f2 in line: f1.write(line) f1.close() f.close() f2.close()
has comment: http://stackoverflow.com/comment/83574368
has comment: http://stackoverflow.com/comment/83574488
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48295285
has comment: http://stackoverflow.com/comment/83574350
tagged with: python
has comment: http://stackoverflow.com/comment/83574417
has answer: http://stackoverflow.com/a/48294932
answer count: 4
has comment: http://stackoverflow.com/comment/83574437
type: Question
has answer: http://stackoverflow.com/a/48295671
has answer: http://stackoverflow.com/a/48294933
possible better answer: http://stackoverflow.com/a/48294933

http://stackoverflow.com/a/48293549
has comment: http://stackoverflow.com/comment/83572643
has comment: http://stackoverflow.com/comment/83572586
has comment: http://stackoverflow.com/comment/83574695
has comment: http://stackoverflow.com/comment/83572753
has comment: http://stackoverflow.com/comment/83574701
score: 0
has comment: http://stackoverflow.com/comment/83574249
has body: Edit-1: You need use below code for your main.py without any changes to downloader.py from __future__ import print_function import urllib3.poolmanager orig_urlopen = urllib3.poolmanager.PoolManager.urlopen def new_urlopen(self, method, url, redirect=True, **kw): if "s3.amazonaws.com" in url and 'authorization' in self.headers: self.headers.pop('authorization') return orig_urlopen(self, method, url, redirect, **kw) urllib3.poolmanager.PoolManager.urlopen = new_urlopen import logging from selenium import webdriver logging.basicConfig(level=logging.DEBUG) from client_config import ClientConfig from pyupdater.client import Client, AppUpdate import http.client as http_client http_client.HTTPConnection.debuglevel = 1 def check_for_update(): client = Client(ClientConfig(), refresh=True, headers={'basic_auth': '&lt;username&gt;:&lt;password&gt;'}) app_update = client.update_check(ClientConfig.APP_NAME, ClientConfig.APP_VERSION, channel='stable') if app_update is not None: if app_update.download(): if isinstance(app_update, AppUpdate): app_update.extract_restart() return True else: app_update.extract() return True return False def main(): print('Current version is ', ClientConfig.APP_VERSION) if check_for_update(): print('there\'s a new update :D') # driver = webdriver.Firefox() # driver.get('http://stackoverflow.com') if __name__ == "__main__": main() original answer You need to use monkey patching for this. Below patch should do the job import urllib3.poolmanager orig_urlopen = urllib3.poolmanager.PoolManager.urlopen def new_urlopen(self, method, url, redirect=True, **kw): if "s3.amazonaws.com" in url and 'Authorization' in self.headers: self.headers.pop('Authorization') return orig_urlopen(self, method, url, redirect, **kw) urllib3.poolmanager.PoolManager.urlopen = new_urlopen A sample test worked for me with the above patch import urllib3 pool = urllib3.PoolManager() pool.headers.update({'Authorization': 'Basic XYZ=='}) r = pool.urlopen('GET', 'https://api.bitbucket.org/…
has comment: http://stackoverflow.com/comment/83577236
answers question: http://stackoverflow.com/q/48218119
has comment: http://stackoverflow.com/comment/83574530
type: Answer
accepted answer of: http://stackoverflow.com/q/48218119
type: AcceptedAnswer

http://stackoverflow.com/q/48206396
has title: Append Multiples of Squares of integers greater than 2 and sort them
type: UnansweredQuestion
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83398780
has answer: http://stackoverflow.com/a/48225098
has body: For Example : 4,8,9,12,16,18,....... How can we do this for big size array? The basic one I made, took a lot of time to execute : for i in range(1,1000): for j in range(2,1000): l.append((i)*((j)*(j))) s=set(l) l1=list(s) l1.sort() print(l1) Size of list should be in order of 10^6.
favorite count: 0
type: Question
tagged with: numbers
score: -3
has comment: http://stackoverflow.com/comment/83396479
tagged with: python
tagged with: sequence
has comment: http://stackoverflow.com/comment/83428981
has comment: http://stackoverflow.com/comment/83400592
downvote count: 4

http://stackoverflow.com/comment/83474977
comment on: http://stackoverflow.com/a/48246009
type: AnswerComment
has text: I just noticed that the power method is much slower when the input array `x` is an array of floating point values instead of integers. Try your timing comparison again, but with `x = np.arange(5000.0)`. (The example `x` in the question is an integer array, so this might not matter to @kmario23.)
score: 1
type: Comment

http://stackoverflow.com/a/48282752
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48282539
score: 1
answers question: http://stackoverflow.com/q/48282539
type: Answer
has body: If you are about to scrape a page that generates its content dynamically, the first thing to do is to look for an API being called. In your browser's development tools, look for XHR requests in the network tab. For the page you refer to, I can see request for https://www.ncbi.nlm.nih.gov/genomes/Genome2BE/genome2srv.cgi?action=GetGenomes4Grid&amp;genome_id=971&amp;genome_assembly_id=&amp;king=Bacteria&amp;mode=2&amp;flags=1&amp;page=1&amp;pageSize=100. If you look in the response, you'll see that it contains the links that are under the FTP column on the page. You can simply use this API to get the information you need. If you really want to render the page and scrape it, I suggest you use Splash. The best way to integrate it with Scrapy is using scrapy-splash library.
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48217754
has answer: http://stackoverflow.com/a/48217877
tagged with: python-3.x
answer count: 2
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/48217877
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/48217879
upvote count: 3
has body: I'm building a new Python 3 interface to an existing mySQL database. The table called "Tickets" may or may not contain a row for a particular member. I'm trying to fetch the ticket number if it exists, and do something else if it doesn't. My code looks like this: import mysql.connector config = { 'user': 'XXXXXXXXXXXXX', 'password': 'XXXXXXXXXXXXX', 'host': 'XXXXXXXXXXXXX', 'database': 'XXXXXXXXXXXXX', 'raise_on_warnings': True } membernum = 9 db = mysql.connector.connect(**config) if db.is_connected(): cursor = db.cursor() query = "SELECT ticketnum FROM Tickets WHERE membernum={} limit 1".format(membernum) cursor.execute(query) if cursor.rowcount == 0: print("No results") else: result = cursor.fetchone() ticketnum = result[0] print(ticketnum) cursor.close db.close else: print("Connection error") It works beautifully if there is a record matching that member. If not, it generates: Traceback (most recent call last): File "/Users/Gary/IPPS/samplecode.py", line 22, in &lt;module&gt; ticketnum = result[0] TypeError: 'NoneType' object is not subscriptable What am I doing wrong? UPDATE The answer from murphy1310 took care of it! I changed the code to the following, and it worked just fine: import mysql.connector config = { 'user': 'XXXXXXXXXXXXX', 'password': 'XXXXXXXXXXXXX', 'host': 'XXXXXXXXXXXXX', 'database': 'XXXXXXXXXXXXX', 'raise_on_warnings': True } membernum = 9 db = mysql.connector.connect(**config) if db.is_connected(): cursor = db.cursor() query = "SELECT ticketnum FROM Tickets WHERE membernum={} limit 1".format(membernum) cursor.execute(query) result = cursor.fetchone() if result != None: ticketnum = result[0] print(ticketnum) else: print("No results") cursor.close db.close else: print("Connection error")
has answer: http://stackoverflow.com/a/48217879
tagged with: mysql
tagged with: mysql-connector
favorite count: 0
has title: Determining when no database rows match with Python mysql.connector
type: Question

http://stackoverflow.com/comment/83511379
type: AnswerComment
comment on: http://stackoverflow.com/a/48221852
has text: That's why we do 'cd ~' to go home directory, Thanks!
type: Comment
score: 0

django-generic-views
type: Tag
tags question: http://stackoverflow.com/q/48176774
tag name: django-generic-views

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/48290089
tags question: http://stackoverflow.com/q/48214975
tags question: http://stackoverflow.com/q/48307363
tags question: http://stackoverflow.com/q/48324176
tag name: xml
tags question: http://stackoverflow.com/q/48324475
tags question: http://stackoverflow.com/q/48291273
tags question: http://stackoverflow.com/q/48313409
tags question: http://stackoverflow.com/q/48329964
type: Tag
tags question: http://stackoverflow.com/q/48272799
tags question: http://stackoverflow.com/q/48280452
tags question: http://stackoverflow.com/q/48232437
tags question: http://stackoverflow.com/q/48206447
tags question: http://stackoverflow.com/q/48226367
tags question: http://stackoverflow.com/q/48280153
tags question: http://stackoverflow.com/q/48217974
tags question: http://stackoverflow.com/q/48321472
tags question: http://stackoverflow.com/q/48212302
tags question: http://stackoverflow.com/q/48268571
tags question: http://stackoverflow.com/q/48252155
tags question: http://stackoverflow.com/q/48229868
tags question: http://stackoverflow.com/q/48269813
tags question: http://stackoverflow.com/q/48206721
tags question: http://stackoverflow.com/q/48314206
tags question: http://stackoverflow.com/q/48230007
tags question: http://stackoverflow.com/q/48276477
tags question: http://stackoverflow.com/q/48292943
tags question: http://stackoverflow.com/q/48278144
tags question: http://stackoverflow.com/q/48326179

http://stackoverflow.com/comment/83682737
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48329350
has text: the editor for math.stackexchange.com is https://stackedit.io/. It's also opensource and you find it there: https://github.com/benweet/stackedit. it uses KaTeX under the hood.

http://stackoverflow.com/comment/83602547
type: Comment
type: QuestionComment
score: 0
has text: @juanpa.arrivillaga what else could the input be? if it's from a file or `input()` then it's a string, and it's not a valid Python object to `pickle` or anything
comment on: http://stackoverflow.com/q/48305898

http://stackoverflow.com/comment/83373336
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48193437
has text: Thanks, this is on the right track! This works in the sense that it prints the stuff in the "address" tag(s). When I try to store it, however, I get errors.

dynamic-dispatch
type: Tag
tag name: dynamic-dispatch
tags question: http://stackoverflow.com/q/48232372

http://stackoverflow.com/q/48282893
has title: JSON file not being loaded because of not defined variable
downvote count: 1
has comment: http://stackoverflow.com/comment/83549599
has body: I have a a python script which is being fed and executed from a html file. This script writes a json file and i'd like to read the json file with javascript. The values are definetely being passed from html to python and they are being processed correctly. As soon as I want to load the json-file the web console throws an error saying "data is not defined". The relevant python code: data = {} for i in range(t_final.size): data[i] = t_final[i] with open('data.json', 'w') as fp: json.dump(data, fp) Javascript call: &lt;script type="text/javascript" src="/cgi-bin/data.json"&gt;&lt;/script&gt; &lt;script type="text/javascript" &gt; function load() { var mydata = JSON.parse(data); var div = document.getElementById('xbtn'); } &lt;/script&gt; &lt;div id="xbtn"&gt;&lt;/div&gt; This is what the json-file contains after executing {"0": 0.0, "1": 0.013508013525931116, ... , "1999": -0.0} I am working on this for days now and maybe I just don't see it. I presume it is something very obvious. thanks for any help.
has comment: http://stackoverflow.com/comment/83549549
has comment: http://stackoverflow.com/comment/83549687
tagged with: http://stackoverflow.com/tag/json
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83551856
upvote count: 0
type: UnansweredQuestion
tagged with: javascript
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48295568

http://stackoverflow.com/comment/83391020
type: Comment
type: QuestionComment
score: 0
has text: you are welcome. :)
comment on: http://stackoverflow.com/q/48187740

http://stackoverflow.com/q/48314588
upvote count: 0
has comment: http://stackoverflow.com/comment/83615004
has answer: http://stackoverflow.com/a/48314707
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48314849
has body: How I can convert following raw data into something easier for computation info.teams ['Australia', 'Sri Lanka'] ['Australia', 'Sri Lanka'] ['Australia', 'Sri Lanka'] ['India', 'West Indies'] ['India', 'West Indies'] ['Bangladesh', 'West Indies'] ['Australia', 'Sri Lanka'] ['Bangladesh', 'India'] ['Australia', 'Sri Lanka'] ['India', 'West Indies'] ['India', 'South Africa'] ['Afghanistan', 'India'] ['India', 'South Africa'] ['Australia', 'Sri Lanka'] ['India', 'Sri Lanka'] ['India', 'Sri Lanka'] ['India', 'Sri Lanka'] ['Australia', 'Sri Lanka'] ['Bangladesh', 'West Indies'] ['Afghanistan', 'India'] ['India', 'South Africa'] ['Australia', 'Sri Lanka'] ['Australia', 'Sri Lanka'] ['Bangladesh', 'West Indies'] ['India', 'West Indies'] ['Bangladesh', 'West Indies'] ['Bangladesh', 'India'] ['India', 'South Africa'] This is the datatype of the column. info.teams 1547 non-null object Suppose if i want to find out the teams that have played together for eg. ['India','Australia'] I Have to code as follows: #choosing particular teams team_1='India' team_2='Australia' team_12='['+"'"+team_1+"'"+', '+"'"+team_2+"'"+']' team_21='['+"'"+team_2+"'"+', '+"'"+team_1+"'"+']' df=df[(df['info.teams']==team_12) | (df['info.teams']==team_21)]
possible better answer: http://stackoverflow.com/a/48314707
has title: pandas changing category of raw data
has comment: http://stackoverflow.com/comment/83614936
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83614983
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/48314849
tagged with: pandas

http://stackoverflow.com/q/48319303
has body: I created a web interface in Grails 3 where you can start different pipelines written in python via a web environment. I have created a simple form with a start button. The idea is now that when you press the start button the python pipeline is started. I can't figure it out I have tried several things a example is: def cmd = "python amplicon_pipeline.py -i 'inputdir' -o 'outputdir' -a 'amplicon'" def proc = cmd.execute() proc.waitFor() But nothing happens. How can I get an external python script to start working when you press the start button?
has comment: http://stackoverflow.com/comment/83624266
type: Question
has comment: http://stackoverflow.com/comment/83624693
has answer: http://stackoverflow.com/a/48319985
linked to: http://stackoverflow.com/q/42126690
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83624211
answer count: 1
tagged with: python
tagged with: grails
has title: Start a python script from grails 3

http://stackoverflow.com/comment/83361970
comment on: http://stackoverflow.com/a/48189386
score: 0
type: Comment
has text: @RudyVelthuis: Now, x and y may have less precision because they are subnormal. Errors could have occurred in prior calculations, and x and y might now not be what you want them to be. But, whatever they **are currently**, that will be the input to the division. **Exactly.** And the division will produce the correct result. And, if x and y do have errors from previous operations, taking their logarithms will not help.
type: AnswerComment

http://stackoverflow.com/comment/83341742
has text: For the most part, that DataFrame API is the exact same...
comment on: http://stackoverflow.com/q/48180935
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48254162
tagged with: python
has comment: http://stackoverflow.com/comment/83490894
answer count: 3
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/55561127
has body: I'm trying to run an existing app in a new environment. The app ran fine in a previous environment, but when I run it locally it refuses to connect with my DB. AssertionError: The sqlalchemy extension was not registered to the current application. Please make sure to call init_app() first. Where I'm confused is that this exact code worked in a previous environment. It's asking me to call init_app() but, from my understanding, that's only if there are multiple apps, which there aren't. In debugging mode, the app does recognize the object i.e. &gt;&gt;&gt; type(Candidate) &lt;class 'flask_sqlalchemy.model.DefaultMeta'&gt; I am unclear how and where to incorporate app_init() into my code. I have tried... db = SQLAlchemy(app) db.init_app(app) but this didn't have any impact. Folder structure... app - static folder - templates folder - _init_.py - config.py - views.py - run.py - Procfile
has answer: http://stackoverflow.com/a/48283279
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83491107
has title: Registering sqlalchemy extension with current application using init_app()
has answer: http://stackoverflow.com/a/48254268

http://stackoverflow.com/q/48273089
type: UnansweredQuestion
favorite count: 0
tagged with: timestamp
tagged with: datetimeindex
has comment: http://stackoverflow.com/comment/83530344
linked to: http://stackoverflow.com/q/48260456
type: Question
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/83569939
has comment: http://stackoverflow.com/comment/83530237
downvote count: 0
has comment: http://stackoverflow.com/comment/83546897
answer count: 0
has title: Pandas DatetimeIndex issue with last week of year
upvote count: 1
has body: Continuing on my previous question, I have another dataframe that the week column starts with 201553. When I change weekly columns to timestamp, belwo occured. Please take a look. a = pd.Int64Index([201553, 201601, 201602, 201603, 201604, 201605, 201606, 201607, 201608, 201609]) print (pd.to_datetime(a.astype(str) + '1', format='%Y%W%w')) DatetimeIndex(['2016-01-04', '2016-01-04', '2016-01-11', '2016-01-18', '2016-01-25', '2016-02-01', '2016-02-08', '2016-02-15', '2016-02-22', '2016-02-29'], dtype='datetime64[ns]', freq=None) Notice that my first index starts with 201553 and when I change into DatatimeIndex, it shows '2016-01-04' which is wrong. I want need to have '2015-12-28' for the first index. Is there a way to change only the first index of a? Please let me know. Thanks! -------edit------- 201553 means year 2015, 53rd week. If you see the DatetimeIndex, each date is Monday of each week. So week number 53 in year 2015 should start with '2015-12-28', but my DatatimeIndex is showing '2016-01-04'. All I need to do is fix this. Hope this makes more sense to everyone. Sorry for the confusion. Thanks! -------edit2------ I kinda self-solved the question. I changed the a.index[0] to 201552 and it gave me the exact date I want. But still, I want to find out correct way to solve this problem. Thanks
tagged with: python

http://stackoverflow.com/comment/83569422
type: QuestionComment
comment on: http://stackoverflow.com/q/48292100
has text: Possible duplicate of [Django: Creating a Mixin for Reusable Model Fields](https://stackoverflow.com/questions/6014282/django-creating-a-mixin-for-reusable-model-fields)
score: 0
type: Comment

http://stackoverflow.com/comment/83329528
type: Comment
type: AnswerComment
has text: I would just install it inside your virtual environment. I think that trying to mix "stuff inside your virtual environment" with "stuff outside the virtual environment" is a recipe for confusion (e.g., different versions of python, or different versions of particular modules installed, etc). But @tripleee has a suggestion if you really want to do that.
comment on: http://stackoverflow.com/a/48174818
score: 0

http://stackoverflow.com/a/48232666
type: Answer
answers question: http://stackoverflow.com/q/48231913
score: 0
type: AcceptedAnswer
has body: As per the comment by coldspeed for pointing out that the variable required to be returned by the function needs to be defined in order to use it. jID = parseXML('status','job') first, and then you can use it outside its function. – cᴏʟᴅsᴘᴇᴇᴅ 53 mins ago Updated the guthub files if anyone wants to review. Thanks again for the help
has comment: http://stackoverflow.com/comment/83448686
has comment: http://stackoverflow.com/comment/83448153
accepted answer of: http://stackoverflow.com/q/48231913

http://stackoverflow.com/comment/83469138
has text: Why not: `len(str(abs(number)))` ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48243348
score: 2

http://stackoverflow.com/comment/83573985
type: AnswerComment
has text: Thanks for the correction, @AlexanderHuszagh :)
comment on: http://stackoverflow.com/a/48294558
score: 1
type: Comment

http://stackoverflow.com/q/48299851
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83589614
tagged with: apply
has answer: http://stackoverflow.com/a/48316714
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83584771
has body: I have a timeseries pandas dataframe and I have calculated a new column df['std_series']= ( df['series1']-df['series1'].rolling(252).mean() )/ df['series1'].rolling(252).std() however I want to winsorize to the 5% level before I standardize and on a rolling basis. So for any datapoint, look back 252 days if it is outside the 5% quantiles clip it to the 5% quantile and then standardize. I couldn't figure out how to make it work with rolling.apply. For instance (rolling on 10 elements): df = pd.DataFrame({'series1':[78, 1, 3, 4, 5, 6, 7, 8, 99]}) and assume I clip at (0.15 and 0.85). Then the clip levels:(min=3.2, max=64). Then winsorized window expected before standardization will be [ 64 3.2 3.2 4 5 6 7 8 64] All the examples I found were winsorize the either dataframe or entire column.
type: UnansweredQuestion
has title: Python pandas rolling winsorize
tagged with: rolling-computation
tagged with: python

http://stackoverflow.com/q/48249750
accepted answer: http://stackoverflow.com/a/48252365
has comment: http://stackoverflow.com/comment/83487311
tagged with: python
has comment: http://stackoverflow.com/comment/83486692
has comment: http://stackoverflow.com/comment/83486816
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48252365
has comment: http://stackoverflow.com/comment/83487150
has comment: http://stackoverflow.com/comment/83486268
has comment: http://stackoverflow.com/comment/83486659
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83485581
has comment: http://stackoverflow.com/comment/83486248
has comment: http://stackoverflow.com/comment/83487147
has comment: http://stackoverflow.com/comment/83484172
has body: My question is little bit different than the question posted here So I thought to open a new thread.I have a pandas data frame with 5 attributes.One of these attribute is created using pandas series.Here is the sample code for creating the data frame import numpy as np mydf1=pd.DataFrame(columns=['group','id','name','mail','gender']) data = np.array([2540948, 2540955, 2540956,2540956,7138932]) x=pd.Series(data) mydf1.loc[0]=[1,x,'abc','abc@xyz.com','male'] I have another data frame,the code for creating the data frame is given below mydf2=pd.DataFrame(columns=['group','id']) data1 = np.array([2540948, 2540955, 2540956]) y=pd.Series(data1) mydf2.loc[0]=[1,y] These are sample data. Actual data will have large number of rows &amp; also the series length is large too .I want to match mydf1 with mydf2 &amp; if it matches,sometime I wont have matching element in mydf2,then I will delete values of id from mydf1 which are there in mydf2 for example after the run,my id will be for group 1 2540956,7138932. I also tried the code mentioned in above link. But for the first line counts = mydf1.groupby('id').cumcount() I got error message as TypeError: 'Series' objects are mutable, thus they cannot be hashed in my Python 3.X. Can you please suggest me how to solve this?
has title: Delete series value from row of a pandas data frame based on another data frame value
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/48241677

http://stackoverflow.com/a/48275079
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48275024
answers question: http://stackoverflow.com/q/48275024
type: Answer
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/83534096
has comment: http://stackoverflow.com/comment/83534147
downvote count: 0
has body: virtualenv tool comes bundled with PyCharm, You just need to install it by following these steps. Steps to Create Virtual Environment Open the Settings dialog box, by going on left and clicking on file and going down the dropdown and select Settings or alternatively hit Ctrl+Alt+S. Click on your project on left and then click on Project Interpreter this opens a window on right. Now just choose Create VirtualEnv from dropdown in Project Interpreter if it is not there then click small button on right and select Create VirtualEnv. CAVEAT: In case this option does not appear, click on existing environment, select the Interpreter option and click on the ... button to look for your virtual environment setup. In your case, you should select C:\Users\myUser\PycharmProjects\virtualenvs\virtualenvs\Scripts\python.exe. Remember that the Scripts folder contains all the libraries that have been downloaded when you created the virtual environment. Select apply and hit OK, so now you should be able to see all your libraries that were downloaded. Now in the Create Virtual Environment Window , give Name to your VirtualEnv choose Location to install and choose Base Interpreter from dropdown or by clicking button on right, Base Interpreter is the Python Interpreter. Click Ok and your new VirtualEnv is created.
has comment: http://stackoverflow.com/comment/83534049

http://stackoverflow.com/a/48302848
has comment: http://stackoverflow.com/comment/83591047
has body: I believe you need double numpy.where, but condition return second value if equality: linebreakvalue = 320 m1 = eoddf['High'] &gt; linebreakvalue m2 = eoddf['Low'] &gt; linebreakvalue eoddf['LBHigh']= np.where(m1, eoddf['High'], eoddf['Low']) eoddf['LBLow'] = np.where(m2, eoddf['Low'], eoddf['High']) print (eoddf) Symbol Series Prev Close Open High Low Last Close \ 2015-01-01 SBIN EQ 311.85 312.45 315.00 310.70 314.00 314.00 2015-01-02 SBIN EQ 314.00 314.35 318.30 314.35 315.60 315.25 2015-01-05 SBIN EQ 315.25 316.25 316.80 312.10 312.80 312.75 2015-01-06 SBIN EQ 312.75 310.00 311.10 298.70 299.90 299.90 2015-01-07 SBIN EQ 299.90 300.00 302.55 295.15 301.40 300.15 2015-01-08 SBIN EQ 300.15 305.00 306.50 302.35 305.25 304.85 2015-01-09 SBIN EQ 304.85 306.70 307.85 302.00 303.00 303.20 2015-01-12 SBIN EQ 303.20 304.15 307.80 301.10 306.90 307.10 2015-01-13 SBIN EQ 307.10 308.15 310.75 304.15 305.25 305.10 2015-01-14 SBIN EQ 305.10 304.00 307.00 302.25 305.00 304.70 2015-01-15 SBIN EQ 304.70 319.90 323.70 314.00 318.40 320.30 2015-01-16 SBIN EQ 320.30 320.00 320.30 313.10 315.25 315.45 2015-01-19 SBIN EQ 315.45 316.55 317.95 312.50 313.20 313.15 2015-01-20 SBIN EQ 313.15 314.00 319.80 314.00 318.00 318.15 2015-01-21 SBIN EQ 318.15 319.90 327.60 319.00 326.00 326.20 2015-01-22 SBIN EQ 326.20 326.90 327.60 321.80 325.20 324.65 2015-01-23 SBIN EQ 324.65 328.25 332.55 324.65 327.05 327.45 2015-01-27 SBIN EQ 327.45 329.40 332.15 322.60 331.45 330.05 2015-01-28 SBIN EQ 330.05 330.40 336.00 328.20 333.40 334.60 LBHigh LBLow 2015-01-01 310.70 315.00 2015-01-02 314.35 318.30 2015-01-05 312.10 316.80 2015-01-06 298.70 311.10 2015-01-07 295.15 302.55 2015-01-08 302.35 306.50 2015-01-09 302.00 307.85 2015-01-12 301.10 307.80 2015-01-13 304.15 310.75 2015-01-14 302.25 307.00 2015-01-15 323.70 323.70 2015-01-16 320.30 320.30 2015-01-19 312.50 317.95 2015-01-20 314.00 319.80 2015-01-21 327.60 327.60 2015-01-22 327.60 321.80 2015-01-23 332.55 324.65 2015-01-27 332.15 322.60 2015-01-28…
has comment: http://stackoverflow.com/comment/83590683
score: 2
answers question: http://stackoverflow.com/q/48302781
downvote count: 0
has comment: http://stackoverflow.com/comment/83590961
has comment: http://stackoverflow.com/comment/83595145
upvote count: 2
type: Answer

http://stackoverflow.com/q/48267633
type: Question
has comment: http://stackoverflow.com/comment/83518403
has answer: http://stackoverflow.com/a/72025540
upvote count: 5
has answer: http://stackoverflow.com/a/61739758
tagged with: python
linked to: http://stackoverflow.com/q/45584241
has comment: http://stackoverflow.com/comment/83518409
tagged with: selenium-webdriver
has title: Python : no module named selenium
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/61739758
downvote count: 2
tagged with: selenium
linked to: http://stackoverflow.com/q/3701646
accepted answer: http://stackoverflow.com/a/48269228
tagged with: webdriver
has answer: http://stackoverflow.com/a/70462150
favorite count: 0
has answer: http://stackoverflow.com/a/48269228
tagged with: python-3.x
has body: After searching the web for hours i didnt yet find an answer to my problem. I am using Python 3.6 and i cant import selenium. I always get the message "No module named 'selenium'' I tried everything, i first downloaded selenium from this website https://pypi.python.org/pypi/selenium/3.6.0 . Then I tried python -m pip install -U selenium and didnt work either. I tried some other things that people said but they didnt work either. Im using windows 10. Any help?
has comment: http://stackoverflow.com/comment/103579188
answer count: 4

http://stackoverflow.com/q/48194802
tagged with: python
type: Question
has title: How to implement a custom layer wit multiple outputs in Keras?
has body: Like stated in the title, I was wondering as to how to have the custom layer returning multiple tensors: out1, out2,...outn? I tried keras.backend.concatenate([out1, out2], axis = 1) But this does only work for tensors having the same length, and it has to be another solution rather than concatenating two by two tensors every time, is it?
tagged with: multipleoutputs
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83370574
answer count: 1
score: 6
upvote count: 6
tagged with: output
has answer: http://stackoverflow.com/a/48195266
tagged with: keras
favorite count: 0
downvote count: 0
tagged with: layer

http://stackoverflow.com/a/48223281
type: Answer
accepted answer of: http://stackoverflow.com/q/48223240
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48223240
has body: you can register your service again and again after an interval of time in which it is getting de register. try this: auto execute a web service in falcon
has comment: http://stackoverflow.com/comment/83427984

http://stackoverflow.com/comment/83493484
type: QuestionComment
has text: even in R I strongly suggest against having a workflow that requires running `rm(list=ls())`. you should be comfortable (in rather language) with completely restarting your session (saving to disk the most time-consuming bits of code you've already run): https://www.tidyverse.org/articles/2017/12/workflow-vs-script/
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48254689

http://stackoverflow.com/comment/83665678
has text: @cbrnr do not modify the code, that is a sensitive part, you could modify errors in the grammar, syntax, but not in the logic, that threatens the response. You should suggest that to the author, although I do not agree with his last suggestion, that makes the code less readable.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48269737

http://stackoverflow.com/comment/83545193
comment on: http://stackoverflow.com/q/48280810
score: 0
type: Comment
type: QuestionComment
has text: No, and i wrote it in to a new file just to check, still comes out as the 10-point phrase.

http://stackoverflow.com/a/48273691
type: AcceptedAnswer
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48273519
has body: The mouseMoveEvent and mousePressEvent methods must be overwritten and in it decide if any action is taken or not. class TreeWidget(QTreeWidget): def mouseMoveEvent(self, event): if QApplication.keyboardModifiers()&amp;(Qt.ShiftModifier|Qt.ControlModifier): QTreeWidget.mouseMoveEvent(self, event) def mousePressEvent(self, event): if QApplication.keyboardModifiers()&amp;(Qt.ShiftModifier|Qt.ControlModifier): QTreeWidget.mousePressEvent(self, event) if __name__ == '__main__': import sys app = QApplication(sys.argv) widget = TreeWidget() widget.setSelectionMode(QAbstractItemView.MultiSelection) widget.setColumnCount(5) for row in range(7): item = QTreeWidgetItem(widget) for col in range(5): item.setText(col, 'Column %s' % col) widget.show() sys.exit(app.exec_())
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48273519

http://stackoverflow.com/a/48310374
has comment: http://stackoverflow.com/comment/83609010
answers question: http://stackoverflow.com/q/48310129
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48310129
has body: I think the problem lies with the way you are trying to find the links. When I curl the same url as you curl https://www.youtube.com/results\?search_query\=hello I don't get any a tags with those css elements on it. This seems based on the User-Agent property set in the header. So there are a few options: Change how you look for the video link. This is what video links markup looks like for my curl Adele - Hello As you can see those classes do not exist here. However you can use some sort of regular expression on the hrefs to find ones that contain the correct format page.find_all("a", {'href': re.compile('/watch?v=[A-Za-z0-9_\-]`)}) (you will have to mess with the regex it isn't perfect Use the Youtube API I would say this would be the preferred method just guessing what you are trying to do. Specifically the search api they even have python snippets
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/83606766

http://stackoverflow.com/comment/83502880
type: QuestionComment
comment on: http://stackoverflow.com/q/48260092
type: Comment
has text: You need to show the code that is causing the error and the full traceback. It’s a bad idea to use different versions of Django in development and production. Use the same versions everywhere.
score: 3

http://stackoverflow.com/comment/83491344
type: Comment
has text: The db would be overwritten. By doing like this, you could import db without conflict with app.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48254268

http://stackoverflow.com/comment/83340661
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48179542
score: 0
has text: Dear Idlehands, I am not able to follow the post you mentioned as it talks about gntp module. Could you please provide me steps to install my target xmltodict module manually (if possible). Thanks

http://stackoverflow.com/a/48295011
has comment: http://stackoverflow.com/comment/83576279
has comment: http://stackoverflow.com/comment/83576293
has comment: http://stackoverflow.com/comment/83576560
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83576144
answers question: http://stackoverflow.com/q/48294273
downvote count: 1
has body: For the second part of your answer I believe apply() function of pandas will be a more efficient solution. Eg: def my_func(a): #your computation here df['A'].apply(lambda x: my_func(x))
has comment: http://stackoverflow.com/comment/83576377
type: Answer

http://stackoverflow.com/comment/83569461
score: 1
has text: Can you show full stack trace error log?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48286364

http://stackoverflow.com/comment/90360033
has text: any luck? Trying to do the same
type: Comment
comment on: http://stackoverflow.com/q/48263154
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83428623
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48223587
has text: ... Create **dictionary** with **list** comprehension? What you're using is **dictionary** comprehension.
type: Comment

http://stackoverflow.com/comment/83558387
comment on: http://stackoverflow.com/q/48286413
has text: My data frame consist of columns [ policy_year, policy_month,policy_no,premium]with values and I need to group by each column and find aggregates for rest of columns and store it in a single dataframe
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83386504
type: Comment
score: 0
has text: thank you! it does what it should and I guess I can go on from here.
type: AnswerComment
comment on: http://stackoverflow.com/a/48202176

http://stackoverflow.com/a/48253632
answers question: http://stackoverflow.com/q/48252631
type: Answer
score: 0
has body: If you're on a Unix machine, you can use os.fork() to create a separate process that will continue running even when the parent process has finished. For example: main.py import os pid = os.fork() if pid == 0: # pid is only equal to 0 in the child process os.system('python second.py') second.py import time time.sleep(2) print("I'm a child process!")

http://stackoverflow.com/comment/83571939
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48293437
has text: This was extremely helpful. I didn't even know PEP existed before. Now I understand as well why professors have students upload code to their server to ensure it's running on the same specification. Had you not explained this, I would have gone forward assuming Python would be interpreted the same way by every compiler. Thanks so much for this informative response, definitely something to watch out for in the future.

http://stackoverflow.com/comment/84231176
score: 0
comment on: http://stackoverflow.com/a/48188499
type: Comment
has text: I have updated a new image,I have tired it using your given solution. i didn't get the result i also used other algo and changed the light intensity/extracted the other planes (Red and green).but i didn't the result.
type: AnswerComment

http://stackoverflow.com/comment/83407195
comment on: http://stackoverflow.com/q/48212690
type: Comment
type: QuestionComment
score: 0
has text: Absent a full example (in the question itself), I'm inclined to agree that it's related to modifying a list while you're iterating over it.

http://stackoverflow.com/a/69890912
answers question: http://stackoverflow.com/q/48184756
score: 3
upvote count: 3
has body: Had the same issue, try executing with python3 -m option My extension in extensions/json_loads.py import json from jinja2.ext import Extension def json_loads(value): return json.loads(value) class JsonLoadsExtension(Extension): def __init__(self, environment): super(JsonLoadsExtension, self).__init__(environment) environment.filters['json_loads'] = json_loads cookiecutter.json { "service_name": "test", "service_slug": "{{ cookiecutter.service_name.replace('-', '_') }}", ... "_extensions": ["extensions.json_loads.JsonLoadsExtension"] } Then I executed with python3 -m cookiecutter . no_input=True timestamp="123" extra_dict="{\"features\": [\"redis\", \"grpc_client\"]}" -f and it works fine.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83425080
type: Comment
comment on: http://stackoverflow.com/q/48221588
score: 1
type: QuestionComment
has text: @Future44 why don't you first start your Django project, write a first draft of your models, add some test data and try and find out by yourself (using the doc) how to get those results with either the ORM or raw SQL - and then post if and when you _really_ have a problem ?

http://stackoverflow.com/comment/83457892
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48235445
has text: try to actually login the website on any browser and check whether any cookies are stored using developer tools, usually after login some cookies are added to browser for user authentication.
type: Comment

windows-7
tags question: http://stackoverflow.com/q/48200825
tag name: windows-7
type: Tag

http://stackoverflow.com/a/48307337
has body: Can you explain why would you want to activate it? From Python Docs: You don’t specifically need to activate an environment; activation just prepends the virtual environment’s binary directory to your path, so that “python” invokes the virtual environment’s Python interpreter and you can run installed scripts without having to use their full path. However, all scripts installed in a virtual environment should be runnable without activating it, and run with the virtual environment’s Python automatically. On the same link you can see the commands you need with more information. P.S. Take a look at another packaging tool, Pipenv. It is easy and will save your time. I highly recommend it.
has comment: http://stackoverflow.com/comment/83601603
upvote count: 3
downvote count: 0
score: 3
type: Answer
answers question: http://stackoverflow.com/q/48307078

http://stackoverflow.com/comment/83622811
type: Comment
type: QuestionComment
has text: Cant you do that in the next steps ? Where do you display the information ? probably, you should do the "cosmetic" part after the pyspark step, where you use or display your data
comment on: http://stackoverflow.com/q/48318515
score: 1

qcombobox
tags question: http://stackoverflow.com/q/48328147
tags question: http://stackoverflow.com/q/48247643
tags question: http://stackoverflow.com/q/48280817
tag name: qcombobox
type: Tag

http://stackoverflow.com/comment/83552715
has text: `lst = [i,j];lst=list(itertools.combinations(lst,2))` results in `lst = [(i, j)]` because there is only one two-length combination of a two item list. What are you really trying to accomplish with those two while-loops at the top? What does `temp` have in it to start with?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48284094

http://stackoverflow.com/a/48331625
answers question: http://stackoverflow.com/q/48330458
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/83656419
has body: Brake your big list into smaller lists &gt;&gt;&gt; big= [(0,1),(3,2),(1,5),(0,3),(3,7)] &gt;&gt;&gt; a=big[0:2] &gt;&gt;&gt; b=big[2:] define a function to look for your tuple and return it or return None &gt;&gt;&gt; def doit(L): for i in L: if i[0]==3: return i return None figure out how to create a new process and call it with each of the smaller lists &gt;&gt;&gt; doit(a) (3, 2) &gt;&gt;&gt; doit(b) (3, 7) look at the tuples returned that are not None in order and choose the first one
accepted answer of: http://stackoverflow.com/q/48330458

http://stackoverflow.com/a/77593653
type: Answer
score: 0
has body: I also want to leave the info here how this works, because during my research this thread came also up often. You have to compile PyGObject yourself, but you get help from a script. You still need MSYS2 to support the compile process, go to http://www.msys2.org/ and download the x86_64 installer. Follow the instructions on the page for setting up the basic environment. You ned a C++ compiler, therefore install Visual Studio Community Edition with the C++ desktop development workload. Then add the future GTK folder to Your Environmental Variables: Type environement with the windows start menu open and click “Edit environment variables for your account”. Double-click the Path row in the top list of variables. Click “New” to add a new item to the list. Paste in C:\gtk-build\gtk\x64\release\bin . Click "OK" twice. Clone [gsvbuild] (scripts for GTK compilation). Open a powershell prompt as administrator and enter the following commands. mkdir C:\gtk-build\github cd C:\gtk-build\github git clone C:\github.com\wingtk\gvsbuild cd *your project dir* python -m venv .venv .\.venv\Scripts\activate.ps1 pip install . gvsbuild build --enable-gi --py-wheel gobject-introspection gtk3 pycairo pygobject Once that builds, you can switch to your project you are trying to use PyGObject for and activate the virtualenv. Then install the wheels you created above: Get-ChildItem C:\gtk-build\build\x64\release\*\dist\*.whl | ForEach-Object -process { poetry run pip install $_ } More details in this thread: File msvc_recommended_pragmas.h missing while installing PyGObject via pip
answers question: http://stackoverflow.com/q/48218319
has comment: http://stackoverflow.com/comment/139639574

http://stackoverflow.com/q/48246777
tagged with: python
has answer: http://stackoverflow.com/a/48246905
has comment: http://stackoverflow.com/comment/83476382
score: 0
tagged with: raw-input
answer count: 2
tagged with: while-loop
has comment: http://stackoverflow.com/comment/83476270
linked to: http://stackoverflow.com/q/22257158
has title: How can I make a Python program terminate when the end of the input file is reached?
has answer: http://stackoverflow.com/a/48247281
type: Question
has body: I am working on a programming assignment, and the directions specify: "Your program should terminate when it reaches the end of the input file, or the end-of-file on stdin (when control-D is typed from the keyboard under Linux)." This is what I have so far: userInput = rawInput() while userInput != "": #other stuff the program will do This is my first time programming in python, and I am using pycharm editor. I am a little confused if this works. Normally in java I would check if userInput is null, but it seems like python doesnt have null objects? Also, does this account for the part in the instructions that says "when control-D is typed from the keyboard under Linux)."? Since I'm using pyCharm to edit and run my file before turning it in, how do I test to simulate when control-D is typed from the keyboard under Linux" ?
duplicate of: http://stackoverflow.com/q/21235855
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/15599639
tagged with: input

http://stackoverflow.com/a/48277234
has comment: http://stackoverflow.com/comment/83541220
has comment: http://stackoverflow.com/comment/83540333
downvote count: 0
has comment: http://stackoverflow.com/comment/83541062
has comment: http://stackoverflow.com/comment/83548226
has comment: http://stackoverflow.com/comment/83540671
has comment: http://stackoverflow.com/comment/83548352
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83540770
has comment: http://stackoverflow.com/comment/83540743
upvote count: 5
accepted answer of: http://stackoverflow.com/q/48276631
has comment: http://stackoverflow.com/comment/83539823
score: 5
has comment: http://stackoverflow.com/comment/83539933
has body: Update Here is some Cython treatment In [1]: import cython In [2]: %load_ext Cython In [3]: %%cython ...: import numpy as np ...: cimport numpy as np ...: def cluster(np.ndarray array, np.float64_t maxdiff): ...: cdef np.ndarray[np.float64_t, ndim=1] flat = np.sort(array.flatten()) ...: cdef list breakpoints = [] ...: cdef np.float64_t seed = flat[0] ...: cdef np.int64_t int = 0 ...: for i in range(0, len(flat)): ...: if (flat[i] - seed) &gt; maxdiff: ...: breakpoints.append(i) ...: seed = flat[i] ...: return np.split(array, breakpoints) ...: Sparsity test In [4]: angles = np.random.choice(np.arange(5000), 500).astype(np.float64)[:, None] In [5]: %timeit cluster(angles, 2) 422 µs ± 12.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) Duplication test In [6]: angles = np.random.choice(np.arange(500), 1500).astype(np.float64)[:, None] In [7]: %timeit cluster(angles, 2) 263 µs ± 14.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) Both tests show a significant improvement. The algorithm now sorts the input and makes a single run over the sorted array, which makes it stable O(N*log(N)). Pre-update This is a variation on seed clustering. It requires no sorting def cluster(array, maxdiff): tmp = array.copy() groups = [] while len(tmp): # select seed seed = tmp.min() mask = (tmp - seed) &lt;= maxdiff groups.append(tmp[mask, None]) tmp = tmp[~mask] return groups Example: In [27]: cluster(angles, 2) Out[27]: [array([[1], [2], [3]]), array([[4], [4], [5]]), array([[10]])] A benchmark for 500, 1000 and 1500 angles: In [4]: angles = np.random.choice(np.arange(500), 500)[:, None] In [5]: %timeit cluster(angles, 2) 1.25 ms ± 60.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [6]: angles = np.random.choice(np.arange(500), 1000)[:, None] In [7]: %timeit cluster(angles, 2) 1.46 ms ± 37 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [8]: angles = np.random.choice(np.arange(500), 1500)[:, None] In [9]: %timeit cluster(angles, 2) 1.99 ms…
type: Answer
answers question: http://stackoverflow.com/q/48276631
has comment: http://stackoverflow.com/comment/83547979

http://stackoverflow.com/comment/99217413
comment on: http://stackoverflow.com/a/48251455
type: Comment
type: AnswerComment
has text: @babygame0ver - What return `print (ax.xaxis.get_ticklabels())` ?
score: 0

http://stackoverflow.com/q/48268826
accepted answer: http://stackoverflow.com/a/48268930
downvote count: 0
has body: I created two tensors (one depending upon another) as follows: weights = tf.random_normal(shape=(3, 3, 1, 64)) filters = get_filters(weights) # get_filters does some operation on weights So, after above operations, weights and filters looks like &lt;tf.Tensor 'random_normal_1:0' shape=(3, 3, 1, 64) dtype=float32&gt; &lt;tf.Tensor 'filters_1/weights:0' shape=(5, 3, 3, 1, 64) dtype=float32&gt; Now, I pass these tensors to the following function def get_alphas(weights, filters, no_filters=5, epochs=500, name=None): with tf.name_scope(name, default_name="alpha_scope"): weights = tf.reshape(weights, [-1], name="reshaped_weights") filters = tf.reshape(filters, [no_filters, -1], name="reshaped_binary_filters") alphas = tf.Variable(tf.zeros(shape=(no_filters, 1)), name="alphas") weighted_sum = tf.reduce_sum(tf.multiply(alphas, filters), axis=0, name="weighted_sum") error = tf.square(weights - weighted_sum, name="error") loss = tf.reduce_mean(tf.reshape(error, [-1]), name="loss") # Optimizer optimizer = tf.train.AdamOptimizer() training_op = optimizer.minimize(loss, name="training_op") print(tf.global_variables()) init = tf.variables_initializer([alphas]) with tf.Session() as sess: init.run() epoch = 0 while epoch &lt; epochs: _, loss_train = sess.run([training_op, loss]) # &lt;-- this is where the error is generated print("\rIteration: {}/{} ({:.1f}%) Loss: {:.5f}".format( epoch+1, epochs, epoch * 100 / epochs, loss_train), end="") epoch += 1 return tf.convert_to_tensor(sess.run(alphas)) On calling get_alphas(weights, filters), I get the following errors FailedPreconditionError (see above for traceback): Attempting to use uninitialized value alpha_scope/beta1_power [[Node: alpha_scope/beta1_power/read = Identity[T=DT_FLOAT, _class=["loc:@alpha_scope/alphas"], _device="/job:localhost/replica:0/task:0/device:GPU:0"](alpha_scope/beta1_power)]] [[Node: alpha_scope/loss/_1 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/…
score: 1
upvote count: 1
has title: Unknown variables in tensorflow state causes error in training operation
answer count: 1
tagged with: initialization
tagged with: tensorflow
favorite count: 0
linked to: http://stackoverflow.com/q/33788989
type: Question
has answer: http://stackoverflow.com/a/48268930
tagged with: python
tagged with: optimization
type: AnsweredQuestion

http://stackoverflow.com/a/48217218
has body: Your second case isn't returning False, it is returning None because you are not returning the result of the recursive call to recur_parse. Compare your code to the following function: def recur_parse(s, pattern): if s[0] == pattern or s[0:2] == pattern: return True elif len(s[1:]) &gt;= len(pattern): return recur_parse(s[1:], pattern) # notice the return here else: return False However, this only works with patterns that are of length 1 or 2. This can be extended with str.startswith. def has_string(s, m): return s.startswith(m) or bool(s) and has_string(s[1:], m) Note that here bool(s) is the base case. Whether or not this is readable is above my pay grade. If this wasn't a practice in recursion, you'd want to use: def has_string(s, m): return m in s
answers question: http://stackoverflow.com/q/48217074
has comment: http://stackoverflow.com/comment/83443012
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/83358103
type: QuestionComment
comment on: http://stackoverflow.com/q/48188881
score: 0
type: Comment
has text: From the looks of it you already got the value: a list of `Friend` objects. So what's the problem? Are you asking about how to use lists in Python?

http://stackoverflow.com/a/48297504
has comment: http://stackoverflow.com/comment/83580757
has comment: http://stackoverflow.com/comment/83580455
answers question: http://stackoverflow.com/q/48297082
score: 0
has body: You have some options to do that. Two of them are: add groups in views view_order_form extension sale.order sales_team.group_sale_manager sales_team.group_sale_manager sales_team.group_sale_manager You need the proper xml resp. external IDs for the group, in this case sales_team.group_sale_manager. This is just one view override, keep in mind that there are two sale order form views in Odoo 10. your way, changing the group directly on field discount = fields.Float(groups="sales_team.group_sale_manager") It should be enough to just change the groups parameter, because the new API allows overriding fields without copying all parameters.
type: Answer

http://stackoverflow.com/a/48299443
has body: t=# create table d(i bigserial, j jsonb); CREATE TABLE t=# insert into d(j) select ('{"foreign_data":{ "some_key": '||g||', "src_data": { "VEHICLE": { "title": "615", "is_working": true, "upc": "85121212121", "dealer_name": "CryptoDealer", "id": '||g||' } } }}')::jsonb from generate_series(1,1222600) g; INSERT 0 1222600 t=# create index ji on d (cast (j-&gt;'foreign_data'-&gt;'src_data'-&gt;'VEHICLE'-&gt;&gt;'id' as int)); CREATE INDEX in order to use such fn() based index youhave to "repeat" function in query: t=# explain analyze select * from d where cast (j-&gt;'foreign_data'-&gt;'src_data'-&gt;'VEHICLE'-&gt;&gt;'id' as int) = 1222551; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------ Index Scan using ji on d (cost=0.43..8.45 rows=1 width=215) (actual time=0.021..0.021 rows=1 loops=1) Index Cond: ((((((j -&gt; 'foreign_data'::text) -&gt; 'src_data'::text) -&gt; 'VEHICLE'::text) -&gt;&gt; 'id'::text))::integer = 1222551) Planning time: 1.585 ms Execution time: 0.045 ms (4 rows) as you see cost is tiny and execution is cheap over index. but if you "skip" formalities and run: t=# explain analyze select * from d where j-&gt;'foreign_data'-&gt;'src_data'-&gt;'VEHICLE'-&gt;&gt;'id' = '1222551'; QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------- Gather (cost=1000.00..50122.31 rows=6113 width=215) (actual time=335.996..336.000 rows=1 loops=1) Workers Planned: 2 Workers Launched: 2 -&gt; Parallel Seq Scan on d (cost=0.00..48511.01 rows=2547 width=215) (actual time=223.548..332.213 rows=0 loops=3) Filter: (((((j -&gt; 'foreign_data'::text) -&gt; 'src_data'::text) -&gt; 'VEHICLE'::text) -&gt;&gt; 'id'::text) = '1222551'::text) Rows Removed by Filter: 407533 Planning time: 0.096 ms Execution time: 343.090 ms (8 rows) index will not be used
answers question: http://stackoverflow.com/q/48292735
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/48194483
has comment: http://stackoverflow.com/comment/83371062
type: Answer
score: 0
type: AcceptedAnswer
has body: I tried many different things, but in the end I ditched the mixin and edited MyDetailView with a get_form method (and within that I could tell it to use the instance): class MyDetailView(DetailView): """ Shows the details """ form_class = forms.MyForm def get_form(self): form = self.form_class(instance=self.object) return form def get_context_data(self, **kwargs): context = super(MyDetailView, self).get_context_data(**kwargs) context.update({ 'form': self.form_class(instance=self.get_object()), }) return context The render_field fields have their values filled with the saved instance values and all the attributes they need are there.
answers question: http://stackoverflow.com/q/48191880
accepted answer of: http://stackoverflow.com/q/48191880
has comment: http://stackoverflow.com/comment/83369981

http://stackoverflow.com/q/48242761
has answer: http://stackoverflow.com/a/48242762
tagged with: refresh-token
accepted answer: http://stackoverflow.com/a/48242762
tagged with: gmail-api
type: AnsweredQuestion
upvote count: 21
has body: So I just spent the last few days trying to figure this out and am asking this question so that I can answer it for other people who are having problems. First, the google documentation is TERRIBLE and uses different oauth2 libraries depending on which of the many google API examples you are looking at. It is often self-contradictory and sometimes straight up has code in it that doesn't work. Oh well. so my questions were basically: how do I use the google api libraries to have my users grant me access to their google accounts? how do I store the oauth2 access tokens that google returns so that I can use them a few days from now? how do i actually use the refresh_token and refresh it? see answer below for a fully functional authorization flow, from getting the initial token to saving it, loading it later, refreshing it, and using it. Cheers.
score: 21
tagged with: python
favorite count: 0
type: Question
tagged with: google-oauth
downvote count: 0
has title: How do I use oauth2 and refresh tokens with the google api?
tagged with: google-api
answer count: 1

http://stackoverflow.com/comment/83618170
score: 0
has text: Another minor tweak: instead of `if dialog.exec_() == QDialog.Rejected:`, you could use `if not dialog.exec_():`.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48269737

http://stackoverflow.com/comment/83422853
type: QuestionComment
score: 3
type: Comment
has text: That's pretty advanced code. I suggest you come back to it in a while after you've learned more of the basics of Python.
comment on: http://stackoverflow.com/q/48220664

http://stackoverflow.com/comment/83561551
score: 0
comment on: http://stackoverflow.com/a/48287703
has text: so this will be a no go? https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_sample-code.html
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83499434
has text: There is a [similar question](/questions/10057095/installing-numpy-lion-with-python-2-7) on SO. Another option would be to uses [Anaconda](https://www.anaconda.com/download/#macos), which guarantees a fully functional scientific Python environment.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48205006
type: QuestionComment

http://stackoverflow.com/comment/83482573
type: AnswerComment
type: Comment
has text: No, I need to click and load. Then, after loading, I will process each new page, collect data, and go back to the initial list, and so on.
comment on: http://stackoverflow.com/a/48249819
score: 0

http://stackoverflow.com/q/48291699
upvote count: 0
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/48292113
favorite count: 0
type: Question
has title: use for-loop to compare two lists
has comment: http://stackoverflow.com/comment/83568747
has comment: http://stackoverflow.com/comment/83568884
has answer: http://stackoverflow.com/a/48291757
has comment: http://stackoverflow.com/comment/83568876
has comment: http://stackoverflow.com/comment/83568731
score: -2
has comment: http://stackoverflow.com/comment/83568754
has body: I have two list at the moment a=[3768, 4893, 6007, 7131, 8246, 9373, 10485, 11610, 12722, 13845, 14960, 16085, 17198, 19262, 20388, 21494, 22614, 23727, 24850] b=[3071, 3516, 4654, 5780, 6892, 8019, 9134, 10258, 11371, 12495, 13606, 14733, 15846, 16971, 18084, 18575, 19035, 20149, 21274, 22382] Both lists have different size and all numbers in both lists are in ascending order. I need to find the index for all elements in list b (b[i]) that is bigger than the element[v] (a[v]) in list a and smaller than the element[v+1] (a[v+1]) in list a, for example, b[i]&gt;a[v] and b[i]&lt;a[v+1] I am not sure how I write the for loop, any suggestions? Thanks in advance.
tagged with: python
has comment: http://stackoverflow.com/comment/83568780
has comment: http://stackoverflow.com/comment/83568727
has comment: http://stackoverflow.com/comment/83568931
has comment: http://stackoverflow.com/comment/83568456
answer count: 3
tagged with: for-loop
has answer: http://stackoverflow.com/a/48293270

http://stackoverflow.com/comment/83522561
type: QuestionComment
comment on: http://stackoverflow.com/q/48231457
has text: Post a stacktrace
score: 0
type: Comment

http://stackoverflow.com/q/48220717
upvote count: 1
answer count: 1
tagged with: django
has answer: http://stackoverflow.com/a/48220791
has comment: http://stackoverflow.com/comment/83422972
has title: Django - How to save files to STATIC_ROOT from views?
favorite count: 0
type: Question
has body: I have made a Django app that takes arguments from the form and makes an image using Pillow. views.py: file_name = "{}.png".format(random.randint(1, 255)) image1.save(file_name) pretty simple stuff, right? Now when I try to render that image with HttpResponse as: return HttpResponse("&lt;img src='" +file_name + "' alt='image here'&gt;") apparently, it will throw an error. Can you please tell me what to do in order to save it properly and show in HttpResponse? Django==1.11.8 Pillow==5.0.0 Python 3.6.2 Thank you!
tagged with: python-imaging-library
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48220791
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/48174323
has comment: http://stackoverflow.com/comment/83329329
tagged with: python
has title: Tensorflow 1.4 tf.metrics.auc for AUC calculation
has comment: http://stackoverflow.com/comment/83329015
has answer: http://stackoverflow.com/a/48175067
has comment: http://stackoverflow.com/comment/83328935
has comment: http://stackoverflow.com/comment/83329343
score: 1
has comment: http://stackoverflow.com/comment/83328233
answer count: 1
has body: I am trying to log AUC during training time of my model. According to the documentation, tf.metric.auc needs a label and predictions, both of same shape. But in my case of binary classification, label is a one-dimensional tensor, containing just the classes. And prediction is two-dimensional containing probability for each class of each datapoint. How to calculate AUC in this case?
downvote count: 0
upvote count: 1
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/83329179
type: Question
has comment: http://stackoverflow.com/comment/83329097
tagged with: auc
type: UnansweredQuestion

http://stackoverflow.com/a/48492432
answers question: http://stackoverflow.com/q/48217449
has body: If you are content to know when each item is finished (instead of started), you could use apply_async with a callback, like this: # dummy data and function all_inputs = list(zip(range(10), range(20,30))) def name_of_function(a, b): return a+b # main code from multiprocessing import Pool num_items = len(all_inputs) num_done = 0 def handle_result(res): global num_done num_done += 1 print('finished item {} of {}.'.format(num_done, num_items)) p = Pool(5) for args in all_inputs: p.apply_async(name_of_function, args, callback=handle_result) p.close() p.join() # wait for tasks to finish result: finished item 1 of 10. finished item 2 of 10. finished item 3 of 10. finished item 4 of 10. finished item 5 of 10. finished item 6 of 10. finished item 7 of 10. finished item 8 of 10. finished item 9 of 10. finished item 10 of 10. Note that results won't necessarily come in the same order as all_inputs. If you need to know exactly which item was processed, you could enumerate the arguments like this: from multiprocessing import Pool num_items = len(all_inputs) num_done = 0 def handle_result(idx): global num_done num_done += 1 print('finished index {} ({}/{}).'.format(idx, num_done, num_items)) def wrapper(idx, args): name_of_function(*args) return idx p = Pool(5) for args in enumerate(all_inputs): p.apply_async(wrapper, args, callback=handle_result) p.close() p.join() # wait for tasks to finish result: finished index 0 (1/10). finished index 1 (2/10). finished index 2 (3/10). finished index 3 (4/10). finished index 4 (5/10). finished index 6 (6/10). finished index 8 (7/10). finished index 7 (8/10). finished index 9 (9/10). finished index 5 (10/10).
type: Answer
score: 0

http://stackoverflow.com/q/48253759
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/83490440
tagged with: dataframe
score: 1
has comment: http://stackoverflow.com/comment/83490008
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83490025
has title: Pandas dataframe. Group by value and count
downvote count: 0
has comment: http://stackoverflow.com/comment/83490071
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83490017
accepted answer: http://stackoverflow.com/a/48253896
type: AnsweredQuestion
has body: I have the following table: Days, Age, Sex 5, 39, F 4, 54, M 4, 26, M 5, 42, M 4, 29, M I want to count number of rows with F and M separately. The following command works, but I'm not OK with the representation: df.groupby("Sex").count() What will be the best way to do it? Thank you.
has answer: http://stackoverflow.com/a/48253896
tagged with: pandas-groupby

http://stackoverflow.com/q/48180594
score: -1
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/42045767
upvote count: 0
has body: It seems pyplot.plot does not align the x and y axes to their respective data endpoints. There are always padded gaps between the plot axes and boundaries and the actual data plot. How can you force a tighter layout for plots such that the plot axes begin and end at their respective terminal data values? Here's an example of what I mean, with a simple plot: import matplotlib.pyplot as plt import numpy as np x = np.arange(0,101) plt.plot(x) As you can see, the plot origin (0,0) and the figure axes origin or intersection (bottom left corner of figure box) are not the same. I want to know how to remove the padding so that the line starting fromx[0] begins from the bottom left corner of the figure.
answer count: 1
downvote count: 1
has title: Matplotlib pyplot plot axes not aligned to data values
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48180708
linked to: http://stackoverflow.com/q/42045767
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/48180708

http://stackoverflow.com/a/48220606
score: 0
has body: You must not upload files to the filesystem on Heroku. As the documentation explains, the filesystem is ephemeral and is not shared between dynos. Anything uploaded will only be seen by the dyno that created it, and will be completely lost when that dunno restarts. You must use a permanent store, for example S3.
answers question: http://stackoverflow.com/q/48217861
type: Answer

http://stackoverflow.com/a/48233482
has body: You could use A.all() or A.any() to get a scalar. This would only work if A contains one element.
downvote count: 1
score: 3
answers question: http://stackoverflow.com/q/48233313
type: Answer
upvote count: 4

http://stackoverflow.com/q/48181836
tagged with: utf-8
has comment: http://stackoverflow.com/comment/83344515
has comment: http://stackoverflow.com/comment/83521416
has title: Converting text into utf-8 in textblob
tagged with: unicode
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83344154
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83346581
upvote count: 1
has body: I have a file which i m using as my input. But it has some special characters which I need to convert it into plain text. How can I do that?
downvote count: 1
tagged with: textblob

http://stackoverflow.com/comment/83339158
type: QuestionComment
comment on: http://stackoverflow.com/q/48179511
score: 0
has text: Check the environment variable settings VS Code is using for Python.
type: Comment

http://stackoverflow.com/comment/83451337
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48234104
has text: Ohhhhh that clarifies a lot. Wish the docs made this distinction as well, but maybe that's just my ignorance of these formats.
type: AnswerComment

http://stackoverflow.com/comment/83615351
has text: @AnupYadav I use the third `rest-auth` lib, there is no View for me. the View is controlled by `rest-auth`.
score: 0
comment on: http://stackoverflow.com/q/48314694
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83475531
comment on: http://stackoverflow.com/a/48245242
type: AnswerComment
has text: Hi, this crashes when the list contains a reference to itself.
score: 1
type: Comment

http://stackoverflow.com/q/48242280
has comment: http://stackoverflow.com/comment/83467110
has comment: http://stackoverflow.com/comment/83467014
score: 0
tagged with: tkinter
answer count: 3
has comment: http://stackoverflow.com/comment/83467189
has answer: http://stackoverflow.com/a/63513134
type: UnansweredQuestion
has title: My Radiobutton is checked on creation
type: Question
has body: My problem is that when creating a Radiobutton it is automatically checked and i can't uncheck it. I create it inside a frame of x and y dimensions. I've tried the .deselect() function but it changes nothing (Python 3.6) code: frm = ttk.Frame(root) frm.place(x=0,y=0,width=1000,height=1000) Ek = ttk.Radiobutton(frm,text="text") Ek.place(x=100,y=400) And photo of it: photo
has answer: http://stackoverflow.com/a/48242417
linked to: http://stackoverflow.com/q/17199086
tagged with: python
has answer: http://stackoverflow.com/a/48242584

http://stackoverflow.com/q/48318113
tagged with: memory
has comment: http://stackoverflow.com/comment/83622857
favorite count: 0
type: Question
tagged with: numpy
upvote count: 2
type: UnansweredQuestion
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/83636029
has comment: http://stackoverflow.com/comment/83621797
score: 2
has comment: http://stackoverflow.com/comment/83621935
has body: I'm trying to perform calculations on very large arrays, dimensions 65536 x 65536. Since I read that np.memmap can allow me to perform calculations out of core so that I'm not limited by memory I tried to do this. This method works for small arrays like 8192 x 8192. However, when I try for the larger dimension, I get a bus error(core dumped). What could be causing this issue? And how can I overcome it? Would appreciate any advice. Code is below. I have 2 arrays X and Y, stored in binary format which I load and perform calculations on. Additionally, I have a RAM of 128 GB so there is no issue in these new arrays being allocated. import numpy as np X = np.memmap('X.bin',dtype='float64',mode='r',shape=(65536,65536)) Y = np.memmap('Y.bin',dtype='float64',mode='r',shape=(65536,65536)) A = np.fft.rfft2(np.fft.fftshift(X)) B = np.fft.rfft2(Y) C = np.fft.irfft2(A*B) alpha_x,alpha_y = np.gradient(C,edge_order=2) Together, this would be alpha_x,alpha_y = np.gradient(np.fft.irfft2(np.fft.rfft2(Y)*np.fft.rfft2(np.fft.fftshift(X))),edge_order=2)
has comment: http://stackoverflow.com/comment/83741080
has comment: http://stackoverflow.com/comment/83621835
has comment: http://stackoverflow.com/comment/83621821
answer count: 0
has comment: http://stackoverflow.com/comment/83649812
has comment: http://stackoverflow.com/comment/83649838
has title: Bus Error : Core dumped when using numpy memmap
downvote count: 0

http://stackoverflow.com/q/48310322
downvote count: 0
favorite count: 0
has body: I am working on a classification problem, where we have a pairwise input, X1 = Input(shape=(input_size,), name='input_1') X2 = Input(shape=(input_size,), name='input_2') and the expected output is binary. To solve this problem, I first design an encoder which takes these pairwise inputs and encode them with the shape of (encoder_size, 2). Next, I want to design an RNN, where can treat the training set as a time series. In other words, I will feed (X1, X2) first, and feed (X1, X3) and so on. The reason is the former input may contain some global information need to memorize, which might be helpful to do the prediction for the later input. For each input pair, I expect to see a binary prediction result. And the model keeps the memory of it and do a prediction for the next input pair. I attach the code below, but I am not sure whether it can work like what I describe or not. encoder = Sequential() encoder.add(Dropout(dropout_rate, input_shape=(input_size,))) encoder.add(Dense(encoder_size, activation='relu')) encoder.add(Reshape((-1,1))) encoded_1 = encoder(X1) encoded_2 = encoder(X2) merged = concatenate([encoded_1, encoded_2]) # RNN model comparer = Sequential() comparer.add(LSTM(64, input_shape=(encoder_size,2), return_sequences=False)) comparer.add(Dropout(dropout_rate)) comparer.add(Dense(1)) comparer.add(Activation('sigmoid')) Y = comparer(merged) model = Model(inputs=[X1, X2], outputs=Y) If not, what is the correct way? If yes, what is the way to treat the (encoder_size, 2) as the time series instead of the whole training set?
tagged with: python
has title: How to design an RNN to treat all training set as a time series in Keras?
tagged with: recurrent-neural-network
type: Question
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: keras

http://stackoverflow.com/q/48311096
score: 0
linked to: http://stackoverflow.com/q/2120248
has answer: http://stackoverflow.com/a/48311651
has comment: http://stackoverflow.com/comment/83608808
has body: I have a problem where I need to call an instance function of a class in parallel and count the number of times it has been called so each call has a unique identifier (to be used to store results in a unique location). Here is a question with solutions for what I want but in Java Here is a minimal example: para2.py, which sets up all the instance-method pickling stuff (less relevant): from copy_reg import pickle from types import MethodType from para import func def _pickle_method(method): return _unpickle_method, (method.im_func.__name__, method.im_self, method.im_class) def _unpickle_method(func_name, obj, cls): return cls.__dict__[func_name].__get__(obj, cls) pickle(MethodType, _pickle_method, _unpickle_method) func() And now para.py contains: from sklearn.externals.joblib import Parallel, delayed from math import sqrt from multiprocessing import Lock class Thing(object): COUNT = 0 lock = Lock() def objFn(self, x): with Thing.lock: mecount = Thing.COUNT Thing.COUNT += 1 print mecount n=0 while n &lt; 10000000:# add a little delay for consistency n += 1 return sqrt(x) def func() thing = Thing() y = Parallel(n_jobs=4)(delayed(thing.objFn)(i**2) for i in range(10)) print y Now running python para2.py in a terminal prints 0 0 0 0 1 1 1 1 2 2 [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] I need those numbers on the vertical to count 0 to 9, but it appears that all four processes are still accessing and trying to update COUNT concurrently. How can I make this do what I want?
tagged with: python
tagged with: joblib
type: AnsweredQuestion
tagged with: locking
has title: Counting parallel function calls python
answer count: 1
tagged with: multiprocessing
type: Question
accepted answer: http://stackoverflow.com/a/48311651

http://stackoverflow.com/q/48228783
tagged with: text
answer count: 3
has body: I am trying to retrieve data from the site: https://api.coinmarketcap.com/v1/ticker/cardano/?convert=usd the code snippet looks like this: with urllib.request.urlopen("https://api.coinmarketcap.com/v1/ticker/cardano/?convert=USD") as url: data = json.loads(url.read().decode()) print(data) The output is: [{'id': 'cardano', 'name': 'Cardano', 'symbol': 'ADA', 'rank': '5', 'price_usd': '0.81872', 'price_btc': '0.00005809', '24h_volume_usd': '213316000.0', 'market_cap_usd': '21227011191.0', 'available_supply': '25927070538.0', 'total_supply': '31112483745.0', 'max_supply': '45000000000.0', 'percent_change_1h': '0.19', 'percent_change_24h': '13.13', 'percent_change_7d': '-19.93', 'last_updated': '1515768856'}] My problem is, how do I work with that text? Can I make it into a better looking list? Thanks in advance. P.S.: I'm working with Python right now
has comment: http://stackoverflow.com/comment/83439592
has comment: http://stackoverflow.com/comment/83439820
score: 0
tagged with: http://stackoverflow.com/tag/json
has title: Convert Json output into good looking text?
has answer: http://stackoverflow.com/a/48229822
tagged with: file
has comment: http://stackoverflow.com/comment/83439814
has comment: http://stackoverflow.com/comment/83439499
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48229749
has comment: http://stackoverflow.com/comment/83440491
has comment: http://stackoverflow.com/comment/83439535
tagged with: python
has answer: http://stackoverflow.com/a/48229004
has comment: http://stackoverflow.com/comment/83439644

algorithm
tags question: http://stackoverflow.com/q/48230296
tags question: http://stackoverflow.com/q/48217471
tags question: http://stackoverflow.com/q/48243492
tags question: http://stackoverflow.com/q/48304365
tags question: http://stackoverflow.com/q/48312206
type: Tag
tags question: http://stackoverflow.com/q/48233306
tag name: algorithm
tags question: http://stackoverflow.com/q/48243369
tags question: http://stackoverflow.com/q/48291444
tags question: http://stackoverflow.com/q/48253730
tags question: http://stackoverflow.com/q/48250410
tags question: http://stackoverflow.com/q/48326565
tags question: http://stackoverflow.com/q/48249459
tags question: http://stackoverflow.com/q/48285434
tags question: http://stackoverflow.com/q/48245128
tags question: http://stackoverflow.com/q/48269471
tags question: http://stackoverflow.com/q/48244542
tags question: http://stackoverflow.com/q/48202334
tags question: http://stackoverflow.com/q/48249253
tags question: http://stackoverflow.com/q/48253612
tags question: http://stackoverflow.com/q/48200788
tags question: http://stackoverflow.com/q/48262314
tags question: http://stackoverflow.com/q/48273945
tags question: http://stackoverflow.com/q/48211037
tags question: http://stackoverflow.com/q/48313993
tags question: http://stackoverflow.com/q/48244991
tags question: http://stackoverflow.com/q/48245860
tags question: http://stackoverflow.com/q/48298111
tags question: http://stackoverflow.com/q/48251704
tags question: http://stackoverflow.com/q/48291543
tags question: http://stackoverflow.com/q/48324806
tags question: http://stackoverflow.com/q/48181613
tags question: http://stackoverflow.com/q/48284147
tags question: http://stackoverflow.com/q/48307183
tags question: http://stackoverflow.com/q/48232388
tags question: http://stackoverflow.com/q/48233950
tags question: http://stackoverflow.com/q/48290831
tags question: http://stackoverflow.com/q/48311021
tags question: http://stackoverflow.com/q/48252234
tags question: http://stackoverflow.com/q/48186709
tags question: http://stackoverflow.com/q/48327672
tags question: http://stackoverflow.com/q/48242369

http://stackoverflow.com/q/48243737
tagged with: module
has comment: http://stackoverflow.com/comment/83472201
has body: When trying to install the module docx I get the error code 1. Also tried to install it from file. I am using Python 3.7.0a4 64bit, pip is uptodate as well as setuptools I tried to install a different module and got the same error. Anyone have an idea? Here is the error: Command ""e:\programme\python 3.7.0a4 64bit\python.exe" -u -c "import setuptools , tokenize;____file____='C:\Users\Marius\AppData\Local\Temp\pip-build-at8ydfxt \lxml\setup.py';f=getattr(tokenize, 'open', open)(____file____);code=f.read().repl ace('\r\n', '\n');f.close();exec(compile(code, ____file____, 'exec'))" install --rec ord C:\Users\Marius\AppData\Local\Temp\pip-90k4qvt1-record\install-record.txt -- single-version-externally-managed --compile" failed with error code 1 in C:\User s\Marius\AppData\Local\Temp\pip-build-at8ydfxt\lxml\
score: 0
answer count: 0
tagged with: installation
type: UnansweredQuestion
tagged with: pip
has comment: http://stackoverflow.com/comment/83472979
type: Question
tagged with: python-3.x
tagged with: python
has title: installing docx module failed with error code 1

http://stackoverflow.com/q/48244609
score: 1
has comment: http://stackoverflow.com/comment/83472804
tagged with: matplotlib
tagged with: python
favorite count: 0
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/83473079
has body: I try to execute the following simplified batch job on my linux machine: root@kali:~/Test_plots# ls batch_job.txt plot.py root@kali:~/Test_plots# more plot.py import matplotlib.pyplot as plt import numpy as np x = np.linspace(0,4) y = np.sin(x) plt.plot(x,y) plt.savefig("test.png") print "done" root@kali:~/Test_plots# more batch_job.txt python plot.py | tee output.txt root@kali:~/Test_plots# batch &lt; batch_job.txt warning: commands will be executed using /bin/sh job 30 at Sat Jan 13 22:35:00 2018 root@kali:~/Test_plots# atq 30 Sat Jan 13 22:35:00 2018 = root root@kali:~/Test_plots# atq root@kali:~/Test_plots# ls batch_job.txt output.txt plot.py root@kali:~/Test_plots# more output.txt root@kali:~/Test_plots# The job should execute plot.py and save the terminal output to output.txt. The job seems to fail because the output.txt is empty. If I execute the job manually, it succeeds: root@kali:~/Test_plots# more batch_job.txt python plot.py | tee output.txt root@kali:~/Test_plots# which sh /bin/sh root@kali:~/Test_plots# sh # python plot.py | tee output.txt Fontconfig warning: ignoring UTF-8: not a valid region tag done # exit root@kali:~/Test_plots# ls batch_job.txt output.txt plot.py test.png root@kali:~/Test_plots# more output.txt done The plot and the output.txt was created correctly. Is there any logging where I could check why the batch job failed? EDIT If I comment out the plt-lines in the script, the batch job finishes correctly. root@kali:~/Test_plots# ls batch_job.txt plot.py root@kali:~/Test_plots# more plot.py import matplotlib.pyplot as plt import numpy as np x = np.linspace(0,4) y = np.sin(x) #plt.plot(x,y) #plt.savefig("test.png") print "done" root@kali:~/Test_plots# batch &lt; batch_job.txt warning: commands will be executed using /bin/sh job 34 at Sun Jan 14 00:02:00 2018 root@kali:~/Test_plots# atq root@kali:~/Test_plots# ls batch_job.txt output.txt plot.py root@kali:~/Test_plots# more output.txt done root@kali:~/Test_plots# EDIT2 According to the comm…
has comment: http://stackoverflow.com/comment/83472252
has title: Batch job fails when using matplotlib
tagged with: batch-processing
answer count: 1
linked to: http://stackoverflow.com/q/37604289
has answer: http://stackoverflow.com/a/48450333
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48450333
has comment: http://stackoverflow.com/comment/83473003
downvote count: 0
duplicate of: http://stackoverflow.com/q/37604289

http://stackoverflow.com/q/48261608
has title: Python AttributeError: 'str' object has no attribute 'cursor'
upvote count: 1
favorite count: 0
type: Question
has body: Today is my 3rd day learning Python and despite numerous web searches I can't seem to get past this issue. The code takes in input on the command line and passes it to the connection script fine and it connects. The problem comes when I try to connect the cursor to the connection object on the line that reads: cor = con.cursor(). I get the error message: AttributeError: 'str' object has no attribute 'cursor'. Basically all I'm trying to do is take in parameters for my connection string to connect to the database and then be able to run my query. I request anyone helping me to bear in mind I'm a starter so detailed answers would be very helpful. Thanks in advance. Code below: import pyodbc import getpass import sys server_name = input('Enter Server Name: ') database_name = input('Enter Database Name: ') uid = input('Enter User ID: ') password = getpass.getpass("Enter your password: ") querystring = "select top 1 * from SomeTable" conStr = ('pyodbc.connect'+"('DRIVER={SQL Server};SERVER=%s;DATABASE=%s;UID=%s;PWD=%s')") % (server_name, database_name, uid, password) con = conStr cur = con.cursor() #Generates error on this line cur.execute(querystring) rows = cur.fetchall() for row in rows: print(row)
tagged with: python
accepted answer: http://stackoverflow.com/a/48261609
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48261609
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/a/48305750
type: Answer
score: 0
has body: You can check if the string is empty and if so, do not run the dictionary search. Python evaluates empty strings as False, which can be utilized here: dict={"tony":1,"jack":2,"apple":3} search = raw_input("select: ") number = 1 if search: for i in dict.keys(): if search in i: print number, i number +=1
answers question: http://stackoverflow.com/q/48305646

http://stackoverflow.com/comment/83434390
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48226141
has text: but now some variables are having spaces inside

http://stackoverflow.com/q/48241601
has comment: http://stackoverflow.com/comment/83465712
downvote count: 0
has comment: http://stackoverflow.com/comment/83465960
tagged with: python
has comment: http://stackoverflow.com/comment/83465994
score: 4
tagged with: sparse-matrix
type: AnsweredQuestion
tagged with: matrix
possible better answer: http://stackoverflow.com/a/48243050
has title: Memory-efficient sparse symmetric matrix calculations
accepted answer: http://stackoverflow.com/a/48242072
has answer: http://stackoverflow.com/a/48243050
has comment: http://stackoverflow.com/comment/83465896
has comment: http://stackoverflow.com/comment/83465866
has answer: http://stackoverflow.com/a/48242072
favorite count: 0
type: Question
upvote count: 4
tagged with: numpy
has body: I have to perform a large number of such calculations: X.dot(Y).dot(Xt) X = 1 x n matrix Y = symmetric n x n matrix, each element one of 5 values (e.g. 0, 0.25, 0.5, 0.75, 1) Xt = n x 1 matrix, transpose of X, i.e. X[np.newaxis].T X and Y are dense. The problem I have is for large n, I cannot store and use matrix Y due to memory issues. I am limited to using one machine, so distributed calculations are not an option. It occurred to me that Y has 2 features which theoretically can reduce the amount of memory required to store Y: Elements of Y are covered by a small list of values. Y is symmetric. How can I implement this in practice? I have looked up storage of symmetric matrices, but as far as I am aware all numpy matrix multiplications require "unpacking" the symmetry to produce a regular n x n matrix. I understand numpy is designed for in-memory calculations, so I'm open to alternative python-based solutions not reliant on numpy. I'm also open to sacrificing speed for memory-efficiency.
answer count: 2

http://stackoverflow.com/comment/83514601
type: Comment
type: QuestionComment
has text: Well you could define the function as `int myfunc(int argc, char **argv) { ... }` and use getopt() to do the parsing. But I am afraid that wont make you any friends ...
comment on: http://stackoverflow.com/q/48264698
score: 1

http://stackoverflow.com/comment/83542610
has text: I can't see any constructive way to answer this that isn't just a broad-ranging discussion of OO principles. Maybe you could try writing some non-toy classes with and without using `__init__`, see what you think the differences are, and ask a question about your real code if you need to?
score: 0
comment on: http://stackoverflow.com/q/48279419
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83571988
comment on: http://stackoverflow.com/q/48293400
score: 0
type: Comment
type: QuestionComment
has text: I tried your suggestions to no avail. The WordCloud code is huge and irrelevant since I have run many tests on it.

http://stackoverflow.com/comment/83366177
type: QuestionComment
has text: While it might seem like nonsense, did you actually try creating a file on your desktop to ensure you can? Also how are you executing the script? If it's in the command lines, what's the directory you're running on? Because in your `open()` you didn't specify a directory, so when you execute the script it'll try to create the file based on your current folder.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48191922

http://stackoverflow.com/a/48231802
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83486077
answers question: http://stackoverflow.com/q/48231233
accepted answer of: http://stackoverflow.com/q/48231233
downvote count: 0
has comment: http://stackoverflow.com/comment/83446763
type: Answer
upvote count: 1
has body: The input_dim is just the shape of the input you pass to this layer. So: input_dim = 7 There are other options, such as: input_shape=(7,) -- This argument uses tuples instead of integers, good when your input has more than one dimension batch_input_shape=(batch_size,7) -- This is not usually necessary, but you use it in cases you need a fixed batch size (there are a few layer configurations that demand that) Now, the size of the output in a Dense layer is the units argument. Which is 128 in your case and should be equal to num_neurons.
score: 1

http://stackoverflow.com/comment/83465347
comment on: http://stackoverflow.com/q/48241048
type: QuestionComment
has text: What if both are 0? continuity and group
score: 1
type: Comment

http://stackoverflow.com/comment/83612655
score: 0
type: AnswerComment
has text: Thank you so much. I already have figured out this solution earlier. Forgot to share. This worked fine. Thanks for your response.
comment on: http://stackoverflow.com/a/48280435
type: Comment

http://stackoverflow.com/a/48185968
type: AcceptedAnswer
has body: How could I solve my problem by using either window or SQL statement within Spark? TL;DR You cannot, or at least not in a scalable way, with current requirements. You can try something similar to sliding over RDD: How to transform data with sliding window over time series data in Pyspark I also noticed that when I try a more simple statement using SQL OVER clause, I got a similar error which maybe means I am not passing SQL statement correctly to Spark It is incorrect. Range specification requires (PRECEDING | FOLLOWING | CURRENT_ROW) specification. Also there should be no semicolon: SELECT *, SUM(x) OVER (ORDER BY rank_id RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS cumsum FROM tempdf I want to sum between indexes x+1 and 2x-1 where x is my row index. When I try to pass it to Spark (in similar way we do for orderBy maybe that's the problem), I got the following error ... TypeError: cannot concatenate 'str' and 'int' objects As exception says - you cannot call + on string and integer. You probably wanted columns: from pyspark.sql.functions import col .rangeBetween(col('rank_id') + 1, 2* col('rank_id') - 1) but this is not supported. Range has to be of fixed size and cannot be defined in terms of expressions. An important point is that I don't want to collect data Window definition without partitionBy: w = Window.orderBy('rank_id').rangeBetween(-1,3) is as bad as collect. So even if there are workarounds for "dynamic frame" (with conditionals and unbounded window) problem, they won't help you here.
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48185535
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48185535

http://stackoverflow.com/q/48329964
has answer: http://stackoverflow.com/a/49502904
tagged with: xsd
type: AnsweredQuestion
score: 0
tagged with: lxml
answer count: 1
has comment: http://stackoverflow.com/comment/83646052
tagged with: python
has body: I wrote a function to validate xml data against an xsd schema. But it raises exception once for the first invalid element. Is there any way to get all of the invalid elements without changing the xml input data. xsd_doc = etree.parse('SDO.XSD') xsd = etree.XMLSchema(xsd_doc) xml = etree.XML(data) xsd.validate(xml) parser = etree.XMLParser(schema=xsd, encoding='utf-8') etree.fromstring(data, parser)
accepted answer: http://stackoverflow.com/a/49502904
tagged with: http://stackoverflow.com/tag/xml
type: Question
tagged with: python-3.x
has title: Get All invalid elements in xml data using python lxml and XSD schema

http://stackoverflow.com/comment/83366666
type: QuestionComment
type: Comment
score: 1
has text: You didn't try what I suggested. You used `site_subnets_set` instead of `sitesubnets_set`.
comment on: http://stackoverflow.com/q/48192255

http://stackoverflow.com/q/48207956
tagged with: tensorflow
has title: How to Optimize a Trained Frozen Model for Inference?
favorite count: 0
type: Question
tagged with: inference
type: UnansweredQuestion
tagged with: python
tagged with: object-detection
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/87746839
tagged with: neural-network
downvote count: 0
upvote count: 1
has body: My goal is to decrease the size and complexity of a pre-trained Model (a Tensorflow Frozen Graph as Protobuf .pb file) as far as possible to make Inference (in my case realtime object detection using Webcams) as fast as possible. (See my project repo for more information: https://github.com/GustavZ/realtime_object_detection) Let's take a look at the pre-trained ssd_mobilenet_v1_coco provided by the tensorflow object detection API: link to ssd_mobilenet graph Which Layers are not necessary for inference (so only for the already completed training) and thus can be removed (from the config file to export a new frozen model using the export_inference_graph.py script)? It would be very nice to get a general answer on how to optimize Models for inference as well as an answer on my special case as I think this could be of interest for others. EDIT: I know now about the optimize_for_inference.py script provided py tensorflow. But i have no experience using it, for example how do i know which are the really necessary Input and Output nodes, or how do i read them from tensorboard?

http://stackoverflow.com/comment/123568229
type: AnswerComment
comment on: http://stackoverflow.com/a/51868734
has text: using `jython-standalone` instead of `jython` worked for me: https://bugs.jython.org/issue2355
type: Comment
score: 0

http://stackoverflow.com/a/48269336
score: 12
answers question: http://stackoverflow.com/q/48268563
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84248818
type: Answer
has comment: http://stackoverflow.com/comment/84250315
accepted answer of: http://stackoverflow.com/q/48268563
has comment: http://stackoverflow.com/comment/83523956
has body: AMSgrad has been added on 11.12.2017 to Keras https://github.com/keras-team/keras/pull/8693 whereas Keras 2.1.2 has been built on 01.12.2017 https://github.com/keras-team/keras/releases/tag/2.1.2 So either you need to wait on the next release or install Keras from scratch if the model uses it.
upvote count: 12

http://stackoverflow.com/q/48193461
upvote count: 3
has answer: http://stackoverflow.com/a/48194146
answer count: 2
accepted answer: http://stackoverflow.com/a/48194146
has title: Use memory_profiler to profile lines in a Flask app
has answer: http://stackoverflow.com/a/48193527
possible better answer: http://stackoverflow.com/a/48193527
linked to: http://stackoverflow.com/q/308999
tagged with: profiling
has body: UPDATE: In memory_profiler version 0.53 and later one can @profile decorate as many routes as you want. Earlier versions only allowed decorating one route. The below question only applies to those versions of memory_profiler with version &lt;= 0.52 Using the normal @profile decorator doesn't work on two or more Flask routes. How do I still get line by line memory usage profiling in two or more Flask routes? I want to profile /route_one and /route_two: from functools import wraps from memory_profiler import profile @app.route("/route_one", methods=["GET"]) @profile def route_one(): api_live = ping_api() if not api_live: return make_response('', 503) return make_response('', 200) @app.route("/route_two", methods=["GET"]) @profile def route_two(): api_live = ping_api() if not api_live: return make_response('', 503) return make_response('', 200) When I start up my flask app with the above decorated routes I get this error: AssertionError: View function mapping is overwriting an existing endpoint function: wrapper
downvote count: 0
favorite count: 0
type: Question
score: 3
tagged with: python
tagged with: flask
type: AnsweredQuestion

http://stackoverflow.com/q/48224245
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83430299
has comment: http://stackoverflow.com/comment/83448439
tagged with: python
has answer: http://stackoverflow.com/a/48224323
has body: I have written a class to represent LZMA compressed data with a base64 encoded string: from base64 import b64decode from lzma import LZMADecompressor class B64LZMA(str): """A string of base64 encoded, LZMA compressed data.""" def __bytes__(self): """Returns the decompressed data.""" return LZMADecompressor().decompress(b64decode(self.encode())) def __str__(self): """Returns the string decoded from __bytes__.""" return bytes(self).decode() TEST_STR = B64LZMA('/Td6WFoAAATm1rRGAgAhARYAAAB0L+WjAQALSGVsbG8gd29ybGQuAGt+oFiSvoAYAAEkDKYY2NgftvN9AQAAAAAEWVo=') if __name__ == '__main__': print(TEST_STR) While this works perfectly in python 3.6 on ArchLinux, I get the following error on python 3.4 on Debian 8: Traceback (most recent call last): File "./test.py", line 22, in &lt;module&gt; print(TEST_STR) File "./test.py", line 16, in __str__ return bytes(self).decode() TypeError: string argument without an encoding Why is there this discrepancy in behaviour between python 3.4 and python 3.6 and how can I get the above class to work in python 3.4 as well? Update Script to verify: #! /usr/bin/env python3 from base64 import b64decode from lzma import LZMADecompressor from sys import version class B64LZMA(str): """A string of base64 encoded, LZMA compressed data.""" def __bytes__(self): """Returns the decompressed data.""" return LZMADecompressor().decompress(b64decode(self.encode())) def __str__(self): """Returns the string decoded from __bytes__.""" return bytes(self).decode() TEST_STR = B64LZMA('/Td6WFoAAATm1rRGAgAhARYAAAB0L+WjAQALSGVsbG8gd29ybGQuAGt+oFiSvoAYAAEkDKYY2NgftvN9AQAAAAAEWVo=') if __name__ == '__main__': print(version) print(TEST_STR) SHA-256 sum: 64513a7508b20dda5cc26c37fa4dc8f516369937569833bb0957c10ea887ae00 Output with python 3.4 on Debian 8: $ ./test.py 3.4.2 (default, Oct 8 2014, 10:45:20) [GCC 4.9.1] Traceback (most recent call last): File "./test.py", line 24, in &lt;module&gt; print(TEST_STR) File "./test.py", line 17, in __str__ return bytes(self).decode() …
has title: TypeError: string argument without an encoding in 3.4 but not in 3.6
has comment: http://stackoverflow.com/comment/83430499
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/48224323
answer count: 1
downvote count: 0
tagged with: character-encoding
tagged with: string
has comment: http://stackoverflow.com/comment/83430369
favorite count: 0
type: Question

http://stackoverflow.com/comment/83428583
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48223504
type: QuestionComment
has text: How long are the strings? looks like you could split it and then remove any entries that contain a letter and number, not sure how efficient it would be.

http://stackoverflow.com/comment/83378230
score: 0
has text: using tox and then doing a pip install . --upgrade fixed this problem.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48192856

http://stackoverflow.com/q/48288393
score: 1
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has title: Subtract & divide frequency counts created by count_values after groupby
has body: I am just getting started with pandas/ python so unfortunately I still have to ask silly questions. I have a df with a column with subject id and then a column coded 1 or 0 like so: df = pd.DataFrame({'ID' : [1] * 4 + [2] * 4, 'accuracy' : [1, 1, 0, 1, 1, 1, 0, 1]}) df ID accuracy 0 1 1 1 1 1 2 1 0 3 1 1 4 2 1 5 2 1 6 2 0 7 2 1 I would need to groupby ID first, get the frequency counts of zeros and ones and then subtract &amp; divide these frequency counts like this: (frequency count ones - frequency count zeros/ number of total counts). So for ID 1 this equation would read ((3-1)/4). Using this, df.groupby(['ID'])['accuracy'].value_counts() I get the frequency counts for the zeros &amp; ones per ID, needed for my subsequent calculation. But I'm unsure how to go from here, or whether an entirely different approach like agg and a lambda function or some approach using apply (both of which I just started to learn) would be a better approach. The output would ideally look something like this: id accuracyTotal 1 0.5 2 0.5 Any ideas are much appreciated! Thank you for your help!
downvote count: 0
has answer: http://stackoverflow.com/a/48289110
tagged with: python
type: AnsweredQuestion
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48289110

http://stackoverflow.com/comment/83470399
comment on: http://stackoverflow.com/a/48243908
score: 1
has text: If that's really the cause, then the question is a typographical error (which should be closed).
type: Comment
type: AnswerComment

matrix
tags question: http://stackoverflow.com/q/48324935
tags question: http://stackoverflow.com/q/48200721
tags question: http://stackoverflow.com/q/48320229
tags question: http://stackoverflow.com/q/48271167
tag name: matrix
tags question: http://stackoverflow.com/q/48179476
tags question: http://stackoverflow.com/q/48224084
tags question: http://stackoverflow.com/q/48308240
tags question: http://stackoverflow.com/q/48228736
tags question: http://stackoverflow.com/q/48177247
tags question: http://stackoverflow.com/q/48200911
tags question: http://stackoverflow.com/q/48255053
tags question: http://stackoverflow.com/q/48238227
tags question: http://stackoverflow.com/q/48220004
tags question: http://stackoverflow.com/q/48230296
tags question: http://stackoverflow.com/q/48329672
tags question: http://stackoverflow.com/q/48280753
tags question: http://stackoverflow.com/q/48211738
tags question: http://stackoverflow.com/q/48245364
tags question: http://stackoverflow.com/q/48232129
tags question: http://stackoverflow.com/q/48207685
tags question: http://stackoverflow.com/q/48285773
type: Tag
tags question: http://stackoverflow.com/q/48324806
tags question: http://stackoverflow.com/q/48269666
tags question: http://stackoverflow.com/q/48241601

http://stackoverflow.com/comment/83413701
type: Comment
comment on: http://stackoverflow.com/a/48214116
score: 0
type: AnswerComment
has text: yes, if you use only lists, strings, ints, floats, bools, dicts, tuples... basic types. Try it.

http://stackoverflow.com/a/48289327
upvote count: 2
has comment: http://stackoverflow.com/comment/83563692
type: AcceptedAnswer
has body: If you are ok with the following assertions: Names and surnames always begin with a capital letter For names reduced to one capital letter, this letter is always immediately followed by a dot Names can be separated with either a comma or the "and" word These names end with a final dot Then you can use this regex: ^©[0-9]{4} +(([A-Z][a-z]+|[A-Z]\.|and|,) *)*\. *
downvote count: 0
has comment: http://stackoverflow.com/comment/83564616
accepted answer of: http://stackoverflow.com/q/48288763
type: Answer
answers question: http://stackoverflow.com/q/48288763
has comment: http://stackoverflow.com/comment/83564471
score: 2

http://stackoverflow.com/comment/83543222
comment on: http://stackoverflow.com/q/48279745
score: 0
has text: In Python 3, plain strings are for (Unicode) text, don't try to use them for binary data. Instead, you should be using `bytearray`, or possibly `bytes` objects. Is Numpy an option for you? How come your RGB values range from 0-254 instead of 0-255?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83451522
has text: Also note, writing getters and setters is not Pythonic.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48234422

http://stackoverflow.com/q/48264580
tagged with: regex-negation
has title: Regex replace everything except match
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83512240
has comment: http://stackoverflow.com/comment/83513362
has comment: http://stackoverflow.com/comment/83512681
has body: I would like to keep just words that start with '@' and continue with letters or dots. Basically I have done opposite that I can match such a words but don't know how to match everything besides this match. So basically just keep those that starts with '@'. So far I have this patter: (@[a-zA-Z0-9.]+\b) I tried to use '?!' but it doesn't work. Thanks!
has comment: http://stackoverflow.com/comment/83512497
has answer: http://stackoverflow.com/a/48265407
has comment: http://stackoverflow.com/comment/83512033
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/83512858
has comment: http://stackoverflow.com/comment/83513091
has comment: http://stackoverflow.com/comment/83512812
type: Question
has comment: http://stackoverflow.com/comment/83512032
accepted answer: http://stackoverflow.com/a/48265407
answer count: 2
possible better answer: http://stackoverflow.com/a/48265416
has comment: http://stackoverflow.com/comment/83512524
has comment: http://stackoverflow.com/comment/83511961
has answer: http://stackoverflow.com/a/48265416

http://stackoverflow.com/comment/83555717
score: 0
type: Comment
type: QuestionComment
has text: This feels like a job for [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming) / [memoization](https://en.wikipedia.org/wiki/Memoization).
comment on: http://stackoverflow.com/q/48285534

http://stackoverflow.com/q/48299199
has body: I got a problem with a dict I want to sort in python 3.5. It looks like : d = {'automate': &lt;Routing.Route.Route object at 0x2b7f84835c18&gt;, 'index': &lt;.Routing.Route.Route object at 0x2b7f8486e5c0&gt;, 'index_1': &lt;Routing.Route.Route object at 0x2b7f8483d400&gt;, 'index_2': &lt;Routing.Route.Route object at 0x2b7f84835f98&gt;, 'second': &lt;Routing.Route.Route object at 0x2b7f8483d470&gt;, 'test_route_parameters': &lt;Routing.Route.Route object at 0x2b7f8486e588&gt;} Where Route class has name, package_name attributes. I want to print this dict like: &gt;&gt; Package_name1: automate index index_1 Package_name2: second index_2 Package_name3: test_route_parameters How can I sort my dict by package_name and print it to match the above output? Have a good day and thank you.
has answer: http://stackoverflow.com/a/48299369
downvote count: 1
favorite count: 0
has title: Sorting and merge values of a python dict
type: Question
accepted answer: http://stackoverflow.com/a/48299369
tagged with: python
tagged with: dictionary
score: -1
has comment: http://stackoverflow.com/comment/83582805
has comment: http://stackoverflow.com/comment/83582853
possible better answer: http://stackoverflow.com/a/48299742
type: AnsweredQuestion
upvote count: 0
answer count: 2
has answer: http://stackoverflow.com/a/48299742

http://stackoverflow.com/comment/83670809
type: AnswerComment
comment on: http://stackoverflow.com/a/48341409
score: 0
type: Comment
has text: You are quite right, and thank you. As stated by all of you the DICOMDIR file is what I was missing. All three libraries vtkDICOM, dcmtk, and Imebra can read that file and allow structured access. As I am already using vtk elsewhere in my project, it was simply the easiest to just add vtkDICOM on rather than bring in another open source library...

http://stackoverflow.com/comment/83525162
type: Comment
score: 0
has text: Other than that, I'm not sure what your problem or question is, since the error message is quite clear. The error is certainly not related to anything you're trying to do (given the title of the question).
comment on: http://stackoverflow.com/q/48270750
type: QuestionComment

http://stackoverflow.com/a/48179102
type: Answer
has comment: http://stackoverflow.com/comment/83479155
score: 4
upvote count: 4
has body: import boto3 client = boto3.client('s3', region_name='ap-southeast-2') client.upload_file('/tmp/foo.txt', 'my-bucket', 'test/images/example/foo.txt')
downvote count: 0
answers question: http://stackoverflow.com/q/48176104
has comment: http://stackoverflow.com/comment/83467920
has comment: http://stackoverflow.com/comment/83421846

http://stackoverflow.com/comment/83599834
type: Comment
type: QuestionComment
has text: ok so i feel like i am misunderstanding what you mean by window. like for instance if Chrome is open is it considered a window?
comment on: http://stackoverflow.com/q/48306887
score: 0

http://stackoverflow.com/comment/83554051
type: AnswerComment
has text: but train[train.dtypes=='object'] why this comes errror
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48284978

http://stackoverflow.com/q/48289534
answer count: 2
has comment: http://stackoverflow.com/comment/83564781
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48289784
tagged with: python
has title: Python3 Timestamp to unix time (with sometime milliseconds)
tagged with: timestamp
has body: I'm trying to convert a timestamp to unix time. Timestamp looks like this: 2018-01-16T20:26:16.35 So now I use this code: timestamp = '2018-01-16T20:26:16.35' ts = timestamp.replace("T", " ") tsUnix = time.mktime(datetime.datetime.strptime(ts, "%Y-%m-%d %H:%M:%S.%f").timetuple()) Sometime the api where get the timestamps from gives me the time without milliseconds. It will result in a error, 'Does not match the format'. (Duh, %f is not in there) Do I need to script a workaround or is there a function for this? And is there a better way to strip the "T" from the original timecode?
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83564356
favorite count: 0
has answer: http://stackoverflow.com/a/48289922
type: Question
has comment: http://stackoverflow.com/comment/83564537
tagged with: unix-timestamp
tagged with: python-3.x

http://stackoverflow.com/comment/111521381
type: QuestionComment
comment on: http://stackoverflow.com/q/48281521
type: Comment
has text: @SebastianKarlsson did you ever manage to solve this? I'm running into the same issue
score: 0

http://stackoverflow.com/a/48230503
has body: The error says it all : ElementNotVisibleException: Message: element not visible As you have tried to locate the Username and Password field through the id attribute, the fields were not uniquely identified. So we have to adopt a Locator Strategy which uniquely identifies the Username and Password field as follows : # populate the Username field self.driver.find_element_by_xpath("//td/img[@src='../images/login_userName.png']//following::input[2]").send_keys("username") # populate the Password field self.driver.find_element_by_xpath("//td/img[@src='../images/login_password.png']//following::input[2]").send_keys("password")
type: Answer
answers question: http://stackoverflow.com/q/48224350
score: 0
has comment: http://stackoverflow.com/comment/83533337

http://stackoverflow.com/a/62594919
answers question: http://stackoverflow.com/q/48295229
score: 1
downvote count: 0
upvote count: 1
has body: I made a library to make it easier to use bokeh in Colab First install it !pip install kora Then your can plot a figure easily from kora.bokeh import figure p = figure(100, 200) # h, w p.line([1, 2, 3, 4], [6, 7, 2, 4]) p # display itself, don't need show() If you call from kora import bokeh, it can work the same as import bokeh. Or you can use them together as well. What I did is just create _repr_html_() that help display the Figure object.
type: Answer

http://stackoverflow.com/a/48321615
upvote count: 6
type: Answer
score: 6
has body: Note The part of my answer with the custom plugin is way too overengineered; it is already sufficient to just reassign the xmlpath option as in this answer. Use that instead. The XML plugin reconfiguration is only needed if you want to make deeper changes in XML report assembly, which isn’t the case here. Original answer First of all, if you want to implicitly add the command line args to pytest, you can use the pytest.ini placed in the tests root dir with the addopts config value: [pytest] addopts=--verbose --junit-xml=/tmp/myreport.xml # etc Of course, if you want to dynamically calculate the directory to store the reports, then you can't put it in the config and will need to extend pytest. The best spot would be the pytest_configure hook. Example: # conftest.py import tempfile import pytest from _pytest.junitxml import LogXML @pytest.hookimpl(tryfirst=True) def pytest_configure(config): if config.option.xmlpath: # was passed via config or command line return # let pytest handle it if not hasattr(config, 'slaveinput'): with tempfile.NamedTemporaryFile(suffix='.xml') as tmpfile: xmlpath = tmpfile.name config._xml = LogXML(xmlpath, config.option.junitprefix, config.getini('junit_suite_name')) config.pluginmanager.register(config._xml) If you remove the first if block, then pytest will completely ignore --junit-xml arg passed via command line or in addopts value in config. Example run: $ pytest =================================== test session starts ==================================== platform darwin -- Python 3.6.3, pytest-3.3.1, py-1.5.2, pluggy-0.6.0 rootdir: /Users/hoefling/projects/private/stackoverflow/so-48320357, inifile: plugins: forked-0.2, asyncio-0.8.0, xdist-1.22.0, mock-1.6.3, hypothesis-3.44.4 collected 1 item test_spam.py . [100%] --- generated xml file: /var/folders/_y/2qk6029j4c7bwv0ddk3p96r00000gn/T/tmp1tleknm3.xml --- ================================ 1 passed in 0.01 seconds ================================== The xml report is now put in a tempfi…
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48320357
accepted answer of: http://stackoverflow.com/q/48320357

http://stackoverflow.com/comment/83549352
has text: If you found this answer useful, you can "accept" it by clicking the checkmark on the left. Welcome.
comment on: http://stackoverflow.com/a/48262649
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83568614
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48197897
has text: Did this work for you? I can update my answer if there are any other exceptions occurring.
type: Comment

http://stackoverflow.com/q/48241191
tagged with: python
has comment: http://stackoverflow.com/comment/83464851
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83464751
has title: Writing writing a large text file in python3
has comment: http://stackoverflow.com/comment/83464924
accepted answer: http://stackoverflow.com/a/48241245
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48241245
has body: While I've seen some literature on the topic I didn't quite understand how to implement a code block which will write large text files without crashing. As I understand, it is supposed to be done line by line however from the implementations I've seen this is only done with files that already exist, instead I want to create and write the file in the block with each iteration of the loop. This is the code block (it's surrounded by a try catch): fileW = open(str(articleDate.title)+"-WC.txt", 'wb') fileW.write(getText.encode('utf-8', errors='replace').strip()+ str(articleDate.publish_date).encode('utf-8').strip()) fileW.close() The reason I know I need an alternate way to write to the file is because I saw that this exception kept being raised, the 'chunks' keywords that kept popping up indicated that the write() method couldn't handle the amount of text: File "/Users/Adrian/anaconda3/lib/python3.6/http/client.py", line 546, in _get_chunk_left chunk_left = self._read_next_chunk_size() File "/Users/Adrian/anaconda3/lib/python3.6/http/client.py", line 513, in _read_next_chunk_size return int(line, 16) ValueError: invalid literal for int() with base 16: b'' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/Adrian/anaconda3/lib/python3.6/http/client.py", line 563, in _readall_chunked chunk_left = self._get_chunk_left() File "/Users/Adrian/anaconda3/lib/python3.6/http/client.py", line 548, in _get_chunk_left raise IncompleteRead(b'') http.client.IncompleteRead: IncompleteRead(0 bytes read) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "webcrawl.py", line 102, in &lt;module&gt; writeFiles() File "webcrawl.py", line 83, in writeFiles extractor = Extractor(extractor='ArticleExtractor', url=urls) File "/Users/Adrian/anaconda3/lib/python3.6/site-packages/boilerpipe/extract/__init__.py", line 39, in __init__ connection = urllib2.urlopen(request) File "/U…
type: Question

http://stackoverflow.com/comment/83468472
type: QuestionComment
score: 0
has text: Kindly note that this is my complete code. I don't have anything else. If you can suggest me solution then that will be very much helpful for me-Thanks
comment on: http://stackoverflow.com/q/48238702
type: Comment

http://stackoverflow.com/a/48197389
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48197248
has comment: http://stackoverflow.com/comment/83390977
has comment: http://stackoverflow.com/comment/83376569
answers question: http://stackoverflow.com/q/48197248
has comment: http://stackoverflow.com/comment/83400222
type: Answer
has comment: http://stackoverflow.com/comment/83378520
has body: Yes, this is quite straightforward with the multiprocessing package. You'll need a function that can be called directly on each dab in lista, something like: def dabify(dab): sdab = dab.split(':') login = sdab[0] senha = sdab[1] myfunction(login,senha) Then, you can use a multiprocessing pool to call dabify on each element of lista: from multiprocessing import Pool pool = Pool(processes=4) # specify number of processes for result in pool.imap_unordered(dabify, lista): # do something with the result here if you want pass Note that the order that the API gets called is no longer guaranteed.
upvote count: 1
score: 1

http://stackoverflow.com/comment/85045204
comment on: http://stackoverflow.com/a/48367523
score: 3
has text: @JouniHelske With HDBSCAN you can do `clusterer.single_linkage_tree_.get_clusters(epsilon_value, min_cluster_size=m)` to get clusters at a cut level of `epsilon_value` and exclude any clusters with less than `m` points.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83525155
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48266736
has text: thanks for the reply. I tested your code but it does not lead to the correct result. It seems to miss the pattern `[True, False, True]`, when it should become `[True, True, True]`. By the way, I found a mistake in my code which I included in the question
type: Comment

http://stackoverflow.com/a/48174859
has comment: http://stackoverflow.com/comment/130000388
answers question: http://stackoverflow.com/q/48174599
score: 0
has comment: http://stackoverflow.com/comment/130000600
type: Answer
has body: You can create a simple wrapper script which runs activate, executes your command, and then deactivates simply by exiting the script in which your environment was activated. #!/bin/sh . ${venv-./env}/bin/activate "$@" This lets you set the environment variable venv to the path of the environment you want to use, or else uses ./env if it is unset. Perhaps a better design would be to pass the env as the first parameter: #!/bin/sh . "$1"/bin/activate shift "$@" Either way, save this somewhere in your PATH ($HOME/bin is a common choice for your private scripts) and give it executable permission.
has comment: http://stackoverflow.com/comment/129988652
upvote count: 2
has comment: http://stackoverflow.com/comment/129979542
downvote count: 2
has comment: http://stackoverflow.com/comment/129979593
has comment: http://stackoverflow.com/comment/130000048
has comment: http://stackoverflow.com/comment/129979608

http://stackoverflow.com/q/48248821
linked to: http://stackoverflow.com/q/19670904
has body: I have a series looking like this: s = pd.Series( np.array([0, 0, 1, 1, 2, 2]), index=np.array([ 0., 1., 2., 4., np.nan, 3.]) ) 0.0 0 1.0 0 2.0 1 4.0 1 NaN 2 3.0 2 dtype: int64 You'll notice the NaN in the index I want to drop. What's the most efficient way of dropping that row? Expected result: 0.0 0 1.0 0 2.0 1 4.0 1 3.0 2 Name: 0, dtype: int64 Current approach: s.reset_index().dropna().set_index('index').squeeze()
has title: How to efficiently dropna when the NaNs are contained in the index?
accepted answer: http://stackoverflow.com/a/48248840
has answer: http://stackoverflow.com/a/48248840
has comment: http://stackoverflow.com/comment/83480129
favorite count: 0
type: Question
tagged with: numpy
duplicate of: http://stackoverflow.com/q/19670904
upvote count: 2
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/48248836
has comment: http://stackoverflow.com/comment/83480206
has answer: http://stackoverflow.com/a/48248836
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/48248854
tagged with: performance
answer count: 3
has comment: http://stackoverflow.com/comment/83480112
tagged with: pandas

http://stackoverflow.com/q/48178039
tagged with: apache-spark-sql
accepted answer: http://stackoverflow.com/a/48179780
has answer: http://stackoverflow.com/a/48179780
tagged with: pyspark
has title: PySpark UDF to return tuples of variable sizes
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
answer count: 2
tagged with: apache-spark
downvote count: 0
has body: I take an existing Dataframe and create a new one with a field containing tuples. A UDF is used to produce this field. For instance, here, I take a source tuple and modify its elements to produce a new one: udf( lambda x: tuple([2*e for e in x], ...) The challenge is that the tuple's length is not known in advance and can change from row to row. From what I understand reading related discussions, to return a tuple, UDF's return type has to be declared as StructType. However, since the number of elements in the returned tuple is not known, I can't just write something like: StructType([ StructField("w1", IntegerType(), False), StructField("w2", IntegerType(), False), StructField("w3", IntegerType(), False)]) It appears that it is possible to return lists, but lists wouldn't work for me, since I need a hashable object in the output Dataframe. What are my options? Thanks in advance
possible better answer: http://stackoverflow.com/a/52636611
favorite count: 0
has answer: http://stackoverflow.com/a/52636611
type: Question
tagged with: user-defined-functions

monkeypatching
tag name: monkeypatching
tags question: http://stackoverflow.com/q/48234723
type: Tag

http://stackoverflow.com/q/48243370
accepted answer: http://stackoverflow.com/a/48244476
has body: I'm new to numba and can't seem to figure the arguments to pass to vectorize. Here's what I'm trying to do: test = [x for x in range(10)] test2 = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'c', 'c'] test_df = pd.DataFrame({'test': test, 'test2': test2}) test_df['test3'] = np.where(test_df['test'].values % 2 == 0, test_df['test'].values, np.nan) test test2 test3 test4 0 0 a 0.0 0.0 1 1 a NaN NaN 2 2 a 2.0 4.0 3 3 b NaN NaN 4 4 b 4.0 16.0 5 5 c NaN NaN 6 6 c 6.0 36.0 7 7 c NaN NaN 8 8 c 8.0 64.0 9 9 c NaN NaN The task is create a new column based on the following logic, first based on standard pandas: def nonnumba_test(row): if row['test2'] == 'a': return row['test'] * row['test3'] else: return np.nan Use apply; I understand I can accomplish this much faster using np.where and the .values attribute of the Series objects, but want to test this against numba. test_df.apply(nonnumba_test, axis=1) 0 0.0 1 NaN 2 4.0 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN 8 NaN 9 NaN dtype: float64 Next, when I try to use the numba.vectorize decorator @numba.vectorize() def numba_test(x, y, z): if x == 'a': return y * z else: return np.nan I get the following error numba_test(test_df['test2'].values, test_df['test'].values, test_df['test3'].values) ValueError: Unsupported array dtype: object I imagine I need to specify the return type in the signature argument, but I can't seem to figure it out.
has answer: http://stackoverflow.com/a/48244476
favorite count: 0
type: Question
upvote count: 4
tagged with: numba
tagged with: python
has title: numba.vectorize - Unsupported array dtype
score: 4
linked to: http://stackoverflow.com/q/32056337
type: AnsweredQuestion
tagged with: pandas
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/83474958
comment on: http://stackoverflow.com/q/48246135
score: 1
type: QuestionComment
has text: `B[A > 4] = 0`?
type: Comment

http://stackoverflow.com/q/48226460
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48226517
downvote count: 0
has answer: http://stackoverflow.com/a/48226504
score: 10
upvote count: 10
favorite count: 0
has body: I have a dataframe with the following structure: 0 1 2 0 0.00086076 500.00000000 [] 1 0.00086075 819.00000000 [] 2 0.00086072 1162.00000000 [] 3 0.00086071 20.00000000 [] 4 0.00086069 10170.00000000 [] 5 0.00086067 18.00000000 [] Then I have another dataframe with update values: 0 1 2 0 0.00086071 50.00000000 [] 1 0.00086068 81.00000000 [] It is sorted on column 0 and I need to merge the two as follows: 0 1 2 0 0.00086076 500.00000000 [] 1 0.00086075 819.00000000 [] 2 0.00086072 1162.00000000 [] 3 0.00086071 50.00000000 [] 4 0.00086069 10170.00000000 [] 5 0.00086068 81.00000000 [] 6 0.00086067 18.00000000 [] So if a value matches one in column 0 it should update column 1 if not it should insert a new row and sort again. Is there an efficient way or predefined function for doing this?
type: Question
possible better answer: http://stackoverflow.com/a/48226504
answer count: 2
has title: Efficient solutions insert or update row pandas
linked to: http://stackoverflow.com/q/15819050
tagged with: python
accepted answer: http://stackoverflow.com/a/48226517
tagged with: pandas

http://stackoverflow.com/a/49237311
has comment: http://stackoverflow.com/comment/112659133
has body: I had the same. In PyCharm I had made a directory "locale" (with a __init__.py for no reason whatsoever) for my internationalisation and got this message: AttributeError: module 'locale' has no attribute 'normalize' This is due to the fact it is looking for a Python module "locale" but that is masked by your Django directory "locale". Either remove the __init__.py and/or rename your directory "locale". I did both... "To stitch something twice is to stich it well" as we say in Holland. It seems that everywhere on the net people use "locale" as directory for their internationlization. Hmm.. it now seems to me a bit like making a class with the name "Class" or a SQL table with the name "Table". I have seen in done, at times it works, I would never recommend it though.
type: Answer
upvote count: 13
score: 13
answers question: http://stackoverflow.com/q/48253070
downvote count: 0

http://stackoverflow.com/comment/83428254
has text: @TCouch thank you, that actually shed some light on the matter! The step ordering is actually almost exactly what I am looking for.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48222977
score: 0

http://stackoverflow.com/comment/83600967
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48307797
has text: You're using a reserved MySQL parameter as a `name` --- `DATETIME` should **not** be used as a `name`. I would rename your field to something less "parameter-ish"

http://stackoverflow.com/comment/83351113
has text: One try is Write into a file. Load into template via ajax call. Otherwise take a look at StreamingHttpResponse
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48185543

http://stackoverflow.com/a/48278872
answers question: http://stackoverflow.com/q/48264656
has body: Do make sure the Amazon SageMaker role has policy attached to it to have access to S3. It can be done in IAM.
upvote count: 5
type: Answer
score: 5
downvote count: 0

http://stackoverflow.com/a/48315854
has comment: http://stackoverflow.com/comment/83689642
answers question: http://stackoverflow.com/q/48315369
has comment: http://stackoverflow.com/comment/83693291
score: 0
type: Answer
has body: if i'm not mistaken: cow2 = list(cow1) cow3 = list(cows) cow_val = [] cow_val1 = [] print(cows, cow3) for x in range(h): current = cow3[0] while current in cow3: cow_val.append(cow1[cow1.index(current)]) cow1.pop(cow1.index(current)) cow1.pop(cow1.index(current)+1) cow_val1.append(sum(cow_val)) cow3.pop(0) why are you popping twice here? You may want to look at your code more carefully if this is unintended. You may want to consider re-organizing the information: {"cow_idhere":{"sunday":{"AM":0, "PM":0}, \ "monday":{"AM":0, "PM":0}, \ "tuesday":{"AM":0, "PM":0}, \ "wednesday":{"AM":0, "PM":0}, \ "thursday":{"AM":0, "PM":0}, \ "friday":{"AM":0, "PM":0}, \ "saturday":{"AM":0, "PM":0}}, "nextcow_id": ... } with functions to access to get the information. (your sections) I don't see the need constantly pop and append with so many cows. I mean variables. Example def get_MilkForDay(cow_data = None, day=""): def get_MilkForWeek(cow_data = None): Also the last section (above) doesn't have a description saying what it is for. What exactly is it suppose to do?
has comment: http://stackoverflow.com/comment/83618521

http://stackoverflow.com/comment/83440096
has text: Does it work? Is it readable and maintainable? Does profiling say it's fast enough?
type: Comment
score: 4
type: QuestionComment
comment on: http://stackoverflow.com/q/48229056

http://stackoverflow.com/comment/83485222
comment on: http://stackoverflow.com/a/48247205
score: 0
type: AnswerComment
has text: Thanks @jezrael for clear and instructive example of HTML scraping
type: Comment

http://stackoverflow.com/comment/83523218
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48269079
has text: I have the async branch. My issue is that imageURL is equal to another variable and not a raw string. My code looks like: `response = requests.get("https://dog.ceo/api/breeds/image/random") soupRaw = BeautifulSoup(response.text, 'lxml') soupBackend = str(soupRaw).split("message") soup2 = soupBackend[1] soup3 = soup2[3:] soup = soup3[:-20] embed = discord.Embed(title = "Here is your dog!", description = "Hope you like it", color = 0x5810ea) embed.set_image(url = soup) await bot.send_message(message.channel, embed=embed)` Any way I can fix this?
type: Comment

http://stackoverflow.com/comment/83535484
type: Comment
comment on: http://stackoverflow.com/a/48275799
has text: @piRSquared - Exactly. And I am surprised isin is so slow :(
type: AnswerComment
score: 0

http://stackoverflow.com/q/48303200
has title: Unable To Click Element Inside Iframe - NoSuchElementException
has body: I navigate to the website, switch to the correct iframe, and everything seems to work fine, but once I need to interact with an element it throws the error: selenium.common.exceptions.ElementNotVisibleException CODE: # IMPORT from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from time import sleep # NAVIGATE driver = webdriver.Chrome("C:\\Program Files (X86)\\Google\\chromedriver.exe") driver.get('http://www.foxnews.com/politics/2018/01/17/ice-plans-major-sweep-in-san-francisco-area-report-says.html') # SWITCH TO IFRAME iframe = driver.find_element_by_xpath('//IFRAME[contains(@src, "https://spoxy-shard4.spot.im/v2/spot/")]') driver.switch_to.frame(iframe) driver.find_element_by_xpath("//INPUT[@placeholder='Your nickname...']").click() I've tried targeting other elements as well, but it always gives an error: "no such element" "element not found" "is not clickable at point (485, 873). Other element would receive the click: &lt;p class="alert-text"&gt;...&lt;/p&gt;".
has comment: http://stackoverflow.com/comment/83592691
tagged with: python
has answer: http://stackoverflow.com/a/48304642
has comment: http://stackoverflow.com/comment/83591137
has comment: http://stackoverflow.com/comment/83592642
has comment: http://stackoverflow.com/comment/83591350
has comment: http://stackoverflow.com/comment/83591228
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83592095
answer count: 1
has comment: http://stackoverflow.com/comment/83595423
tagged with: selenium
linked to: http://stackoverflow.com/q/27927964
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83631221
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83593862
has comment: http://stackoverflow.com/comment/83591431

http://stackoverflow.com/q/48177847
tagged with: python
linked to: http://stackoverflow.com/q/4630465
has body: I am trying to write a Python script that performs diff -r on two directories. I would like to exclude hidden files on the directories. Here is what I have. source = "/Users/abc/1/" target = "/Users/abc/2/" bashCommand = 'diff -x ".*" -r ' + source + ' ' + target # Below does not work either # bashCommand = "diff -x '.*' -r " + source + ' ' + target import subprocess process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE) output, error = process.communicate() if output: print "Directories do not match: " + output else: print "Directories match" I know that I should use -x '.*' to ignore dot files. I looked at this SO post. But it didn't help. How should I write this line? bashCommand = 'diff -x ".*" -r ' + source + ' ' + target Edit 1: I also tried this and it does not work either pat = "-x \".*\"" bashCommand = "diff " + pat + " -r " + source + " " + target print bashCommand When I print the output and run the command manually it works as expected. However the Python script is not producing the desired result $python BashCommand.py diff -x ".*" -r /Users/abc/1/ /Users/abc/2/ Directories do not match: Only in /Users/abc/1/: .a $diff -x ".*" -r /Users/abc/1/ /Users/abc/2/ $
tagged with: diff
type: Question
accepted answer: http://stackoverflow.com/a/48177931
tagged with: bash
score: 5
has title: Perform diff on two directories by excluding hidden files using Python
has answer: http://stackoverflow.com/a/48177931
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/6697753
type: AnsweredQuestion
upvote count: 5

http://stackoverflow.com/comment/83499118
type: Comment
score: 1
type: QuestionComment
has text: you need provide a field name: `-F "file=@/home/dev/datafiles/file.parquet`.
comment on: http://stackoverflow.com/q/48257387

http://stackoverflow.com/comment/83418182
type: QuestionComment
comment on: http://stackoverflow.com/q/48217961
has text: Edit your code down to relevant portions so you don't risk crushing innocent bystanders.
score: 1
type: Comment

http://stackoverflow.com/comment/83600505
score: 0
type: QuestionComment
has text: @Usernamenotfound Yes, i have saved the shell file and lpthw in the same folder.
type: Comment
comment on: http://stackoverflow.com/q/48290132

http://stackoverflow.com/a/48312757
type: Answer
has body: Not sure the reasoning but this was caused due to using Scattergl instead of Scatter.
answers question: http://stackoverflow.com/q/48292436
score: 0

http://stackoverflow.com/comment/83366762
has text: post the actual input text
comment on: http://stackoverflow.com/q/48193118
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48247419
score: 3
type: Answer
has body: You can define a list of tuples. Each tuple should contain a character and desired frequency. Then you can create a list where each element is repeated with specified frequency and finally shuffle it using random.shuffle &gt;&gt;&gt; import random &gt;&gt;&gt; l = [('A',3),('B',5),('C',10)] &gt;&gt;&gt; a = [val for val, freq in l for i in range(freq)] &gt;&gt;&gt; random.shuffle(a) &gt;&gt;&gt; ['A', 'B', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'A', 'C', 'B', 'C']
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48247314

http://stackoverflow.com/comment/83991560
score: 0
comment on: http://stackoverflow.com/q/48275475
type: QuestionComment
type: Comment
has text: I can tell you that if you wait enough, it works on Debian too.

http://stackoverflow.com/q/48265933
tagged with: qt
type: AnsweredQuestion
has title: Draw filled circle in matplotlib figure and show with Qt
tagged with: matplotlib
answer count: 1
has answer: http://stackoverflow.com/a/48266871
score: 1
has body: I am writing a program to plot orbits around the Earth. The orbits are represented by lists of x and y coordinates and plotted with the plot() function. Now I would like to have Earth shown as a filled circle with the correct radius around origin. I tried to use the MatLab function rectangle() but get error messages saying that there is no suck attribute. I have read in other sources that using pyplot might cause unexpected behavior and would like to achieve this without using that library. In short, I would like a filled circle with radius r around the * in this figure. How can I implement this function in my MWE: import sys from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure from PyQt4 import QtCore, QtGui, uic qtCreatorMain = "GUI.ui" Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorMain) class MainGUI(QtGui.QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MainGUI, self).__init__(parent) self.setupUi(self) #### Lots of other code goes here #### # PlotView self.figure = Figure(tight_layout=True) self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) self.plotLayout.addWidget(self.toolbar) self.plotLayout.addWidget(self.canvas) self.graph = self.figure.add_subplot(111) self.graph.axis('equal') self.graph.plot([-3, -2, -1, 0, 1, 2, 3], [0, -1, 4, 2, 0, -3, -5]) self.graph.plot(0, 0, '*') ### Even more code goes here #### if __name__ == "__main__": app = QtGui.QApplication(sys.argv) window = MainGUI() window.show() sys.exit(app.exec_()) GUI.ui: <?xml version="1.0" encoding="UTF-8"?> MainWindow <x>0</x> <y>0</y> 800 600 MainWindow QFrame::StyledPanel QFrame::Raised Lots of stuff goes in this part 0 QLayout::SetDefaultConstraint verticalLayoutWidget frame label <x>0</x> <y>0</y> 800 27 <resources/> <connections/>
has comment: http://stackoverflow.com/comment/83516427
favorite count: 0
linked to: http://stackoverflow.com/q/9215658
type: Question
has comment: http://stackoverflow.com/comment/83515081
has comment: http://stackoverflow.com/comment/83516377
accepted answer: http://stackoverflow.com/a/48266871
downvote count: 0
duplicate of: http://stackoverflow.com/q/9215658
upvote count: 1
tagged with: python

http://stackoverflow.com/q/48266118
downvote count: 1
has comment: http://stackoverflow.com/comment/83517467
favorite count: 0
has title: Convolution of two signals with constrained output measuring unit
type: Question
tagged with: numpy
has body: I'm programming in Python and I have two signals, a rectangular signal f(t) and a distribution function g(t) (e.g. normal distribution, log-normal distribution etc.). Both signals are defined over time (x-axis) with a resolution of 0.001 s and the measure of the rectangle is in pulses per second (1/s, y-axis). Both functions shall be convolved, whereby the unit of the result (y-axis) has to be again pulses per second for the subsequent calculations. The original domain of definition in which the results make sense is 0-250 1/s (or at least not much higher). Since I'm programming in Python, f(t) is just an array of ones, multiplied with a respective amplitude. I read in the literature, that g(t) has to be a PDF for my sort of calculations, so I normalized it to its area. The specific background is, that g(t) is a time delay profile whose influence on the original signal f(t) shall be investigated. This means, I want to find out in which way the shape of f(t) is altered and which impact that has on the subsequent calculations. My first question is: can I convolve these two signals without any further considerations, or do I have to transform the rectangle at first into a PDF as well? My second problem is: after the convolution, what measure does the result have? Lets say I convolved the PDF of g(t) with the original f(t) ... is the resulting unit simply 1/s again? If not, how do I convert it into a signal with the unit 1/s? The thing is, I tested both approaches case1 PDF(f(t)) * g(t) and case2 PDF(f(t)) * PDF(g(t)). Both results are way to high as that it would make any sense for the subsequent computations. Let me give you an example: time resolution = 1 ms Amplitude f(t) = 250 1/s duration f(t) = 1.2 s duration g(t) = 0.18 s In case1 the resulting maximal amplitude of the convolution product would be slightly less than 250k. One solution might be to divide this result by 1000 (the time resolution, because this is the parameter to which I normalized the PDF). So in …
has comment: http://stackoverflow.com/comment/83647448
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83625733
tagged with: math
has comment: http://stackoverflow.com/comment/83625746
tagged with: python
has comment: http://stackoverflow.com/comment/83517504
has comment: http://stackoverflow.com/comment/83515510
tagged with: statistics
has comment: http://stackoverflow.com/comment/83567722
has comment: http://stackoverflow.com/comment/83567702
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83520086
has comment: http://stackoverflow.com/comment/83567740
upvote count: 1
has comment: http://stackoverflow.com/comment/83600660

http://stackoverflow.com/q/48174955
tagged with: python
has answer: http://stackoverflow.com/a/48175011
score: -1
accepted answer: http://stackoverflow.com/a/48175011
tagged with: url-routing
has comment: http://stackoverflow.com/comment/83329839
has title: whats wrong with my django url in this basic search function?
type: AnsweredQuestion
has body: I tried implementing a search bar in my nav bar that sends a GET request with parameters to /search. When I type something into the search bar and hit enter it just takes me to /search/ with a 404 error. Same if I manually type /search/?searchstring=32423 I also get a page not found. views.py def basic_search(request): query = request.GET.get('searchstring') if query: context={"query": query} return render(request, 'root_index.html', context) else: return redirect('/') urls.py url(r'^search/$', views.basic_search,) in my base.html
downvote count: 1
has comment: http://stackoverflow.com/comment/83330163
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83329905
upvote count: 0
answer count: 1
tagged with: django

http://stackoverflow.com/q/48328786
has title: Ability for a user to chose the amount of games they play - for loop
has comment: http://stackoverflow.com/comment/83643128
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/83643186
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
answer count: 1
has body: #Welcome Messages: print 'Welcome To Rock Paper Scissors! ' print 'Game Settings:' ammountofgames = int(input("How many games do you want to play?")) #------------------------------------------- #For Statement - Ammount Of Games for i in range ammountofgames: Basically, the for loop won't work but what I want it to do is allow the user to chose how many games they want to play which loops the scripts below however many times. Can someone please help me with this one, but most likely there is a much simpler way to do this. Yes my spelling is really bad
favorite count: 0
has answer: http://stackoverflow.com/a/48328884

http://stackoverflow.com/comment/83481797
has text: @AndréRoggeriCampos I changed back to my first settings example in the question, ran `collectstatic`, and it made static files work again. However, I still don't understand why I can't simply change back the settings and have them work like before. Does anyone know why?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48249613
score: 0

http://stackoverflow.com/comment/83525090
has text: Aside: near the end, you have `if playAgain=="n": END`. That will not do anything: it doesn't change `END` to `True`, it doesn't break the loop. Probably the most idiomatic solution is to use `while True:` `if playAgain == "n": break`.
type: Comment
comment on: http://stackoverflow.com/q/48270653
score: 0
type: QuestionComment

http://stackoverflow.com/q/48200170
has comment: http://stackoverflow.com/comment/83381648
has title: python sometimes recognized sometimes not recognized
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83382275
has comment: http://stackoverflow.com/comment/83382625
has comment: http://stackoverflow.com/comment/83381796
answer count: 0
downvote count: 0
has body: I have made an executable from a python script using pyinstaller to check whether a system has python installed or not. Here is the python code: import subprocess subprocess.call('python -V 1&gt; nul 2&gt; zwzwzw.txt' , shell = True) var1 = subprocess.call('find /i "not recognized" zwzwzw.txt', shell = True) subprocess.call('del zwzwzw.txt' , shell = True) if(var1 == 0): print ("python not found") else: print ("python found") What this code does is calls the python -V command and stores it into a text file zwzwzw.txt. Then it searches for the word "not recognized" in the text file. If "not recognized" is found then var1 = 0 and thus I get "python not found" else "python found". The computer I am testing it on has python installed. on typing python in cmd prompt of the system, it recognizes python on typing python -V in cmd prompt of the system it shows the python version In short everything is fine regarding python on that system. But on running this executable it shows "python not recognized as an internal or an external command". Usually this line is displayed when the path has not been added. But that can't be the case here as when i manually type python or python -v python is recognized. Its only when I try to call this command from the executable it shows this error. However the command works fine on my laptop. It shows python found. It seems the other system has the python path added to only the user variables and not the system variable. Is that why this difference is caused? No I tried it after adding the path to the system variables yet it's not working. Any help is highly appreciated.
tagged with: cmd
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83382029
type: Question
has comment: http://stackoverflow.com/comment/83381385

http://stackoverflow.com/q/48284954
downvote count: 0
has body: Im trying to upload to my server a static file that contains photos from a previous version which has been overwritten since then (same name, different image). I think the upload skips these files, how can I make it go over these files?
upvote count: 1
linked to: http://stackoverflow.com/q/33223616
tagged with: flask
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48285814
has title: "gcloud app deploy" does not override the static folder
score: 1
has answer: http://stackoverflow.com/a/48285814
answer count: 1
tagged with: python
tagged with: gcloud
favorite count: 0
type: Question
tagged with: google-cloud-platform
tagged with: google-app-engine

http://stackoverflow.com/a/48344897
has comment: http://stackoverflow.com/comment/88561492
type: Answer
has body: The error suggests you are passing an additional parameter to the method. I noticed that the super() call is incorrect. You can replace that with: obj = super().to_representation(obj)
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/88548508
answers question: http://stackoverflow.com/q/48330135
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48330135

http://stackoverflow.com/a/48242667
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48242570
has body: The Profile model has a OneToOne relationship with User, so you can simply say: hook.save() hook.user.profile.account_paid = hook.eventType == 'RenewalSuccess' hook.user.profile.save()
has comment: http://stackoverflow.com/comment/83468177
has comment: http://stackoverflow.com/comment/83468224
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48242570
has comment: http://stackoverflow.com/comment/83468303
has comment: http://stackoverflow.com/comment/83469102
has comment: http://stackoverflow.com/comment/83468828
has comment: http://stackoverflow.com/comment/83468061
has comment: http://stackoverflow.com/comment/83468776

http://stackoverflow.com/a/48254417
has comment: http://stackoverflow.com/comment/83495019
upvote count: 2
has body: Here is one method that works for this image using Imagemagick. You trim the black area first, then divide the image into 3 equal sections, then trim those, then flatten onto white. The trim and crop keep track of the original offsets since I do not use +repage to remove the virtual canvas. magick original.png -fuzz 5% -trim -crop 3x1@ -trim -background white -flatten result.png See https://www.imagemagick.org/Usage/crop/#crop_equal https://www.imagemagick.org/Usage/crop/#trim
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48251501

http://stackoverflow.com/comment/83545534
has text: That website uses bot mitigating services. You'll need to change more than user agent to be able to scrape it.
comment on: http://stackoverflow.com/q/48281000
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83497996
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48221553
has text: @generationX The 2nd example will work as expected. The reason is that `self.fetch` will return a Future object, which you can `yield` in another coroutine. If you find this example confusing, feel free to ignore it. It's not very important, really.

http://stackoverflow.com/q/48319949
downvote count: 0
has answer: http://stackoverflow.com/a/48321798
has comment: http://stackoverflow.com/comment/83628643
has answer: http://stackoverflow.com/a/48320105
tagged with: python
tagged with: msgpack
possible better answer: http://stackoverflow.com/a/60852571
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/48321798
score: 7
upvote count: 7
has body: I am having issues with msgpack in python. It seems that when serialising a dict, if the keys are strings str, they are not unserialised properly and causing KeyError exceptions to be raised. Example: &gt;&gt;&gt; import msgpack &gt;&gt;&gt; d = dict() &gt;&gt;&gt; value = 1234 &gt;&gt;&gt; d['key'] = value &gt;&gt;&gt; binary = msgpack.dumps(d) &gt;&gt;&gt; new_d = msgpack.loads(binary) &gt;&gt;&gt; new_d['key'] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 'key' This is because the keys are not strings after calling loads() but are unserialised to bytes objects. &gt;&gt;&gt; d.keys() dict_keys(['key']) &gt;&gt;&gt; new_d.keys() dict_keys([b'key']) It seems this is related to a unimplemented feature as mentioned in github My question is, Is there a way to fix this issue or a work around to ensure that the same keys can be used upon deserialisation? I would like to use msgpack but if I cannot build a dict object with str keys and expect to be able to use the same key upon deserilisation, it becomes useless.
has comment: http://stackoverflow.com/comment/83625567
favorite count: 0
has title: msgpack unserialising dict key strings to bytes
type: Question
has answer: http://stackoverflow.com/a/60852571

http://stackoverflow.com/comment/83556617
type: AnswerComment
has text: Awesome it worked pretty well. Can you please help me understand why did not work with my code?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48267183

http://stackoverflow.com/comment/83775196
type: Comment
type: AnswerComment
score: 1
has text: @DebanjanB, your solution of hardcoding the chromedriver.exe path worked for me. Thanks alot
comment on: http://stackoverflow.com/a/48230710

http://stackoverflow.com/comment/83482291
score: 0
type: Comment
has text: @Markus that's because your query returns a list of elements. It might be a list with one element, but it's still a list. You need to check whether it's bigger than 0 and click on the first element.
comment on: http://stackoverflow.com/a/48249833
type: AnswerComment

http://stackoverflow.com/a/48205080
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/83391839
answers question: http://stackoverflow.com/q/48204445
accepted answer of: http://stackoverflow.com/q/48204445
type: AcceptedAnswer
has body: This is common shape mismatch error Error is self-explanatory Your target tensor is of shape [None, 2] You are feeding you target tensor an array of (1, 1666) Your model.fit() should be: model.fit(train_x, train_y, n_epoch=1000, batch_size=8, show_metric=True) See the second parameter which is the target train_y but you have given the second parameter as train_x which means you are saying that your inputs are you labels which is not true May be that's why its throwing you the error

http://stackoverflow.com/q/48260098
type: UnansweredQuestion
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/83515520
tagged with: python
has comment: http://stackoverflow.com/comment/83514224
tagged with: opencv
has comment: http://stackoverflow.com/comment/83513282
score: 0
has comment: http://stackoverflow.com/comment/83513245
tagged with: raspberry-pi3
has comment: http://stackoverflow.com/comment/83506902
has title: How to play the live video capturing from camera in PyQt4?
has comment: http://stackoverflow.com/comment/83508421
type: Question
has body: Actually I am working on raspberry pi 3, for which I have made a GUI using PyQt4 and I want to play the live stream of video which I am capturing from camera in the GUI. I know that video is played in PyQt4 using phonon .....but I don't know how can I feed the live stream to it. import sys from PyQt4 import QtGui,QtCore from PyQt4.phonon import Phonon class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.setGeometry(10,10,320,240) self.first_box = QtGui.QVBoxLayout() self.second_box = QtGui.QVBoxLayout() self.third_box = QtGui.QVBoxLayout() #self.zvbox = QtGui.QVBoxLayout() vbox = QtGui.QVBoxLayout() vbox.addLayout(self.first_box) vbox.addLayout(self.second_box) vbox.addLayout(self.third_box) self.setLayout(vbox) self.first_view() #self.resize(100, 200) #self.center() self.setWindowTitle('Trying Final') def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Escape: self.close() def first_view(self): powerButton = QtGui.QPushButton("Power") settingButton = QtGui.QPushButton("Settings") videoButton = QtGui.QPushButton("Video") savedfileButton = QtGui.QPushButton("Saved Records") newButton = QtGui.QPushButton("New Record") powerButton.clicked.connect(self.first_second_view) settingButton.clicked.connect(self.first_third_view) videoButton.clicked.connect(self.first_fourth_view) savedfileButton.clicked.connect(self.first_fifth_view) newButton.clicked.connect(self.first_sixth_view) hbox = QtGui.QHBoxLayout() #hbox.addStretch(1) hbox.addWidget(newButton) hbox.addWidget(savedfileButton) hbox.addWidget(videoButton) hbox.addWidget(settingButton) hbox.addWidget(powerButton) #vbox = QtGui.QVBoxLayout() font = QtGui.QFont() font.setBold(True) font.setPixelSize(12) lbl1 = QtGui.QLabel('Select an option', self) lbl1.setFont(font) lbl2 = QtGui.QLabel('Welcome to the Pupilometer', self) lbl2.setFont(font) self.first_box.addWidget(lbl1) self.second_box.addWidget(lbl2) #self.second_box.addStretch(1) self.third_box.addLayout(hbox) def first_sec…
answer count: 0

http://stackoverflow.com/q/48282539
accepted answer: http://stackoverflow.com/a/48282752
tagged with: scrapy
has answer: http://stackoverflow.com/a/48282752
answer count: 1
has comment: http://stackoverflow.com/comment/83548908
type: Question
tagged with: python
has title: Scrape JS generated content with Scrapy and Python
type: AnsweredQuestion
score: 0
has body: There is a web page which is partially generated with JS: https://www.ncbi.nlm.nih.gov/genome/genomes/971 I want to scrape the links in FTP column. All of them are JS generated. By default, scrapy gets only HTML without executing JS. How can I change it?

http://stackoverflow.com/comment/83741080
type: Comment
type: QuestionComment
has text: Seems like this is the only option, those temporary arrays are the issue...Thanks for the advice
score: 0
comment on: http://stackoverflow.com/q/48318113

http://stackoverflow.com/comment/83349859
score: 0
comment on: http://stackoverflow.com/q/48184930
type: QuestionComment
type: Comment
has text: thank you but I didn't mention that I need timestamp in my x-axis

http://stackoverflow.com/q/48297678
tagged with: python
tagged with: python-2.7
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83580554
downvote count: 0
accepted answer: http://stackoverflow.com/a/48298494
upvote count: 1
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/48298494
favorite count: 0
has title: Concat multiple columns with loop Pyspark
type: Question
tagged with: pyspark
has body: I have n arrays of string columns. I would like concatenate this n columns in one, using a loop. I have this function to concat columns: def concat(type): def concat_(*args): return list(chain(*args)) return udf(concat_, ArrayType(type)) concat_string_arrays = concat(StringType()) And in the following example, I have 4 columns that I will concatenate like this: df_aux = df.select('ID_col',concat_string_arrays(col("patron_txt_1"),col("patron_txt_2"),col('patron_txt_3'),col('patron_txt_0')).alias('patron_txt') But, if I have 200 columns, how can I use dynamically this function with a loop?

http://stackoverflow.com/comment/83632519
type: AnswerComment
has text: Tried it, same result.
comment on: http://stackoverflow.com/a/48323597
score: 0
type: Comment

gmail
type: Tag
tag name: gmail
tags question: http://stackoverflow.com/q/48326732
tags question: http://stackoverflow.com/q/48256600
tags question: http://stackoverflow.com/q/48188211

http://stackoverflow.com/q/48242515
type: Question
has comment: http://stackoverflow.com/comment/83468707
tagged with: raspberry-pi
answer count: 0
upvote count: 2
type: UnansweredQuestion
has title: How to edit /etc/rc.local when raspbian shuts down immediately
has comment: http://stackoverflow.com/comment/83477922
downvote count: 1
favorite count: 0
tagged with: startup
has comment: http://stackoverflow.com/comment/83468508
has comment: http://stackoverflow.com/comment/83473203
tagged with: linux
has comment: http://stackoverflow.com/comment/83477915
score: 1
tagged with: python
has body: I dun screwed up. I have a raspberry pi zero W and I have a project that needs to be as low power as possible. For my use case it's ok for the raspi to be powered down for long periods as it just needs to send a wifi message in response to a button being triggered. So I edited /etc/rc.local to run my python script on startup, and (rather stupidly, apparently) put call("sudo shutdown -h now", shell=True) at the end of my python script. The result is the pi starts up when powered (or when pins 5-6 are shorted), sends the message, and shuts itself down. But-- now I can't make the pi stay booted up so that I can make an update to the code. Is there any way to edit either my python script (in /home/somedir) or /etc/rc/local now? I tried putting the sd card into a different computer, but it appears my files are embedded in .tar.xz files. Can anyone help?

http://stackoverflow.com/q/48186159
has comment: http://stackoverflow.com/comment/83352172
has answer: http://stackoverflow.com/a/49309567
type: Question
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83351979
has answer: http://stackoverflow.com/a/48186255
has title: Migration error in django models.py database
tagged with: django
score: 0
has body: My app is installed correctly and its models.py reads: from django.db import models class Album(models.Model): artist = models.CharField(max_lenght=250) album_title = models.CharField(max_lenght=500) genre = models.CharField(max_lenght=100) album_logo = models.CharField(max_lenght=1000) class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_lenght=10) song_title = models.CharField(max_lenght=250) But whenever I run python manage.py migrate, I get the following error: Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.0-py3.6.egg\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\dougl\AppData\Local\Programs\Python\Python36-32\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;fro…
tagged with: python

http://stackoverflow.com/q/48203832
tagged with: python
has body: I try to download CSV data from GoogleTrend by selenium(python). In previous, I tried to print source page and extract data that I want later. It worked for some period, but now it does not work. I try to click download button to got CSV file but nothing happen. Do you have any idea for this case? I got button path from firebug+firepath (firefox plugin). html/body/div[2]/div[2]/div/md-content/div/div/div[1]/trends-widget/ng-include/widget/div/div/div/widget-actions/div/button[1] I try on chrome driver and firefox drive. This code; put 1 (word)argument that you want to get trend of search. import sys import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import Select from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC def run_text_extract(search_word): try: print(search_word) driver = webdriver.Firefox('/home/noah/Desktop/Google_Trend_downloader/chromedriver/geckodriver') # driver = webdriver.Chrome('/home/noah/Desktop/Google_Trend_downloader/chromedriver') driver.get("https://trends.google.com/trends/explore?date=all&amp;geo=TH&amp;q="+search_word) driver.find_element_by_xpath('html/body/div[2]/div[2]/div/md-content/div/div/div[1]/trends-widget/ng-include/widget/div/div/div/widget-actions/div/button[1]').click() try: driver.manage().deleteAllCookies() clear_cache(driver) except TimeoutException as ex: isrunning = 0 print("Exception has been thrown. " + str(ex)) print("Timeout line is", line ,".") driver.close() except Exception: print ("Here 5") pass time.sleep(2) driver.close() print("======== END_OF_FILE ===============") except: pass if name == 'main': run_text_extract(sys.argv[1]) time.sleep(8) # run_text_extract()
has comment: http://stackoverflow.com/comment/83389092
has comment: http://stackoverflow.com/comment/83388730
type: UnansweredQuestion
has title: How to click and download with python selenium
answer count: 1
tagged with: selenium
tagged with: google-trends
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49574066
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/a/48183384
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48178619
has comment: http://stackoverflow.com/comment/83438548
has comment: http://stackoverflow.com/comment/83439237
upvote count: 1
has body: As you have tried to identify the Member Number/User ID field with xpath as //*[@id="memberNo"], this xpath exactly matches 5 elements in the HTML. So we need to construct an unique css or xpath which will uniquely identify the Member Number/User ID field as follows : xpath driver.find_element_by_xpath("//div[@class='homepage-banner-block-grx desktop']//input[@id='memberNo' and @type='text']").send_keys(user_id) css_selector driver.find_elements_by_css_selector("div.homepage-banner-block-grx.desktop input#memberNo[type=text]").send_keys(user_id) Note : While constructing the xpath ensure we need to avoid the field Member Number/User ID in START TO JUMP CONTENT LINK section, mobile nav section and with mobile-buttons class. Also we need to ensure that the xpath identifies the text field not any hidden field. Finally, if you are invoking send_keys(user_id) method on an element it returns void
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83439026
accepted answer of: http://stackoverflow.com/q/48178619
downvote count: 0

sublimetext
tags question: http://stackoverflow.com/q/48249335
type: Tag
tag name: sublimetext
tags question: http://stackoverflow.com/q/48276861
tags question: http://stackoverflow.com/q/48285766

http://stackoverflow.com/a/48231626
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48230180
downvote count: 0
has body: I was able to duplicate this with one of the sklearn datasets. from sklearn.datasets import load_iris form sklearn.decomposition import KernelPCA iris = load_iris() data = iris.data target = iris.target data.shape (150, 4) kpca = KernelPCA(4, kernel='rbf', fit_inverse_transform=False, gamma=0.01) transformed = kpca.fit_transform(data) transformed.shape (150, 4) kpca = KernelPCA(150, kernel='rbf', fit_inverse_transform=False, gamma=0.01) transformed = kpca.fit_transform(data) /Users/grr/anaconda/lib/python3.6/site-packages/sklearn/decomposition/kernel_pca.py:264: RuntimeWarning: invalid value encountered in sqrt X_transformed = self.alphas_ * np.sqrt(self.lambdas_) transformed.shape (150, 150) What this leads me to believe is that you are setting the n_components parameter of KernelPCA to a number greater than the number of features in your data. Perhaps you are confusing the shape. It seems odd to have a dataset with only 41 rows and 77K+ features, moreover any predictive modeling from such a dataset would be functionally useless. I would check the shape of your dataset again and make sure you are not setting the value of n_components to be greater than the number of features present.
has comment: http://stackoverflow.com/comment/83504792

http://stackoverflow.com/a/48731846
accepted answer of: http://stackoverflow.com/q/48265137
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48265137
type: Answer
has body: I managed to reproduce the problem with the Tools/freeze/freeze.py script in the cpython repo, so the problem is indeed deeper than cx_freeze or pyinstaller. After some more digging I discovered that I'm not the only one having the problem - the following issue was opened about a month before I hit the problem: https://bugs.python.org/issue32146 They have some ideas for fixes which hopefully will make it into a 3.7.x release.

http://stackoverflow.com/comment/83472910
type: Comment
comment on: http://stackoverflow.com/q/48245089
score: 1
type: QuestionComment
has text: Is this exactly how your code appears? You're missing a colon after your function definition (among other issues...)

http://stackoverflow.com/q/48243446
type: AnsweredQuestion
tagged with: recursion
score: 1
has comment: http://stackoverflow.com/comment/83469599
tagged with: python
has comment: http://stackoverflow.com/comment/83469817
has title: Generic Tree in Recursion in Python
type: Question
has comment: http://stackoverflow.com/comment/83469586
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48243712
upvote count: 1
has answer: http://stackoverflow.com/a/48243712
favorite count: 0
has body: I am quite new in Python and stuck in a generic tree. I have 2 columns. Assume names to be A and B. Now the thing is values of column A are parents of the corresponding value in column B. Now the value of column B is again searched in column A. Now it becomes the parent and its corresponding value a child. For example: A B -------- 1 2 5 3 2 5 3 Now here for value '1'. 1 is parent. 2 is child of 1. Now 2 is again searched in column A. this now makes 2 a parent and 5 its child. Now we search for again it gives us the Value 3 . Same goes for 3 but there is no value in front of 3 so tree ends here and 3 is the leaf node of tree. Here in example I have displayed one child of each parent but in my dataset each parent can have many child and tree goes until all leaf nodes are reached. I know recursion is the solution here but how? What I need in output is all possibles sets with the parent. In this case [1,2], [1,2,5], [1,2,5,3]. Also if 1 had 2 children let's say 2 and 4. Then [1,2,4] will also be counted as a set. Any help here? I am struggling really hard! Venky = {} def Venkat(uno): x = df[df.ColA == uno] data = list(zip(x['ColB'],x.ColA)) Venky[uno] = Node(uno) for child,parent in data: Venky[child] = Node(child, parent=Venky[uno]) print(Venky[child]) y = df[df['ColA'] == (Venky[child]).name] if (y['ColB'].empty == False): data = list(zip(y['ColB'],y.ColA,)) #y_unique = y['ColB'].unique() for k in y['ColB']: res = Venkat(k) return res udo = 'a' Venkat(udo) for pre, fill, node in RenderTree(Venky[udo]): print("%s%s" % (pre, node.name)) Above is my sample code. df is my colA and colB dataframe . ColA is column A and same for colB. I have also imported Anytree and pandas library for this code. The outbut I am getting is something like this: Node('/1/2') Node('/4/nan') 1 └── 2 Node('/1/2') Node('/4/nan') None Here 4 is sibling of 2 in the tree i.e 1 has 2 child here 2 and 4 unlike dataset. But currently I don't care about output. I want to construct a tree now. Then I wi…
tagged with: tree

http://stackoverflow.com/a/48213140
has comment: http://stackoverflow.com/comment/83408005
has comment: http://stackoverflow.com/comment/83407920
answers question: http://stackoverflow.com/q/48212965
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48212965
upvote count: 1
has body: Try this to remove your block of text. You may need to adjust the numbers in case line number doesn't match the index. with open(os.path.join('folder', 'text.txt'),'r') as file: content = file.readlines() new_content = content[0:452] + content[471:] with open(os.path.join('folder', 'new_text.txt'),'w+') as out: out.writelines(new_content)
type: Answer

amazon-emr
tags question: http://stackoverflow.com/q/48272093
type: Tag
tag name: amazon-emr

http://stackoverflow.com/comment/83471017
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48243958
has text: This is a great answer, and I wish I could accept both answers. Unfortunately I can't, and @COLDSPEED's answer seems to be a bit more straightforward. Thanks a lot anyway!

http://stackoverflow.com/q/48181950
answer count: 0
tagged with: multithreading
has title: Multiple messages exchange in python socket network
type: Question
tagged with: python-3.x
tagged with: network-programming
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/83345493
has body: This is my simple program for asking input basis on news options : from newsapi.articles import Articles import sys a=Articles('cff9541f3b5a4558957e63ea59b3743b') #key is working you can use it for testing def news_choice(): options = ['news', 'jokes', 'life_style'] print(options) print('\n') print('------------------------------') inpu = input("what do you want? ") #input_1 if inpu == 'news': print([k for i in a.get_by_popular(source='techcrunch')['articles'] for k in i]) print('\n') print('------------------------------') inpu = input( 'Which option would you like to select : description , author , url , urlToImage , title, publishedAt ') #input_2 print([i[inpu] for i in a.get_by_popular(source='techcrunch')['articles']]) inpu = input("would you like to quit ? yes | No ") #input_3 if inpu == 'yes': sys.exit() else: news_choice() news_choice() output is : ['news', 'jokes', 'life_style'] ------------------------------ what do you want? news ['urlToImage', 'title', 'publishedAt', 'author', 'url', 'description', 'urlToImage', 'title', 'publishedAt', 'author', 'url', 'description', 'urlToImage', 'title', 'publishedAt', 'author', 'url', 'description', 'urlToImage', 'title', 'publishedAt', 'author', 'url', 'description'] ------------------------------ Which option would you like to select : description , author , url , urlToImage , title, publishedAt title ['Huawei’s Richard Yu is really pissed at US\xa0carriers', 'H-1B visa extensions for workers waiting on green cards are safe for\xa0now', 'Kodak announces ICO, stock jumps\xa044%', 'Razer moves into wireless power, debuts HyperFlux mouse and\xa0pad'] would you like to quit ? yes | No yes Process finished with exit code 0 Now i want to make my script as sever and anyone can connect to my script via telnet so i have this server and client script : import socket import threading import last_commit class ThreadedServer(object): dict_cache={} def __init__(self, host, port): self.host = host self.port = port self.sock = sock…
score: 0
has comment: http://stackoverflow.com/comment/83344431

http://stackoverflow.com/q/48249098
has body: Our App is receiving webhooks via POST from our payment processor. When I was building this function I originally had it to GET for testing purposes so I could use the URL to test paramaters. Everything worked fine but now I need to test with fake purchases which sends POST request to our URL. So I updated the code but no new webhooks are being saved in our database now. views.py @require_POST def webhook(request): template_name = 'payment/index.html' hook = Webhook() user = User.objects.get(id=request.POST.get('clientAccnum', '')) hook.user = user hook.clientSubacc = request.POST.get('clientSubacc', '') hook.eventType = request.POST.get('eventType') hook.eventGroupType = request.POST.get('eventGroupType', '') hook.subscriptionId = request.POST.get('subscriptionId', '') hook.timestamp = request.POST.get('timestamp', '') hook.timestamplocal = timezone.now() hook.save() hook.user.profile.account_paid = hook.eventType == 'RenewalSuccess' hook.user.profile.save() return render(request, template_name) models.py class Webhook(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=False) clientSubacc = models.CharField(max_length=120, blank=True, null=True) eventType = models.CharField(max_length=120, blank=True, null=True) eventGroupType = models.CharField(max_length=120, blank=True, null=True) subscriptionId = models.CharField(max_length=120, blank=True, null=True) timestamp = models.DateTimeField(blank=True, null=True) timestamplocal = models.DateTimeField(blank=True, null=True) I'm firing POST requests now from our payment processor and their support is telling me webhooks are being fired but nothing new is saving in the db. This leads me to believe the views.py code is wrong. Anyway I can test this?
has comment: http://stackoverflow.com/comment/83480798
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/83487066
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83480865
score: 0
has comment: http://stackoverflow.com/comment/83480870
has title: Django receive POST from webhook

http://stackoverflow.com/comment/83486794
comment on: http://stackoverflow.com/q/48252114
type: Comment
type: QuestionComment
has text: @TrigonaMinima Thank you, I will go over it. Actually, I am using basic Panda frequently but crosstab was new to me.
score: 0

http://stackoverflow.com/comment/83350759
type: QuestionComment
has text: `python setup.py bdist_wheel`?
comment on: http://stackoverflow.com/q/48185439
type: Comment
score: 0

http://stackoverflow.com/a/48303570
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48303526
answers question: http://stackoverflow.com/q/48303526
has body: With numpy's bitwise_or.reduce, AFAIK pandas can't do this on its own. &gt;&gt;&gt; np.bitwise_or.reduce(df.A.values) 3
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83516472
type: Comment
has text: what about making all `set`s
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48266643

http://stackoverflow.com/comment/86134697
score: 0
has text: I tried to rewrite it. Sorry for disturbing. But this is how I tried to fix my problem.
comment on: http://stackoverflow.com/a/49502904
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48180725
answers question: http://stackoverflow.com/q/48180706
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/48180706
has comment: http://stackoverflow.com/comment/83341453
has comment: http://stackoverflow.com/comment/83341379
score: 2
has comment: http://stackoverflow.com/comment/83341420
type: AcceptedAnswer
downvote count: 0
has body: What you described is map and not filter. def foo(n): return n+2; print (map(foo,[1,2])) Prints out [3,4]

http://stackoverflow.com/a/48217544
score: 1
has comment: http://stackoverflow.com/comment/83417164
answers question: http://stackoverflow.com/q/48217059
type: Answer
downvote count: 0
has body: The problem is due to python's garbage collector. You're not keeping a reference to the instance of SideMenu so it's getting garbage-collected. Due to a quirk of how tkinter is implemented, that causes the image object to be destroyed even though the widget itself is not destroyed. It's highly unusual to have the target of a button be a class. Instead, create a proper function that creates an instance of SideMenu, and saves a reference to that object. class MainMenu(object): ... def launch_ManMenu(self): ... tk.Button(..., command=self.sidemenu, ...) def sidemenu(self): self.sidemenu = SideMenu() You also need to keep a reference of the image in SideMenu, just like you do in MainMenu: class SideMenu(object): ... def launch_sideMenu(self): ... self.my_image = tk.PhotoImage(...) myCanvas.create_image(..., image=self.my_image) ...
upvote count: 1

http://stackoverflow.com/comment/83450492
type: Comment
type: QuestionComment
has text: Sorry, this was for Windows. But eventually will make the same for Linux systems.
comment on: http://stackoverflow.com/q/48233768
score: 0

http://stackoverflow.com/q/48245151
answer count: 1
has comment: http://stackoverflow.com/comment/83473409
favorite count: 0
type: Question
tagged with: python-3.x
has title: Getting rows of coordinates from text file and checking whether points are inside polygon
has comment: http://stackoverflow.com/comment/83473058
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48245584
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83473781
has body: I have hundreds of coordinates (control points) in a text file in the following order (x y): 5480.000 -4880.000 5480.000 -4860.000 5480.000 -4840.000 5480.000 -4820.000 5480.000 -4800.000 5480.000 -4780.000 5480.000 -4760.000 5480.000 -4740.000 5480.000 -4720.000 5480.000 -4700.000 and polygon's coordinates (12): 259.59 229.87 329.07 284.19 397.76 262.62 480.03 397.60 336.26 545.37 325.88 400.00 142.17 440.74 92.65 275.40 158.95 265.02 180.51 196.33 265.97 119.65 259.59 229.87 What I have to do is to check if control points are inside the polygon. Generaly I can do it if I have simple few coordinates in my script, but I have no idea how I can read tuples like this. I have a script that for now does not work. It returns File "C:/......../test.py", line 16, in &lt;module&gt; xc.append(row[0]) IndexError: list index out of range Best solution would be if coordinates that are inside a polygon would appear in the Terminal. from shapely.geometry import Point, Polygon import csv poly = open(r"polygon.txt","r") control = open(r"controlPoints.txt","r") xp, yp = [], [] for l in poly: row = l.split() xp.append(row[0]) yp.append(row[1]) xc,yc = [], [] for l in control: row = l.split() xc.append(row[0]) yc.append(row[1]) print(xc) print(yc) # Create Point objects p = Point(xc, yc) # Create a Polygon coords = [xp, yp] poly1 = Polygon(coords) print(poly1) # CHECK p.within(poly1) print(p) check=poly1.contains(p) print(check)
type: AnsweredQuestion
tagged with: shapely
has comment: http://stackoverflow.com/comment/83474383
accepted answer: http://stackoverflow.com/a/48245584
score: 1
has comment: http://stackoverflow.com/comment/83474235

http://stackoverflow.com/comment/83603018
type: QuestionComment
score: 0
has text: posted the screenshot. Please see.
comment on: http://stackoverflow.com/q/48308350
type: Comment

http://stackoverflow.com/comment/83605051
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48309531
has text: The example you gave is not really "casting" to integers. Any class that implements `__index__` can do the same.
type: Comment

http://stackoverflow.com/q/48177934
has body: Snippet from TMDB csv file: movie_id,title,cast,crew 19995,Avatar,"[{""cast_id"": 242, ""character"": ""Jake Sully"", ""credit_id"": ""5602a8a7c3a3685532001c9a"", ""gender"": 2, ""id"": 65731, ""name"": ""Sam Worthington"", ""order"": 0}, {""cast_id"": 3, ""character"": ""Neytiri"", ""credit_id"": ""52fe48009251416c750ac9cb"", ""gender"": 1, ""id"": 8691, ""name"": ""Zoe Saldana"", ""order"": 1}, {""cast_id"": 25, ""character"": ""Dr. Grace Augustine"", ""credit_id"": ""52fe48009251416c750aca39"", ""gender"": 1, ""id"": 10205, ""name"": ""Sigourney Weaver"", ""order"": 2}, {""cast_id"": 4, ""character"": ""Col. Quaritch"", ""credit_id"": ""52fe48009251416c750ac9cf"", ""gender"": 2, ""id"": 32747, ""name"": ""Stephen Lang"", ""order"": 3}, {""cast_id"": 5, ""character"": ""Trudy Chacon"", ""credit_id"": ""52fe48009251416c750ac9d3"", ""gender"": 1, ""id"": 17647, ""name"": ""Michelle Rodriguez"", ""order"": 4}, {""cast_id"": 8, ""character"": ""Selfridge"", ""credit_id"": ""52fe48009251416c750ac9e1"", ""gender"": 2, ""id"": 1771, ""name"": ""Giovanni Ribisi"", ""order"": 5} Code: tmdb_credit_df = pd.read_csv('tmdb.csv') tmdb_credit_df['cast'] = tmdb_credit_df['cast'].apply(eval) The each cell in cast column contain a list of dicts. Example: [{'cast_id': 242, 'character': 'Jake Sully', 'credit_id': '5602a8a7c3a3685532001c9a', 'gender': 2, 'id': 65731, 'name': 'Sam Worthington', 'order': 0}, {'cast_id': 3, 'character': 'Neytiri', 'credit_id': '52fe48009251416c750ac9cb', 'gender': 1, 'id': 8691, 'name': 'Zoe Saldana', 'order': 1}, ...] I'm trying to flatten the dataframe so that it looks like: movie_id title cast_id character ... 0 19995 Avatar 242 Jake Sully ... 1 19995 Avatar 3 Neytiri ... Is there a way to use json_normalize() or maybe .apply() to flatten/unpack this table as opposed to looping through every row? I tried to use json_normalize(tmdb_credit_df.cast), but I got an error: 'list' object has no attribute 'values' I also tried tmdb_credit_df.cast.apply(lambda…
tagged with: nested
downvote count: 0
accepted answer: http://stackoverflow.com/a/48178127
upvote count: 1
possible better answer: http://stackoverflow.com/a/48178344
favorite count: 0
has answer: http://stackoverflow.com/a/48178127
type: Question
tagged with: http://stackoverflow.com/tag/json
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/48178344
type: AnsweredQuestion
answer count: 2
has title: Flatten or unpack list of nested dicts in DataFrame
tagged with: pandas
score: 1

http://stackoverflow.com/comment/83549368
score: 0
type: AnswerComment
has text: What is your pandas version?
comment on: http://stackoverflow.com/a/48282738
type: Comment

http://stackoverflow.com/comment/83338660
comment on: http://stackoverflow.com/q/48177880
score: 0
has text: Sorry this probably sounds like a stupid question but how would I check if it redirected me to a login page?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48217709
has title: Generic approach to deferred all?
has answer: http://stackoverflow.com/a/48226286
type: Question
has body: I need something in twistd similar to JS' Promise.all(). I found this FireWhenAllFinish example, but it is buggy (throws exceptions, maybe outdated). This is not really a question, cause I found a solution, see below. Still posting it here so it might help others.
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48217714
tagged with: python
tagged with: twistd
score: 0
tagged with: twisted

http://stackoverflow.com/q/48197250
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48198745
tagged with: python
type: AnsweredQuestion
score: 0
has title: Unable to append data to a worksheet in an excel file using openpyxl
has answer: http://stackoverflow.com/a/48198745
tagged with: openpyxl
answer count: 1
upvote count: 1
tagged with: web-scraping
has body: How can I append data to my existing worksheet using openpyxl? I've created a scraper in python which is able to grab titles and links from a webpage. I wish to write them in an excel file using openpyxl. However, my scraper neither writes those newly populated data in the excel file nor throws an error? Where am I going wrong? Thanks in advance to take a look into it. Here is my try: import requests from bs4 import BeautifulSoup from openpyxl import load_workbook wb = load_workbook("scraper.xlsx") ws = wb.worksheets[0] res = requests.get("https://www.yify-torrent.org/search/1080p/") soup = BeautifulSoup(res.text, 'lxml') for item in soup.select(".mv"): name = item.select("a")[0].text link = item.select("a")[0]['href'] ws.append([name,link])
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/48252941
has answer: http://stackoverflow.com/a/48253179
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83488840
type: AnsweredQuestion
has title: Adding values from a dictionary
has body: I would like to know how can I, using a raw_input command, pick out the values of two user chosen keys to add together? What I have attempted is: dict = {"one" : 1, "two" : 2, "three" : 3} Total = Sum(v for v in dict.values() if raw_input1 and raw_input2 in dict) I did borrow that line from another thread but can't figure out how to shape it the way I need to. All the above achieves is the sum of everything in the dictionary instead of the 2 the user picks.
tagged with: raw-input
answer count: 2
has comment: http://stackoverflow.com/comment/83488384
upvote count: 2
possible better answer: http://stackoverflow.com/a/48252992
has comment: http://stackoverflow.com/comment/83488796
downvote count: 3
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48253179
tagged with: addition
has answer: http://stackoverflow.com/a/48252992
has comment: http://stackoverflow.com/comment/83489019
has comment: http://stackoverflow.com/comment/83489458
tagged with: python
score: -1

http://stackoverflow.com/comment/83530401
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48272325
has text: Thank you very much! This helped greatly. I hadn't thought to just create another variable and open a new file from there. Thanks again.

http://stackoverflow.com/comment/83462353
type: AnswerComment
score: 0
has text: yeah its what is being asked, he didnt ask for a matrix just arrays
type: Comment
comment on: http://stackoverflow.com/a/48239985

http://stackoverflow.com/a/48277987
has comment: http://stackoverflow.com/comment/83539362
accepted answer of: http://stackoverflow.com/q/48277590
has comment: http://stackoverflow.com/comment/83539996
answers question: http://stackoverflow.com/q/48277590
has body: .config() is only to set value. To get value you have .cget() if widget.cget("text") == "2": or dictionary if widget["text"] == "2": text is string so you have to compare with string "2" or you have to convert string to integer if int(widget["text"]) == 2: EDIT: cget() doc shows it returns strings but for int and float it doesn't convert value to string.
has comment: http://stackoverflow.com/comment/83540864
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83539467
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48219745
has body: Is this what you need ? sns.factorplot(x='date', y='count', data=data, kind='bar',col='kind')
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83421254
accepted answer of: http://stackoverflow.com/q/48219684
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/83421219
answers question: http://stackoverflow.com/q/48219684

http://stackoverflow.com/a/48288619
type: Answer
answers question: http://stackoverflow.com/q/48288553
has comment: http://stackoverflow.com/comment/83562087
has body: I think your issue is just that you only have two closing parens for three open parens in the third line of the loop. Making the change, your code seems to work for me. Also, since you're doing the append inside the loop, there's no reason to use num[x] instead of numx directly. Unless you're using it for something else, you can get rid of num entirely. And your call to str is unnecessary.
has comment: http://stackoverflow.com/comment/83562063
score: 0

http://stackoverflow.com/a/56407391
accepted answer of: http://stackoverflow.com/q/48180690
has comment: http://stackoverflow.com/comment/124750154
has body: For anyone looking for an answer that works in python 3 invalidTags = ['br','b','font'] def stripTags(html, invalid_tags): soup = BeautifulSoup(html, "lxml") for tag in soup.findAll(True): if tag.name in invalid_tags: s = "::" for c in tag.contents: if not isinstance(c, NavigableString): c = stripTags(str(c), invalid_tags) s += str(c) tag.replaceWith(s) return soup
has comment: http://stackoverflow.com/comment/124750497
type: Answer
answers question: http://stackoverflow.com/q/48180690
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/83364241
type: AnswerComment
type: Comment
has text: Im using cupy (https://docs-cupy.chainer.org/en/stable/). As I metioned in the commend to the solution of scholi, your solution is the fastest, when n is about 512, followed by scholis solution and then mine with np.stack
comment on: http://stackoverflow.com/a/48191338
score: 0

http://stackoverflow.com/comment/83494899
has text: You *are* doing it outside the list comp. And what does "won't modify each of the elements accordingly" mean?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48255952

http://stackoverflow.com/q/48330540
has title: Trouble appending values across the rows using openpyxl
tagged with: python
score: -1
type: AnsweredQuestion
has body: I've written a script in python to read some value from an excel file and then again write the populated item right next to the concerning rows. However, when It comes to appending values next to the rows, I get stuck. Here is my try: from openpyxl import load_workbook wb = load_workbook('item.xlsx') ws = wb['Sheet1'] for row in ws["A4":"D4"]: data = [cell.value for cell in row] ws.append(data) wb.save("New_File.xlsx") The populated values are 12 13 14 15 derived from A4 to D4. Now i wish to append the same values in the next rows, as in 12 13 14 15 will be again in E4 to H4. And the final output should look like 12 13 14 15 12 13 14 15 in A4 to H4. My above script is appending the values to the last row. How can i rectify my script to serve the purpose? Thanks in advance.
upvote count: 0
accepted answer: http://stackoverflow.com/a/48330792
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: openpyxl
has answer: http://stackoverflow.com/a/48330792

http://stackoverflow.com/comment/83382603
has text: I understand all the diagnal values are multiply by zero, but would other values be effected by multiply?
type: AnswerComment
comment on: http://stackoverflow.com/a/48200773
score: 0
type: Comment

http://stackoverflow.com/a/48245278
upvote count: 1
has body: It's a convention for implementing your own scoring object [1]. And it must be positive, because you can create a non-loss function to compute a custom positive score. That means that by using a loss function (for a score object) you have to the negative value. The range of a loss function is: (optimum) [0. ... +] (e.g. unequal values between y and y'). For instance check the formula of the mean squared error, it's always positive: Image source: http://scikit-learn.org/stable/modules/model_evaluation.html#mean-squared-error
type: Answer
answers question: http://stackoverflow.com/q/48244219
score: 1
downvote count: 0

http://stackoverflow.com/comment/83358455
type: AnswerComment
score: 0
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ I have updated my question, your answer could not solve the third situation(new_lst3)
comment on: http://stackoverflow.com/a/48179418

http://stackoverflow.com/q/48193665
has answer: http://stackoverflow.com/a/48194133
upvote count: 3
linked to: http://stackoverflow.com/q/16866602
has comment: http://stackoverflow.com/comment/83367810
answer count: 1
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has body: I am writing a Python script that requires the use of an executable that occasionally gets stuck in an infinite loop. When stuck in this loop, the executable spits out the same line of text to standard out. This I intend to catch and once I do, kill the executable. When I run this script manually I can just use CTRLC. What is the correct way to programmatically kill off the executable from within the Python script? I am using Python 2.7, yet I am also curious as to the 3.x solution. I am using an os.system() call.
score: 2
tagged with: python-2.7
has title: How to kill an executable that was launched from within a Python script
has comment: http://stackoverflow.com/comment/83368168

http://stackoverflow.com/a/54885841
type: Answer
has body: I tried two methods for the question. the method in the picture can works. add environment variables PYSPARK_PYTHON=/usr/local/bin/python3.7;PYSPARK_DRIVER_PYTHON=/usr/local/bin/python3.7;PYTHONUNBUFFERED=1
answers question: http://stackoverflow.com/q/48260412
downvote count: 3
upvote count: 0
score: -3

http://stackoverflow.com/comment/83483194
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48250315
has text: you want to make 3 copies of a 2d array and put those in an array? take a look at `copy.deepcopy`
type: Comment

http://stackoverflow.com/comment/83508114
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48261171
has text: Thanks for the helpful comments. I just tried swapping the sequence of the join()'s on the "q_jobPart_1.join()" and "q_jobPart_2.join()" and suddenly the main process terminates naturally! But, now if I remove the terminate event and wait for all the jobs to be done normally, the main process hangs!
score: 0

http://stackoverflow.com/q/48269074
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48269746
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/48269746
downvote count: 0
favorite count: 0
type: Question
has body: I've been working on this small game for a while and I've encountered a headache. Below you can see that "square1" and "square2" are drawn with pygame. I want to replace them with images, but it messes up the colliderect stuff I've done. Is it possible to "convert" a loaded .png image into a rect object? import pygame import os from test_menu import drawmenu from game_over import player1wins from game_over import player2wins from game_over import tie pygame.init() while True: screen_size = (1080, 400) screen = pygame.display.set_mode(screen_size) background = (255,255,255) image = pygame.image.load("background(1).png") imagerect = image.get_rect() wall_left = pygame.Rect(0,0,1,950) wall_right = pygame.Rect(1080,0,1,950) square1 = pygame.Rect(750, 350, 20, 20) square2 = pygame.Rect(330, 350, 20, 20) x_movement = 0 y_movement = 0 x2_movement = 0 y2_movement = 0 accelx1 = 0 accely1 = 0 accelx2 = 0 accely2 = 0 jumping = False jumping2 = False def health_bars(player1_health, player2_health): if player1_health &gt; 75: player1_health_color = (62, 219, 41) elif player1_health &gt; 50: player1_health_color = (239, 212, 9) else: player1_health_color = (239, 9, 9) if player2_health &gt; 75: player2_health_color = (62, 219, 41) elif player2_health &gt; 50: player2_health_color = (239, 212, 9) else: player2_health_color = (239, 9, 9) pygame.draw.rect(screen, player1_health_color, (70, 50, player1_health, 25)) pygame.draw.rect(screen, player2_health_color, (900, 50, player2_health, 25)) player1_health = int(100) player2_health = int(100) drawmenu() while True: screen.fill(background) screen.blit(image, imagerect) pygame.display.update() pygame.draw.rect(screen, (255,0,0), square1) pygame.draw.rect(screen, (0,0,255), square2) pygame.draw.rect(screen, (0,0,0), wall_left) pygame.draw.rect(screen, (0,0,0), wall_right) health_bars(player1_health, player2_health) pygame.display.update() events = pygame.event.get() for event in events: if event.type == pygame.QUIT: exit() keys_pressed …
has title: Pygame: converting .png file to rect?
accepted answer: http://stackoverflow.com/a/48280158
has answer: http://stackoverflow.com/a/48280158
tagged with: python
tagged with: pygame
tagged with: python-3.6
score: 2

http://stackoverflow.com/q/48262792
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83508967
tagged with: django
upvote count: 1
tagged with: python
favorite count: 0
has body: Suppose I have the following model: class Location(models.Model): name = models.CharField(max_length=32) class Event(models.Model): start = models.DateTimeField() end = models.DateTimeField() location = models.ManyToManyField(Location) The Event model has two invariants: end can't be before start a Location can't have overlapping events What would be a better pattern in Django: validating this in your form (EventForm.clean_end()) or in your model (Event.clean())? According to the docs, when you define a clean() method in your model, it won't be automatically called when using save(), so when manipulating objects outside the Form API I can't really see the added value (unless you call full_clean() by yourself). Also, in my case, my application only has one EventModelForm which manipulates Event objects, so both options would be equally DRY. In short: should I put these kind of validations in my models or in my forms?
score: 1
has title: Business logic validations in Django: Model or ModelForm?
has comment: http://stackoverflow.com/comment/83508744
type: Question
answer count: 0

http://stackoverflow.com/comment/83535422
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48273725
type: Comment
has text: on Linux works `<KeyPress-a>` and even `` but I have to keep pressed it, and there is small time before system (Windows/Linux/Mac) starts repeat pressed key and then it moves all the time.

http://stackoverflow.com/q/48227710
score: -3
tagged with: numerical
has answer: http://stackoverflow.com/a/48228113
answer count: 2
has comment: http://stackoverflow.com/comment/83437466
has comment: http://stackoverflow.com/comment/83437846
upvote count: 0
downvote count: 3
tagged with: polynomials
favorite count: 0
has answer: http://stackoverflow.com/a/48228281
type: Question
has comment: http://stackoverflow.com/comment/83437722
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83438330
has title: How use creating polynomial expression like function in Python?
tagged with: python
has body: I'd like to write a program in Python where user define a deegre of polynomial and coefficients (a,b,c). When program create a polynomial expression with this data I'd like to use it like function because I need this to other operations. How can i get it? For example when I have polynomial= x^n+a^n-1+b^n-2+c^-3 I'd like to use it in polynomial(x) to calculate value. Now the creating polynomial method looks: def polynomial(n,a,b,c): return a*x**n+b*x**3-c*x

http://stackoverflow.com/comment/83603200
comment on: http://stackoverflow.com/q/48308350
score: 0
type: Comment
type: QuestionComment
has text: Please, run `dir` then run the command. I'm very curious to see if it's even listed in that directory.

http://stackoverflow.com/q/48235232
tagged with: python
possible better answer: http://stackoverflow.com/a/48236417
score: 6
tagged with: valueerror
upvote count: 6
has answer: http://stackoverflow.com/a/48236417
tagged with: numpy
type: AnsweredQuestion
answer count: 2
downvote count: 0
favorite count: 0
has title: ValueError: math domain error from math.acos and NaN from numpy.arccos
type: Question
accepted answer: http://stackoverflow.com/a/48235342
has answer: http://stackoverflow.com/a/48235342
has body: I've seen similar questions asked but I haven't found an answer to help me yet. I'm trying to find the angle between two vectors using the dot product method. import math as m import numpy as np def mag(x): return np.sqrt(np.sum(i**2 for i in x)) u = np.array([1,1,1]) v = np.array([-1,-1,-1]) theta = m.degrees(np.arccos(np.dot(u,v) / (mag(u) * mag(v)))) It works for most cases but when I set u and v to vectors that are 180deg apart (as above) apart I get ValueError: math domain error. I switched from m.acos to np.arccos (as above) which returns NaN but it's essentially the same problem. I know this caused by floating point rounding errors producing a value that is slightly below -1 which is outside the domain of acos/arrcos but I can't figure out what to do about it. print('theta = ', theta) print('magnitude product = ', mag(u) * mag(v)) print('dot product = ', np.dot(u,v)) print('dot prod / mag prod = ', np.dot(u,v) / (mag(u) * mag(v))) print('dot prod / mag prod &lt; -1.0 = ', (np.dot(u,v) / (mag(u) * mag(v))) &lt; -1.0) theta = nan magnitude product = 3.0 dot product = -3 dot prod / mag prod = -1.0 dot prod / mag prod &lt; -1.0 = True I've tried using the decimal module but so far only managed to make things worse. I can't imagine this is an unusual problem so I'm guessing there's a good, clean solution somewhere but I just can't find it.
tagged with: math

http://stackoverflow.com/comment/83578706
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48295136
type: Comment
has text: `return super(WebsiteBannerSerializer, self).list(*args, **kwargs) TypeError: super(type, obj): obj must be an instance or subtype of type` Why there is a error?

http://stackoverflow.com/comment/83410555
comment on: http://stackoverflow.com/q/48210056
type: QuestionComment
has text: @wwii i'll try that out later
score: 0
type: Comment

http://stackoverflow.com/q/48291313
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/53720332
tagged with: nlp
tagged with: named-entity-recognition
tagged with: spacy
accepted answer: http://stackoverflow.com/a/53720332
has comment: http://stackoverflow.com/comment/83598072
tagged with: python
answer count: 1
has title: Named Entity Recognition in practice
has body: I am a NLP novice trying to learn, and would like to better understand how Named Entity Recognition (NER) is implemented in practice, for example in popular python libraries such as spaCy. I understand the basic concept behind it, but I suspect I am missing some details. From the documentation, it is not clear to me for example how much preprocessing is done on the text and annotation data; and what statistical model is used. Do you know if: In order to work, the text has to go through chunking before the model is trained, right? Otherwise it wouldn't be able to perform anything useful? Are the text and annotations typically normalized prior to the training of the model? So that if a named entity is at the beginning or middle of a sentence it can still work? Specifically in spaCy, how are things implemented concretely? Is it a HMM, CRF or something else that is used to build the model? Apologies if this is all trivial, I am having some trouble finding easy to read documentation on NER implementations.
type: Question
tagged with: entity-framework

http://stackoverflow.com/comment/83419243
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48218145
score: 0
has text: @C.Yduqoli Hi thanks for the reply! I have also tried `verify = False`(didnt work for me) and this way of disabling warning I found from the web too, I just tried your code still giving error oh well.. I am kind of wondering can it be the problem of the link itself?

http://stackoverflow.com/q/48185543
has comment: http://stackoverflow.com/comment/83351113
score: 0
answer count: 0
type: Question
has title: display console output inside a template in Django
type: UnansweredQuestion
has body: I'm working on a project in which I'm using Python(3.6) and Django(1.10), from few days I'm struggling to display the console output inside a Django template but couldn't find any solution. For example code below prints various statements to the console, I want to display these messages to the Django templates. if form.is_valid(): deployment = form deployment.user = request.user deployment.project = form.cleaned_data['project'] deployment.deploymentName = form.cleaned_data['deploymentName'] deployment.zone = form.cleaned_data['zone'] deployment.cluster = form.cleaned_data['cluster'] deployment.sourceFile = form.cleaned_data['sourceFile'] deployment.save() # Start awd deployment from here tempdir = tempfile.mkdtemp() saved_unmask = os.umask(0o077) temp_dir_path = os.path.join(tempdir) archive_path = os.path.join(settings.MEDIA_ROOT, 'archives/', deployment.sourceFile.name) print(archive_path) # Extract uploaded archive inside temporary dir patoolib.extract_archive(archive_path, outdir=temp_dir_path) # Try to retrieve path of dockerfile directory docker_glob = os.path.join(temp_dir_path, "*", "Dockerfile") print(docker_glob) docker_file = glob.glob(docker_glob)[0] docker_folder = os.path.dirname(docker_file) print(docker_folder) docker_client = docker.from_env() print("Start Building your docker image...") docker_client.login(username='arycloud', password='Abd37214@cloud') docker_client.images.build(path=docker_folder, gzip=False, tag=deployment.deploymentName) image = docker_client.images.get(deployment.deploymentName) shutil.rmtree(tempdir) img_id = image.short_id print(img_id) # prepare tag for image tag = deployment.deploymentName.lower() docker_api_client = docker.APIClient( base_url='unix://var/run/docker.sock') tagged = docker_api_client.tag(image=img_id, repository='arycloud/istio_dep', tag=tag, force=True) if tagged is True: print('image has been tagged!') print('Pushing....') pushing_image = docker_client.images.push(repository='arycloud/istio_dep', tag=tag)…
tagged with: django
has comment: http://stackoverflow.com/comment/83359542
tagged with: python

http://stackoverflow.com/comment/83332724
has text: `[Gig|Ten|Hun]` is equivalent to `[GgHienTu|]`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48175219
score: 0

http://stackoverflow.com/comment/83432288
comment on: http://stackoverflow.com/q/48225334
score: 0
has text: Could be because of the home page you are trying to load has only 16 data points for you scrape !?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48255358
linked to: http://stackoverflow.com/q/46130443
has comment: http://stackoverflow.com/comment/83493480
type: Question
has title: Calculating Pythagorean lengths using a Python list comprehension?
has comment: http://stackoverflow.com/comment/83493540
duplicate of: http://stackoverflow.com/q/46130443
has comment: http://stackoverflow.com/comment/83493703
has comment: http://stackoverflow.com/comment/83493521
tagged with: python
has comment: http://stackoverflow.com/comment/83493686
has comment: http://stackoverflow.com/comment/83493518
tagged with: list-comprehension
has body: I am attempting to port the following Haskell code into Python and I am being greeted with an 'Invalid Syntax' response. let rightTriangles' = [ (a,b,c) | c &lt;- [1..10], b &lt;- [1..c], a &lt;- [1..b], a^2 + b^2 == c^2, a+b+c == 24] My unsuccessful attempt is below: [(i,j,k) for i in range(1,11) for j in range(1,i+1) for k in range(1,j+1) if i**2 + j**2 == k**2 i + j + k == 24] Python 3.4.4
has comment: http://stackoverflow.com/comment/83493502
has comment: http://stackoverflow.com/comment/83493591
accepted answer: http://stackoverflow.com/a/48255391
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48255391
has comment: http://stackoverflow.com/comment/83493498
answer count: 1

svd
type: Tag
tags question: http://stackoverflow.com/q/48279647
tag name: svd

http://stackoverflow.com/comment/83515520
type: QuestionComment
comment on: http://stackoverflow.com/q/48260098
score: 0
has text: @eyllanesc please tell the solution with opencv
type: Comment

http://stackoverflow.com/comment/84025716
has text: @ShashankSingh They apply to both. You are confusing scoping and the interpretation flow between functions and classes.
type: Comment
comment on: http://stackoverflow.com/a/48247834
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83507635
type: Comment
has text: yes... I don't want to pass column 's' to the function
comment on: http://stackoverflow.com/a/48261961
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83580230
type: QuestionComment
has text: The above mentioned is a list and not a dictionary
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48297800

http://stackoverflow.com/comment/83418895
comment on: http://stackoverflow.com/a/48218427
has text: If you do not want the name, remove `name` and you will get something like `<QuerySet [<Person: A>, <Person: B>, ...]>`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48206880
has answer: http://stackoverflow.com/a/48206915
has body: I am using numpy and I'm trying to compare between 2 arrays and get the higher value between them into a new array arr1= array([1,2,3,4]) arr2= array([6,0,2,4]) newarr = array([6,2,3,4]) is there any way to do that
has title: making a new array out of 2 arrays with the higher value inside
duplicate of: http://stackoverflow.com/q/46558114
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48206915
linked to: http://stackoverflow.com/q/46558114
type: Question
tagged with: numpy

http://stackoverflow.com/a/48204602
has comment: http://stackoverflow.com/comment/83390328
has body: It's probably not an error. The map you're accessing is not the python's builtin map, but rather some implementation which instead of ready result returns an object which implements everything you'd expect from an iterable list, but does some optimisation magic underneath. If you want it to be a list, you can try: list(map(....)) Otherwise, you could try iterating it and see if you get a result you expect.
score: 0
answers question: http://stackoverflow.com/q/48204501
type: Answer

http://stackoverflow.com/comment/83570919
type: AnswerComment
type: Comment
has text: You have to call `destory` on each `Label` object, @BibekBhandari.
comment on: http://stackoverflow.com/a/48292833
score: 0

http://stackoverflow.com/comment/83498607
type: QuestionComment
comment on: http://stackoverflow.com/q/48257887
type: Comment
score: 0
has text: the expected result should be only in the first row the column header and then in each row to write the data. Understand?

http://stackoverflow.com/q/48303409
has comment: http://stackoverflow.com/comment/83595183
has comment: http://stackoverflow.com/comment/83591544
upvote count: 1
has body: My goal is to have two rows and three columns of plots using matplotlib. Each graph in the top row will contain two data series, and two y-axes. I want to make the scales on each axis line up so that the corresponding data series are directly comparable. Right now I have it so that the primary y-axis on each graph is aligned, but I can't get the secondary y-axes to align. Here is my current code: import matplotlib.pyplot as plt import pandas as pd excel_file = 'test_data.xlsx' sims = ['Sim 02', 'Sim 01', 'Sim 03'] if __name__ == '__main__': data = pd.read_excel(excel_file, skiprows=[0, 1, 2, 3], sheetname=None, header=1, index_col=[0, 1], skip_footer=10) plot_cols = len(sims) plot_rows = 2 f, axes = plt.subplots(plot_rows, plot_cols, sharex='col', sharey='row') secondary_ax = [] for i, sim in enumerate(sims): df = data[sim] modern = df.loc['Modern'] traditional = df.loc['Traditional'] axes[0][i].plot(modern.index, modern['Idle']) secondary_ax.append(axes[0][i].twinx()) secondary_ax[i].plot(modern.index, modern['Work']) axes[1][i].bar(modern.index, modern['Result']) axes[0][i].set_xlim(12, 6) if i &gt; 0: secondary_ax[0].get_shared_y_axes().join(secondary_ax[0], secondary_ax[i]) # secondary_ax[0].get_shared_y_axes().join(x for x in secondary_ax) plt.show() The solution I tried (Both the line in the if statement, and the last line before plt.show()) were solutions to similar questions, however it didn't resolve my issue. Nothing breaks, the secondary axes just aren't aligned. I also tried adding an extra row in the plt.subplots method and using twinx() to combined the first two rows, but it created an empty second row of plots none-the-less. As a fall back I think I could manually check each axes for the maxes and mins, and loop through each to update manually, but I'd love to find a cleaner solution if one is out there, and anyone has any insight. Thanks.
has answer: http://stackoverflow.com/a/48305000
answer count: 1
accepted answer: http://stackoverflow.com/a/48305000
tagged with: python
downvote count: 1
tagged with: plot
favorite count: 0
linked to: http://stackoverflow.com/q/12919230
has comment: http://stackoverflow.com/comment/83592791
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83593982
score: 0
has comment: http://stackoverflow.com/comment/83592047
has comment: http://stackoverflow.com/comment/83593109
has comment: http://stackoverflow.com/comment/83591709
has comment: http://stackoverflow.com/comment/83592909
duplicate of: http://stackoverflow.com/q/12919230
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83591859
has comment: http://stackoverflow.com/comment/83593280
has title: Sharing two y axes on multiple matplotlib subplots
type: Question

http://stackoverflow.com/q/48282546
has body: I have a django website on linux using Postgre SQL in New Jersey server USA (linode.com) But the users are in a different timezone (Brazil). It is something fool I know, but I do some tests changing settings but nothing positive. Here is some enviroment settings: Linux Server (USA): $cat /etc/timezone Etc/UTC Postgres Console (USA): postgres=# show timezone; UTC Django settings.py (USA): TIME_ZONE = 'America/Sao_Paulo' USE_TZ = True Now the results. Brazil time now: 10:07h Linux Server time(USA): 12:07:52 UTC Here is something wrong! But ok, I don´t use system local time in my website! POSTGRE Console (USA): select now(); 2018-01-16 12:07:36.967415+00 I have a model 'coleta' with a field DATA_LEITURA. data_leitura = models.DateTimeField(null=True) Now I insert a register with 10:07:16h. This is correct time in Brazil! See: br_tz = timezone('America/Sao_Paulo') coleta.data_leitura = datetime(2018, 01, 16, 10, 07, 16, tzinfo=br_tz) In postgre console (USA): SELECT data_leitura FROM coleta; 2018-01-16 15:13:16+00 So incorrect! When the users (Brazil) open the website, they see: 15:13:16 I put this line br_tz = timezone('America/Sao_Paulo') This line solves the NAIVE warning and auto convertion! I am now changing each configuration to see the results... but nothing positive. I think that are two changes to do. My first experience with postgres and django using timezones... What do I have to change!? has Somebody some tip! Thank you again guys and girls for help, you rock!
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83579075
type: Question
tagged with: postgresql
has title: Timezone settings django postgresql linux
type: UnansweredQuestion
tagged with: timezone
has comment: http://stackoverflow.com/comment/83636923
tagged with: datetime
tagged with: django
tagged with: python

http://stackoverflow.com/q/48242272
has answer: http://stackoverflow.com/a/48242310
has comment: http://stackoverflow.com/comment/83466877
has body: If we have a dictionary with 'n' key-value pairs, then, does typecasting it to a list a linear time operation (i.e. O(n))?
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83466986
score: -3
downvote count: 5
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83466925
has comment: http://stackoverflow.com/comment/83466910
tagged with: list
has title: Time complexity of typecasting dictionary to list in Python
duplicate of: http://stackoverflow.com/q/31214308
answer count: 1
has comment: http://stackoverflow.com/comment/83466894
favorite count: 0
type: Question

http://stackoverflow.com/comment/83520558
comment on: http://stackoverflow.com/q/48260672
type: QuestionComment
type: Comment
has text: then what is your problem?
score: 0

http://stackoverflow.com/q/48249253
has comment: http://stackoverflow.com/comment/83591102
has answer: http://stackoverflow.com/a/48301522
downvote count: 1
upvote count: 17
type: AnsweredQuestion
tagged with: python-2.7
has body: Motivation Take a look at the following picture. Given are the red, blue, and green curve. I would like to find at each point on the x axis the dominating curve. This is shown as the black graph in the picture. From the properties of the red, green, and blue curve (increasing and constant after a while) this boils down to find the dominating curve on the very right hand side and then move towards the left hand side finding all intersection points and update the dominating curve. This outlined problem should be solved T times. There is one final twist in the problem. The blue, green, and red curve of the next iteration are constructed via the dominating solution from the previous iteration plus some varying parameters. As an example in the picture above: The solution is the black function. This function is used to generate a new blue, green, and red curve. Then the problem start again to find the dominating one for these new curves etc. Question in a nutshell In each iteration I start at the fixed very right hand side and evaluate all three functions to see which is the dominating one. This evaluations are taking longer and longer over iteration. My feeling is that I don't pass optimally the old dominating function to construct the new blue, green, and red curve. Reason: I got in an earlier version a maximum recursion depth error. Other parts of the code where the value of the current dominating function (which is essential either the green, red, or blue curve) is required are also taking longer and longer with iteration. For 5 iterations just evaluating the functions on one point on the very right hand side grows: The results were produced via test = A(5, 120000, 100000) And then running test.find_all_intersections() &gt;&gt;&gt; test.find_all_intersections() iteration 4 to compute function values it took 0.0102479457855 iteration 3 to compute function values it took 0.0134601593018 iteration 2 to compute function values it took 0.0294270515442 iteration 1 to comput…
has comment: http://stackoverflow.com/comment/83756858
has comment: http://stackoverflow.com/comment/83771307
has comment: http://stackoverflow.com/comment/83778775
has comment: http://stackoverflow.com/comment/83489940
has title: How to efficiently pass function through?
accepted answer: http://stackoverflow.com/a/48403961
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83672567
has answer: http://stackoverflow.com/a/48403961
has comment: http://stackoverflow.com/comment/83487848
answer count: 2
has comment: http://stackoverflow.com/comment/83805671
has comment: http://stackoverflow.com/comment/83593931
has comment: http://stackoverflow.com/comment/83799260
tagged with: algorithm
has comment: http://stackoverflow.com/comment/83662267
possible better answer: http://stackoverflow.com/a/48301522
score: 16
tagged with: python

http://stackoverflow.com/comment/83491395
type: QuestionComment
has text: I don't see why you need a metaclass for this. The metaclass `__new__` is executed when you define the *class* `Query`, and it doesn't seem like you want to do anything at that time. If you want to check when Query is instantiated, just do the check in `Query.__new__`.
score: 1
comment on: http://stackoverflow.com/q/48254371
type: Comment

http://stackoverflow.com/q/48237283
has comment: http://stackoverflow.com/comment/83457636
type: AnsweredQuestion
score: 0
has title: Python Regular expression: Find adjacent characters
has comment: http://stackoverflow.com/comment/83457547
tagged with: regex
linked to: http://stackoverflow.com/q/11430863
type: Question
has answer: http://stackoverflow.com/a/48237300
answer count: 2
possible better answer: http://stackoverflow.com/a/48237300
linked to: http://stackoverflow.com/q/38163366
has comment: http://stackoverflow.com/comment/83457500
duplicate of: http://stackoverflow.com/q/38163366
tagged with: python
has answer: http://stackoverflow.com/a/48237296
accepted answer: http://stackoverflow.com/a/48237296
has comment: http://stackoverflow.com/comment/83457463
has body: I need to get a list that contains every two adjacent characters in the string hello such that ['he', 'el', 'll', 'lo'] I thought I could do it int this way &gt;&gt;&gt;import re &gt;&gt;&gt;re.findall(r'..', 'hello') ['he', 'll'] Which is not what I want. I need to get a list as I mentioned above using Regular Expression

http://stackoverflow.com/q/48198810
downvote count: 1
has comment: http://stackoverflow.com/comment/83379764
type: AnsweredQuestion
has body: I have a set of data I am pulling from an API for stock market history. The history is then stored in a file "history.json". I need to get all recurring sets of the key "4. close". There are between 100 days &amp; 10 years of data in a call. The data is formatted like so: { "Meta Data": { "1. Information": "Daily Prices (open, high, low, close) and Volumes", "2. Symbol": "SPY", "3. Last Refreshed": "2018-01-10", "4. Output Size": "Compact", "5. Time Zone": "US/Eastern" }, "Time Series (Daily)": { "2017-08-18": { "1. open": "242.9000", "2. high": "244.1900", "3. low": "242.2000", "4. close": "242.7100", "5. volume": "136748000" }, "2017-08-21": { "1. open": "242.6400", "2. high": "243.2000", "3. low": "241.8300", "4. close": "242.9000", "5. volume": "65469700" } Preferably I would like the output in order as a list with the values excluding the keys as a list. It can be called into memory or converted into another file to open - it does need to retain order as it will be used sequentially in the algorithm. (I try to figure things out on my own, I am new to programming though so if you could simplify things as much as possible I would appreciate it.)
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/48198934
score: -1
possible better answer: http://stackoverflow.com/a/48198922
has answer: http://stackoverflow.com/a/48198934
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48198922
answer count: 2
has title: Python: Extracting Set of Values from JSON
upvote count: 0
tagged with: python

python-requests
tags question: http://stackoverflow.com/q/48185476
tags question: http://stackoverflow.com/q/48250734
tags question: http://stackoverflow.com/q/48308973
tags question: http://stackoverflow.com/q/48197776
tags question: http://stackoverflow.com/q/48222953
tags question: http://stackoverflow.com/q/48285971
tags question: http://stackoverflow.com/q/48221338
tags question: http://stackoverflow.com/q/48300412
tags question: http://stackoverflow.com/q/48187627
tags question: http://stackoverflow.com/q/48176618
tags question: http://stackoverflow.com/q/48271494
type: Tag
tags question: http://stackoverflow.com/q/48313109
tags question: http://stackoverflow.com/q/48327742
tags question: http://stackoverflow.com/q/48193316
tags question: http://stackoverflow.com/q/48312589
tags question: http://stackoverflow.com/q/48302325
tags question: http://stackoverflow.com/q/48191738
tags question: http://stackoverflow.com/q/48235445
tags question: http://stackoverflow.com/q/48325908
tags question: http://stackoverflow.com/q/48316773
tags question: http://stackoverflow.com/q/48199019
tags question: http://stackoverflow.com/q/48176377
tags question: http://stackoverflow.com/q/48176990
tags question: http://stackoverflow.com/q/48213328
tags question: http://stackoverflow.com/q/48217312
tags question: http://stackoverflow.com/q/48187696
tags question: http://stackoverflow.com/q/48176411
tags question: http://stackoverflow.com/q/48229059
tag name: python-requests
tags question: http://stackoverflow.com/q/48283909
tags question: http://stackoverflow.com/q/48227100
tags question: http://stackoverflow.com/q/48281529
tags question: http://stackoverflow.com/q/48329534
tags question: http://stackoverflow.com/q/48286927
tags question: http://stackoverflow.com/q/48246875
tags question: http://stackoverflow.com/q/48265692
tags question: http://stackoverflow.com/q/48267762
tags question: http://stackoverflow.com/q/48255336
tags question: http://stackoverflow.com/q/48247200
tags question: http://stackoverflow.com/q/48320660
tags question: http://stackoverflow.com/q/48326162
tags question: http://stackoverflow.com/q/48234609
tags question: http://stackoverflow.com/q/48300303
tags question: http://stackoverflow.com/q/48186625
tags question: http://stackoverflow.com/q/48218119
tags question: http://stackoverflow.com/q/48228739
tags question: http://stackoverflow.com/q/48232238
tags question: http://stackoverflow.com/q/48245151
tags question: http://stackoverflow.com/q/48215222
tags question: http://stackoverflow.com/q/48257387
tags question: http://stackoverflow.com/q/48202387
tags question: http://stackoverflow.com/q/48326026

http://stackoverflow.com/a/48373682
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48252564
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48252564
has body: Solved executing this command in MySQL Server: set global max_allowed_packet = 67108864; This solution was suggested here Lost connection to MySQL server during query
score: 1

http://stackoverflow.com/q/48256873
has answer: http://stackoverflow.com/a/48258698
upvote count: 0
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83499744
has comment: http://stackoverflow.com/comment/83499711
has comment: http://stackoverflow.com/comment/83499804
has body: I'm trying to run the below script to capture text entered by a user into a form using tkinter. from tkinter import * class Window(Frame): def __init__(self, master = None): Frame.__init__(self, master) self.master = master self.init_window() # create init window def init_window(self): self.master.title("Example Title") self.pack(fill = BOTH, expand = 1) #submit button submitButton = Button(self, text = "submit", command = self.showEntry).grid(row = 6, column = 1, sticky = W, pady = 5) # entry widgets Label(self, text = "Firstname").grid(row = 0) Label(self, text = "Surname").grid(row = 1) Label(self, text = "Age").grid(row = 2) Label(self, text = "Gender").grid(row = 3) e1 = Entry(self) e2 = Entry(self) e3 = Entry(self) e4 = Entry(self) e1.grid(row=0, column=1) e2.grid(row=1, column=1) e3.grid(row=2, column=1) e4.grid(row=3, column=1) # show entries def showEntry(self): txt = e1.get() print("Firstname is %s" % txt) root.destroy() root = Tk() root.geometry("400x300") app = Window(root) app.mainloop() When doing so the below NameError occurs: NameError: name 'e1' is not defined I am very new to tkinter, so any help in how to get the text entered by the user, and why this error is occurring would be greatly appreciated. Thanks
tagged with: python
score: -1
tagged with: tkinter-entry
has title: Capture Text from tkinter entry widget
has comment: http://stackoverflow.com/comment/83496554
accepted answer: http://stackoverflow.com/a/48258698
type: AnsweredQuestion
tagged with: tkinter

http://stackoverflow.com/comment/83573805
type: Comment
type: QuestionComment
score: 0
has text: Well, `d.popitem()` will remove an item from the dictionary, but will be fairly quick, compared to `.items()` methinks, perhaps even if you have to reinsert the key.
comment on: http://stackoverflow.com/q/48294434

http://stackoverflow.com/comment/83389834
type: Comment
type: QuestionComment
has text: Out of curiosity - why do you need such solution?
comment on: http://stackoverflow.com/q/48204075
score: 1

http://stackoverflow.com/a/48204740
type: Answer
answers question: http://stackoverflow.com/q/48204584
downvote count: 0
score: 1
upvote count: 1
has body: this works for me: import pandas as pd T = [50, 48, 47, 49, 51, 53, 54, 52] v1 = [1, 3, 2, 4, 5, 5, 6, 2] v2 = [2, 5, 4, 2, 3, 1, 6, 9] dataframe = pd.DataFrame({'T': T, 'v1': v1, 'v2': v2}) def timeseries_to_supervised(data, ts=1, dropnan=True): # n_vars = 1 if type(data) is list else data.shape[1] # y = data.loc[1] # Create lags for i, col in enumerate(list(data)): name = col rename = name + '(t-1)' lag = pd.DataFrame(data.iloc[:, i].shift(1).values, columns=[rename], index=data.index) data = pd.concat([data, lag], axis=1) return data reframed = timeseries_to_supervised(dataframe, 1) print reframed only changed the way you create the new lag. This gives me: T v1 v2 T(t-1) v1(t-1) v2(t-1) 0 50 1 2 NaN NaN NaN 1 48 3 5 50.0 1.0 2.0 2 47 2 4 48.0 3.0 5.0 3 49 4 2 47.0 2.0 4.0 4 51 5 3 49.0 4.0 2.0 5 53 5 1 51.0 5.0 3.0 6 54 6 6 53.0 5.0 1.0 7 52 2 9 54.0 6.0 6.0

http://stackoverflow.com/comment/83558822
score: 0
type: Comment
type: QuestionComment
has text: When testing `argparse` code, I recommend using a `print(args)` statement. Do this before trying to use `args` attributes, so you understand what it is producing.
comment on: http://stackoverflow.com/q/48278187

python-import
tags question: http://stackoverflow.com/q/48231995
tags question: http://stackoverflow.com/q/48218101
tags question: http://stackoverflow.com/q/48298077
tag name: python-import
type: Tag
tags question: http://stackoverflow.com/q/48257598
tags question: http://stackoverflow.com/q/48271675
tags question: http://stackoverflow.com/q/48292196
tags question: http://stackoverflow.com/q/48317606
tags question: http://stackoverflow.com/q/48213210
tags question: http://stackoverflow.com/q/48324056
tags question: http://stackoverflow.com/q/48329498
tags question: http://stackoverflow.com/q/48330615
tags question: http://stackoverflow.com/q/48193822
tags question: http://stackoverflow.com/q/48245734
tags question: http://stackoverflow.com/q/48251968
tags question: http://stackoverflow.com/q/48208370

http://stackoverflow.com/comment/83578611
score: 1
type: Comment
type: QuestionComment
has text: nope. Just tried it. the results were very fast compared to other methods.
comment on: http://stackoverflow.com/q/48293509

http://stackoverflow.com/a/48325831
has comment: http://stackoverflow.com/comment/83637142
has comment: http://stackoverflow.com/comment/83637211
score: 1
has body: You've declared a function, made a print statement inside but you have never actually called the function. All you do to call it is just put type the name of it in the program. Importantly, make sure you call the function BELOW the declaration because it's procedural
downvote count: 2
answers question: http://stackoverflow.com/q/48325779
has comment: http://stackoverflow.com/comment/83637268
type: Answer
upvote count: 3

http://stackoverflow.com/comment/83331677
type: QuestionComment
comment on: http://stackoverflow.com/q/48175967
has text: See above.. and fix the title to avoid an excessive number of reactionary downvotes. Because the answer is: ***No**, you should fix your code*.
type: Comment
score: 3

http://stackoverflow.com/comment/83485633
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48244376
has text: If my program installs it, I want to uninstall it once I'm finish.

http://stackoverflow.com/comment/83396418
type: AnswerComment
comment on: http://stackoverflow.com/a/48207391
has text: This is what I meant in my comment that you need to pass the address of PRec1 rather than the instance.
score: 0
type: Comment

http://stackoverflow.com/comment/83506831
has text: check once with all the values as 001 for any one group
type: Comment
comment on: http://stackoverflow.com/a/48261397
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83579660
has text: Thanks for your kind reply. If I print files[::2] and files[1::2], I get the following, respectively: ['a.1.jpg', 'a.3.jpg'] ['a.2.jpg', 'a.4.jpg']. How can I get the results in order, for instance ['a.1.jpg', 'a.2.jpg'] and ['a.3.jpg', 'a.4.jpg']?
comment on: http://stackoverflow.com/a/48295182
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83333313
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48176618
type: Comment
has text: Yes, if server takes too long to respond. But then the entire request in itself can take *days* without an exception being thrown. Also could just catch `except Timeout as e:` - also, why would you raise the new exception and just not the original

http://stackoverflow.com/a/48177782
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83335816
has comment: http://stackoverflow.com/comment/83335926
has comment: http://stackoverflow.com/comment/83336041
accepted answer of: http://stackoverflow.com/q/48177746
has body: Option 1 You can do this with pivot_table, specifying max as the aggfunc - df = df.pivot_table( index='element', columns='name', values='max', aggfunc='max' )\ .add_prefix('max')\ .rename_axis(None, axis='columns') df maxA maxB maxC element line_1 101.0 102.0 103.0 line_2 110.0 111.0 NaN line_3 106.0 NaN 107.0 line_4 100.0 101.0 100.0 Option 2 Another option is pd.crosstab - df = pd.crosstab( index=df.element, columns=df.name, values=df['max'] aggfunc='max' )\ .add_prefix('max')\ .rename_axis(None, axis='columns') df maxA maxB maxC element line_1 101.0 102.0 103.0 line_2 110.0 111.0 NaN line_3 106.0 NaN 107.0 line_4 100.0 101.0 100.0
type: Answer
answers question: http://stackoverflow.com/q/48177746
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/83425224
type: QuestionComment
comment on: http://stackoverflow.com/q/48221962
score: 3
has text: I think you need to mention the full path to 'adxl345test.py'
type: Comment

http://stackoverflow.com/q/48219342
has body: I have a dataframe,df1 inp aco drtn 2.3.6 dp Less than 1 min 2.3.6 ft 5-10 min 2.5.9 dp More than 1 hour 0.8.0 dp 1-5 min 2.3.6 dp 10-30 min 2.3.6 dp More than 1 hour 0.8.0 dp Less than 1 min 0.8.0 dp 1-5 min df1 should be grouped by the 3 columns by counting the occurrences. The new dataframe,df2 will look like this: inp aco drtn count 2.3.6 dp Less than 1 min 1 2.3.6 ft 5-10 min 1 2.5.9 dp More than 1 hour 1 0.8.0 dp 1-5 min 2 2.3.6 dp 10-30 min 1 2.3.6 dp More than 1 hour 1 6.2.6 dp 1-5 min 1 the column: 'drtn' should be converted into a new column:'convrt'. This convrt column, for example will look like: less than 1 min=0.59minute, more than 1 hour=61 minutes, 1-5 min= 5 minutes,5-10 min=10, 10-30 min=30 minutes. Another new column:'calc' should be defined as the value of the 'count' column multiplied by the value in column: 'convrt' .Then a new dataframe,df3 should look like this: inp aco drtn count convrt calc 2.3.6 dp Less than 1 min 1 0.59 0.59 2.3.6 ft 5-10 min 1 10 10 2.5.9 dp More than 1 hour 1 61 61 0.8.0 dp 1-5 min 2 5 10 2.3.6 dp 10-30 min 1 30 30 2.3.6 dp More than 1 hour 1 61 61 6.2.6 dp 1-5 min 1 5 5 then a new dataframe,df4 that is filtered by the column:'aco'. for example:only values having dp should only be retained. then a new column:pct that computes percentage of changes in column:'calc'. inp aco drtn count convrt calc pct 2.3.6 dp Less than 1 min 1 0.59 0.59 0.003 2.5.9 dp More than 1 hour 1 61 61 36.40 0.8.0 dp 1-5 min 2 5 10 0.060 2.3.6 dp 10-30 min 1 30 30 17.90 2.3.6 dp More than 1 hour 1 61 61 36.40 6.2.6 dp 1-5 min 1 5 5 0.030 then a new dataframe,df5 with a new column:'pct' which adds all the values in the column:'calc' of df3 and also in the column:'calc' of df4 and proceeds to divide(df4/df3) and multiply by 100 with the index named as the filtered value of column:'aco'. Then, a new column 'totalCalcFilteredColumn' gets the total sum of the column:'calc' in filtered dataframe,df4. Another column named:'diff' which adds all the values…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83420674
downvote count: 0
has comment: http://stackoverflow.com/comment/83420949
tagged with: python
accepted answer: http://stackoverflow.com/a/48238566
has comment: http://stackoverflow.com/comment/83420864
has title: dataframes manipulation and merging python
has comment: http://stackoverflow.com/comment/83420503
has answer: http://stackoverflow.com/a/48238566
has comment: http://stackoverflow.com/comment/83421109
has comment: http://stackoverflow.com/comment/83421698
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83420613
upvote count: 1
has comment: http://stackoverflow.com/comment/83420637

http://stackoverflow.com/comment/83620270
comment on: http://stackoverflow.com/q/48317329
score: 0
has text: Why are you calling `questions.readlines()` twice? After the 1st call you've read all the lines, so there's nothing left for the 2nd call to read.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48198215
accepted answer: http://stackoverflow.com/a/48229182
answer count: 2
has answer: http://stackoverflow.com/a/48198365
possible better answer: http://stackoverflow.com/a/48198365
tagged with: multithreading
tagged with: python
has title: Python 3.6 - How to start a thread from within a daemon thread and have sub-thread exit once the function it is running completes
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/14782894
has body: I am learning Python (3.6) and I am writing some code in a functional style (not using classes) - I have functions which are started as daemon threads by a manager() function. I need to start an additional function in its own thread, that is passed arguments from within one of the functions that is started by the manager function as a daemon thread, as it throws an exception if it is started from within the manager function, as the argument which it expects does not exist when it is started... Here is a representation of my code and the problem I am having - I want to be able to start func4 in its own thread and pass it an argument from within func3... func3 will call func4 a large number of times, so I need the thread in which func4 runs to die as soon as soon as the code completes... import threading threads = [] def func1(): // runs in its own thread and receives messages from a message queue def func2(): // runs in its own thread and sends messages in a loop to a message queue def func3(): // runs in its own thread and receives messages from a message queue, does some // processing, assigns values to a variable then passes variable to func4 def func4(passed_variable_from func3): // performs actions on variable passed from func3 and I would like it to // run in its own thread... IS THIS POSSIBLE? def manager(): # Thread t1 t1 = threading.Thread(target=func1) t1.daemon = True threads.append(t1) # Thread t2 t2 = threading.Thread(target=func2) t2.daemon = True threads.append(t2) t2.start() # Thread t3 t3 = threading.Thread(target=func3) t3.daemon = True threads.append(t3) t3.start() t1.start() for t in threads: t.join() manager()
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48229182

http://stackoverflow.com/comment/83569022
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48291757
has text: This is not a solution. You can't index through the two lists in lock-step since, in the OP's terminology, `i` does not necessarily equal `v`.
type: Comment

parallel-processing
tags question: http://stackoverflow.com/q/48273001
tags question: http://stackoverflow.com/q/48250410
type: Tag
tag name: parallel-processing
tags question: http://stackoverflow.com/q/48287812
tags question: http://stackoverflow.com/q/48243418
tags question: http://stackoverflow.com/q/48288140
tags question: http://stackoverflow.com/q/48219077
tags question: http://stackoverflow.com/q/48185746
tags question: http://stackoverflow.com/q/48314234
tags question: http://stackoverflow.com/q/48280129

http://stackoverflow.com/comment/83528305
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48271888
type: AnswerComment
has text: Actually you are quite correct, when the GUI was freezing it was the while loop causing the freeze. I have since removed it at tried your answer and it does work thank you!

http://stackoverflow.com/comment/83510850
type: QuestionComment
comment on: http://stackoverflow.com/q/48263872
has text: Your failed attempts may seem irrelevant to you, but they can help inform potential answerers on what specifically you're stuck on. "Why isn't this working?" type questions tend to fare better than "How do I do this?" type questions.
score: 0
type: Comment

http://stackoverflow.com/q/48242387
has title: Enforcing the order of extension loading
has comment: http://stackoverflow.com/comment/83467148
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48242618
has comment: http://stackoverflow.com/comment/83467356
answer count: 1
has answer: http://stackoverflow.com/a/48242618
has comment: http://stackoverflow.com/comment/83467224
tagged with: shared-libraries
has body: I have two python extensions (dynamic libraries), say a.so and b.so. Of the two, a.so depends on b.so, specifically it uses a type defined in b.so. In python, I could safely do import b import a # work But when I do import a import b It imports fine, but when running the code, it reports that the type b.the_type in a is not the b.the_type in b. A close examination with gdb gives me that the PyTypeObject of that type in a.so and b.so have two different addresses (and different refcnt). My question is how do I enforce the loading order, or make sure that both ways work. In order to make it possible for people who know well about shared libraries but not python to help me, here's some extra information. In python extensions, a python type is essentially a unique global variable that is initialized in its module (the .so file). Types MUST be initialized before it can be used (this is done by a call to python API). These required initialization is wrapped within specific function that has a particular name. Python will call this function when it loads the extension. My guess is that, as the OS knows that a.so depends on b.so, the system loads b (instead of python) when python requests only a.so. Yet it is python's responsibility to call the module initialization function and python doesn't know a depends on b, so OS only loads b without initializing. On import b, when python then actually calls the module initialization function, it results in a different PyTypeObject. If the solution is platform-dependent, my project is currently running on linux (archlinux).
type: Question
has comment: http://stackoverflow.com/comment/83467249

http://stackoverflow.com/comment/84042447
comment on: http://stackoverflow.com/a/48174981
has text: I'm guessing here cause I don't see your Forms.py but following your code, BidCreationForm function is to create a Bid Model instance. This can be done within your forms.py. Basically what you want is to extend your form to class form.ModelForm, so it maps your Bid Model Instance. This type of code is super easy to maintain and to scale due your form is already creating the Bid instance from your Model Instance. In this case you can call that Form from any view and create your Bid Instance without explicitly calling a view https://docs.djangoproject.com/en/2.0/topics/forms/modelforms
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83328242
has text: I wanted to create anonymous objects that's why i thought { } can be used.
comment on: http://stackoverflow.com/a/48174161
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48201919
type: AnsweredQuestion
tagged with: list
answer count: 2
has comment: http://stackoverflow.com/comment/83385008
score: 0
has body: Right now I have a list of dictionaries e.g. x = [{ '1':1, '2':2, '3':3, '4':'b'}, { '1':1, '2':3, '4':'d'}, ......] I also have a second list of dictionaries e.g. y = [{'a':'a', 'b':'b'}, {'f':'f', 'h':'i', 'o':'p'}, {'a':'a', 'b':'b', 'c':'c', 'd':'d'}, .....] Some of the data within the second dictionary is a subsection of the initial list, how I can append the dictionary with a list of elements from the second dictionary. (e.g. if it has the value b at key b.) Result x = [{ '1':1, '2':2, '3':3, 4:[{'a':'a', 'b':'b'}, {'a':'a', 'b':'b', 'c':'c', 'd':'d'}]}, { '1':1, '2':3, '4':'d'} ......] I have created a loop to go through and find the required elements, but I have been unable to add a single dictionary, but unable to add a list of them. I have tried to use x.append[1]['4'] = y[1] or looped through adding them, but I cannot get it to work. Any help would be greatly appreciated. My attempt to simplify might of made it more awkward. Edited samples of the dictionaries provided below to clear things up. Thank you for the answers, I'm trying to get them to work, this is for clarification. balance = [{'Currency': 'ADA', 'Balance': 30}, {'Currency': 'SC', 'Balance': 200.2} .....] Second history = [{'XC': 'ADA', 'Quantity': 13.2, 'PricePerUnit': 5}, {'XC': 'NAV', 'Quantity': 39.1, 'PricePerUnit': 25}, {'XC': 'ADA', 'Quantity': 63.49, 'PricePerUnit': 0.1} ....] After first iteration it would be Result balance = [{'Currency': 'ADA', 'Balance': 30, 'History': [{'XC': 'ADA', 'Quantity': 13.2, 'PricePerUnit': 5}, {'XC': 'ADA', 'Quantity': 63.49, 'PricePerUnit': 0.1}]}, {'Currency': 'SC', 'Balance': 200.2} .....] Solution For the first example it is done with: x[1]['4'].append(y[2]) The task I was trying to do, the answer without iteration is: balance[0]['History'].append(history[0]) balance[0]['History'].append(history[2]) Thanks to both Faibbus and Rakesh for their solutions!
possible better answer: http://stackoverflow.com/a/48202138
tagged with: iteration
has title: Python: List of Dictionaries, within a list of dictionaries
type: Question
has answer: http://stackoverflow.com/a/48202138
accepted answer: http://stackoverflow.com/a/48202092
has comment: http://stackoverflow.com/comment/83385067
has answer: http://stackoverflow.com/a/48202092
has comment: http://stackoverflow.com/comment/83388667
has comment: http://stackoverflow.com/comment/83384742
tagged with: python
tagged with: dictionary

http://stackoverflow.com/a/48187723
has comment: http://stackoverflow.com/comment/129095314
upvote count: 39
has body: The closest I've come so far is to loop through the dict and union a whole bunch of filtered query sets based on the dict keys. Like so: value_dict = {"model1": 123.4, "model2": 567.8} array_of_qs = [] for k, v in value_dict.items(): array_of_qs.append( ModelClass.objects.filter(model__code=k).annotate(value=Value(v)) ) qs = array_of_qs[0].union(*array_of_qs[1:]) The qs will then have the result that I want, which is the values of the dict based on the keys of the dict annotated to each instance. The beauty of this is that there is only one call to the db which is when I decide to use qs, other than that this whole process doesn't touch the DB from what I understand. Not sure there is a better way yet but will wait to see if there are other responses before accepting this one. NEW IMPROVED WORKING METHOD BELOW Unfortunately the above doesn't work with values_list or values as of this current version 1.11 of Django due to this issue: https://code.djangoproject.com/ticket/28900 I devised a cleaner way below: value_dict = {"model1": 123.4, "model2": 567.8} whens = [ When(model__code=k, then=v) for k, v in value_dict.items() ] qs = ModelClass.objects.all().annotate( value=Case( *whens, default=0, output_field=DecimalField() ) ) Hope it helps someone
downvote count: 0
score: 39
has comment: http://stackoverflow.com/comment/86744205
has comment: http://stackoverflow.com/comment/86790361
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48186782
has comment: http://stackoverflow.com/comment/89471277
accepted answer of: http://stackoverflow.com/q/48186782

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/48238958
tags question: http://stackoverflow.com/q/48202897

http://stackoverflow.com/comment/83525273
has text: Whew. So glad to have that resolved; thanks @ian-thompson! Still, not sure I understand why. If 'Out AM' contained NaT values like 'In PM' and 'Out PM', why wasn't it converted to timedelta as well?
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48270730
type: AnswerComment

http://stackoverflow.com/a/48230888
type: Answer
answers question: http://stackoverflow.com/q/48230576
has body: you're using python-3.x print syntax but you are probably just running python 2.7 . print in python2 isn't a function it's a statement, it only looks like a function. when you do print('Name:', self.name) you're telling the print statement to print a tuple with 2 items in it - and that is exactly what it does you can just remove the parenthesis and have it look like so: print 'Name:', self.name print 'Branch:', self.branch print 'Year:', self.year which would print what you want (actually print multiple items not the tuple itself) or you can get the python3 style print function in your code by importing it from future (in python 2.7): from __future__ import print_function and it will give you your desired output
accepted answer of: http://stackoverflow.com/q/48230576
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83390037
comment on: http://stackoverflow.com/q/48203931
type: QuestionComment
type: Comment
score: 0
has text: ya it is correct , in question it came like that , actually i am able to read the output through open("output1.csv").read() , but file is empty when opened in linux vi output1.csv

http://stackoverflow.com/comment/83369501
type: QuestionComment
has text: Maybe not a dupe but this question helps explain the different between figures and axes - https://stackoverflow.com/questions/47065244/do-i-need-a-figure-what-are-they-for/47065412#47065412
score: 0
comment on: http://stackoverflow.com/q/48194193
type: Comment

plot
tags question: http://stackoverflow.com/q/48198334
tags question: http://stackoverflow.com/q/48192836
tags question: http://stackoverflow.com/q/48191792
tags question: http://stackoverflow.com/q/48288366
tags question: http://stackoverflow.com/q/48272437
type: Tag
tags question: http://stackoverflow.com/q/48285286
tags question: http://stackoverflow.com/q/48268025
tags question: http://stackoverflow.com/q/48301044
tags question: http://stackoverflow.com/q/48303409
tags question: http://stackoverflow.com/q/48318892
tags question: http://stackoverflow.com/q/48313654
tags question: http://stackoverflow.com/q/48260014
tags question: http://stackoverflow.com/q/48273099
tags question: http://stackoverflow.com/q/48240792
tag name: plot
tags question: http://stackoverflow.com/q/48197803
tags question: http://stackoverflow.com/q/48226295
tags question: http://stackoverflow.com/q/48326627
tags question: http://stackoverflow.com/q/48235880
tags question: http://stackoverflow.com/q/48250225
tags question: http://stackoverflow.com/q/48323734
tags question: http://stackoverflow.com/q/48249521
tags question: http://stackoverflow.com/q/48191593
tags question: http://stackoverflow.com/q/48258994
tags question: http://stackoverflow.com/q/48328481
tags question: http://stackoverflow.com/q/48190614
tags question: http://stackoverflow.com/q/48284453
tags question: http://stackoverflow.com/q/48216692
tags question: http://stackoverflow.com/q/48289129
tags question: http://stackoverflow.com/q/48184332
tags question: http://stackoverflow.com/q/48320804
tags question: http://stackoverflow.com/q/48210544
tags question: http://stackoverflow.com/q/48208222
tags question: http://stackoverflow.com/q/48238471
tags question: http://stackoverflow.com/q/48214760
tags question: http://stackoverflow.com/q/48177746
tags question: http://stackoverflow.com/q/48176920

http://stackoverflow.com/q/48246875
favorite count: 0
type: Question
has title: Web scraping with Python urllib or requests
has body: I'm trying to get the latest ratio of gold to USD by scraping information from https://goldprice.org/. How can I do this using urllib or requests in Python? from urllib.request import urlopen from bs4 import BeautifulSoup html=urlopen("https://goldprice.org/") bs=BeautifulSoup(html,"html.parser") lists=bs.findAll(id="gpxtickerLeft_price") print(lists)
has comment: http://stackoverflow.com/comment/83480541
tagged with: python
downvote count: 4
tagged with: urllib
has comment: http://stackoverflow.com/comment/83476727
upvote count: 1
type: UnansweredQuestion
score: -3
answer count: 1
tagged with: web
tagged with: python-requests
has answer: http://stackoverflow.com/a/48258973

http://stackoverflow.com/comment/88655301
comment on: http://stackoverflow.com/a/50009747
score: 1
has text: this should be the best answer.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48227108
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48229161
answer count: 1
tagged with: sonarqube
tagged with: unit-testing
type: Question
has body: We've started to use SonarQube to analyze our python code and its reporting the following minor "code smell": That is a method that I'm overriding from the TestCase class so I can't rename it to set_up() to match python naming conventions. How can I ignore the rule or adjust the Python rule to ignore this. We use Nosetests all over the place and most of them contain a setUp() method.
has answer: http://stackoverflow.com/a/48229161
has title: SonarQube Code Smell: Rename "setUp" method overridden from TestCase class

http://stackoverflow.com/q/48237226
tagged with: python
has comment: http://stackoverflow.com/comment/83481970
has answer: http://stackoverflow.com/a/48302842
score: 0
has comment: http://stackoverflow.com/comment/83943923
has title: How to add Icon to the window in maya using python
tagged with: user-interface
has body: Code: import maya.cmds as cmd cmd.window(title='GUI') cmd.showWindow() This code creates a window with title and i want to add Icon too .Can anyone tell me how to do it ?
answer count: 1
tagged with: maya
type: Question
has comment: http://stackoverflow.com/comment/83461478
type: UnansweredQuestion

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/48283904
tags question: http://stackoverflow.com/q/48326186
tags question: http://stackoverflow.com/q/48175892
tags question: http://stackoverflow.com/q/48309590
tags question: http://stackoverflow.com/q/48326527
tags question: http://stackoverflow.com/q/48266197
tags question: http://stackoverflow.com/q/48274053
tags question: http://stackoverflow.com/q/48252750
type: Tag

http://stackoverflow.com/q/48326601
type: Question
has body: I cannot make a reproducible example for this question; please just scrutinise my logic for misunderstandings or if I'm missing something. I am trying to write a script that checks on a python application that should be constantly running and if it has stopped working, send me an email. I am using psutil to check on running processes. Here's my function that checks if the program in question is running (I'm calling this function at regular intervals). def programRunning(): cmdLines = [] for pid in psutil.pids(): p = psutil.Process(pid) if p.name() == "pythonw.exe": cmdLines.append(p.cmdline()[-1]) #scheduler.py is my script if any('scheduler' in process for process in cmdLines): return True else: return False Now, my main program has produced an error and stopped running, however this function is still returning True as in the cmdLines list I am getting (amongst others): ['C:\\Users\\..omitted..\\scheduler.py', ..omitted..] so I am clearly missing something on my understanding of how psutils works. Any idea what it is and how to tackle it?
type: UnansweredQuestion
has title: psutil returns module that has stopped warning
downvote count: 0
has answer: http://stackoverflow.com/a/48326761
tagged with: python
score: 1
answer count: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/83413925
type: Comment
has text: The goal of my script is to allow multiple plot windows to be open and interactive at the same time. I do not want to update the data of a given plot window. Can you think of a way to accomplish this?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48215060

http://stackoverflow.com/q/48299353
has comment: http://stackoverflow.com/comment/83583514
tagged with: oop
tagged with: pandas
tagged with: genetic-algorithm
score: 0
has body: Currently trying to implement Genetic Algorithm. I have built a Python class Gene I am trying to load an object Gene from a dataframe df class Gene: def __init__(self,id,nb_trax,nb_days): self.id=id self.nb_trax=nb_trax self.nb_days=nb_days and then create another object Chrom class Chromosome(object): def __init__(self): self.port = [Gene() for id in range(20)] And a second class Chromosome with 20 Gene objects as its property This is the dataframe ID nb_obj nb_days ECGYE 10259 62.965318 NLRTM 8007 46.550562 I successfully loaded the Gene using tester=df.apply(lambda row: Gene(row['Injection Port'],row['Avg Daily Injection'],random.randint(1,10)), axis=1) But i cannot load Chrom class using f=Chromosome(tester) I get this error Traceback (most recent call last): File "chrom.py", line 27, in &lt;module&gt; f=Chromosome(tester) TypeError: __init__() takes 1 positional argument but 2 were given Any help please?
answer count: 1
has title: Populating an object from dataframe
type: Question
has answer: http://stackoverflow.com/a/48466289
tagged with: dataframe
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/48256557
linked to: http://stackoverflow.com/q/34717934
has comment: http://stackoverflow.com/comment/83495817
answer count: 0
has comment: http://stackoverflow.com/comment/83495820
has title: numeric range in dict constant
has comment: http://stackoverflow.com/comment/83495848
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/33393714
has comment: http://stackoverflow.com/comment/83495874
has comment: http://stackoverflow.com/comment/83495964
has comment: http://stackoverflow.com/comment/83495764
type: Question
has comment: http://stackoverflow.com/comment/83496081
duplicate of: http://stackoverflow.com/q/13464143
has comment: http://stackoverflow.com/comment/83495782
linked to: http://stackoverflow.com/q/41491227
has comment: http://stackoverflow.com/comment/83495983
has comment: http://stackoverflow.com/comment/83496028
has comment: http://stackoverflow.com/comment/83495891
duplicate of: http://stackoverflow.com/q/6852283
duplicate of: http://stackoverflow.com/q/41491227
has comment: http://stackoverflow.com/comment/83495798
has comment: http://stackoverflow.com/comment/83495980
has comment: http://stackoverflow.com/comment/83496322
tagged with: python
duplicate of: http://stackoverflow.com/q/34717934
has comment: http://stackoverflow.com/comment/83495921
has body: Looking for a way to write the dictionary constant. For example, EXAMPLE = {0~10: 'low', 11-20: 'medium', 21:30: 'high} is there a way to code 0~10 where I can do EXAMPLE[5] and it will output 'low'?
has comment: http://stackoverflow.com/comment/83496007
score: 0
linked to: http://stackoverflow.com/q/6852283
has comment: http://stackoverflow.com/comment/83495901

http://stackoverflow.com/a/79005270
answers question: http://stackoverflow.com/q/48174599
score: 0
type: Answer
has body: You can run it in a temporary subshell $ python -m venv .venv $ (source .venv/bin/activate &amp;&amp; python cmd args) Benefits: Uses the whole virtual environment and not just the Python installed into it. You do not stay in the environment after the execution
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/83439540
type: Comment
has text: I tried killing it too. But still same error.
comment on: http://stackoverflow.com/q/48227539
type: QuestionComment
score: 0

http://stackoverflow.com/q/48284387
tagged with: backtracking
has body: I'm relatively new to Python world and having trouble with regex. I'm trying to extract Firm's name before the word 'sale(s)' (or Sale(s)). I found that Firm's names in my text data are all start with capital letter(and the other parts can be lowercase or uppercase or numbers or '-' or ', for example 'Abc Def' or 'ABC DEF' or just 'ABC' or 'Abc'), and some of them are taking forms like ('Abc and Def' or 'Abc &amp; Def'). For example, from the text, ;;;;;PRINCIPAL CUSTOMERS In fiscal 2005, the Company derived approximately 21% ($4,782,852) of its consolidated revenues from continuing operations from direct transactions with Kmart Corporation. Sales of Computer products was good. However, Computer's Parts and Display Segment sale has been decreasing. I only want to extract 'Computer's Parts and Display Segment'. So I tried to create a regex ((?:(?:[A-Z]+[a-zA-Z\-0-9\']*\.?\s?(?:and |\&amp; )?)+)+?(?:[S|s]ales?\s)) ( 1.[A-Z]+[a-zA-Z-0-9\']*.?\s => this part is to find words start with capital letter and other parts are composed of a-z or A-Z or 0-9 or - or ' or . . (?:and |\&amp; )? => this part is to match word with and or &amp; ) However, at https://regex101.com/ it calls out catastrophic backtracking and I read some related articles, but still cannot find way to solve this problem. Could you help me? Thanks!
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83553200
has comment: http://stackoverflow.com/comment/83553391
tagged with: regex
has title: regex catastrophic backtracking ; extracting words starts with capital before the specific word
has answer: http://stackoverflow.com/a/48284555
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/48284555
tagged with: python

http://stackoverflow.com/comment/83641137
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48326859
has text: Why wouldn't you just write a single query with both clauses? select * from dbo.table_name where month_id IN monthList and Class in classList
type: Comment

http://stackoverflow.com/q/48202321
tagged with: python
accepted answer: http://stackoverflow.com/a/48202359
type: AnsweredQuestion
score: 0
has title: trying to find and remove nan values from path
type: Question
has answer: http://stackoverflow.com/a/48202359
has body: Im trying to move some folders,the folder names i want to move are stored in a dictinary,but the problem is some folders dont exist in the orignal folder and those values have been copied as nan, when i run this code,since there are nan values in the path it throws an error, I have tried removing nan values by doing for i in some_list: if i == nan: do something(remove it) but it does not work for level1,value1 in data_dict.items(): for level2, value2 in value1.items(): if value2 == nan: pass else: from_path = os.path.join(src_path,level1,value2) to_path = os.path.join(dst_path,level1,value2) print (from_path) os.mkdir(to_path) shutil.copytree(from_path,to_path) so how can i remove nan values or ignore them in this case, Any suggestions are helpful,Thank you
answer count: 1

http://stackoverflow.com/q/48177683
has comment: http://stackoverflow.com/comment/83336823
tagged with: python-3.x
tagged with: tkinter
answer count: 0
tagged with: setup.py
has comment: http://stackoverflow.com/comment/83336828
has body: So I've been working a while on a tkinter program that kills windows explorer and pulls up a dialogue box with an image, button, and canvas. So I got the python script itself to work. But when I try to compile it with cx_Freeze for use on my other 64 bit windows computer, and then run it, nothing happens. No errors, no dialogue messages, nothing. Just a loading animation over the cursor for a few seconds before it stops. I made a batch file that pauses the application before it finishes in hopes of finding an error that I may have missed: my-application-name.exe %1 PAUSE This gave me no info on what might be preventing this program to work. So my question is, since there is no obvious solution, when a tkinter python application doesn't work at all and behaves like this, where in the code would I look to find the cause of it not working? It has to be in the setup.py file I used for cx_Freeze, since the Python script works without it, right? Here is my setup.py code used to compile with cx_Freeze: import sys, os from cx_Freeze import setup, Executable base = None if sys.platform == 'win32': base = 'Win32GUI' os.environ['TCL_LIBRARY'] = r'C:\Users\jbond\AppData\Local\Programs\Python\Python36\tcl\tcl8.6' os.environ['TK_LIBRARY'] = r'C:/Users/jbond/AppData/Local/Programs/Python/Python36/tcl/tk8.6' executables = [ Executable('brrf.py', base=base) ] setup(name='simple_Tkinter', version='0.1', description='Sample cx_Freeze Tkinter script', executables=executables ) Thanks for any help.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83336728
has comment: http://stackoverflow.com/comment/83335560
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/92497628
has comment: http://stackoverflow.com/comment/83336325
has comment: http://stackoverflow.com/comment/83335585
favorite count: 0
type: Question
tagged with: cx-freeze
has title: Where to start looking in the code when your .exe doesn't work after cx_freeze?
tagged with: python

http://stackoverflow.com/q/48281026
type: Question
has comment: http://stackoverflow.com/comment/83592484
linked to: http://stackoverflow.com/q/32745541
answer count: 0
type: UnansweredQuestion
tagged with: cluster-analysis
tagged with: python
has body: I want to cluster 3.5M 300-dimensional word2vec vectors from my custom gensim model to determine whether I can use those clustering to find topic-related words. It is not the same as model.most_similar_..., as I hope to attach quite distant, but still related words. The overall size of the model (after normalization of vectors, i.e. model.init_sims(replace=True)) in memory is 4GB: words = sorted(model.wv.vocab.keys()) vectors = np.array([model.wv[w] for w in words]) sys.getsizeof(vectors) 4456416112 I tried both scikit's DBSCAN and some other implementations from GitHub, but they seem to consume more and more RAM during processing and crash with std::bad_alloc after some time. I have 32 GB of RAM and 130GB swap. Metric is euclidean, I convert my cosine distance threshold cos=0.48 as eps=sqrt(2-2*0.48), so all the optimizations should be applied. The problem is that I don't know the number of clusters and want to determine them by setting the threshold for closely related words (let it be cos&lt;0.48 or d_l2 &lt; sqrt(2-2*0.48)). DBSCAN seems working on small subsets, but I can't pass the computation on the full data. Is there any algorithm or workaround in Python which can help with that? EDIT: Distance matrix seem to be for a size(float)=4bytes: 3.5M*3.5M*4/1024(KB)/1024(MB)/1024(GB)/1024(TB) = 44.5 TB, so it's impossible to precompute it. EDIT2: Currently trying ELKI, but cannot make it to cluster data on toy subset properly.
tagged with: optimization
has comment: http://stackoverflow.com/comment/83589570
score: 0
has comment: http://stackoverflow.com/comment/83592419
has title: Fixed RAM DBSCAN or another clustering algorithm without predefined number of clusters?
tagged with: gensim
has comment: http://stackoverflow.com/comment/83579016

http://stackoverflow.com/comment/83413558
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48196865
type: Comment
has text: But are these methods faster than `udf`? Or did you mean that these methods had no performance difference than `udf`?

http://stackoverflow.com/a/48250841
has body: Comments to answer: If return: print (df.columns.tolist()) ['date', 'time', 'user_id', 'url', 'IP'] then use strip for remove trailing whitespaces: df.columns = df.columns.str.strip() In this particular case, it was : df.columns = df.columns.str.strip("")
accepted answer of: http://stackoverflow.com/q/48250713
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48250713
type: AcceptedAnswer

http://stackoverflow.com/comment/83565699
comment on: http://stackoverflow.com/a/48290219
score: 1
type: Comment
has text: @ZoharPeled I wanted to answer about method, because the OP is looking for algorithms, and wants to learn how to do the code themselves. Publishing the solution would be my usual go-to, but it would seem to spoil the OP's learning experience.
type: AnswerComment

http://stackoverflow.com/comment/83377970
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [Aspect ratio in subplots with various y-axes](https://stackoverflow.com/questions/14907062/aspect-ratio-in-subplots-with-various-y-axes)
comment on: http://stackoverflow.com/q/48190628

http://stackoverflow.com/a/48190199
type: Answer
answers question: http://stackoverflow.com/q/48189978
score: 0
has body: You should group the prompts and the expected answers and replies by the chatbot, e.g. as tuples in the form (prompt, expected_answer, [some, possible, replies]) feeling = ("How are you feeling right now " +str(x)+"? ", "tired", ['I wish I can make you feel better.','I hope school is not making you feel stressed.','You deserve the right to relax.']) miss = ... homesick = ... prompts = [feeling,homesick,miss] choice = random.choice(prompts)() prompt, ans, replies resp = input(promp) if resp == ans: print(random.choice(replies)) else: exit() This will also make it easier to extend your chatbot with more question/answer pairs or also to provide different chatbot replies to different user-answers.

http://stackoverflow.com/comment/83429042
score: 0
type: Comment
has text: Question updated, please let me know if I need to clarify anything more. Thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/48203111

http://stackoverflow.com/comment/83397453
type: Comment
type: AnswerComment
score: 0
has text: @Satish if that worked for you then you can accept this as answer. As you seem new here thus sharing how it is done: [How to Accept Answer](https://stackoverflow.com/help/someone-answers)
comment on: http://stackoverflow.com/a/48201895

http://stackoverflow.com/comment/83452740
type: AnswerComment
comment on: http://stackoverflow.com/a/48234928
type: Comment
has text: I tried sum() and it is working fine, but when I tried mean() instead of sum, it s not working
score: 0

http://stackoverflow.com/comment/83670092
comment on: http://stackoverflow.com/a/48318223
score: 0
type: Comment
has text: @Cina Added, but you should post your code next time.
type: AnswerComment

http://stackoverflow.com/a/48328311
answers question: http://stackoverflow.com/q/48328187
has body: you can use this: with open('data/data.txt', 'r') as f1, open('data/data2.txt', 'r') as f2: for line1, line2 in zip(f1, f2): # do something
score: 1
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48208180
favorite count: 0
type: Question
has title: Pandas: Combine subsetting and filtering
possible better answer: http://stackoverflow.com/a/48210252
score: 1
has answer: http://stackoverflow.com/a/48210252
has body: Let's say that I have the following data frame. df = pd.DataFrame({'group':list('aaaabbbb'), 'hour':[1,3,3,2,5,6,6,2], 'id':[1,1,2,2,2,3,3,3]}) df What I'd like to do is find the most common (mode) unique hour per group. The following gets me a count of hours per group. df'group','hour'.groupby(['group']).agg(lambda x:x.value_counts().index[0]).reset_index() Now let's say that I want to subset the hour. I can't seem to figure that out in one line. df'group','hour' &amp; df.hour==3].groupby(['group']).agg(lambda x:x.value_counts().index[0]).reset_index() That doesn't work. Any ideas on how to combine hour==3 and selecting columns together in one line
tagged with: python
accepted answer: http://stackoverflow.com/a/48208218
type: AnsweredQuestion
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/48208218
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48220050
has body: I encounter an error, code as below. I want to check the gradient of function floor, the error occurs: import numpy as np import tensorflow as tf def floor(x): return tf.floor(x) # code w1 = tf.Variable([[1.5, 0.5, -0.5, -1.5]]) res = floor(w1) grads = tf.gradients(res, [w1]) with tf.Session() as sess: tf.global_variables_initializer().run() print(sess.run(grads)) error info
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48247282
score: 0
tagged with: gradient
answer count: 1
tagged with: tensorflow
tagged with: floor
has title: TypeError: Fetch argument None has invalid type <type 'NoneType'>
type: Question

http://stackoverflow.com/comment/83466636
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48240500
type: AnswerComment
has text: @t.m.adam, Yep. I was trying to feel out if a DoS prevention strategy might be causing the error, but the op said the code errored out on the first url.

http://stackoverflow.com/comment/83601115
has text: @cbrnr. I thought I made that obvious by showing how to add a simple callback. Anyway, I have altered my code example to make it explicit. (PS: please remember to re-accept my answer).
comment on: http://stackoverflow.com/a/48269737
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83609235
comment on: http://stackoverflow.com/q/48309877
score: 0
type: Comment
type: QuestionComment
has text: @RohanVarma yes that is exactly what I'm doing. I'm trying not to use the django query, but rather data that has been serialized.

http://stackoverflow.com/a/48302491
type: Answer
has comment: http://stackoverflow.com/comment/83589590
has comment: http://stackoverflow.com/comment/83589650
accepted answer of: http://stackoverflow.com/q/48301044
has comment: http://stackoverflow.com/comment/83590311
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48301044
has body: There seems to be no need for a stem plot here, since the markers are anyway made invsibible and would not make sense due to the large number of points. Instead the use of a LineCollection may make sense. This is how matplotlib will do it in a future version anyways - see this PR. The code below runs within 0.25 seconds for me. (This is still slightly longer than using plot, due to the large number of lines.) import numpy as np from scipy.fftpack import fft import matplotlib.pyplot as plt import time import matplotlib.collections as mcoll N=2048 k = np.arange(0,N) dr = 100 cos = np.cos pi = np.pi w = 1-1.932617*cos(2*pi*k/(N-1))+1.286133*cos(4*pi*k/(N-1))-0.387695*cos(6*pi*k/(N-1))+0.0322227*cos(8*pi*k/(N-1)) y = np.concatenate([w, np.zeros((7*N))]) H = abs(fft(y, axis = 0)) H = np.fft.fftshift(H) H = H/max(H) H = 20*np.log10(H) H = dr+H H[H &lt; 0] = 0 # Set all negative values in dr+H to 0 plotdata = ((np.arange(1,(8*N)+1,1))-1-4*N)/8 lines = [] for thisx, thisy in zip(plotdata,H): lines.append(((thisx, 0), (thisx, thisy))) stemlines = mcoll.LineCollection(lines, linestyles="-", colors="C0", label='_nolegend_') plt.gca().add_collection(stemlines) plt.axis([(-4*N)/8, (4*N)/8, 0, dr]) plt.grid() plt.ylabel('decibels') plt.xlabel('DFT bins') plt.title('Frequency response (Flat top)') plt.show()
has comment: http://stackoverflow.com/comment/83589936

http://stackoverflow.com/comment/83463682
has text: @Fozoro, Can you `print(template_url)` and post the url that causes the error?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48240500
type: AnswerComment

http://stackoverflow.com/a/48308099
has comment: http://stackoverflow.com/comment/83601867
has comment: http://stackoverflow.com/comment/83604555
has body: You could use EOL's NumPy-based code to calculate weighted averages and standard deviation. To use this in a Pandas groupby/apply operation, make weighted_average_std return a DataFrame: import numpy as np import pandas as pd def weighted_average_std(grp): """ Based on http://stackoverflow.com/a/2415343/190597 (EOL) """ tmp = grp.select_dtypes(include=[np.number]) weights = tmp['Weight'] values = tmp.drop('Weight', axis=1) average = np.ma.average(values, weights=weights, axis=0) variance = np.dot(weights, (values - average) ** 2) / weights.sum() std = np.sqrt(variance) return pd.DataFrame({'mean':average, 'std':std}, index=values.columns) np.random.seed(0) df = pd.DataFrame({ "Date": pd.date_range(start='2018-01-01', end='2018-01-03 18:00:00', freq='6H'), "Weight": np.random.uniform(3, 5, 12), "V1": np.random.uniform(10, 15, 12), "V2": np.random.uniform(10, 15, 12), "V3": np.random.uniform(10, 15, 12)}) df.index = df["Date"] df_agg = df.groupby(pd.Grouper(freq='1D')).apply(weighted_average_std).unstack(-1) print(df_agg) yields mean std V1 V2 V3 V1 V2 V3 Date 2018-01-01 12.105253 12.314079 13.566136 1.803014 1.725761 0.679279 2018-01-02 13.223172 12.534893 11.860456 1.709583 0.950338 1.153895 2018-01-03 13.782625 12.013557 12.105231 0.969099 1.189149 1.249064
score: 2
answers question: http://stackoverflow.com/q/48307663
has comment: http://stackoverflow.com/comment/83602708
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48307663
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83604702
has comment: http://stackoverflow.com/comment/83602530
has comment: http://stackoverflow.com/comment/83602000
type: Answer
has comment: http://stackoverflow.com/comment/83604872

http://stackoverflow.com/comment/83540303
type: Comment
score: 0
type: AnswerComment
has text: No.. How to share my excel
comment on: http://stackoverflow.com/a/48276504

http://stackoverflow.com/comment/83569715
comment on: http://stackoverflow.com/q/48292152
type: Comment
type: QuestionComment
score: 2
has text: Side-note: I'd strongly recommend avoiding subprocesses, in favor of `shutil`/`os` functions that perform the same work (e.g. `shutil.rmtree` to delete directory trees, then `os.makedirs`/`os.mkdir` to remake the directory root).

http://stackoverflow.com/comment/83529831
type: Comment
type: QuestionComment
has text: nthread has been deprecated. If you are using the new version of xgboost, try setting the `n_jobs`
score: 0
comment on: http://stackoverflow.com/q/48269248

http://stackoverflow.com/comment/83408900
type: Comment
type: QuestionComment
has text: `sleep` does not stop the system, it usually means the current process looses its CPU allocation for that period of time.
score: 0
comment on: http://stackoverflow.com/q/48212571

http://stackoverflow.com/comment/124281610
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48314921
score: 0
has text: This answer works https://stackoverflow.com/a/22171182/8761414

http://stackoverflow.com/comment/83533296
type: Comment
comment on: http://stackoverflow.com/q/48274882
type: QuestionComment
has text: This questions was answered here: https://stackoverflow.com/questions/48273921/how-do-i-return-the-number-of-unique-digits-in-a-positive-integer/48274012#48274012 moments ago.
score: 1

http://stackoverflow.com/comment/83377523
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48198034
has text: Thank you for the information. The reason why I said was some of the column heading names in `mylist` is not actually in my dataframe. So I get an error like this `KeyError: "['recipe' 'food' 'calories' ..., ] not in index"`. Is there a way to avoid this?

http://stackoverflow.com/a/48208431
upvote count: 5
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/83397708
downvote count: 1
has body: You can flatten, discard the first and then regroup: &gt;&gt;&gt; q = [[0.0,4.0], [10.0,12.0], [15.0,20.0], [21.0,28.0], [32.0,36.0],[41.0,44.0]] &gt;&gt;&gt; from itertools import chain, islice &gt;&gt;&gt; list(map(list, zip(*2*(islice(chain(*q), 1, None),)))) [[4.0, 10.0], [12.0, 15.0], [20.0, 21.0], [28.0, 32.0], [36.0, 41.0]] Python 2 version: &gt;&gt;&gt; from itertools import chain, islice, izip &gt;&gt;&gt; map(list, izip(*2*(islice(chain(*q), 1, None),)))
answers question: http://stackoverflow.com/q/48208216

http://stackoverflow.com/comment/83511827
type: QuestionComment
comment on: http://stackoverflow.com/q/48201944
score: 0
has text: `server = Server("/Users/adietz/Projects/Invest/browsermob/browsermob-proxy/browsermob-dist/src/main/scripts/browsermob-proxy") server.start()` gives error: `browsermobproxy.exceptions.ProxyServerError: Can't connect to Browsermob-Proxy`
type: Comment

http://stackoverflow.com/a/48206255
score: 0
answers question: http://stackoverflow.com/q/48205806
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83393816
has comment: http://stackoverflow.com/comment/83393698
has body: How about this? import numpy as np from scipy.stats import kurtosis a = np.arange((1000)) #replace a with your array ks = np.zeros((100)) for i range(100): ks[i] = kurtosis(a[i*10:i*10+10]) This will loop through the i's, so that when i = 0, a[i*10:i*10+10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], when i = 1, a[i*10:i*10+10] = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], etc. ks is then a list of 100 kurtosis values.
type: Answer
accepted answer of: http://stackoverflow.com/q/48205806

http://stackoverflow.com/a/48316823
has body: See the comments inline. #import shutil # commented out as this is not used for anything here import os # use r'...' strings for file names with backslashes (or use forward slashes instead) source = r'C:\Users\home\Desktop' #Unsorted = r'C:\Users\home\Desktop\' # also not used Sorted = r'B:\Pictures' # listdir produces an unsorted list of files so no need to muck with it for f in os.listdir(source): # you had the wrong variable name here, and missing parens around the tuple if f.endswith((".png",".jpg")): # again, the variable is f # and of course "Sorted" is just a string, you want the variable print(os.path.join(Sorted, f)) Some general advice: Python has good documentation and is easy to play around with; just starting up Python and typing in a fragment of your program lets you try things until you can see what to write in your program to make it do what you want, without guesswork, typos, or unfounded expectations. Don't use reserved keywords for your variables. Understand the difference between a string and a variable name (and a keyword). Many of the things you had wrong are extremely common beginner errors. A bit of googling (especially with an error message or a phrase describing what's not working) will very often lead you to an excellent answer on Stack Overflow explaining exactly what's wrong and how to fix it. Thus, don't cram too much into a single question. Most of the time, if your question is specific enough, you don't even have to ask it once you see what's wrong. To concretize with an example, in the Python interactive REPL, maybe you are actually wondering whether endswith works with an uppercase file name, so you try it: &gt;&gt;&gt; 'PANGEA.PNG'.endswith(".png",".jpg") This gives you a somewhat incredulous message that "slice indices must be integers" which isn't very helpful by itself (until you understand what it's trying to say -- endswith wants a "suffix" argument and an (optional) "start" argument, which is then used to "slice" the string; …
type: AcceptedAnswer
score: 3
answers question: http://stackoverflow.com/q/48316666
type: Answer
accepted answer of: http://stackoverflow.com/q/48316666
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/83414546
has text: Note also that `Btn` is not storing what you think it is. If you want to store a reference to `Btn` don't pack it in the same instruction line as the `Button` constructor call. Just make `Btn.pack()` in the next line.
comment on: http://stackoverflow.com/q/48216159
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48286364
has answer: http://stackoverflow.com/a/48302767
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83564046
tagged with: python-3.x
score: 3
has title: Pandas Series.apply doesn't work consist of strings
accepted answer: http://stackoverflow.com/a/48303816
has answer: http://stackoverflow.com/a/48303816
has comment: http://stackoverflow.com/comment/83568691
tagged with: mecab
tagged with: python
has body: It's seems possible to relate with Japanese Language problem, So I asked in Japanese StackOverflow also. When I use string just object, it works fine. I tried to encode but I couldn't find the reason of this error. Could you please give me advice? MeCab is an open source text segmentation library for use with text written in the Japanese language originally developed by the Nara Institute of Science and Technology and currently maintained by Taku Kudou (工藤拓) as part of his work on the Google Japanese Input project. https://en.wikipedia.org/wiki/MeCab sample.csv 0,今日も夜まで働きました。 1,オフィスには誰もいませんが、エラーと格闘中 2,デバッグばかりしていますが、どうにもなりません。 This is Pandas Python3 code import pandas as pd import MeCab # https://en.wikipedia.org/wiki/MeCab from tqdm import tqdm_notebook as tqdm # This is working... df = pd.read_csv('sample.csv', encoding='utf-8') m = MeCab.Tagger ("-Ochasen") text = "りんごを食べました、そして、みかんも食べました" a = m.parse(text) print(a)# working! # But I want to use Pandas's Series def extractKeyword(text): """Morphological analysis of text and returning a list of only nouns""" tagger = MeCab.Tagger('-Ochasen') node = tagger.parseToNode(text) keywords = [] while node: if node.feature.split(",")[0] == u"名詞": # this means noun keywords.append(node.surface) node = node.next return keywords aa = extractKeyword(text) #working!! me = df.apply(lambda x: extractKeyword(x)) #TypeError: ("in method 'Tagger_parseToNode', argument 2 of type 'char const *'", 'occurred at index 0') This is the trace error りんご リンゴ りんご 名詞-一般 を ヲ を 助詞-格助詞-一般 食べ タベ 食べる 動詞-自立 一段 連用形 まし マシ ます 助動詞 特殊・マス 連用形 た タ た 助動詞 特殊・タ 基本形 、 、 、 記号-読点 そして ソシテ そして 接続詞 、 、 、 記号-読点 みかん ミカン みかん 名詞-一般 も モ も 助詞-係助詞 食べ タベ 食べる 動詞-自立 一段 連用形 まし マシ ます 助動詞 特殊・マス 連用形 た タ た 助動詞 特殊・タ 基本形 EOS --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-174-81a0d5d62dc4&gt; in &lt;module&gt;() 32 aa = extractKeyword(text) #working!! 33 ---&gt; 34 me = df.apply(lambda x: extrac…
has comment: http://stackoverflow.com/comment/83569461
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/83570928
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48302767
has comment: http://stackoverflow.com/comment/83570962
upvote count: 3
has comment: http://stackoverflow.com/comment/83570892
has comment: http://stackoverflow.com/comment/83569723
downvote count: 0

pyqt5
tags question: http://stackoverflow.com/q/48266752
tags question: http://stackoverflow.com/q/48193325
tags question: http://stackoverflow.com/q/48247643
tags question: http://stackoverflow.com/q/48273065
type: Tag
tags question: http://stackoverflow.com/q/48330016
tags question: http://stackoverflow.com/q/48189041
tags question: http://stackoverflow.com/q/48260543
tags question: http://stackoverflow.com/q/48226392
tags question: http://stackoverflow.com/q/48178493
tags question: http://stackoverflow.com/q/48290707
tags question: http://stackoverflow.com/q/48238204
tags question: http://stackoverflow.com/q/48285256
tags question: http://stackoverflow.com/q/48179891
tags question: http://stackoverflow.com/q/48269688
tags question: http://stackoverflow.com/q/48299491
tags question: http://stackoverflow.com/q/48238146
tags question: http://stackoverflow.com/q/48303984
tags question: http://stackoverflow.com/q/48239076
tags question: http://stackoverflow.com/q/48326817
tags question: http://stackoverflow.com/q/48273519
tags question: http://stackoverflow.com/q/48235729
tags question: http://stackoverflow.com/q/48280817
tags question: http://stackoverflow.com/q/48279684
tags question: http://stackoverflow.com/q/48317828
tags question: http://stackoverflow.com/q/48255567
tags question: http://stackoverflow.com/q/48183151
tags question: http://stackoverflow.com/q/48330721
tag name: pyqt5
tags question: http://stackoverflow.com/q/48262716
tags question: http://stackoverflow.com/q/48180157
tags question: http://stackoverflow.com/q/48329703
tags question: http://stackoverflow.com/q/48328147
tags question: http://stackoverflow.com/q/48315501
tags question: http://stackoverflow.com/q/48204226
tags question: http://stackoverflow.com/q/48277850
tags question: http://stackoverflow.com/q/48221364
tags question: http://stackoverflow.com/q/48267563
tags question: http://stackoverflow.com/q/48264553
tags question: http://stackoverflow.com/q/48190404
tags question: http://stackoverflow.com/q/48244675
tags question: http://stackoverflow.com/q/48317367
tags question: http://stackoverflow.com/q/48321743

ipython-parallel
type: Tag
tag name: ipython-parallel
tags question: http://stackoverflow.com/q/48264496

http://stackoverflow.com/comment/83576504
comment on: http://stackoverflow.com/q/48295949
type: Comment
type: QuestionComment
has text: If you have created any venv then you can activate it if not you have to install django. Are you sure installed django properly in your system ?
score: 0

http://stackoverflow.com/q/48328067
score: 1
tagged with: python
tagged with: py2exe
type: Question
tagged with: numpy
answer count: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83642043
has title: python - error py2exe (DLL missing)
favorite count: 0
has body: I have tried to compile my python script to exe file with py2exe (python 2.7.14), but unfortunately i got this error while runnig this code: (runs perfect in PyCharm) from distutils.core import setup import py2exe setup(console=['Dev.py']) error: [Errno 2] No such file or directory: 'numpy-atlas.dll' so i tried to fix it with this code: from distutils.core import setup import py2exe import numpy import os import sys def numpy_dll_paths_fix(): paths = set() np_path = numpy.__path__[0] for dirpath, _, filenames in os.walk(np_path): for item in filenames: if item.endswith('.dll'): paths.add(dirpath) sys.path.append(*list(paths)) numpy_dll_paths_fix() setup(console=['dev.py']) and now when i run it, i got this error: Your executable(s) also depend on these dlls which are not included, you may or may not need to distribute them. Make sure you have the license if you distribute any of them, and make sure you don't distribute files belonging to the operating system. OLEAUT32.dll - C:\WINDOWS\system32\OLEAUT32.dll USER32.dll - C:\WINDOWS\system32\USER32.dll IMM32.dll - C:\WINDOWS\system32\IMM32.dll COMCTL32.dll - C:\Python27\DLLs\COMCTL32.dll WINMM.dll - C:\WINDOWS\system32\WINMM.dll USER32.dll - C:\Python27\DLLs\USER32.dll WS2_32.dll - C:\Python27\DLLs\WS2_32.dll ADVAPI32.dll - C:\WINDOWS\system32\ADVAPI32.dll mfc90.dll - C:\Users\Papom\AppData\Roaming\Python\Python27\site-packages\Pythonwin\mfc90.dll SHELL32.dll - C:\Python27\DLLs\SHELL32.dll msvcrt.dll - C:\WINDOWS\system32\msvcrt.dll WS2_32.dll - C:\WINDOWS\system32\WS2_32.dll GDI32.dll - C:\WINDOWS\system32\GDI32.dll COMDLG32.dll - C:\Python27\DLLs\COMDLG32.dll GDI32.dll - C:\Python27\DLLs\GDI32.dll ole32.dll - C:\Python27\DLLs\ole32.dll NETAPI32.dll - C:\WINDOWS\system32\NETAPI32.dll IMM32.dll - C:\Python27\DLLs\IMM32.dll KERNEL32.dll - C:\WINDOWS\system32\KERNEL32.dll OLEAUT32.dll - C:\Python27\DLLs\OLEAUT32.dll MSVCP90.dll - C:\Python27\MSVCP90.dll KERNEL32.dll - C:\Python27\DLLs\KERNEL32.dll ADVAPI32.dll - C:\Pytho…
tagged with: dll
downvote count: 0

http://stackoverflow.com/a/48216149
accepted answer of: http://stackoverflow.com/q/48216128
has comment: http://stackoverflow.com/comment/83414438
has body: IIUC: In [100]: df.groupby('OrderNum', as_index=False).last() Out[100]: OrderNum RevNum TotalPrice 0 0AXL3 3 $8.00 1 0BDF1 2 $8.50 UPDATE: If there were other columns in the data frame, would this keep those as well? In [116]: df['new'] = np.arange(len(df)) In [117]: df Out[117]: OrderNum RevNum TotalPrice new 0 0AXL3 0 $5.00 0 1 0AXL3 1 $4.00 1 2 0AXL3 2 $7.00 2 3 0AXL3 3 $8.00 3 4 0BDF1 0 $3.00 4 5 0BDF1 1 $2.50 5 6 0BDF1 2 $8.50 6 In [118]: df.groupby('OrderNum', as_index=False).last() Out[118]: OrderNum RevNum TotalPrice new 0 0AXL3 3 $8.00 3 1 0BDF1 2 $8.50 6
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48216128
type: Answer

http://stackoverflow.com/q/48278369
answer count: 2
has comment: http://stackoverflow.com/comment/83540211
type: Question
accepted answer: http://stackoverflow.com/a/48278798
linked to: http://stackoverflow.com/q/2154249
has title: method that generates unique combinations of numbers
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83540744
has answer: http://stackoverflow.com/a/48278798
has comment: http://stackoverflow.com/comment/83540189
has comment: http://stackoverflow.com/comment/83540637
possible better answer: http://stackoverflow.com/a/48305211
has comment: http://stackoverflow.com/comment/83540803
tagged with: python
has comment: http://stackoverflow.com/comment/83540220
has answer: http://stackoverflow.com/a/48305211
has body: I have an array: A = [0,2,5,6] B = [5,6,8,9] C = [6,7,8,9] I want to write two functions, below are the details: Problem 1 When I pass in any of the arrays defined above, I get the combinations of numbers on a sequential manner (by sequential meaning, n+1). So the desired outputs are: ResultA = [[0],[2],[5],[6],[5,6]] ResultB = [[5],[6],[8],[9],[5,6],[8,9]] ResultC = [[6],[7],[8],[9],[6,7],[7,8],[8,9],[6,7,8],[7,8,9],[6,7,8,9]] Below is what I've tried: sorted_ids = sorted(number_collection) combinations = [sorted_ids[j: j + i] for i in range(1, len(sorted_ids)) for j in range(len(sorted_ids) - i + 1)] the issue is it works for the array C but doesn't work that well with the others. Problem 2 The result of the problem 1 is the input of for this problem. The thing is I want the combinations that exist on unique elements for the numbers. (I am not sure I can explain it in words properly), below is the desired output: FinalResultA = [[0],[2],[5,6]] FinalResultB = [[5,6],[8,9]] FinalResultC = [[6,7,8,9]] Is there any approaches (performance oriented) that I can use that'll help?
has comment: http://stackoverflow.com/comment/83540290
has comment: http://stackoverflow.com/comment/83540875

http://stackoverflow.com/comment/83652328
score: 1
has text: Thanks Phil! Works perfectly. Only thing to note is for both exceptions I added the respective floor and ceiling arguments, otherwise they would return the original times. Also are you able to give me any insight as to why row works but not item?
type: Comment
comment on: http://stackoverflow.com/a/48318618
type: AnswerComment

http://stackoverflow.com/comment/83645993
has text: Yes, but i don't think you have to wait that much - `sleep(randint(10,100))` is 10 - 100 sec. This `sleep(random.uniform(0.2, 2))` should be enough.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48329753
type: QuestionComment

http://stackoverflow.com/q/48288304
has answer: http://stackoverflow.com/a/48290513
has title: pandas, keep groupby groups after apply
type: AnsweredQuestion
score: 3
tagged with: pandas-groupby
tagged with: pandas
linked to: http://stackoverflow.com/q/27304538
has comment: http://stackoverflow.com/comment/83561526
has body: I would like to use groupby on my dataframe and then chain a series of function calls on each group with apply. As a first prototype, I've set up an example where I convert the entries of my dataframe from string to numeric. The dataframe looks like this: frame = pd.DataFrame({ "number": ["1", "2", "3", "4", "5", "6", "7", "8"], "type": ["a",] * 4 + ["b",] * 4}) The resulting dataframe is: The numbers in this dataframe are strings. So before I can use any math operations, they have to be converted to a numerical type. That's what I would like to do with apply: frame.groupby("type")["number"].apply(pd.to_numeric) But the result is a single series which contains all items: 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 Name: number, dtype: int64 I've read the docs for this. Apparently you can use transform or apply. In the samples, the grouped structure seems to be kept. Maybe it is something related to pd.to_numeric ? So I tried: frame.groupby("type")["number"].apply(lambda x: int(x)) Which results in a TypeError: TypeError: cannot convert the series to Apparently the apply gets a whole group as parameter. The results for each group seem to be concatenated into one dataframe. Is it possible to use apply in a way that keeps the grouped structure ? I would like a call that applies the function to each column within the groups and keeps the groups. Then I could chain the calls. A related question I've found is this: pandas: sample groups after groupby But the answer suggests to apply the function before the grouping. Which doesn't work well with chaining the functions. And not at all for something like mean().
tagged with: python
has comment: http://stackoverflow.com/comment/83561649
favorite count: 0
upvote count: 3
type: Question
tagged with: pandas-apply
has comment: http://stackoverflow.com/comment/83563738
answer count: 1
accepted answer: http://stackoverflow.com/a/48290513
downvote count: 0

http://stackoverflow.com/comment/83341569
type: QuestionComment
score: 0
has text: @eyllanesc Thanks! if you make your comment an answer, I'll accept it.
comment on: http://stackoverflow.com/q/48180157
type: Comment

http://stackoverflow.com/comment/83385104
type: Comment
has text: ProxyServerError: The Browsermob-Proxy server process failed to start. Check <open file '/home/adietz/Projects/Jenkins/bsp-usecase-tests/server.log', mode 'w' at 0x7fc9d3012db0>for a helpful error message.
comment on: http://stackoverflow.com/a/48202061
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83771945
comment on: http://stackoverflow.com/a/48282772
type: AnswerComment
has text: It is possible in Python to have the object method without parentheses like b.get_sheet_names ?
score: 0
type: Comment

http://stackoverflow.com/a/68810970
score: 0
has body: Here is a function I have been using to compose generators together. def compose(*funcs): &quot;&quot;&quot; Compose generators together to make a pipeline. e.g. pipe = compose(func1, func2, func3) result = pipe(range(0, 5)) &quot;&quot;&quot; return lambda x: reduce(lambda f, g: g(f), list(funcs), x) Where funcs is a list of generator functions. So your example would look like pipe = compose(mock_datasource, data_filter) print(list(pipe)) This is not original
answers question: http://stackoverflow.com/q/48232573
type: Answer

http://stackoverflow.com/q/48271099
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/48271153
has answer: http://stackoverflow.com/a/48271136
has answer: http://stackoverflow.com/a/48271124
favorite count: 0
type: Question
has body: I need to have 1 and 0 instead of True and False in a pandas data frame for only columns starting with abc_. Is there any better way of doing this other than my loop: for col in df: if col[:4] =='abc_': df[col] = df[col].astype(int)
type: AnsweredQuestion
upvote count: 5
accepted answer: http://stackoverflow.com/a/48271153
tagged with: pandas
has title: Convert multiple boolean columns which names start with string `abc_` at once into integer dtype
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/48271124
score: 5

http://stackoverflow.com/q/48295624
answer count: 2
tagged with: pandas
has body: I have date's in different date formats in date column of dataframe. like this: print(df['date'].head(15)) 5/27/1972 12/15/1979 10/11/1972 9/15/1992 12/9/1980 0000-00-00 2000-00-00 1988-00-00 0000-00 2000-10-10 6/25/1976 6/6/1987 8/24/1987 0000-00-00 2000-00-00 How can I get year in seperate column in dataframe pandas ?
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83577422
has comment: http://stackoverflow.com/comment/83615876
tagged with: dataframe
tagged with: python
has title: Extract year from date column in dataframe having 'different date format" - python
has answer: http://stackoverflow.com/a/48315348
has comment: http://stackoverflow.com/comment/83578633
has comment: http://stackoverflow.com/comment/83575905
tagged with: datetime-format
has answer: http://stackoverflow.com/a/48295979

http://stackoverflow.com/a/54136830
answers question: http://stackoverflow.com/q/48254689
upvote count: 2
has body: If you wish to simply clear all variables you've defined in the console.. That is to undo everything your code has done and 'start fresh'.. Type: exit in the console In Spyder this simply clears the workspace of anything your code has done. The same effect as closing and restarting Anaconda, but without having to do so. Now you can run your code with a fresh workspace!
score: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83511881
type: AnswerComment
comment on: http://stackoverflow.com/a/48253991
score: 0
type: Comment
has text: I tried your suggestion. Code: `labelencoder_X=LabelEncoder() X_train[:, 2]=labelencoder_X.fit_transform(X_train[:, 2]) onehotencoder=OneHotEncoder(categorical_features=[0]) X_train=onehotencoder.fit_transform(X_train).toarray()` But instead of categorising just the 3rd column, it is seemingly categorising the whole of X_train.

http://stackoverflow.com/a/48233889
has comment: http://stackoverflow.com/comment/83451402
has comment: http://stackoverflow.com/comment/83451503
has comment: http://stackoverflow.com/comment/83450634
score: 0
accepted answer of: http://stackoverflow.com/q/48233692
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83451082
has comment: http://stackoverflow.com/comment/83450962
has body: I think you need to split each row to eliminate the semicolons. rows = [['11/01/2018;79830;78590;79845;78555;;']] dates = [] prices = [] for row in rows: row = ''.join(rows[0]).split(';') dates.append(int(row[0].split('/')[0])) prices.append(float(row[1])) print(dates) # [11] print(prices) # [79830.0] Rewriting the function: def get_data(IndFut): with open(IndFut,'r') as csvfile: csvFileReader = csv.reader(csvfile) next(csvFileReader) for row in csvFileReader: row = ''.join(rows[0]).split(';') dates.append(int(row[0].split('/')[0])) prices.append(float(row[1]))
has comment: http://stackoverflow.com/comment/83450518
type: Answer
answers question: http://stackoverflow.com/q/48233692

http://stackoverflow.com/comment/83434270
has text: data is not displayed probably because you did not call `matplotlib.pyplot.show()`
comment on: http://stackoverflow.com/q/48226295
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48259293
has title: The transactions created by web3 (python) aren't reflected on the Ethereum blockchain
type: AnsweredQuestion
has body: I'm trying to use web3.py with infura.io to send ethereum tokens from one address to another. This returns to me a transaction ID. But it just never goes on to the blockchain when I check it. I have used high gas amount but it still doesn't work (The transaction id isn't present on the blockchain as per etherscan.io and also as per web3.py functions) I tried a few other ways of signing the transaction but they didn't work either. Please help me make this work. import web3 import time w = web3.Web3(web3.HTTPProvider('https://mainnet.infura.io/12345678')) # gas example gas_limit = 250000 gas_price = 60 transaction = { 'to':to_addr, 'from':from_addr, 'value':int(eth_amount*(10**18)), 'gas':gas_limit, 'gasPrice':int(gas_price*(10**9)), 'chainId':1, 'nonce':int(time.time()) } signed_transaction = w.eth.account.signTransaction(transaction, key) transaction_id = w.eth.sendRawTransaction(signed_transaction.rawTransaction) print ('\nhttps://etherscan.io/tx/{0}'.format(transaction_id.hex()))
tagged with: ethereum
downvote count: 0
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48268105
answer count: 1
favorite count: 0
tagged with: web3py
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48268105
tagged with: python
has comment: http://stackoverflow.com/comment/83518450

http://stackoverflow.com/comment/83513198
comment on: http://stackoverflow.com/q/48264917
has text: @t.m.adam but I want it to be submitted at http://site24.way2sms.com/main.action?Token=4D6F18D8D010F9455BE4C0441D120E2C.w803&section=s the token is changing with each login try
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48248771
favorite count: 0
type: Question
tagged with: rest
upvote count: 2
type: UnansweredQuestion
has body: I am using flask with flask-restplus and sqlalchemy. My rest API function looks like the following: @ns.route('/user') class UsersCollection(Resource): @jwt_optional @permissions.user_has('admin_view') @ns.marshal_list_with(user_details) def get(self): """ Returns list of users. """ users = User.query.all() return users I am willing to add additional data to users collection which should be returned by the API. Some of this data may be stored in other DB tables, while other is stored in memory. What I am usually doing is something like this: @ns.route('/user') class UsersCollection(Resource): @jwt_optional @permissions.user_has('admin_view') @ns.marshal_list_with(user_details) def get(self): """ Returns list of users. """ users = User.query.all() # Add additional data for user in users: user.activity = UserActivity.query ... # from DB user.online_status = "Active" # Taken somewhere from memory return users Obviously I don't like this approach of adding data to the User object on the fly. But what is the best design pattern to achieve it?
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/83505367
score: 2
tagged with: flask-restplus
has answer: http://stackoverflow.com/a/63376123
has comment: http://stackoverflow.com/comment/83480059
has title: Design patterns for flask API implementation
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83480093
has comment: http://stackoverflow.com/comment/83505334
tagged with: sqlalchemy

http://stackoverflow.com/q/48173774
has answer: http://stackoverflow.com/a/48174205
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48195390
tagged with: python
answer count: 6
has title: How to cancel the last method called?
score: 4
has answer: http://stackoverflow.com/a/48174502
has answer: http://stackoverflow.com/a/48174183
upvote count: 4
has answer: http://stackoverflow.com/a/48174186
has comment: http://stackoverflow.com/comment/83327082
has answer: http://stackoverflow.com/a/48174295
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
has body: class Minobot: def __init__(self): self.x,self.y = 0, 0 self.angle = 90 def forward(self, d): angle = radians(90-self.angle) nx, ny = self.x + d * cos(angle), self.y + d * sin(angle) self.x, self.y = nx, ny def right(self): self.angle += 90 def left(self): self.angle -= 90 def coordinates(self): return round(self.x, 1), round(self.y, 1) def manhattan_distance(self): return int(abs(round(self.x, 1))+abs(round(self.y, 1))) def cancel(self): ???? Now I need to add another method to this class that cancels the last method called. For example: a.forward(2) => a.right() => a.cancel() This would set the Minobot before the a.right() is used.

http://stackoverflow.com/a/48269611
has comment: http://stackoverflow.com/comment/83578996
type: AcceptedAnswer
score: 6
upvote count: 6
accepted answer of: http://stackoverflow.com/q/48212123
downvote count: 0
has comment: http://stackoverflow.com/comment/83577950
answers question: http://stackoverflow.com/q/48212123
has comment: http://stackoverflow.com/comment/83578309
type: Answer
has comment: http://stackoverflow.com/comment/83577714
has comment: http://stackoverflow.com/comment/83575796
has comment: http://stackoverflow.com/comment/83564149
has comment: http://stackoverflow.com/comment/83576977
has comment: http://stackoverflow.com/comment/83550221
has body: There are two different types "memory leaks" in your question. Valgrind is telling you about the first type of memory leaks. However, it is pretty usual for python modules to "leak" memory - it is mostly some globals which are allocated/initialized when the module is loaded. And because the module is loaded only once in Python its not a big problem. A well known example is numpy's PyArray_API: It must be initialized via _import_array, is then never deleted and stays in memory until the python interpreter is shut down. So it is a "memory leak" per design, you can argue whether it is a good design or not, but at the end of the day there is nothing you could do about it. I don't have enough insight into the tensorflow-module to pin-point the places where such memory leaks happen, but I'm pretty sure that it's nothing you should worry about. The second "memory leak" is more subtle. You can get a lead, when you compare the valgrind output for 10^4 and 10^5 iterations of the loop - there will be almost no difference! There is however difference in the peak-memory consumption. Differently from C++, Python has a garbage collector - so you cannot know when exactly an object is destructed. CPython uses reference counting, so when a reference count gets 0, the object is destroyed. However, when there is a cycle of references (e.g. object A holds a reference of object B and object B holds a reference of object B) it is not so simple: the garbage collector needs to iterate through all objects to find such no longer used cycles. One could think, that keras.layers.Input has such a cycle somewhere (and this is true), but this is not the reason for this "memory leak", which can be observed also for pure python. We use objgraph-package to inspect the references, let's run the following python script: #pure.py from keras.layers import Input import gc import sys import objgraph def foo(param): a = Input(shape=(1280,)) return "str" ### MAIN : print("Counts at the beginning:") objgraph.s…

http://stackoverflow.com/a/48200158
has comment: http://stackoverflow.com/comment/117256772
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/117256758
downvote count: 1
has body: If you don't care whether your original lists (a and b in the following example) change, you can use the following snippet: def twolists(a, b): result = [] while len(a) &gt; 0: result.append(a.pop(0)) if len(b) &gt; 0: result.append(b.pop(0)) result += a + b return result twolists([ ], ['w', 'x', 'y', 'z']) print(outcome) outcome = twolists([0, 1], ['w', 'x']) print(outcome) outcome = twolists([0, 1], ['w', 'x', 'y', 'z']) print(outcome) outcome = twolists([0, 1, 2, 3], ['w', 'x']) print(outcome) Produces the following output: ['w', 'x', 'y', 'z'] [0, 'w', 1, 'x'] [0, 'w', 1, 'x', 'y', 'z'] [0, 'w', 1, 'x', 2, 3]
has comment: http://stackoverflow.com/comment/115411814
answers question: http://stackoverflow.com/q/48199961
has comment: http://stackoverflow.com/comment/83381728
type: Answer

http://stackoverflow.com/q/48247301
tagged with: keras
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/48247312
tagged with: deep-learning
upvote count: 3
has title: How do you initialize a constant bias in tf.layers.keras.Conv2D?
has body: So, the title pretty much says it all. The default argument is, bias_initializer='zeros', but I intend on initializing with a constant value of 0.1. I'm assuming this is a very easy question to answer, but I can't seem to make sense of the documentation for this on the internet.
accepted answer: http://stackoverflow.com/a/48247646
tagged with: initialization
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48247646
answer count: 2
has answer: http://stackoverflow.com/a/48247312
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/83394799
comment on: http://stackoverflow.com/a/48206957
has text: You should explain your answer rather than just posting code.
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/comment/83606989
score: 2
comment on: http://stackoverflow.com/q/48310610
type: QuestionComment
has text: Yeah that is possible. Any attempt from your side?
type: Comment

http://stackoverflow.com/q/48240102
has comment: http://stackoverflow.com/comment/83463451
has comment: http://stackoverflow.com/comment/83481084
score: 0
answer count: 0
duplicate of: http://stackoverflow.com/q/26767591
upvote count: 1
has comment: http://stackoverflow.com/comment/83465193
downvote count: 1
has title: python pygame.error: video system not initialized
favorite count: 0
type: Question
tagged with: python-3.x
has body: I am trying to open a window in pygame but keep getting this error: Traceback (most recent call last): File "python", line 3, in &lt;module&gt; pygame.error: video system not initialized This is my code: import pygame pygame.init() pygame.display.list_modes() pygame.display.set_mode([700, 500]) black = (0, 0, 0) red = (255, 0, 0) white = (255, 255, 255) If I do not have 'pygame.display.list_modes()' included it has the error: Traceback (most recent call last): File "python", line 3, in &lt;module&gt; pygame.error: No available video device I have used 'pygame.init()' so do not know what has gone wrong, Can anyone please help me to figure out what has gone wrong? Thanks in advance to anyone who tries to help my out. I don't think it makes a difference but I am using Repl.it to code this.
has comment: http://stackoverflow.com/comment/83465221
type: UnansweredQuestion
tagged with: python
tagged with: pygame
linked to: http://stackoverflow.com/q/26767591

http://stackoverflow.com/comment/83657434
type: QuestionComment
comment on: http://stackoverflow.com/q/48328255
score: 0
type: Comment
has text: @MooingRawr: Thanks a lot! I managed to figure it out after this.

http://stackoverflow.com/q/48266277
has answer: http://stackoverflow.com/a/48271121
type: UnansweredQuestion
downvote count: 0
tagged with: python
has body: I am working with OpenCV+Python and I want to find the geometrical centre of the following contour: The OpenCV documentation suggests the following to find the centroid of a contour: import numpy as np import cv2 as cv img = cv.imread('star.jpg',0) ret,thresh = cv.threshold(img,127,255,0) im2,contours,hierarchy = cv.findContours(thresh, 1, 2) cnt = contours[0] M = cv.moments(cnt) print( M ) #Centroid cx = int(M['m10']/M['m00']) cy = int(M['m01']/M['m00']) If I am right, according to this formula the centroid is calculated as the mean (or the average?) of all the points of the contour. However, if for example fewer points are detected at the upper part of the contour than at the lower part of the contour then the centroid will be a bit higher than the actual geometrical centre of the (fully detected) contour. Am I right? If so, then is it better to calculate the average of the extreme points of the contour to find the geometrical centre of the contour and in this way to not depend at all on if the points of the contour are uniformly detected?
tagged with: opencv
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83516061
upvote count: 1
favorite count: 0
type: Question
has title: Is the centroid of a contour always its geometrical centre? (OpenCV, Python)

http://stackoverflow.com/comment/83495476
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48256307
has text: If it explicitly runs `"path\to\python.exe" "path\to\script.py"`, then yes, it's possible to get the LNK path by calling `GetStartupInfo` and getting `lpTitle`. In this case the `dwFlags` field includes `STARTF_TITLEISLINKNAME`.
type: Comment

http://stackoverflow.com/comment/83696705
has text: check my answer for reply to your question Martin.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48331004
score: 0

http://stackoverflow.com/comment/83339143
type: Comment
has text: Can you edit the original so I can see your updated code?
type: AnswerComment
comment on: http://stackoverflow.com/a/48179091
score: 0

http://stackoverflow.com/comment/83357822
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48188739
score: 0
has text: Thank you so much for your help! So you suggest that I download mxnet source code and then use cmake to compile it?

http://stackoverflow.com/comment/83525819
type: AnswerComment
comment on: http://stackoverflow.com/a/48260214
has text: `@Mark Setchell` Yes, I agree. Your other two methods are much more robust. The one is quite simple and elegant.
type: Comment
score: 0

http://stackoverflow.com/comment/83604135
type: Comment
type: QuestionComment
has text: the simple answer: find the funky values, haha. You can try using [`select_dtypes`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html) to filter out what might be causing it or some other way.
comment on: http://stackoverflow.com/q/48308698
score: 0

http://stackoverflow.com/q/48192862
favorite count: 0
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/48193413
type: Question
has comment: http://stackoverflow.com/comment/83366911
has answer: http://stackoverflow.com/a/48193413
tagged with: python
has comment: http://stackoverflow.com/comment/83366345
possible better answer: http://stackoverflow.com/a/48193744
tagged with: hash
has title: How do i search for a line of text in whole text file
has answer: http://stackoverflow.com/a/48193744
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: file
tagged with: string
has body: How do I read every line of a file in Python and check if that line is in another one of the lines of the same text? I've created hash of 2000 images and stored it in the same text file. So to find if the duplicate image exists I want to cross-check hash of all the images generated. Below is the code in list in which I have extracted the data, with open('hash_info.txt') as f: content = f.readlines() ['fbefcfdf961f1919\n', 'aecc9e9696961f2f\n', 'cc1c9c9c1c1e272f\n', 'a4ce9e9e9793134b\n', 'e2e7e7e7e7e7e763\n', 'e64fcbcfcf8f0f27\n', '9c1c3c3c3e1e1e9c\n', 'c8cc9cb43e3c3b1b\n', 'cccd9e9e9e1e1f9f\n', 'ccce9e9e9ece0e4e\n', 'a6a7cbcfcf071736\n', 'f69c9c3c3636373b\n', 'ec9c9cbc3c26272b\n', 'f0cccc9c8c0e3f3b\n', '4c9c363e3e3e1e5d\n', '9c9cbc3e3c3c376f\n', 'f5ccce9e9e9e1f2c\n', 'cccc8c9ccc9ccdca\n', 'dc98ac2c363e5e5f\n', 'f2e7e7e7e7e76746\n', '9a9a1e3e3e3e373f\n', 'cc8c9e9e8ecece8f\n', 'db9f9f1e363e9e9e\n', 'e4cece8e9ececfcf\n', 'cecede9f9bce8f8f\n', 'b8ce4e4e9f1b1b29\n', 'ece6e6e7efcf0d05\n', 'cd8e9696b732163f\n', 'cece9e9ecececfcd\n', 'cc9d9f9f9f8dcdd9\n', '992d2c2c3c3ebe9e\n', 'e6e6cece8f2d2939\n', 'eccfcfcfcf4f6f7d\n', 'e6cecfcfcfefcec6\n', 'edf8e4cecece4e0e\n', 'e9d6e6e7e7a76667\n', 'edcecfcfcfcfcecf\n', 'a5a6c6ce8e0f43c7\n', '3a3e7c7c3d3e3f2f\n', 'cc9c963c361f173f\n', '8c9c9c9d9d9d1a9a\n', 'f0cc8e9e9e9f9d9e\n', '989c3c3c1c2e6e5b\n', 'f0989c1c9e1e1adb\n', 'f09c9c9c9c9e9e9f\n', 'e6ce4e1e86333309\n', 'a6cece9e8f0f0f2f\n', 'e8cccc9cccdc8d8c\n', 'f0ecced6969f0f2d\n', 'e0d89c3c3c3d3d1f\n', 'e6e7c7cfc7c64e4f\n', 'a6cf4b0f0e073739\n', 'cececececccf4b5b\n', 'a6c6cfcfcfc6c6c6\n', 'f0fcf3e3e3e3f303\n', 'f9f2e7e7cbcfcf97\n','fbefcfdf961f1919\n', 'f3e7e5e5e7e5c7c3\n', 'b3e7e7c7c7070f1e\n', 'cb9d97963e3f3325\n', '9b1e2c1c1e1e2e2b\n', '9d9e969f9f9f9f0f\n', 'e6a7a7e7e666666c\n', 'c64e9e9b0b072727\n','fbefcfdf961f1919\n', 'c7cfcfcfcfc7ce86\n', 'e6cecfcfcfc7c745\n', 'e6e6cecececfcfcf\n', 'cbcd9f9f9e1f3a7a\n', 'ccce9ecececec646\n', 'f1c7cfdf9f970325\n', '989d9c1c1e9e9f1f\n', '9c9e1c1e9e9d9…

http://stackoverflow.com/a/48199276
has comment: http://stackoverflow.com/comment/83379851
has body: while True: choice1 = raw_input("Were would " + name + " like to go?\nThe Kitchen\nThe Couch\nOutside") if choice1 == "The Kitchen": choices.append("The Kitchen") print(name + " walked towards The Kitchen.") break elif choice1 == "The Couch": choices.append("The Couch") print(name + " went and had sat on The Couch.") break elif choice1 == "Outside": choices.append("Outside") print(name + " put on their pack and went out the door.") break else: print("error") continue
downvote count: 1
has comment: http://stackoverflow.com/comment/83379928
answers question: http://stackoverflow.com/q/48199153
upvote count: 0
type: Answer
score: -1

http://stackoverflow.com/q/48293273
tagged with: python
has title: rxpy: buffer_with_time with a random jitter?
tagged with: rx-py
answer count: 0
type: UnansweredQuestion
score: 1
has body: I am using buffer_with_time, it accepts a keyword argument: timespan – Length of each buffer (specified as an integer denoting milliseconds) However, the timestamp is fixed. I want to add a random jitter to it. If my parallel task was started at the same time, a fixed timespan=5000 would jam at the same time every five seconds. How to make timespan more dynamic, something like 5000±300ms so gradually buffer events would be fired evenly?
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: reactivex

http://stackoverflow.com/comment/91392911
has text: Worth noting that when Glue compiles your Scala job it may be a little different to the spark shell in a dev endpoint (ie, at the very least warnings are treated as fatal, which is not the case in the spark-shell).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48823484
type: AnswerComment

http://stackoverflow.com/q/48196521
answer count: 2
score: 0
type: UnansweredQuestion
tagged with: raspberry-pi3
has body: py on a raspberry pi with python 2.7.9 and pip 1.5.6. I installed and uninstalled pyvisa and pyvisa-py several times, but the problems stay. I connected the KEITHLEY Multimeter 2000 per R232 to USB with the Raspberry. When I run the basic Code: import visa rm = visa.ResourceManager('@py') a=rm.list_resources() print(a) I receive: Traceback (most recent call last): File "pyvisa.py", line 1, in &lt;module&gt; import visa File "/usr/local/lib/python2.7/dist-packages/visa.py", line 16, in &lt;module&gt; from pyvisa import logger, __version__, log_to_screen, constants File "/home/pi/pyvisa.py", line 2, in &lt;module&gt; rm = visa.ResourceManager('@py') AttributeError: 'module' object has no attribute 'ResourceManager' as well when I try python -m visa info Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/usr/local/lib/python2.7/dist-packages/visa.py", line 16, in &lt;module&gt; from pyvisa import logger, __version__, log_to_screen, constants File "pyvisa.py", line 1, in &lt;module&gt; import visa File "/usr/local/lib/python2.7/dist-packages/visa.py", line 16, in &lt;module&gt; from pyvisa import logger, __version__, log_to_screen, constants ImportError: cannot import name logger On the other hand i can't upgrade, because the requirements are already up-to-date. pip install pyvisa-py --upgrade Requirement already up-to-date: pyvisa-py in /usr/local/lib/python2.7/dist-packages Requirement already up-to-date: pyvisa&gt;=1.8 in /usr/local/lib/python2.7/dist-packages (from pyvisa-py) Requirement already up-to-date: enum34 in /usr/local/lib/python2.7/dist-packages (from pyvisa&gt;=1.8-&gt;pyvisa-py) I would be very thankfull if somebody could help me with this issue.
tagged with: python-2.7
tagged with: pyvisa
has title: pyvisa-py on raspberry pi AttributeError: 'module' object has no attribute 'ResourceManager'
has answer: http://stackoverflow.com/a/61260910
tagged with: python
has answer: http://stackoverflow.com/a/48204460
type: Question

http://stackoverflow.com/comment/83600538
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48290132
has text: @BillBell Is this the same as saving both the shell and ex25.py in the same folder?
score: 0

http://stackoverflow.com/a/48188556
answers question: http://stackoverflow.com/q/48184098
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: I have completed similar project to yours recently. If internet connection is not a problem for you, I would suggest using Wit.ai. It has nice Python API, or you could use it through HTTP API. Your assistant would have to record speech, then send data to remote API and receive response with text as an answer. Take into account, that STT process is quite complex, so trying to solve it with local solutions might be a bit too much to cope with for Raspberry. What's more, you would have to (probably) prepare vocabularies, etc. Using remote STT service, you don't have to do that. If you cannot, or do not want to use remote service, you can always try CMU Sphinx. But for that, you need somebody else to help you with it, as I have no experience using it whatsoever.
accepted answer of: http://stackoverflow.com/q/48184098
type: Answer

http://stackoverflow.com/comment/83516306
has text: @Krishna, tried now with the same configuration in my home it's working.Access can be a issue i guess.
comment on: http://stackoverflow.com/q/48262698
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48280548
type: Question
has body: I am trying to export a database using this code os.system('mysqldump -u %s -p%s %s &gt; %s' % (user, password, database, filepath)) When I run the program for the first time it exports my database and everything works fine just it gives me this error. sh: 1: mysqldump: not found Next run (when database is already exported) it works without any error. how can I fix this ?
has answer: http://stackoverflow.com/a/48280860
type: UnansweredQuestion
downvote count: 0
tagged with: python
has title: mysqldump: not found - exporting database in python
has comment: http://stackoverflow.com/comment/83544777
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83545109
upvote count: 1
has comment: http://stackoverflow.com/comment/83545001
favorite count: 0

http://stackoverflow.com/q/48258428
type: Question
has title: Sum of squares function in Python?
tagged with: numbers
score: 1
linked to: http://stackoverflow.com/q/26222693
tagged with: python
has body: In Mathematica, there's a function called SquaresR that determines the number of summing k square integers to equal some specific natural number n: http://mathworld.wolfram.com/SumofSquaresFunction.html I have looked online for a Python package including a similar function and found nothing. Is there a Python implementation somewhere out there? (If it helps, I only need it for k=3). If not, is there a more efficient method to implement it than brute force?
has comment: http://stackoverflow.com/comment/83501251
has comment: http://stackoverflow.com/comment/83502641
answer count: 0
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83499614
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/83747155
has text: so say you have 2 keywords {cost benefit analysis} and {machine learning} - you want to find documents that contain those keywords or any permutation of those keywords, possibly with some non-keyword characters in between the constituents of the keyword. Does 'the cost benefit of different machine learning techniques requires more analysis' match only {machine learning} or both keywords?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48258692

http://stackoverflow.com/q/48255651
has comment: http://stackoverflow.com/comment/83494203
has comment: http://stackoverflow.com/comment/83494238
has comment: http://stackoverflow.com/comment/83494388
accepted answer: http://stackoverflow.com/a/48255778
tagged with: python
has answer: http://stackoverflow.com/a/48255778
tagged with: operations
has comment: http://stackoverflow.com/comment/83494221
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83494361
tagged with: list
answer count: 2
has title: Calculations using a list with operations with numbers python
possible better answer: http://stackoverflow.com/a/48255754
has comment: http://stackoverflow.com/comment/83494065
has body: I am trying to use a list that has operations attached to them, but i can't get the numbers out of the list. Here is the list. mylist=["+1", "-2", "*2"] I was wondering if there was a way to put them together as a float, and then do the operation so it would do 1-2*2 and output the answer. Smaller the better. thanks :) the expected output is -2.
has comment: http://stackoverflow.com/comment/83494119
has comment: http://stackoverflow.com/comment/83494218
has comment: http://stackoverflow.com/comment/83494375
has answer: http://stackoverflow.com/a/48255754
has comment: http://stackoverflow.com/comment/83494116
type: Question
has comment: http://stackoverflow.com/comment/83494432
has comment: http://stackoverflow.com/comment/83494107
has comment: http://stackoverflow.com/comment/83494227
has comment: http://stackoverflow.com/comment/83494215
has comment: http://stackoverflow.com/comment/83494094

http://stackoverflow.com/q/48328938
has comment: http://stackoverflow.com/comment/83683490
score: 2
has title: What happens if I overwrite __qualname__ of a function
has comment: http://stackoverflow.com/comment/83644013
linked to: http://stackoverflow.com/q/10875442
has body: For debugging purposes I wanted some lambda functions to be named, i.e. see a __repr__ string. Possible to change a function&#39;s repr in python? provides some good answers to how this can be properly done, but I do wonder about the following, "quick and dirty" version (which I won't keep in production code!): I simply changed the functions' __qualname__. Is that safe to use or do I have to expect some strange side effects - and if so, why? I.e. what other functions might rely on __qualname__? The code looks somewhat like this: def make_listener(consumer): def listener(obj): if _is_doc_of_interest(obj, consumer): consumer.put(obj) listener.__qualname__ = f'listener({consumer})' return listener And will produce a bunch of functions which will look like: [make_listener(c) for c in [MyObject(1), SomethingElse(True, 42, 'foo')] &gt; [ &gt; &lt;function listener(MyObject(1))&gt;, &gt; &lt;function listener(SomethingElse(True, 42, 'foo'))&gt; &gt; ] Again, this is only meant for the purposes of debugging (as I generate a whole lot of listeners and like to identify them quickly), but now I'm curious if this actually produces any side effects or if I can keep using it for quick investigations
tagged with: python
has comment: http://stackoverflow.com/comment/83683570
has comment: http://stackoverflow.com/comment/83643577
type: Question
answer count: 0
upvote count: 2
tagged with: function
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83683615
tagged with: repr
favorite count: 0

http://stackoverflow.com/comment/83647265
type: AnswerComment
comment on: http://stackoverflow.com/a/48330564
has text: @Kailaugen See my comment on your question - you need to escape backslashes.
score: 0
type: Comment

http://stackoverflow.com/comment/83622689
has text: You would probably benefit a lot by leveraging Django's generic views. There are also many popular extensions that would probably fit your use case very nicely. Be sure to explore those options. It also doesn't look like you've using your form class in your views or templates. Most of this material should be covered in the django official tutorial.
comment on: http://stackoverflow.com/q/48318344
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83336147
has text: yes, that's exactly the syntax I used to connect ... and I did import both pyodbc and pypyodbc
comment on: http://stackoverflow.com/a/48177924
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83447812
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48232629
has text: Fair enough, still +1ed as it's alternative. I also found [this](https://stackoverflow.com/questions/1247486/python-list-comprehension-vs-map) useful, if you want to give it a read.
type: AnswerComment

http://stackoverflow.com/q/48212571
tagged with: list
score: 0
tagged with: printing
has comment: http://stackoverflow.com/comment/83406517
tagged with: subtitle
has comment: http://stackoverflow.com/comment/83408483
type: Question
has answer: http://stackoverflow.com/a/48213632
has body: I am trying to print a large list like a sequence of charterers or subtitle in TV. I have attached the following photo to understand more: And as you can see the input text should rotate from right to left. To arrive at this point I wrote the following code: from __future__ import print_function import os from time import sleep text = """A company which supplied lingerie to the Queen has lost its royal warrant over a book which revealed details of royal bra fittings.Rigby & Peller, a luxury underwear firm founded in London, had held the royal warrant since 1960. It was withdrawn after June Kenton, who fitted bras for the Quee n, released a book called 'Storm in a D-Cup'.Mrs Kenton said there was "nothing" in the book to "be upset about", adding that it was an "unbelieva ble" decision.Buckingham Palace said it did not comment on individual companies""" whole_Str = [] i = 0 while(i < len(text)): rest = text[i:i+50] i+=1 whole_Str.append(rest) for sequence in whole_Str: print (sequence, end ='\r') sleep(0.1) However, there are two problems: First, python editors do not allow me to over write different parts of this text on the same place. Second and most important, I guess sleep() is not a reasonable solution to create a delay since for a large scale text, system should not stop to print just subtitles. Any kind of help would be greatly appreciated
answer count: 2
has answer: http://stackoverflow.com/a/48213952
type: UnansweredQuestion
tagged with: delay
has title: Printing a dynamic and large list in Python
tagged with: python
has comment: http://stackoverflow.com/comment/83408900

http://stackoverflow.com/q/48325562
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/48328448
downvote count: 2
accepted answer: http://stackoverflow.com/a/48328448
has body: I have this code that extracts too much text. I am trying to extract only the title from top-content. from bs4 import BeautifulSoup import requests r = requests.get("https://education.maharashtra.gov.in/saral/27230500360") data = r.text soup = BeautifulSoup(data) soup.find("div", {"class": "top-content"}) How do I extract the name of school that is not part of inner div? Expected output: BHARATI VIDYAMANDIR HINDI NIGHT HIGH SCHOOL AND JR COLLEGE (27230500360) update: Is it possible to save the text as dict? {27230500360 : "BHARATI VIDYAMANDIR HINDI NIGHT HIGH SCHOOL AND JR COLLEGE"}
has title: extract text not part of inner division
has answer: http://stackoverflow.com/a/48327385
possible better answer: http://stackoverflow.com/a/48327385
tagged with: beautifulsoup
type: AnsweredQuestion
answer count: 3
score: -2
has answer: http://stackoverflow.com/a/48328287
tagged with: python
favorite count: 0

http://stackoverflow.com/q/48195796
tagged with: python
tagged with: date
has comment: http://stackoverflow.com/comment/83411468
has body: I am trying enter today's date into a date picker field rather than just click the today button and below is how my code is set up, but not able to do so. I am using BDD framework. And I input todays date @When('I input todays date') def step_impl(context): value_paystub_dateOfPayStub(context.webdriver) Getting element of said date picker: def get_dateOfPaystub(driver): element = None try: element = WebDriverWait(driver, 70).until( EC.visibility_of_element_located( (By.XPATH, "//input[@id='chl.CustomerFinancials.primaryFinancialsForm.paystub.6134.DateOfPaystub']")) ) except TimeoutException: logger.error("Date of Paystub element was not found") return element Trying to enter today's date: def value_paystub_dateOfPayStub(driver): currentdate = datetime.datetime.today() try: element = get_dateOfPaystub(driver) element.send_keys() # to set focus on the selector element.send_keys(currentdate, "%m-%d-%Y") except Exception: logger.error("Unable to enter value into Paystub Employer Name field") Any help would be appreciated.
has comment: http://stackoverflow.com/comment/83380608
answer count: 3
has title: Passing today's date for a date picker field in Selenium using Python
has answer: http://stackoverflow.com/a/48197897
score: 0
tagged with: selenium
upvote count: 1
has answer: http://stackoverflow.com/a/67926836
downvote count: 1
linked to: http://stackoverflow.com/q/311627
has comment: http://stackoverflow.com/comment/83414245
favorite count: 0
type: Question
tagged with: bdd
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83414278
has answer: http://stackoverflow.com/a/64749996
has comment: http://stackoverflow.com/comment/83411490

http://stackoverflow.com/q/48213235
has title: How can you split a node based on a categorical variable in Scikit Learn Decision Tree?
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: categorical-data
downvote count: 0
answer count: 1
tagged with: scikit-learn
tagged with: decision-tree
favorite count: 0
type: Question
has body: I am trying to make a decision tree for the following dataset: https://archive.ics.uci.edu/ml/datasets/Contraceptive+Method+Choice This dataset contains some categorical variables (for example Husband's occupation: 1, 2, 3, 4 ). When I create my Decision Tree, the categorical values are split based on 'smaller or greater than' value. In other words, there is a node in my tree that splits the data as follows: "Occupation Husband &lt;= 2.5". How can I adjust this code so that it keeps into account categorical variables? When I print 'data.info()', the datatypes are correct. import pandas as pd import numpy as np import os from sklearn import tree from sklearn.tree import DecisionTreeClassifier, export_graphviz from sklearn.model_selection import train_test_split from matplotlib import pyplot as plt import seaborn as sns import graphviz import pydotplus import io from scipy import misc os.chdir("path") #path containing datacontra.csv file data = pd.read_csv("datacontra.csv", dtype={'Age': np.float64, 'EduW':np.object, 'EduH':np.object, 'Child': np.int64, 'ReliW': np.object, 'WorkW':np.object, 'OccuH': np.object, 'SOLI': np.object, 'MediaExp': np.object, 'T':np.object}) data.describe() data.head() data.tail() data.info() train, test = train_test_split(data,test_size = 0.05) print("Training size" + str(len(train))) print("Test size " + str(len(test))) train.shape features = list(data.columns[:9]) label = list(data.columns[9]) print(list(data.columns[:9])) print(list(data.columns[9])) X_train = train[features] print(X_train.shape) y_train = train[label] print(y_train.shape) X_test= test[features] y_test = test[label] c = DecisionTreeClassifier() dt = c.fit(X_train,y_train) path = ("/Users/sabinekuypers/Documents/Charlotte 461/") def show_tree(tree, features, path): f = io.StringIO() export_graphviz(tree, out_file=f, feature_names = features) pydotplus.graph_from_dot_data(f.getvalue()).write_png(path) img = misc.imread(path) plt.rcParams["figure.figsize"]=(20,20) plt.imsho…
has answer: http://stackoverflow.com/a/48213493
accepted answer: http://stackoverflow.com/a/48213493
tagged with: python

http://stackoverflow.com/comment/83478268
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48247844
type: QuestionComment
has text: sry, i didn't usually use python, but i mean list or kind.. :D

http://stackoverflow.com/comment/83397249
type: Comment
type: AnswerComment
has text: Very nice solution !
comment on: http://stackoverflow.com/a/48208185
score: 1

http://stackoverflow.com/comment/83381016
comment on: http://stackoverflow.com/a/48195116
score: 0
type: Comment
has text: It gives error in case of first code when I use this line ws.write(row, 0, numorf), but when I changed this to ws.write(row, 0, row) it works fine. Thanks for it.
type: AnswerComment

http://stackoverflow.com/a/48236956
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48236866
answers question: http://stackoverflow.com/q/48236866
has body: StandardScaler will shift the data by mean and scale it by std, since you only pass one row to it, mean for each column is the value itself and value will be shifted to zero. See more here. &gt;&gt;&gt; sc = StandardScaler() &gt;&gt;&gt; arr = np.array([[1.0,2.0,3.0]]) &gt;&gt;&gt; sc.fit(arr) &gt;&gt;&gt; sc.mean_, sc.scale_ array([ 1., 2., 3.]), array([ 1., 1., 1.])) In your case, you should fit the scaler to all the data and for each row, you can use transform to get the result. sc.fit(data) # this will compute mean and std on all rows scaled_row = sc.transform(row) # apply shift to a single row
score: 5
upvote count: 5
type: Answer
downvote count: 0

http://stackoverflow.com/comment/83554068
type: AnswerComment
comment on: http://stackoverflow.com/a/48284628
score: 0
has text: Yes, I actually meant one output per batch :) thank you for the detailed answer!
type: Comment

http://stackoverflow.com/comment/83585893
has text: Without annotating it as `@contextmanager`, this does not work. The error you get: `AttributeError: __enter__`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48299862

http://stackoverflow.com/comment/83798728
type: AnswerComment
comment on: http://stackoverflow.com/a/48189923
has text: Please put more description to your answer, otherwise the answer will landing in the Low Quality Posts and It will be removed. I will give you +1.
score: 0
type: Comment

http://stackoverflow.com/comment/83528976
comment on: http://stackoverflow.com/q/48272540
score: 0
type: Comment
type: QuestionComment
has text: Could you please point us out to which piece of code is throwing this error? What is your expectation for this sample data?

http://stackoverflow.com/a/48257008
answers question: http://stackoverflow.com/q/48256911
type: AcceptedAnswer
has body: The issue in your case is you are inserting single document. my_dict = {"key1": "value1", "key2", "value2"} This is a single document. If you want it to be treated as two separate documents. You should try this : my_dict = [{"key1": "value1"},{"key2", "value2"}] You can refer the pymongo documentation for more details.
type: Answer
has comment: http://stackoverflow.com/comment/83519200
accepted answer of: http://stackoverflow.com/q/48256911
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/48216067
favorite count: 0
has body: I have a Keras model I converting to a tensorflow serving model. I can successfully convert my pretrained keras model to take b64 input, preprocess that input, and feed it to my model. My problem is that I don't know how to take the prediction data I am getting (which is enormous) and only export the top result. I am doing image segmentation so my output prediction is of shape (?, 473, 473, 3) and I'd like to get the top result and return it in b64 encoded format. What I have currently that just returns the entire prediction: sess = K.get_session() g = sess.graph g_def = graph_util.convert_variables_to_constants(sess, g.as_graph_def(), [model.output.name.replace(':0','')]) with tf.Graph().as_default() as g_input: input_b64 = tf.placeholder(shape=(1,), dtype=tf.string, name='b64') tf.logging.info('input b64 {}'.format(input_b64)) image = tf.image.decode_image(input_b64[0])#input_bytes) image_f = tf.image.convert_image_dtype(image, dtype=tf.float16) input_image = tf.expand_dims(image_f, 0) image_r = tf.image.resize_bilinear(input_image, [HEIGHT, WIDTH], align_corners=False) input_data = preprocess_image(image_r) output = tf.identity(input_data, name='input_image') # Convert to GraphDef g_input_def = g_input.as_graph_def() with tf.Graph().as_default() as g_combined: x = tf.placeholder(tf.string, name="b64") im, = tf.import_graph_def(g_input_def, input_map={'b64:0': x}, return_elements=["input_image:0"]) pred, = tf.import_graph_def(g_def, input_map={model.input.name: im}, return_elements=[model.output.name]) with tf.Session() as session: inputs = {"image_bytes": tf.saved_model.utils.build_tensor_info(x)} outputs = {"output_bytes":tf.saved_model.utils.build_tensor_info(pred)} signature =tf.saved_model.signature_def_utils.build_signature_def( inputs=inputs, outputs=outputs, method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME ) """Convert the Keras HDF5 model into TensorFlow SavedModel.""" if os.path.exists(export_path): shutil.rmtree(export_path) legacy_ini…
type: AnsweredQuestion
has title: tensorflow serving prediction as b64 output top result
score: 1
accepted answer: http://stackoverflow.com/a/48245749
tagged with: tensorflow-serving
tagged with: python
type: Question
tagged with: prediction
tagged with: predict
downvote count: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48245749
tagged with: tensorflow

http://stackoverflow.com/a/48219494
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48219170
type: Answer
answers question: http://stackoverflow.com/q/48219170
score: 0
has body: Turn out it is pretty easy. I even don't need to change the setup.py I just moved the children classes' code to their own files and include them from the parent class. It would became something like this Child1.pyx Child2.pyx Child3.pyx MyLibrary.pyx and in the MyLibrary.pyx . . . include Child1.pyx include Child2.pyx include Child3.pyx class parent: . . .

http://stackoverflow.com/comment/124446867
score: 0
comment on: http://stackoverflow.com/a/48210341
type: Comment
type: AnswerComment
has text: is there any way to apply it to python2? T.T

http://stackoverflow.com/comment/83410511
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48210056
type: QuestionComment
has text: @Ev.Kounis the current dict has a depth of 4. however, i don't want the last id to be included, so it should calculate to 3

http://stackoverflow.com/a/48244447
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83477769
score: 6
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83477484
has comment: http://stackoverflow.com/comment/83476828
has comment: http://stackoverflow.com/comment/83476214
has comment: http://stackoverflow.com/comment/83476752
upvote count: 6
has comment: http://stackoverflow.com/comment/83477207
has comment: http://stackoverflow.com/comment/83476900
has comment: http://stackoverflow.com/comment/83477694
has comment: http://stackoverflow.com/comment/83476724
has comment: http://stackoverflow.com/comment/83476303
has comment: http://stackoverflow.com/comment/83477430
has comment: http://stackoverflow.com/comment/83476335
answers question: http://stackoverflow.com/q/48244172
has comment: http://stackoverflow.com/comment/83476287
has body: So there are 3 problems: Problem 1: In your example event, ['Records'][0]['Sns']['Message'] is a str in JSON format. That means that you need to parse to a dict like this: message = event['Records'][0]['Sns']['Message'] message = json.loads(message) Problem 2: message['Trigger']['Dimensions'] is a list but you are trying to access it like if it were a dict. So you only need to change your code to: message = message['Trigger']['Dimensions'][0]['name'] Problem 3: Message is a str that means that you need to verify that is a plain str or json str (otherwise you are going to have problems with multiple structures and types). For that your code could look like: message = event['Records'][0]['Sns']['Message'] if isinstance(message, str): try: message = json.loads(message) except Exception as e: print(e) # Or do nothing, this is just to log the error elif isinstance(message, list): message = message[0] # Maybe evaluate bool, tuple, etc other types print('RESPONSE', message['Trigger']['Dimensions'][0]['name'] if isinstance(message, dict) else message) However I would also recommend to make it more extensible iterating the elements that you know are list. And for safety reasons (trying to avoid null pointer exceptions), use the get() function with a default value. http://www.tutorialspoint.com/python/dictionary_get.htm . Try maybe to create a function to parse structures and make it reusable. Good luck!
has comment: http://stackoverflow.com/comment/83476426
has comment: http://stackoverflow.com/comment/83476441
accepted answer of: http://stackoverflow.com/q/48244172
has comment: http://stackoverflow.com/comment/83477607
has comment: http://stackoverflow.com/comment/83477282
has comment: http://stackoverflow.com/comment/83476235
has comment: http://stackoverflow.com/comment/83476925
has comment: http://stackoverflow.com/comment/83476857
has comment: http://stackoverflow.com/comment/83476321
has comment: http://stackoverflow.com/comment/83476547
has comment: http://stackoverflow.com/comment/83477526

http://stackoverflow.com/comment/83544066
has text: Congratulations on 200k :)
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48280051

http://stackoverflow.com/comment/83503234
score: 1
has text: Personally, I feel it's exceedingly elegant and fast *enough* for my needs. If I need to go faster I'd definitely go with Rawing's answer.
comment on: http://stackoverflow.com/a/48259961
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48197932
has comment: http://stackoverflow.com/comment/99067837
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/98978013
has body: Using sparsity you can easily gain a speedup of &gt;50x: import numpy as np from scipy.sparse import rand as r1 from numpy.random import rand as r2 from time import time np.random.seed(1000) nrow,ncol = 5000,4000 x = r1(nrow, ncol, format='csc', density=.05) y = (r2(nrow)&lt;=.6).astype(int) t = [] t.append(time()) correl = [np.corrcoef(np.asarray(x[:,n].todense()).reshape(-1), y)[0,1] for n in range(ncol)] t.append(time()) yy = y - y.mean() xm = x.mean(axis=0).A.ravel() ys = yy / np.sqrt(np.dot(yy, yy)) xs = np.sqrt(np.add.reduceat(x.data**2, x.indptr[:-1]) - nrow*xm*xm) correl2 = np.add.reduceat(x.data * ys[x.indices], x.indptr[:-1]) / xs t.append(time()) print('results equal --', np.allclose(correl, correl2)) print('run time (sec) -- OP: {}, new: {}'.format(*np.diff(t))) Sample output: results equal -- True run time (sec) -- OP: 1.38134884834, new: 0.0178880691528 Explanation: To be able to take advantage of sparsity we standardise y which is dense anyway. And then compute the raw correlation between x and y. Because y is already zero-mean at this point the mean of x is nixed. It therefore remains to divide by the standard deviation of x. Here too we can avoid going through a dense matrix by calculating the raw 2nd moment and subtracting the squared mean. Implementation detail: Please note that I have taken the liberty of switching to csc which is more suitable here (if needed, add x=x.tocsc() at the start). We use np.add.reduceat to perform the sums along the 'ragged' columns in a vectorized fashion. indices from the csc representation of the sparse matrix is convenient for selecting the elements of y corresponding to nonzero elements in x.
has comment: http://stackoverflow.com/comment/98985386
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48197097
upvote count: 7
accepted answer of: http://stackoverflow.com/q/48197097
has comment: http://stackoverflow.com/comment/83383709

http://stackoverflow.com/comment/83487540
has text: yes, thank you for your answer! The context is I have some data of length `N` and within the `j` loop I compute `np.var(data[r])` each time. Whereas in the second instance I compute `np.var(data[r],axis=1)` only once. Then in both cases take the mean of the results. I had gotten used to thinking that if you could vectorize a task that would automatically be quicker in numpy.
score: 0
comment on: http://stackoverflow.com/a/48251951
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48190883
type: Answer
score: 0
has body: If you keep the plot static, then plot each data series in sequence the legend will be created automatically: import itertools import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax.set_xlabel('PC 1') ax.set_ylabel('PC 2') marker = itertools.cycle(('o', '^', 's', 'x', '*')) # Get the method name, and its measurements for all datasets for method, measurements in method_metric_dict.items(): # Get the measurements for the requested data, and calc their stats # Plot the line for the method and dataset ax.scatter(measurements[:,0], measurements[:,1], label=method, marker=next(marker)) plt.legend()
answers question: http://stackoverflow.com/q/48190614

http://stackoverflow.com/q/48281261
has comment: http://stackoverflow.com/comment/83546448
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
accepted answer: http://stackoverflow.com/a/48281305
tagged with: if-statement
downvote count: 2
has answer: http://stackoverflow.com/a/48281305
upvote count: 1
tagged with: python
score: -1
has body: The following code is for a simple number guessing game in python that I made. The first version works flawlessly. But the second one, in which I have only modified the closing if statement causes the code following the statement to not run.Can anyone explain why? Valid Code from random import randint tries = 0 secret = randint(1,10) for tries in range(5): guess=int(input("Try to guess the number between 1 and 10 that I'm thinking of.")) tries+=1 if guess&lt;secret: print("Guess higher!") elif guess&gt;secret: print("Guess Lower!") else: print("Whoa!You got it right!The number I was thinking of was %s and you guessed it in %s tries."%(secret,tries)) break if guess!=secret: print("Sorry,you\'re out of tries.The number was %s"%secret) Wrong code from random import randint tries = 0 secret = randint(1,10) for tries in range(5): guess=int(input("Try to guess the number between 1 and 10 that I'm thinking of.")) tries+=1 if guess&lt;secret: print("Guess higher!") elif guess&gt;secret: print("Guess Lower!") else: print("Whoa!You got it right!The number I was thinking of was %s and you guessed it in %s tries."%(secret,tries)) break if tries&gt;5: print("Sorry,you\'re out of tries.The number was %s"%secret)
possible better answer: http://stackoverflow.com/a/48281687
has title: concluding statement trouble:number guessing game python
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83546584
has answer: http://stackoverflow.com/a/48281687

http://stackoverflow.com/comment/83546222
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48280759
has text: Nope, I do not want to switch to other release, I am with Python 2.7. It was just a question.

http://stackoverflow.com/q/48239206
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: statsmodels
has answer: http://stackoverflow.com/a/48241094
accepted answer: http://stackoverflow.com/a/48241094
has body: Is there a general way to ignore NaNs in statsmodels? I am using statsmodels' AnovaRM function to run repeated measures ANOVAs on various data sets. There are missing values in different columns for different rows. When running AnovaRM, it obviously returns nan for F- and p-values. I have tried aovrm = AnovaRM(df3, 'RT', 'id', within=['iv'], missing = 'drop') as suggested in Ignoring missing values in multiple OLS regression with statsmodels, however this does not seem to work for AnovaRM. So far I have simply excluded the subjects with missing data points, but that's a) really not the point and b) is simply not feasible for many data sets.
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/22234589
has title: Ignore NaNs in Python's statsmodels
tagged with: nan
favorite count: 0
type: Question
tagged with: anova
upvote count: 2
tagged with: missing-data

http://stackoverflow.com/comment/83525148
score: 0
type: Comment
type: QuestionComment
has text: please post a [mcve].
comment on: http://stackoverflow.com/q/48265583

http://stackoverflow.com/q/48276452
has title: How to get the bounding box x y coordinates of the detected faces
accepted answer: http://stackoverflow.com/a/48276615
score: 2
type: AnsweredQuestion
upvote count: 3
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48276615
has body: I'm working for face detection application. I need to get the bounding box coordinates of every detected face in an image. This is the code and the problem is it print bbox coordinate for one face only in a scenario where there were many faces detected. import mxnet as mx import cv2 import os detector = MtcnnDetector(model_folder='model', ctx=mx.cpu(0)) img = cv2.imread("amm.png") results = detector.detect_face(img, False) t2 = time.time() -t1 print("time: ",t2) if results is not None: total_boxes = results[0] points = results[1] draw = img.copy() for b in total_boxes: cv2.rectangle(draw, (int(b[0]), int(b[1])), (int(b[2]), int(b[3])),(250, 100, 0),1) face_count = 0 # counting number of detected faces within the image for b in total_boxes: face_count +=1 print("detected faces" , face_count) # printing number of detected faces. # I want to print the x and y coordinates of every faces detected for z in b : print(int(z), end=" ", flush=True) So this is the results I got: detected faces 12 199 302 257 377 0 (this bbox for only one face whereas 12 faces detected ) Could someone help me to figure out how to get the bboxes for all detected faces? Thank you in advance
tagged with: python

http://stackoverflow.com/comment/83569750
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48272367
type: Comment
has text: Yeah, the site-packages directory was already there and the other answers didn't help. I'd like to be able to do this in Eclipse, but it is pretty byzantine. I'll just use Anaconda to gather the data and Eclipse for the full project thanks.

http://stackoverflow.com/q/48290719
type: Question
accepted answer: http://stackoverflow.com/a/48290798
has answer: http://stackoverflow.com/a/48290798
possible better answer: http://stackoverflow.com/a/48290836
has body: I noticed the following unittest.TestCase assertion failing and am wondering how to correctly compare empty recarrays: fails: self.assertEqual( np.array( [], dtype=[ ('time', 'datetime64[ns]'), ('end_time', int) ] ).view(np.recarray), np.array( [], dtype=[ ('time', 'datetime64[ns]'), ('end_time', int) ] ).view(np.recarray) ) passes: self.assertEqual( np.array( [(1,1)], dtype=[ ('time', 'datetime64[ns]'), ('end_time', int) ] ).view(np.recarray), np.array( [(1,1)], dtype=[ ('time', 'datetime64[ns]'), ('end_time', int) ] ).view(np.recarray) ) Is this a bug or am I doing something wrong here?
tagged with: python-unittest
tagged with: python
has answer: http://stackoverflow.com/a/48290836
upvote count: 4
tagged with: numpy
type: AnsweredQuestion
answer count: 2
has title: Unittest equality of empty record arrays
tagged with: arrays
downvote count: 0
score: 4
favorite count: 0

http://stackoverflow.com/comment/83585541
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48286431
has text: The reason this fails is as indicated by @CristiFati: You are trying to plot the mean of some strings. This operation is not defined, you can only calculate the mean of an array of numbers, not strings. Ignoring the above comment and saying that it did not solve the issue is not helpful.

http://stackoverflow.com/q/48197626
possible better answer: http://stackoverflow.com/a/48197781
upvote count: 0
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: pyglet
has answer: http://stackoverflow.com/a/48197781
has comment: http://stackoverflow.com/comment/83376424
tagged with: python
score: -1
tagged with: pygame
has comment: http://stackoverflow.com/comment/83376518
has body: Here is my full code: http://codr.io/tscumzc And the error occurs with a music player called player: Traceback (most recent call last): File "test.py", line 915, in &lt;module&gt; player.eos_action = player.EOS_LOOP AttributeError: 'Player' object has no attribute 'EOS_LOOP' I can confirm that all of the sound files are in the directory and I have installed pyglet with pip3, pygame, etc. My game was working months ago but now that I'm coming back to it it is not working all of a sudden. The offending piece of code is only the player initialization and the EOS_LOOP part, since I tried only doing that in python3 in the terminal and it wouldn't work even with pyglet imported.
accepted answer: http://stackoverflow.com/a/48197726
has comment: http://stackoverflow.com/comment/83376515
type: Question
has answer: http://stackoverflow.com/a/48197726
tagged with: python-3.x
has title: Haven't changed my code but it stopped working: `object has no attribute 'EOS_LOOP'`
answer count: 2
has comment: http://stackoverflow.com/comment/83376506

http://stackoverflow.com/q/48307663
tagged with: aggregate
tagged with: grouping
tagged with: python
tagged with: weighted-average
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/2413522
has body: I am trying to do weighted standard deviation on top of weighted average on my pandas dataframe. I have a pandas dataframe like: import numpy as np import pandas as pd df = pd.DataFrame({"Date": pd.date_range(start='2018-01-01', end='2018-01-03 18:00:00', freq='6H'), "Weight": np.random.uniform(3, 5, 12), "V1": np.random.uniform(10, 15, 12), "V2": np.random.uniform(10, 15, 12), "V3": np.random.uniform(10, 15, 12)}) Currently, to get the weighted mean, inspired by this post, I am doing the following: def weighted_average_std(grp): return grp._get_numeric_data().multiply(grp['Weight'], axis=0).sum()/grp['Weight'].sum() df.index = df["Date"] df_agg = df.groupby(pd.Grouper(freq='1D')).apply(weighted_average_std).reset_index() df_agg Where I get the following: Date V1 V2 V3 Weight 0 2018-01-01 11.421749 13.090178 11.639424 3.630196 1 2018-01-02 12.142917 11.605284 12.187473 4.056303 2 2018-01-03 12.034015 13.159132 11.658969 4.318753 I want to modify weighted_average_std so that it returns standard deviation for each column in addition to weighted average. The idea is to use the weighted average for each group in a vectorized fashion. The new column names for Weighted Standard Deviation can be something like V1_WSD, V2_WSD and V3_WSD. PS1: This post goes through the theory of weighted standard deviation. PS2: Column Weight in df_agg is meaningless.
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/48308099
upvote count: 1
has title: Getting weighted average and standard deviation on several columns in Pandas
score: 1
accepted answer: http://stackoverflow.com/a/48308099
answer count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/10951341

http://stackoverflow.com/a/48302116
has comment: http://stackoverflow.com/comment/83614677
has comment: http://stackoverflow.com/comment/83615553
has comment: http://stackoverflow.com/comment/83615200
score: 2
has body: Have you tried F() expressions ? You can use it in this way. from django.db.models import F queryset.annotate(final_name=F('selected_name')) For more information check this. Don't forget to change the values with final_name(s).
type: Answer
answers question: http://stackoverflow.com/q/48301889
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/48305631
has comment: http://stackoverflow.com/comment/83596856
answers question: http://stackoverflow.com/q/48287059
type: AcceptedAnswer
type: Answer
has body: So I just had to switch to pyodbc which has better support for Windows authentication. Keep in mind that the latest release of pyodbc (4.0.21) does not support Python 3.6, so you need to use 3.5. Apparently there is a wheel for python 3.6, but I haven't tested it and it appears pip is unable to natively install it on Windows. I also had to change a few things such as the connection string and how stored procedures are called (pyodbc does not have the callproc function). Here is my connection string now: import pyodbc conn = pyodbc.connect(server='server',database='database',Trusted_Connection='yes', driver = '{ODBC Driver 13 for SQL Server}')
score: 0
accepted answer of: http://stackoverflow.com/q/48287059

http://stackoverflow.com/comment/83642184
score: 0
type: AnswerComment
has text: beautiful, thanks! I see I could have reproduced my problem is a simpler way ^.
type: Comment
comment on: http://stackoverflow.com/a/48328144

http://stackoverflow.com/comment/101765272
has text: Yes, that's exactly what I was saying - Windows doesn't support `fork()`, so no forking there, other than Cygwin/WSL workarounds.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48310939

http://stackoverflow.com/comment/83470522
type: QuestionComment
comment on: http://stackoverflow.com/q/48243829
has text: You still have not specified what you expect the behavior to be when you :`b.function_name2_1()` given that `function_name2_1` is a method on an entirely different class.
score: 0
type: Comment

http://stackoverflow.com/comment/83514953
type: Comment
type: QuestionComment
has text: @Bilkokuya No, I am just comparing BitBlt(). Although I tried comparing complete block also, but compare to BitBlt(), other calls are very insignificant in timing.
comment on: http://stackoverflow.com/q/48265569
score: 0

http://stackoverflow.com/q/48195038
has title: Celery + django - pdf generator
score: 1
tagged with: http://stackoverflow.com/tag/pdf
has body: I have some question: how to catch a pdf file which I generated in tasks.py and start downloading it automatically after redirect to home page and put the download link into this page? My task.py works because I see the result in terminal. My tasks.py: @shared_task def html_to_pdf(ctx): html_string = render_to_string('pdf_template.html', ctx) html = HTML(string=html_string) html.write_pdf('/tmp/report.pdf') fs = FileSystemStorage('/tmp') with fs.open('report.pdf') as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] \ = 'attachment; filename="report.pdf"' return response My views.py: class PdfCreatorView(View): def get(self, request): form = PdfForm return render(request, 'home_page.html', {'form': form}) def post(self, request): form = PdfForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] date_of_generation = form.cleaned_data['date_of_generation'] pdf_text_content = form.cleaned_data['pdf_text_content'] pdf_numbers_content = form.cleaned_data['pdf_numbers_content'] ctx = {'name': name, 'date_of_generation': date_of_generation, 'pdf_text_content': pdf_text_content, 'pdf_numbers_content': pdf_numbers_content} html_to_pdf.delay(ctx) url = reverse('home_page') return HttpResponseRedirect(url)
answer count: 1
downvote count: 0
upvote count: 1
tagged with: celery
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48195275
tagged with: django
tagged with: python

http://stackoverflow.com/comment/83411611
type: Comment
type: QuestionComment
has text: If it weren't for the XY problem going on here, this would be an obvious duplicate.
comment on: http://stackoverflow.com/q/48214852
score: 1

http://stackoverflow.com/q/48236223
tagged with: python
score: -1
tagged with: regex
type: Question
has body: I am working on the regular expression on python. I spend the whole week I can't understand what wrong with my code. it obvious that multi-string should match, but I get a few of them. such as "model" , '"US"" but I can't match 37abc5afce16xxx and "-104.99875". My goal is just to tell whether there is a match for any string on the array or not and what is that matching. I have string such as:' text = {'"version_name"': '"8.5.2"', '"abi"': '"arm64-v8a"', '"x_dpi"': '515.1539916992188', '"environment"': '{"sdk_version"', '"time_zone"': '"America\\/Wash"', '"user"': '{}}', '"density_default"': '560}}', '"resolution_width"': '1440', '"package_name"': '"com.okcupid.okcupid"', '"d44bcbfb-873454-4917-9e02-2066d6605d9f"': '{"language"', '"country"': '"US"}', '"now"': '1.515384841291E9', '{"extras"': '{"sessions"', '"device"': '{"android_version"', '"y_dpi"': '37abc5afce16xxx', '"model"': '"Nexus 6P"', '"new"': 'true}]', '"only_respond_with"': '["triggers"]}\n0\r\n\r\n', '"start_time"': '1.51538484115E9', '"version_code"': '1057', '"-104.99875"': '"0"', '"no_acks"': 'true}', '"display"': '{"resolution_height"'} An array has multi-string as : Keywords =["37abc5afce16xxx","867686022684243", "ffffffff-f336-7a7a-0f06-65f40033c587", "long", "Lat", "uuid", "WIFI", "advertiser", "d44bcbfb-873454-4917-9e02-2066d6605d9f","deviceFinger", "medialink", "Huawei","Andriod","US","local_ip","Nexus", "android2.10.3","WIFI", "operator", "carrier", "angler", "MMB29M", "-104.99875"] My code as for x in Keywords: pattern = r"^.*"+str(x)+"^.*" if re.findall(pattern, str(values1),re.M): print "Match" print x else: print "Not Match"
upvote count: 0
has comment: http://stackoverflow.com/comment/83455394
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/83455205
has title: Array has multi strings against text with multiline ( regular expression) Python
has comment: http://stackoverflow.com/comment/83455313
downvote count: 1
has answer: http://stackoverflow.com/a/48236346
favorite count: 0
has comment: http://stackoverflow.com/comment/83456734
has comment: http://stackoverflow.com/comment/83455699

random
tags question: http://stackoverflow.com/q/48236521
tags question: http://stackoverflow.com/q/48246528
tags question: http://stackoverflow.com/q/48248196
tags question: http://stackoverflow.com/q/48243303
tags question: http://stackoverflow.com/q/48178433
tags question: http://stackoverflow.com/q/48182874
tags question: http://stackoverflow.com/q/48293024
tags question: http://stackoverflow.com/q/48270653
tag name: random
tags question: http://stackoverflow.com/q/48237162
tags question: http://stackoverflow.com/q/48181072
tags question: http://stackoverflow.com/q/48247522
tags question: http://stackoverflow.com/q/48320442
tags question: http://stackoverflow.com/q/48303711
tags question: http://stackoverflow.com/q/48255243
tags question: http://stackoverflow.com/q/48251534
type: Tag
tags question: http://stackoverflow.com/q/48205282
tags question: http://stackoverflow.com/q/48247314
tags question: http://stackoverflow.com/q/48248817
tags question: http://stackoverflow.com/q/48266880
tags question: http://stackoverflow.com/q/48255710
tags question: http://stackoverflow.com/q/48198573
tags question: http://stackoverflow.com/q/48196536
tags question: http://stackoverflow.com/q/48187816
tags question: http://stackoverflow.com/q/48173538

http://stackoverflow.com/q/48270296
has title: Facepy Error 803:Some of the aliases you requested do not exist: group_id
has body: I'm trying to use configparser and pull the group ID from the config. Basically the configparser is to pull the group ID from a separate config file and insert it into all of the group_id instances. What I think is happening is it is unable to read the group_id from the 'group_id/feed'. group_id=config.get('settings','GROUPID') and the facepy line itself is; graph.post('group_id/feed', message=(random.choice(list(open('text.txt'))))) Here is the error I am getting File "C:\Users\0000\AppData\Local\Programs\Python\Python36-32\lib\site-pac kages\facepy\graph_api.py", line 96, in post retry=retry File "C:\Users\0000\AppData\Local\Programs\Python\Python36-32\lib\site-pac kages\facepy\graph_api.py", line 334, in _query return load_with_retry(method, url, data)[0] File "C:\Users\0000\AppData\Local\Programs\Python\Python36-32\lib\site-pac kages\facepy\graph_api.py", line 288, in load_with_retry return load(method, url, data) File "C:\Users\0000\AppData\Local\Programs\Python\Python36-32\lib\site-pac kages\facepy\graph_api.py", line 273, in load result = self._parse(response.content) File "C:\Users\0000\AppData\Local\Programs\Python\Python36-32\lib\site-pac kages\facepy\graph_api.py", line 404, in _parse raise exception(**self._get_error_params(data)) facepy.exceptions.OAuthError: [803] (#803) Some of the aliases you requested do not exist: group_id I have one already created to pull random text from a file and post to a user's page, now I'm trying to do it for groups, but am running into this issue. I've tried to manually add in the ID and scrap the config and still get the same error.
score: 0
tagged with: facepy
has comment: http://stackoverflow.com/comment/83524147
type: Question
has comment: http://stackoverflow.com/comment/83524456
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48311908
has comment: http://stackoverflow.com/comment/83609867
has answer: http://stackoverflow.com/a/48312033
tagged with: loops
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83609685
possible better answer: http://stackoverflow.com/a/48312033
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/48312006
tagged with: python
has answer: http://stackoverflow.com/a/48312006
type: AnsweredQuestion
has title: Index not starting at zero when using PANDAS iterrows() in Python
has comment: http://stackoverflow.com/comment/83609815
has body: I'm running a loop where I iterate through a DataFrame and append an item to a list at each iteration. The code is like this: l=[] for i,row in df.iterrows(): print len(l) print i l.append(df['A']) Getting a situation where i and len(l) are not equal, and i may be different in subsequent runs. My assumption was that i was an integer that increments by one each iteration and starts at zero, but this seems to be incorrect. So, what defines the value of i for each iteration in the loop?
tagged with: pandas
has comment: http://stackoverflow.com/comment/83609860
score: 1

http://stackoverflow.com/comment/84111066
comment on: http://stackoverflow.com/q/48287040
has text: I see. However could you post (in the question not in a comment) the *win32api* code so it's obvious what it *ctypes* counterpart should do?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83632363
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48319633
has text: @Tai Converting the dates was done in the first two lines of my solution, but I moved it up to the data creation if that helps. It was just the formatting from the actual data.
type: Comment

http://stackoverflow.com/a/48231603
type: AcceptedAnswer
downvote count: 0
has body: With your dtype I can create an array: In [37]: np.array([_],dtype=SPECIAL_TYPE) Out[37]: array([ (array([[0, 0, 0], [0, 0, 0], [0, 0, 0]], dtype=uint8), 1, 'a', 1, 1, list([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]), 1)], dtype=[('arr', 'O'), ('int1', 'u1'), ('str', 'O'), ('int2', 'u1'), ('int3', 'u1'), ('list', 'O'), ('int4', 'u1')]) But trying to create dataset with it, even 1d, dumps me out of the interpreter: In [38]: f=h5py.File('vlentest.h5','w') In [39]: db = f.create_dataset('db',(10,), dtype=SPECIAL_TYPE) In [40]: db[:] Segmentation fault (core dumped) There two issues - does vlen work in a 2d array, and does it work in a compound dtype? You are pushing the bounds with multiple vlen in a dtype in a 2d array. Have you seen documentation or examples using vlen in a compound dtype? Notice how h5py implements the vlen in numpy - it defines those fields a 'O' object dtype. That stores a pointer in the array, not the variable length object itself. Normally object dtype arrays cannot be saved with h5py. But these fields must has some added annotation that h5py uses to translate the pointer into the kind of structure that HDF5 accepts. Storing string datasets in hdf5 with unicode explores how a vlen str is stored. Storing multidimensional variable length array with h5py Experimenting, stating with something small In [14]: f = h5py.File('temp.h5') In [15]: db1 = f.create_dataset('db1',(5,), dtype=dt1) In [16]: db2 = f.create_dataset('db2',(5,), dtype=dt2) In [17]: db1[:] Out[17]: array([('',), ('',), ('',), ('',), ('',)], dtype=[('str', 'O')]) In [18]: db2[:] Out[18]: array([('', 0), ('', 0), ('', 0), ('', 0), ('', 0)], dtype=[('str', 'O'), ('int4', '&lt;i4')]) Setting some db1 values: In [24]: db1[0]=('a',) In [25]: db1[1]=('ab',) In [26]: db1[:] Out[26]: array([('a',), ('ab',), ('',), ('',), ('',)], dtype=[('str', 'O')]) db2 works the same way: In [30]: db2[0]=('abc',10) In [31]: db2[1]=('abcde',6) In [32]: db2[:] Out[32]: array([('abc', 10), ('abcde', 6), ('', 0), (…
answers question: http://stackoverflow.com/q/48221841
has comment: http://stackoverflow.com/comment/84023229
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48221841

http://stackoverflow.com/q/48209667
linked to: http://stackoverflow.com/q/53082891
accepted answer: http://stackoverflow.com/a/48209785
tagged with: indexing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65255256
has answer: http://stackoverflow.com/a/48209785
upvote count: 52
has comment: http://stackoverflow.com/comment/125045394
linked to: http://stackoverflow.com/q/52318016
type: Question
has comment: http://stackoverflow.com/comment/119265423
has answer: http://stackoverflow.com/a/71844431
possible better answer: http://stackoverflow.com/a/48211877
has body: I am using monotonically_increasing_id() to assign row number to pyspark dataframe using syntax below: df1 = df1.withColumn("idx", monotonically_increasing_id()) Now df1 has 26,572,528 records. So I was expecting idx value from 0-26,572,527. But when I select max(idx), its value is strangely huge: 335,008,054,165. What's going on with this function? is it reliable to use this function for merging with another dataset having similar number of records? I have some 300 dataframes which I want to combine into a single dataframe. So one dataframe contains IDs and others contain different records corresponding to them row-wise
score: 51
linked to: http://stackoverflow.com/q/48164206
has answer: http://stackoverflow.com/a/48211877
has title: Using monotonically_increasing_id() for assigning row number to pyspark dataframe
has comment: http://stackoverflow.com/comment/99093951
tagged with: pyspark
tagged with: python
has answer: http://stackoverflow.com/a/59103341
tagged with: merge
answer count: 6
downvote count: 1
has comment: http://stackoverflow.com/comment/126839490
has answer: http://stackoverflow.com/a/55059588
favorite count: 0

http://stackoverflow.com/q/48327826
has comment: http://stackoverflow.com/comment/83641601
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/48352260
tagged with: list
has comment: http://stackoverflow.com/comment/83641473
answer count: 3
downvote count: 3
has comment: http://stackoverflow.com/comment/83641361
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83641213
has answer: http://stackoverflow.com/a/48328100
tagged with: python
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48328100
possible better answer: http://stackoverflow.com/a/48328277
has comment: http://stackoverflow.com/comment/83641293
score: -3
has answer: http://stackoverflow.com/a/48328277
has body: I'm new to Python and I'm working with Python 3.4, but I would like to have an answer that could be work generally on Python 3.x. I had 3 lists A, B and C. The first list is a data structure, the second and the third lists are integer values (but if we want to develop a more generic solution they could be of any types). The values contained in the same position of the 3 lists are related. I want to sort all the 3 lists according to the values contained in B or in C. There is an easy way to do that? Example: A = ['orange', 'apple', 'pear', 'kiwi', 'banana'] B = [415, 450, 420, 480, 400] C = [3, 2, 1, 5, 3] Sort according to B: A = ['banana', 'orange', 'pear', 'apple', 'kiwi'] B = [400, 415, 420, 450, 480] C = [3, 3, 1, 2, 5] Thank you very much for your help!
tagged with: sorting
has title: Python 3.x - Sorting 2 or more lists according to the value of 1 of them

http://stackoverflow.com/comment/83354459
score: 0
comment on: http://stackoverflow.com/q/48186608
type: Comment
type: QuestionComment
has text: (If having a space after the opening parenthesis is acceptable, maybe attractiveness is not a factor. Sorry, couldn't resist.)

http://stackoverflow.com/comment/83614303
score: 0
has text: I don't know what your code is trying to do, but make a dictionary with a key `(row[0], row[1])`, and the value being the sum of `row[2]` and you can do everything in one pass.
comment on: http://stackoverflow.com/q/48314209
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48314739
has title: 'Request' object is not iterable
accepted answer: http://stackoverflow.com/a/48314803
linked to: http://stackoverflow.com/q/28760356
answer count: 1
favorite count: 0
type: Question
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83615568
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/83615292
upvote count: 2
type: AnsweredQuestion
score: 2
has body: I am trying to do simple crud demo project API's for mobile using django rest framework and getting below error Project Name : crud_demo App Name : crud_operations crud_demo/urls.py from django.conf.urls import include, url from django.urls import path urlpatterns= [ path('models/', views.model_list), path('models/&lt;int:pk&gt;/', views.model_detail), ] crud_operations/models.py from django.db import models # Create your models here. class Member(models.Model): firstname = models.CharField(max_length=40) lastname = models.CharField(max_length=40) crud_operations/serializers.py from crud_operations.models import Member from rest_framework import serializers class MemberSerializer(serializers.ModelSerializer): class Meta: model = Member fields = ('firstname', 'lastname') crud_operations/views.py from django.shortcuts import render, redirect from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import Member from crud_operations.serializers import MemberSerializer @api_view(['GET', 'POST']) def model_list(request): if request == 'GET': member = Member.objects.all() serializer = MemberSerializer(member) return Response(serializer.data) elif request == 'POST': serializer = MemberSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'key': request}, status=status.HTTP_200_OK) @api_view(['GET', 'PUT', 'DELETE']) def model_detail(request, pk): try: member = Member.objects.get(pk=pk) except Member.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request == 'GET': serializer = MemberSerializer(member) return Response(serializer.data) elif request == 'PUT': serializer = MemberSerializer(member, data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: retu…
downvote count: 0
has answer: http://stackoverflow.com/a/48314803

sl4a
tag name: sl4a
type: Tag
tags question: http://stackoverflow.com/q/48183407
tags question: http://stackoverflow.com/q/48248939

http://stackoverflow.com/comment/83636599
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48267017
score: 0
has text: @Linovia I posted my own answer that preserves the user input in the form.

http://stackoverflow.com/comment/83393996
type: Comment
comment on: http://stackoverflow.com/q/48202387
type: QuestionComment
has text: @ddor254 i am passing both app_key and app_id.
score: 0

http://stackoverflow.com/a/48225098
has comment: http://stackoverflow.com/comment/83462427
answers question: http://stackoverflow.com/q/48206396
type: Answer
has body: I wrote your code in a more better way: my_list = sorted([i*(j**2) for i in range(1, 1000) for j in range(2, 1000)]) However, what you are asking is execution time which for this operation takes a fraction of seconds (around 1.5 second) and what you are seeing is printing time which in different editors and interfaces is different. For example I ran this script in sublime text it took almost 9 minutes while it took 1.4 minute in command line. if you check the length of your list: print len(sorted([i*(j**2) for i in range(1, 1000) for j in range(2, 1000)])) you will see, to print a list with 997002 elements, obviously you should consider an execution time. Another factor which you should take into account is the Big-O Notation which in your case called O(n^2) notation and this run time will exponentially increase if you increase the number of loops.
score: 0

http://stackoverflow.com/q/48276017
has body: I'm building mutation process in genetic algorithm for feature selection. Here is the code: def mutation(pm): sum_mut = int(round(pm*total)) i = 0 while i &lt; sum_mut: mut_row = int(random.random()*total) mut_col = int(random.random()*2393) offspring[mut_col][mut_row] ^= 1 i = i + 1 mutation(0.05) print offspring The mutation process is reversing the bit. Bit 1 means selected feature, and bit 0 means unselected feature. pm is the mutation probability, sum_mut is the sum of mutation, total is sum of all individuals plus offsprings from crossover process. Number 2393 is the sum of features. offspring is a dataframe, consist of all individuals plus offsprings from crossover process. That code doesn't work. Here is the traceback of error: KeyError Traceback (most recent call last) &lt;ipython-input-38-6f4580f1221c&gt; in &lt;module&gt;() 8 mut_col = int(random.random()*2393) 9 offspring[mut_col][mut_row] ^= 1 ---&gt; 10 mutation(0.05) 11 offspring &lt;ipython-input-38-6f4580f1221c&gt; in mutation(pm) 7 mut_row = int(random.random()*total) 8 mut_col = int(random.random()*2393) ----&gt; 9 offspring[mut_col][mut_row] ^= 1 10 mutation(0.05) 11 offspring C:\Users\HEWLETT PACKARD\Anaconda2\lib\site-packages\pandas\core\frame.pyc in __getitem__(self, key) 1962 return self._getitem_multilevel(key) 1963 else: -&gt; 1964 return self._getitem_column(key) 1965 1966 def _getitem_column(self, key): C:\Users\HEWLETT PACKARD\Anaconda2\lib\site-packages\pandas\core\frame.pyc in _getitem_column(self, key) 1969 # get column 1970 if self.columns.is_unique: -&gt; 1971 return self._get_item_cache(key) 1972 1973 # duplicate columns &amp; possible reduce dimensionality C:\Users\HEWLETT PACKARD\Anaconda2\lib\site-packages\pandas\core\generic.pyc in _get_item_cache(self, item) 1643 res = cache.get(item) 1644 if res is None: -&gt; 1645 values = self._data.get(item) 1646 res = self._box_item_values(item, values) 1647 cache[item] = res C:\Users\HEWLETT PACKARD\Anaconda2\lib\site-packages\pandas\co…
tagged with: python
tagged with: mutation
has title: Mutation in Genetic Algorithm: error at reversing bits
has comment: http://stackoverflow.com/comment/83535542
answer count: 0
upvote count: 2
type: UnansweredQuestion
score: 1
tagged with: genetic-algorithm
has comment: http://stackoverflow.com/comment/83536033
has comment: http://stackoverflow.com/comment/83536117
has comment: http://stackoverflow.com/comment/83536551
downvote count: 1
has comment: http://stackoverflow.com/comment/83536359
favorite count: 0
type: Question

http://stackoverflow.com/comment/83378006
score: 0
type: Comment
type: QuestionComment
has text: You should include in `__hash__` all data that you consider part of the object's identity, such that two object's would be equivalent if they had the same values for these attributes. If an attribute isn't important to the object's identity, it can be left out of the hash. And provide a corresponding `__eq__` method.
comment on: http://stackoverflow.com/q/48198383

http://stackoverflow.com/comment/83643136
has text: People are telling you that `if difficulty=="a" or "easy": is wrong Python, it always evaluates to True regardless of the value of `difficulty`. The related duplicate question explains why.
type: QuestionComment
comment on: http://stackoverflow.com/q/48307044
type: Comment
score: 0

http://stackoverflow.com/comment/83546950
type: Comment
has text: @Ta946 As I said use `return np.r_[linv(bins), len(a)]` instead and then slicing. For example `mn, mx = zip(*((np.min(a[l:r]), np.max(a[l:r])) for l, r in zip(bins[:-1], bins[1:])))`.
comment on: http://stackoverflow.com/a/48279403
score: 0
type: AnswerComment

excel
tags question: http://stackoverflow.com/q/48313756
tags question: http://stackoverflow.com/q/48212397
tags question: http://stackoverflow.com/q/48266457
tags question: http://stackoverflow.com/q/48304947
tags question: http://stackoverflow.com/q/48217861
tags question: http://stackoverflow.com/q/48305125
tags question: http://stackoverflow.com/q/48233386
tags question: http://stackoverflow.com/q/48325478
tags question: http://stackoverflow.com/q/48245233
tags question: http://stackoverflow.com/q/48298427
tag name: excel
tags question: http://stackoverflow.com/q/48200757
tags question: http://stackoverflow.com/q/48327714
tags question: http://stackoverflow.com/q/48254575
tags question: http://stackoverflow.com/q/48192424
tags question: http://stackoverflow.com/q/48189688
tags question: http://stackoverflow.com/q/48233266
tags question: http://stackoverflow.com/q/48179039
tags question: http://stackoverflow.com/q/48183643
type: Tag
tags question: http://stackoverflow.com/q/48299320
tags question: http://stackoverflow.com/q/48181949
tags question: http://stackoverflow.com/q/48308619
tags question: http://stackoverflow.com/q/48288164
tags question: http://stackoverflow.com/q/48247361
tags question: http://stackoverflow.com/q/48226392
tags question: http://stackoverflow.com/q/48199383
tags question: http://stackoverflow.com/q/48244679
tags question: http://stackoverflow.com/q/48273159
tags question: http://stackoverflow.com/q/48253244
tags question: http://stackoverflow.com/q/48216974
tags question: http://stackoverflow.com/q/48269813
tags question: http://stackoverflow.com/q/48313420
tags question: http://stackoverflow.com/q/48200628
tags question: http://stackoverflow.com/q/48236905
tags question: http://stackoverflow.com/q/48177174
tags question: http://stackoverflow.com/q/48280260
tags question: http://stackoverflow.com/q/48315405
tags question: http://stackoverflow.com/q/48315988
tags question: http://stackoverflow.com/q/48237024

http://stackoverflow.com/q/48287316
tagged with: textblob
downvote count: 0
has comment: http://stackoverflow.com/comment/83559663
upvote count: 1
score: 1
favorite count: 0
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48288384
has answer: http://stackoverflow.com/a/48288384
has comment: http://stackoverflow.com/comment/83560546
tagged with: http://stackoverflow.com/tag/csv
has body: I used sentiment analysis on a CSV file and the output prints the polarity and subjectivity of a sentence. How can I get the output in a table format along with the classification of the sentence as positive or negative or neutral added to it? import csv from textblob import TextBlob infile = 'sentence.csv' with open(infile, 'r') as csvfile: rows = csv.reader(csvfile) for row in rows: sentence = row[0] blob = TextBlob(sentence) print (sentence) print (blob.sentiment.polarity, blob.sentiment.subjectivity) the output for my code is : i am very happy 1.0 1.0 its very sad -0.65 1.0 they are bad -0.6999999999999998 0.6666666666666666 hate the life -0.8 0.9 she is so fantastic 0.4 0.9 Thanks in advance.
tagged with: python
has comment: http://stackoverflow.com/comment/83560581
tagged with: sentiment-analysis
has title: Sentiment analysis on a csv file using textblob
answer count: 1

http://stackoverflow.com/q/48198670
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83379270
answer count: 2
has answer: http://stackoverflow.com/a/48198746
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83378588
has comment: http://stackoverflow.com/comment/83379200
upvote count: 1
has body: I have a file that have this format: username password (base64 encoded) id I have to read this password (base64 encoded) and decode it to pass as a paramater in the password to authenticate. The problem is, when I read this password it is being readed as string and I get an error when I try to decode because this is expecting to be bytes. def getSecret(self): home = expanduser("~/.user/credentials") with open(home,"r") as file: self.password = list(file)[1] self.password = base64.b64decode(self.password) return self.password conn = User() decode = base64.b64decode(conn.getSecret()) print(decode) But this is returning a string and should be bytes, when I try to decode this i got this error return binascii.a2b_base64(s) binascii.Error: Incorrect padding How can I read and decode this? Thank you.
downvote count: 1
has answer: http://stackoverflow.com/a/48208571
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/83396983
has title: Converting string to bytes
tagged with: python
tagged with: shell

http://stackoverflow.com/comment/83501570
type: QuestionComment
score: 1
has text: You need to provide more details - dataset size, dataset type, the output from your network, etc.
type: Comment
comment on: http://stackoverflow.com/q/48259290

http://stackoverflow.com/q/48251545
downvote count: 2
has answer: http://stackoverflow.com/a/60258091
has answer: http://stackoverflow.com/a/48265189
upvote count: 7
tagged with: opencv
has title: module 'cv2.cv2' has no attribute 'cv'
has comment: http://stackoverflow.com/comment/83485564
tagged with: python
has body: import cv2 import numpy as np cap = cv2.VideoCapture('1.MP4') fourcc = cv2.FOURCC(*'XVID') out = cv2.videoWriter('output.avi',fourcc,20.0,(640,480)) while (1): #Capture frame-by-frame #ret = cap.set(3,960),cap.set(4,720) ret, frame = cap.read() if ret == True: frame = cv2.flip(frame,0) out.write(frame) cv2.imshow('frame',frame) if cv2.waitKey(1) == ord('q'): break else: break cap.release() out.release() cv2.destroyAllWindows() As is shown above ,this is a demo in opencv document.while it can work in my PC. Traceback like this: Traceback (most recent call last): File "E:\opencv\Pic\test.py", line 34, in &lt;module&gt; fourcc = cv2.cv.FOURCC(*'XVID') AttributeError: module 'cv2.cv2' has no attribute 'cv' And i also see some solution such as change cv2.cv to cv2 ,while the traceback below: Traceback (most recent call last): File "E:\opencv\Pic\test.py", line 34, in &lt;module&gt; fourcc = cv2.FOURCC(*'XVID') AttributeError: module 'cv2.cv2' has no attribute 'FOURCC' i am very thanks any warm heart solution for my question.
linked to: http://stackoverflow.com/q/15584608
favorite count: 0
type: Question
answer count: 2
score: 5
type: UnansweredQuestion

http://stackoverflow.com/q/48285534
has comment: http://stackoverflow.com/comment/83555819
tagged with: python
has body: I'm currently working on a python problem: Given a number line from -infinity to +infinity. You start at 0 and can go either to the left or to the right. The condition is that in i’th move, you take i steps. In the first move take 1 step, second move 2 steps and so on. Hint: 3 can be reached in 2 steps (0, 1) (1, 3). 2 can be reached in 3 steps (0, 1) (1,-1) (-1, 2) a) Find the optimal number of steps to reach position 1000000000 and -1000000000. I have managed to code the following: def steps(source, step, dest): if abs(source) &gt; dest: return sys.maxint if source == dest: return step pos = steps(source+step+1, step+1, dest) neg = steps(source-step-1, step+1, dest) return min(pos, neg) The problem is that even though this function gives me the correct answer, it cannot extend to the range asked of me. Is there a work around for this or would I have to go about a different method of solving the question?
score: 2
has answer: http://stackoverflow.com/a/48285799
answer count: 2
upvote count: 2
tagged with: function
downvote count: 0
has title: Python Recursion Limit Work Around
has comment: http://stackoverflow.com/comment/83555732
has comment: http://stackoverflow.com/comment/83555717
favorite count: 0
type: Question
tagged with: recursion
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48285705

http://stackoverflow.com/q/48267934
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83519014
type: Question
has title: Windows Python 3.6.4: Can't find IDLE
has comment: http://stackoverflow.com/comment/83519268
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83519052
has comment: http://stackoverflow.com/comment/83519109
has comment: http://stackoverflow.com/comment/83518958
tagged with: python
has comment: http://stackoverflow.com/comment/83519440
accepted answer: http://stackoverflow.com/a/48268062
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48268062
has comment: http://stackoverflow.com/comment/83519201
has body: I just installed the newest version of python (3.6.4) and I just had it upgrade from python 3.6.2 but now I can't find IDLE. Please help I really need to get my work done.
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/83518995
answer count: 1
has comment: http://stackoverflow.com/comment/83519461

http://stackoverflow.com/comment/83441199
score: 0
has text: I am using 100 points for training and 6 parameters.. Do you think this is causing the problem ?
comment on: http://stackoverflow.com/q/48219986
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83329572
has text: For flake8 in particular I *always* install that into my venv, because I rely on that for syntax error checking in my editor so it needs to be using the same version of python for which I am currently developing...
comment on: http://stackoverflow.com/a/48174818
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48252473
linked to: http://stackoverflow.com/q/21046717
has title: Passing different raw_input to a function being tested in Python
tagged with: python-unittest
tagged with: python
has answer: http://stackoverflow.com/a/48252615
accepted answer: http://stackoverflow.com/a/48252615
has comment: http://stackoverflow.com/comment/83488354
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83488169
has body: I want to test with unittest a function in Python (2.7) that use different raw_input. How can I achieve this? Function (in module fc): def main(): name = raw_input("name: ").lower() surname = raw_input("surname: ").lower() birth_date = raw_input("Birth date (dd/mm/yyyy): ").lower() city = raw_input("city: ").lower() sex = raw_input("sex (m/f): ").lower() #other tasks... test function: import fc import unittest class test_main_fc(unittest.TestCase): def test_main(self): #how can I give to main the parameters that will ask? self.assertEqual(fc.main(), 'rssmra80a01l781k') if __name__ == '__main__': unittest.main() The solution I could find, this, works for 1 input passed at a time. I want to know how to pass different values to the main function. This works for only 1 value of raw_input requested, in this case, name. class test_main_fc(unittest.TestCase): def test_fc_output(self): original_raw_input = __builtins__.raw_input __builtins__.raw_input = lambda _: 'mario' #capturing the output with captured_output() as (out, err): fc.main() output = out.getvalue().strip() self.assertEqual(output, 'rssmra80a01l781k') __builtins__.raw_input = original_raw_input
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83488437
favorite count: 0
type: Question

http://stackoverflow.com/q/48322332
answer count: 1
has answer: http://stackoverflow.com/a/48372987
has comment: http://stackoverflow.com/comment/83630084
has comment: http://stackoverflow.com/comment/83643689
type: Question
linked to: http://stackoverflow.com/q/24490090
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83630000
has comment: http://stackoverflow.com/comment/83630217
has comment: http://stackoverflow.com/comment/83630078
tagged with: python
has body: I want to call the function onClick in order to return x and y positions of the mouse click. However, I am not sure what event to put when calling the function. When I print the event, I get &lt;MouseClickEvent (420,306) button=1&gt;. This is my code for clicking: def onClick(event): print(event) return(x, y) w1.scene().sigMouseClicked.connect(onClick) I am trying to call my function print(onClick(------)) and MOUSEPRESSEVENT, MouseClickEvent, and Button=1 do not work when filling in the parameters for onClick(). How do I fix this?
tagged with: mouseevent
tagged with: onclick
linked to: http://stackoverflow.com/q/27222016
accepted answer: http://stackoverflow.com/a/48372987
tagged with: pyqt
score: 0
has title: Parameters for calling onClick() function not working?

http://stackoverflow.com/a/48232005
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: The open function expects a path-like object that points to a file in an existing directory. When the directory does not exist an error is raised, in my case in Python 3.6 the error is: NotADirectoryError: [Errno 20] Not a directory: '/Users/grr/datei.log/' As @cᴏʟᴅsᴘᴇᴇᴅ pointed out the trailing os.sep adds a '/' at the end of your file descriptor making it appear to be a path instead of a file. This is what is causing the error.
accepted answer of: http://stackoverflow.com/q/48231893
answers question: http://stackoverflow.com/q/48231893
type: Answer
has comment: http://stackoverflow.com/comment/121668350
score: 1

http://stackoverflow.com/comment/138144629
type: Comment
has text: Gunicorn will load your app for each of your workers. 4 workers means 4 separate copies of your apps are loaded for each workers. But you can [preload the app](https://docs.gunicorn.org/en/stable/settings.html#preload-app) before forking the worker processes, but again [workers will have a separate copy of the app](https://stackoverflow.com/a/47413626/2455888).
comment on: http://stackoverflow.com/a/48174868
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83489746
has text: the problem is that you overwrite `lunch` list with `lunch=input()`
comment on: http://stackoverflow.com/q/48253593
type: Comment
score: 4
type: QuestionComment

http://stackoverflow.com/comment/83414320
type: QuestionComment
comment on: http://stackoverflow.com/q/48215892
has text: I've tried several different WebDriverWaits... they say "'str' object is not callable"
score: 0
type: Comment

http://stackoverflow.com/comment/83419534
comment on: http://stackoverflow.com/q/48217961
type: Comment
type: QuestionComment
has text: Hi, I have Modified my code (functions "ResultTablePanel" and "analysisOrder"), and my last paragraph, hopefully this will make my question more clear. As I have "ResultTablePanel" and "SearchConditionPanel" imported by different pages of different notebooks, my question is how do I pass variables from "SearchConditionPanel" to "ResultTablePanel" within any specific page of a notebook. Thanks.
score: 0

http://stackoverflow.com/q/48304365
has title: Creating a list of groups of pairs under constraint
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48304614
favorite count: 0
has comment: http://stackoverflow.com/comment/83594096
has answer: http://stackoverflow.com/a/48306198
tagged with: algorithm
score: 1
tagged with: python
has body: I'm trying to create a list of groups of pairs given a list of pairs, e.g., [(a1,b1), (a2,b2)...] such that all tuples in each resulting group satisfies the constraint abs(ai - aj) &lt; 2 and abs(bi - bj) &lt; 3. For instance, given: [(1, 2), (2, 3), (6, 4), (7, 5), (8, 15)] the result will be a list of 3 groups: [[(1, 2), (2, 3)], [(6, 4), (7, 5)], [(8, 15)]]. Similarly: [(1, 2), (2, 3), (6, 2), (9, 3), (10, 4)] -> [[(1, 2), (2, 3)], [(6, 2)], [(9, 3), (10, 4)]] [(1, 2), (2, 3), (6, 2), (7, 4), (8, 15)] -> [[(1, 2), (2, 3)], [(6, 2), (7, 4)], [(8, 15)]] Does anyone know of an efficient way to create the groups?
type: Question
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83599566

http://stackoverflow.com/comment/83606742
score: 2
type: Comment
has text: Could you add the (minimized) code that "creates the numpy array of strings in a C extension module" and gives you the wrong result?
type: QuestionComment
comment on: http://stackoverflow.com/q/48310452

http://stackoverflow.com/a/53447648
score: 1
answers question: http://stackoverflow.com/q/48258687
type: Answer
has body: After consideration making use of django permissions (which are added to the context via a context processor automatically) is the best route in my opinion. Using something like this in the template: {% if perms.foo.can_vote %} However, in my case I cut corners and make a query for all the leave approvers in the base template which is much slower than the prebuilt perms in the context. {% if user in user.company.leave_approvers.all %} Pending Leave Approval {% endif %}
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48258687

http://stackoverflow.com/q/48301186
accepted answer: http://stackoverflow.com/a/48301735
has answer: http://stackoverflow.com/a/48301637
possible better answer: http://stackoverflow.com/a/48301637
has body: How can I crop a concave polygon from an image. My Input image look like . and the coordinates of closed polygon are [10,150],[150,100],[300,150],[350,100],[310,20],[35,10]. I want region bounded by concave polygon to be cropped using opencv. I searched for other similar questions but I did not able to find correct answer. That's why I am asking it ? Can you help me. Any help would be highly appreciated.!!!
score: 29
upvote count: 29
has answer: http://stackoverflow.com/a/72167488
tagged with: crop
has title: Cropping Concave polygon from Image using Opencv python
favorite count: 0
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83586893
answer count: 3
tagged with: python
tagged with: image-processing
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/48301735

windows
tags question: http://stackoverflow.com/q/48312986
tags question: http://stackoverflow.com/q/48273449
tags question: http://stackoverflow.com/q/48182760
tags question: http://stackoverflow.com/q/48244232
tags question: http://stackoverflow.com/q/48213358
tags question: http://stackoverflow.com/q/48295658
tags question: http://stackoverflow.com/q/48314069
tags question: http://stackoverflow.com/q/48231948
tags question: http://stackoverflow.com/q/48217036
tags question: http://stackoverflow.com/q/48322679
tags question: http://stackoverflow.com/q/48328526
tags question: http://stackoverflow.com/q/48215944
type: Tag
tags question: http://stackoverflow.com/q/48247027
tags question: http://stackoverflow.com/q/48195422
tags question: http://stackoverflow.com/q/48256307
tags question: http://stackoverflow.com/q/48323677
tags question: http://stackoverflow.com/q/48310132
tags question: http://stackoverflow.com/q/48311909
tags question: http://stackoverflow.com/q/48224674
tags question: http://stackoverflow.com/q/48219591
tags question: http://stackoverflow.com/q/48241779
tag name: windows
tags question: http://stackoverflow.com/q/48306314
tags question: http://stackoverflow.com/q/48184995
tags question: http://stackoverflow.com/q/48308350
tags question: http://stackoverflow.com/q/48191922
tags question: http://stackoverflow.com/q/48251934
tags question: http://stackoverflow.com/q/48318443
tags question: http://stackoverflow.com/q/48210938
tags question: http://stackoverflow.com/q/48271869
tags question: http://stackoverflow.com/q/48307078
tags question: http://stackoverflow.com/q/48241595

http://stackoverflow.com/comment/83626172
type: Comment
type: QuestionComment
score: 0
has text: Maybe: read all items, compare with what needs to be added and then only add what is not already in the file.
comment on: http://stackoverflow.com/q/48320483

http://stackoverflow.com/q/48303022
answer count: 1
has answer: http://stackoverflow.com/a/48345788
accepted answer: http://stackoverflow.com/a/48345788
favorite count: 0
type: Question
tagged with: gunicorn
has title: How to deploy the airbnb knowledge feed
tagged with: python
has body: I have been using airbnbs knowledge repo on local host. The problem is that I have very little web dev experience so I am pretty clueless on how to get this to run on online, preferably on a password protected site. Thus far I have only used runserver to view the knowledge feed. I would now like to deploy. It does not matter to me where it deploys. It could be a custom domain name, or heroku, or anything else. I am just a little lost on how to deploy. From reading the documentation I got this far. knowledge_repo --repo app/ deploy From this I get the following: INFO:knowledge_repo.repositories.gitrepository:Fetching updates to the knowledge repository... INFO:alembic.runtime.migration:Context impl SQLiteImpl. INFO:alembic.runtime.migration:Will assume non-transactional DDL. [2018-01-09 19:33:58 -0500] [17729] [INFO] Starting gunicorn 19.7.1 [2018-01-09 19:33:58 -0500] [17729] [INFO] Listening at: http://0.0.0.0:7000 [2018-01-09 19:33:58 -0500] [17729] [INFO] Using worker: sync [2018-01-09 19:33:58 -0500] [17772] [INFO] Booting worker with pid: 17772 [2018-01-09 19:33:58 -0500] [17775] [INFO] Booting worker with pid: 17775 [2018-01-09 19:33:58 -0500] [17778] [INFO] Booting worker with pid: 17778 [2018-01-09 19:33:58 -0500] [17781] [INFO] Booting worker with pid: 17781 This is obviously only viewable on my computer at http://0.0.0.0:7000. How do I make this deployable to the web?
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
tagged with: heroku
upvote count: 3
score: 3
downvote count: 0
tagged with: knowledge-repo

http://stackoverflow.com/comment/83478232
comment on: http://stackoverflow.com/q/48247844
score: 0
has text: Those aren't arrays....
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83523076
type: Comment
type: AnswerComment
score: 0
has text: The purpose of using "if dummy" is to check if dummy list is empty or not. The code that I've shared in question works well for arrays with more than one members.
comment on: http://stackoverflow.com/a/48269557

http://stackoverflow.com/comment/83617085
comment on: http://stackoverflow.com/a/48315596
score: 0
has text: What do you mean i dont understand
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83529468
has text: @EricPostpischil Been through all that, none of those tests show the issue as they all behave as expected. Stefan figured it out see answer below.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48272389
type: QuestionComment

http://stackoverflow.com/q/48184882
tagged with: python
tagged with: cython
upvote count: 2
tagged with: ctypes
has title: Use python ctypes array data in cython functions
has body: I have python ctypes array. I would like to use it in cython def and cdef functions. import ctypes from my_cython_extention import * class Test_Node(ctypes.Structure): _fields_ = [ ("i", ctypes.c_int), ("f", ctypes.c_float), ] my_array = (Test_Node * 10)() my_cython_function(my_array) How should I define cython function my_cython_function to access my_array data? Can I get my_array C++ data pointer?
type: UnansweredQuestion
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48186940
type: Question
score: 2

http://stackoverflow.com/q/48308910
has comment: http://stackoverflow.com/comment/83603397
tagged with: python
has comment: http://stackoverflow.com/comment/83603460
has title: Unsure with Dijkstra's algorithm
has comment: http://stackoverflow.com/comment/83603474
downvote count: 2
upvote count: 0
answer count: 1
favorite count: 0
has body: With the help of so many people on this site, I have some brilliant code. Unfortunately, the Dijkstra Algorithm doesn't work. It is supposed to find the shortest distance between the AI and the player and move the AI closer to the player. I don't know how to get this to return a path and how to move the AI one step closer to the player or even if it works as I intended it to. def search(x, y): if maze[x][y] == visblock(): return False elif maze[x][y] == 3: return False elif maze[x][y] == player(): print("Found Player") return True maze[x][y] = 3 if ((x &lt; 5 - 1 and search(x+1, y)) or (y &gt; 0 and search(x, y+1)) or (x &gt; 0 and search(x-1, y)) or (y &lt; 5-1 and search(x, y-1))): return True return False
tagged with: dijkstra
type: Question
tagged with: recursion
has answer: http://stackoverflow.com/a/48309491
type: UnansweredQuestion
score: -2

http://stackoverflow.com/comment/83477560
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48247401
has text: from the max value in the data, thank you for the input, jezrael line of code got me the needed value. thanks again guys.
score: 0

http://stackoverflow.com/a/48327508
has comment: http://stackoverflow.com/comment/83646297
accepted answer of: http://stackoverflow.com/q/48326897
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48326897
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83640793
type: Answer
has body: I suspect there is a more efficient way to do this, but simple way to do it is to build a dict of counts and then prune if those values are below the count threshold. Consider the example df: df= pd.DataFrame([12,11,4,15,6,12,4,7],columns=['foo']) foo 0 12 1 11 2 4 3 15 4 6 5 12 6 4 7 7 # make a dict with counts count_dict = {d:(df['foo']==d).sum() for d in df.foo.unique()} # assign that dict to a column df['bar'] = [count_dict[d] for d in df.foo] # loc in the 'pruned' tag df.loc[df.bar &lt; 2, 'foo']='pruned' Returns as desired: foo bar 0 12 2 1 pruned 1 2 4 2 3 pruned 1 4 pruned 1 5 12 2 6 4 2 7 pruned 1 (and of course you would change 2 to 5 and dump that bar column if you want). UPDATE Per request for an in-place version, here is a one-liner that can do it without assigning another column or creating that dict directly (and thanks @TrigonaMinima for the values_count() tip): df= pd.DataFrame([12,11,4,15,6,12,4,7],columns=['foo']) print(df) df.foo = df.foo.apply(lambda row: 'pruned' if (df.foo.value_counts() &lt; 2)[row] else row) print(df) which returns again as desired: foo 0 12 1 11 2 4 3 15 4 6 5 12 6 4 7 7 foo 0 12 1 pruned 2 4 3 pruned 4 pruned 5 12 6 4 7 pruned
has comment: http://stackoverflow.com/comment/83649023

http://stackoverflow.com/comment/83440109
type: QuestionComment
has text: Why are you setting the `content-type` header in your python code, when you're not setting this with `curl`?
comment on: http://stackoverflow.com/q/48229059
score: 0
type: Comment

http://stackoverflow.com/q/48216951
upvote count: 6
favorite count: 0
accepted answer: http://stackoverflow.com/a/48218341
linked to: http://stackoverflow.com/q/37278647
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/29296064
has answer: http://stackoverflow.com/a/48218341
downvote count: 0
score: 6
tagged with: python
linked to: http://stackoverflow.com/q/36342899
has body: What is the pythonic way to push a coroutine onto an event thread from outside of the event thread?
has title: Python asyncio difference between loop.create_task and asyncio.run_coroutine_threadsafe
type: AnsweredQuestion
tagged with: python-asyncio
answer count: 1

http://stackoverflow.com/a/48275291
has comment: http://stackoverflow.com/comment/83534122
downvote count: 1
has body: Just use the u prefix by itself. In Python 2.7: &gt;&gt;&gt; reg = u"((?P&lt;initial&gt;[+\-])(?P&lt;rest&gt;.+?))$" &gt;&gt;&gt; re.match(reg, u"hello").groupdict() {'initial': '', 'rest': 'hello'}
has comment: http://stackoverflow.com/comment/83534180
has comment: http://stackoverflow.com/comment/83534062
answers question: http://stackoverflow.com/q/48274890
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/83697026
has comment: http://stackoverflow.com/comment/83534165
has comment: http://stackoverflow.com/comment/83534337
score: 3
has comment: http://stackoverflow.com/comment/83534186

http://stackoverflow.com/a/48272433
type: Answer
upvote count: 2
score: 2
downvote count: 0
has body: Mark's morphology method is a little simpler than this. So I suggest going with it as the best method so far. But here is a similar method (kind of a hybrid of his last two methods) that may be of interest. I have include +write tmpX.png to show the steps. Those can be removed. (Unix Syntax using Imagemagick 6.9.9.33) convert original.png \ \( -clone 0 -morphology edgeout square:3 -negate +write tmp1.png \) \ \( -clone 0 -morphology dilate square:3 \ -morphology edge square:3 +write tmp2.png \) \ -delete 0 \ -evaluate-sequence max \ result.png Line 1: reads the input Line 2 - tmp1.png: uses morphology edgeout to convert the image to black curves with black box around them on a white background (as in Mark's other example). Line 3 and 4 - tmp2.png: uses morphology dilate (to remove the curves) and edge to just create a white outline box around the white areas on a black background. Line 6 and 7: result.png removes the black box in the tmp1.png using tmp2.png by taking the maximum between the two images pixel-by-pixel. For comparison, here is Mark's elegant method that I have simplified a little: convert original.png \ \( +clone -morphology close square:3 -negate +write tmp1.png \) \ -evaluate-sequence max \ result.png Line 1: read the input Line 2: - tmp1.png: use morphology close (same as dilate and erode) to create a black box to replace the white area including the black curve in the original. The square size can be as low as 3, but not lower for this to work. The smaller the less is removed from the curve ends. Line 3: remove all the black in the original other than the curves by computing the maximum between the two image pixel-by-pixel.
answers question: http://stackoverflow.com/q/48251501

deserialization
type: Tag
tags question: http://stackoverflow.com/q/48327661
tag name: deserialization

http://stackoverflow.com/q/48250877
downvote count: 0
tagged with: local-variables
has comment: http://stackoverflow.com/comment/83484262
upvote count: 1
has title: In ipython, how to get a list of all local variables of a specific type and with a pattern?
favorite count: 0
has answer: http://stackoverflow.com/a/48251006
type: AnsweredQuestion
tagged with: python
accepted answer: http://stackoverflow.com/a/48251006
score: 1
has body: For example, I have created 5 pd.DataFrames in the working space, which are: trade_i = pd.DataFrame(np.random.rand(5, 2)) trade_xt = pd.DataFrame(np.random.rand(5, 2)) trade_mmt = pd.DataFrame(np.random.rand(5, 2)) trade_pg = pd.DataFrame(np.random.rand(5, 2)) trade_fg = pd.DataFrame(np.random.rand(5, 2)) As you can see, the types are all pandas.core.frame.DataFrame, and startswith trade_: type(trade_fg) Out[508]: pandas.core.frame.DataFrame So, how can I return a list of them? not just returning the name of the variables in a list. So far, I can get the names of the variables startswtih trade_ in a list like this: df_list = [x for x in dir() if x.startswith('trade_')] df_list Out[514]: ['trade_i', 'trade_xt', 'trade_mmt', 'trade_pg', 'trade_fg'] But this is not what I want. And by the way, the reason that I want to return these dataFrame variables in a list is to append one column for each of them.
type: Question
possible better answer: http://stackoverflow.com/a/48250969
answer count: 2
has comment: http://stackoverflow.com/comment/83484186
has answer: http://stackoverflow.com/a/48250969

http://stackoverflow.com/q/48322679
has title: How to route pip specific version to a specific python version?
has body: Currently i have python2.7 with pip v9.0.1 routed on this location c:\python27\lib\site-packages (python 2.7) Now when i installed python3.6 using installation wizard, it messed up. running python on cmd always refers to python3. $ python Python 3.6 &gt;&gt;&gt; To solve i need to do this: $ set-alias py2 c:\python27\python.exe $ set-alias py3 c:\python36\python.exe Now how can i do the same way for pip? python3 has its own pip installed from the wizard. when running pip and pip3 it always yield this result $ pip pip 9.0.1 from c:\python36\lib\site-packages (python 3.6) $ pip3 pip 9.0.1 from c:\python36\lib\site-packages (python 3.6)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83631847
upvote count: 0
accepted answer: http://stackoverflow.com/a/48323528
answer count: 1
has answer: http://stackoverflow.com/a/48323528
duplicate of: http://stackoverflow.com/q/34803040
downvote count: 1
has comment: http://stackoverflow.com/comment/83631510
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/34803040
has comment: http://stackoverflow.com/comment/83632318
tagged with: windows
tagged with: pip
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83631901

http://stackoverflow.com/q/48183074
tagged with: wagtail
has title: Does Easy-Thumbnails use a "box" parameter in order to crop an image?
has answer: http://stackoverflow.com/a/48217352
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83351528
type: AnsweredQuestion
score: 0
has body: I'm developing a website with: Python Django Wagtail In this project there are a lot of images and all of them have an ugly yellow border. In order to remove this border I need to crop all the images sistematically. Every image has its own focal area (feature supplied by wagtail), a box that exclude the yellow border. However the standard tool for cropping, of wagtail, is useless in this situation and to achieve my goal I've decided to use easy-thumbnails. Here an example of code in which I use the focal_point of image_object to set all the parameters needed for the cropping operation: parameters = { 'size': (width, height), 'crop': True, 'detail': False, 'upscale': False, } if image_object.has_focal_point(): focal_point = image_object.get_focal_point() parameters['box'] = "%s,%s,%s,%s" % ( int(focal_point.left), int(focal_point.top), int(focal_point.right - focal_point.left), int(focal_point.bottom - focal_point.top), ) return get_thumbnailer(image_object.file).get_thumbnail(parameters, generate=True).url My question is about the "box" parameter. I can't find it on the easy thumbnails docs but I've found examples of use around internet. Can anyone tell me where I can found any reference about it? Or at least a list of all the parameters allowed with the get_thumbnail method? Thanks in advance, nifel87
answer count: 1
tagged with: easy-thumbnails
type: Question
accepted answer: http://stackoverflow.com/a/48217352

http://stackoverflow.com/comment/83341826
type: Comment
type: QuestionComment
has text: Can you please show what you tried?
comment on: http://stackoverflow.com/q/48180935
score: 1

http://stackoverflow.com/comment/83516562
comment on: http://stackoverflow.com/q/48266450
score: 0
type: Comment
type: QuestionComment
has text: You're overwriting the cell in column B every time you loop through `n`.

http://stackoverflow.com/a/48216465
has comment: http://stackoverflow.com/comment/83414926
accepted answer of: http://stackoverflow.com/q/48216417
answers question: http://stackoverflow.com/q/48216417
type: Answer
has body: There's a bug with your format. As @MaxU commented, if you don't pass a format argument, then pandas will automagically convert your column to datetime. df['Timestamp'] = pd.to_datetime(df['A']) Or, to fix your code - df['Timestamp'] = pd.to_datetime(df['A'], format='%m/%d/%Y %H:%M') For your first query, use dt.normalize or, dt.floor (thanks, MaxU, for the suggestion!) - df['Date'] = df['Timestamp'].dt.normalize() Or, df['Date'] = df['Timestamp'].dt.floor('D') For your second query, use dt.time. df['Time'] = df['Timestamp'].dt.time df.drop('A', 1) Date Time Timestamp 0 2008-01-23 15:41:00 2008-01-23 15:41:00 1 2010-03-10 14:42:00 2010-03-10 14:42:00 2 2010-10-14 15:23:00 2010-10-14 15:23:00 3 2008-01-02 11:39:00 2008-01-02 11:39:00 4 2008-04-03 13:35:00 2008-04-03 13:35:00 5 2008-05-02 09:29:00 2008-05-02 09:29:00
has comment: http://stackoverflow.com/comment/83415887
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48276504
score: 0
has comment: http://stackoverflow.com/comment/83825904
has comment: http://stackoverflow.com/comment/83783726
has comment: http://stackoverflow.com/comment/83540252
has comment: http://stackoverflow.com/comment/83782240
has comment: http://stackoverflow.com/comment/83540380
has comment: http://stackoverflow.com/comment/83796750
has comment: http://stackoverflow.com/comment/83783931
has body: You can use: #convert to list of df with condition for add list L = [pd.DataFrame(x) if isinstance(x, list) else pd.DataFrame([x]) for x in df['b']] #join together, reshape and remove all NaNs columns df1 = pd.concat(L, keys=df.index).unstack().dropna(how='all', axis=1) #flattening MultiIndex in columns df1.columns = ['{}{}'.format(a,b) for a,b in df1.columns] print (df1) c0 c1 d0 0 1.0 3.0 NaN 1 NaN NaN 3.0 2 5.0 NaN 6.0 #remove original column b and join df1 df = df.drop('b',1).join(df1) print (df) a c0 c1 d0 0 1 1.0 3.0 NaN 1 2 NaN NaN 3.0 2 3 5.0 NaN 6.0
answers question: http://stackoverflow.com/q/48276313
has comment: http://stackoverflow.com/comment/83782281
has comment: http://stackoverflow.com/comment/83544115
type: Answer
has comment: http://stackoverflow.com/comment/83798122
has comment: http://stackoverflow.com/comment/83833687
has comment: http://stackoverflow.com/comment/83800693
has comment: http://stackoverflow.com/comment/83833740
has comment: http://stackoverflow.com/comment/83540303
has comment: http://stackoverflow.com/comment/83540140
has comment: http://stackoverflow.com/comment/83837554

http://stackoverflow.com/a/50694172
has body: You can use something like below from django.db import connections conn = connections['default'] conn.connect() or from django.db import connection connection.connect()
answers question: http://stackoverflow.com/q/48329685
type: Answer
score: 85
accepted answer of: http://stackoverflow.com/q/48329685
has comment: http://stackoverflow.com/comment/131867508
upvote count: 85
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83570511
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/48291931
has text: `einsum` literally contracts the for loops as shown, there are no temporaries built.
type: Comment

http://stackoverflow.com/a/48188499
has comment: http://stackoverflow.com/comment/83426368
has comment: http://stackoverflow.com/comment/83426290
type: Answer
has comment: http://stackoverflow.com/comment/83426678
has comment: http://stackoverflow.com/comment/83426770
upvote count: 3
score: 3
has body: I backup your source image, avoid you replace or delete it. I analysis the image in different ColorSpace, and find the B(BGR) channel is good for your task. Then do following steps: Read and extract the blue channel. Threshold the blue channel. Find contours. Filter by area. The code and the result. #!/usr/bin/python3 # 2017.12.09 00:25:47 CST # 2018.01.10 21:10:07 CST import cv2 import numpy as np ## (1) read and extract the blue channel img = cv2.imread("img01.png") blue = img[...,0] ## (2) threshold the blue th, threshed = cv2.threshold(blue, 200, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU) ## (3) find contours cnts = cv2.findContours(threshed,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)[-2] ## (4) filter by AREA canvas = img.copy() H,W = img.shape[:2] AREA = H*W for cnt in cnts: area = cv2.contourArea(cnt) if not AREA/100&lt;area&lt;AREA/20: continue box = cv2.minAreaRect(cnt) box = cv2.boxPoints(box) box = np.array(box,dtype="int") cv2.drawContours(canvas, [box], -1,(255,0,255) , 2, cv2.LINE_AA) ## save cv2.imwrite("result.png", canvas) Similar questions: (1) How to find the object on the noisy background? (2) Python OpenCV - Trying to identify a completely visible tile (all four edges are visible) and draw a green contour edges
answers question: http://stackoverflow.com/q/48181764
downvote count: 0
has comment: http://stackoverflow.com/comment/83428654
has comment: http://stackoverflow.com/comment/83428360
has comment: http://stackoverflow.com/comment/83428087
has comment: http://stackoverflow.com/comment/83426906
has comment: http://stackoverflow.com/comment/83427367
has comment: http://stackoverflow.com/comment/84231176

http://stackoverflow.com/comment/83544591
type: Comment
has text: Hi thanks for this. I am sure it will help. The only issue I now having running the code is the message: .... line 28, in <module> root = tk.Tk() NameError: name 'tk' is not defined
type: AnswerComment
comment on: http://stackoverflow.com/a/48276807
score: 0

http://stackoverflow.com/a/48228766
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83453721
answers question: http://stackoverflow.com/q/48217961
has comment: http://stackoverflow.com/comment/83532994
upvote count: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83532985
has comment: http://stackoverflow.com/comment/83455168
score: 2
has comment: http://stackoverflow.com/comment/83451560
has comment: http://stackoverflow.com/comment/83449022
accepted answer of: http://stackoverflow.com/q/48217961
has body: I usually recommend using Pubsub for this sort of thing. It's very easy to implement and makes it easy to pass a message to one or more recipients (panels). Here's a simple example: import wx from wx.lib.pubsub import pub class OtherFrame(wx.Frame): """""" def __init__(self): """Constructor""" wx.Frame.__init__(self, None, wx.ID_ANY, "Secondary Frame") panel = wx.Panel(self) msg = "Enter a Message to send to the main frame" instructions = wx.StaticText(panel, label=msg) self.msgTxt = wx.TextCtrl(panel, value="") closeBtn = wx.Button(panel, label="Send and Close") closeBtn.Bind(wx.EVT_BUTTON, self.onSendAndClose) sizer = wx.BoxSizer(wx.VERTICAL) flags = wx.ALL|wx.CENTER sizer.Add(instructions, 0, flags, 5) sizer.Add(self.msgTxt, 0, flags, 5) sizer.Add(closeBtn, 0, flags, 5) panel.SetSizer(sizer) def onSendAndClose(self, event): """ Send a message and close frame """ msg = self.msgTxt.GetValue() pub.sendMessage("panelListener", message=msg) pub.sendMessage("panelListener", message="test2", arg2="2nd argument!") self.Close() class MyPanel(wx.Panel): """""" def __init__(self, parent): """Constructor""" wx.Panel.__init__(self, parent) pub.subscribe(self.myListener, "panelListener") btn = wx.Button(self, label="Open Frame") btn.Bind(wx.EVT_BUTTON, self.onOpenFrame) def myListener(self, message, arg2=None): """ Listener function """ print "Received the following message: " + message if arg2: print "Received another arguments: " + str(arg2) def onOpenFrame(self, event): """ Opens secondary frame """ frame = OtherFrame() frame.Show() class MyFrame(wx.Frame): """""" def __init__(self): """Constructor""" wx.Frame.__init__(self, None, title="PubSub Tutorial") panel = MyPanel(self) self.Show() if __name__ == "__main__": app = wx.App(False) frame = MyFrame() app.MainLoop() And here is some additional information: https://wxpython.org/Phoenix/docs/html/wx.lib.pubsub.html https://www.blog.pythonlibrary.org/2013/09/05/wxpython-2-9-and-the-newer-pubsub-api-a-simple-tutorial/
has comment: http://stackoverflow.com/comment/83513376

mongodb
tags question: http://stackoverflow.com/q/48237302
tags question: http://stackoverflow.com/q/48260963
tags question: http://stackoverflow.com/q/48291139
tags question: http://stackoverflow.com/q/48176081
tags question: http://stackoverflow.com/q/48285458
tag name: mongodb
tags question: http://stackoverflow.com/q/48296069
tags question: http://stackoverflow.com/q/48288688
tags question: http://stackoverflow.com/q/48262939
type: Tag
tags question: http://stackoverflow.com/q/48236087
tags question: http://stackoverflow.com/q/48256911
tags question: http://stackoverflow.com/q/48219544
tags question: http://stackoverflow.com/q/48281521

http://stackoverflow.com/q/48295093
has comment: http://stackoverflow.com/comment/83649964
accepted answer: http://stackoverflow.com/a/48353408
has comment: http://stackoverflow.com/comment/83667966
has comment: http://stackoverflow.com/comment/83628335
has answer: http://stackoverflow.com/a/48353408
has comment: http://stackoverflow.com/comment/83665819
tagged with: python
has body: I have the following model in which it uses Jeffrey's prior for Geometric distribution for one of the distributions. I have one of the distributions that is derived from the others and uses that in Mixture distribution. I am getting IndexError: axis 1 is out of bounds [-1, 1) error. Please find my code below. actual_visit_mod_90_days = df_visit_period['mod_90_days'].values def jeffreys_logp(theta): #log(((1-theta)**-1) * theta**-0.5 ) return -(T.log(1-theta) + 0.5 * T.log(theta)) with Model() as pattern_study: dist1 = Binomial('dist1',n=14,p=0.5) dist2 = DiscreteUniform('dist2',lower = 0, upper = 89) pp = pm.DensityDist('pp',jeffreys_logp, testval = 0.05) dist3 = Geometric('dist3',pp) someDervDist = pm.DensityDist('someDervDist', lambda x: dist2-dist1+dist3 -1) likelihoodDist1 = DiscreteUniform.dist(lower=0, upper=89) likelihoodDist2 = pm.DensityDist.dist(lambda x: pm.logsumexp(someDervDist)) p=0.05 p_vd = Mixture('p_vd',[p,1-p],[likelihoodDist1,likelihoodDist2],observed = actual_visit_mod_90_days) The Error message is --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-19-1c9d266976ce&gt; in &lt;module&gt;() 28 p=0.05 29 ---&gt; 30 p_vd = Mixture('p_vd',[p,1-p],[likelihoodDist1,likelihoodDist2],observed = actual_visit_mod_90_days) 31 32 #print pm.distributions.generate_samples(postponeProbability) C:\Users\mdevananda\Continuum\Anaconda2\lib\site-packages\pymc3\distributions\distribution.pyc in __new__(cls, name, *args, **kwargs) 35 total_size = kwargs.pop('total_size', None) 36 dist = cls.dist(*args, **kwargs) ---&gt; 37 return model.Var(name, dist, data, total_size) 38 else: 39 raise TypeError("Name needs to be a string but got: {}".format(name)) C:\Users\mdevananda\Continuum\Anaconda2\lib\site-packages\pymc3\model.pyc in Var(self, name, dist, data, total_size) 780 var = ObservedRV(name=name, data=data, 781 distribution=dist, --&gt; 782 total_size=total_size, model=self) 783 sel…
has title: Using UniformDiscrete and DensityDist for Mixture distribution throws IndexError: axis 1 is out of bounds [-1, 1)
type: AnsweredQuestion
score: 0
tagged with: mixture-model
has comment: http://stackoverflow.com/comment/83665662
has comment: http://stackoverflow.com/comment/83688564
tagged with: pymc3
tagged with: index-error
has comment: http://stackoverflow.com/comment/83664806
answer count: 1
has comment: http://stackoverflow.com/comment/83651633
has comment: http://stackoverflow.com/comment/83613058
type: Question
has comment: http://stackoverflow.com/comment/83647561
has comment: http://stackoverflow.com/comment/83605867
has comment: http://stackoverflow.com/comment/83647929

http://stackoverflow.com/comment/83577006
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48288364
type: Comment
has text: the term 'size' is not fixed. it can be different for different configs. size is for embedding and I may have 'level' for Log config. I need to pass the name of the attribute to metaclass via `class Log(BaseConfig, level=logging.DEBUG)` for instance

http://stackoverflow.com/q/48236529
has body: How can I use both HTML and Python code in same file in CGI as we can do the same thing wiht PHP and HTML. I have following HTML code in Python file. #!C:/python36/python.exe import cgi print("Content-type:text/html") print(""" html form """) now I want use python code in this file to get form data and my python code is as follow: form = cgi.FieldStorage() username = form.getvalue("username") password = form.getvalue("password") print(username,password) Now, if submit is clicked, I want Python code to be executed and also I do not want to reference my Python code in form action.
has comment: http://stackoverflow.com/comment/83455766
score: 0
has title: in CGI, how it is possible to use both python code and html code
answer count: 0
tagged with: cgi
type: UnansweredQuestion
type: Question
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: forms
has comment: http://stackoverflow.com/comment/83456013

http://stackoverflow.com/q/48246360
has body: I have some code which is creating a scrollable Tkinter canvas with buttons inside. I believe my configuration of the scrollbar and Canvas is ok, but when I run the program, the scrollbar does not scroll. I have looked at other solutions online and I believe I am fulfilling everything that should be applied. Thank you for any and all help:) from tkinter import * root = Tk() responsesFr = Frame(root, width=700, height=275, bg="#d40b04") responseFrCoverCanvas = Canvas(root, width=700,height=14 ,highlightthickness=0, border=0,bg="#d40b04") w = Canvas(responsesFr, width=650, height=225, borderwidth=0,highlightthickness=0,background="white") w.config(scrollregion=[0,0,1000,225]) for column in range(30): button1 = Button(w, width=20, height=4) button1.pack(side='left', padx=25) if column == 29: w.config(scrollregion=[0,0,1000,1000]) print("done") else: pass w.pack(padx=25,pady=10) hbar=Scrollbar(responsesFr, orient=HORIZONTAL) hbar.pack(padx=25, side=TOP, fill=X) hbar.config(command=w.xview) w.config(xscrollcommand=hbar.set) responsesFr.pack() root.mainloop()
has comment: http://stackoverflow.com/comment/83475665
has answer: http://stackoverflow.com/a/48246836
has comment: http://stackoverflow.com/comment/83475632
accepted answer: http://stackoverflow.com/a/48246836
tagged with: python
tagged with: scrollbar
type: AnsweredQuestion
score: 0
tagged with: tkinter
has title: Tkinter Scrollbar not scrolling
answer count: 1
tagged with: scroll
type: Question

http://stackoverflow.com/q/48238029
upvote count: 1
has title: Django app: on modelse.py any kind of def is not working
favorite count: 0
type: Question
type: UnansweredQuestion
score: 1
has body: here my code, last two function is not working i am also trying more function but still they are not working. from django.db import models # Create your models here. class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) # nothing to show def __str__(self): return self.title def snippet(self): return self.body[0:50]
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/83458466
has comment: http://stackoverflow.com/comment/83458494
answer count: 0
downvote count: 0
tagged with: django

http://stackoverflow.com/comment/83359473
comment on: http://stackoverflow.com/q/48189745
score: 0
type: QuestionComment
type: Comment
has text: email = form.cleaned_data.get('eemail') shouldn't be email = form.cleaned_data.get('email') ? and raw_password = form.cleaned_data.get('password1') shouldn't it be raw_password = form.cleaned_data.get('password')?

http://stackoverflow.com/comment/83567058
score: 0
type: Comment
has text: That I get, only problem is, with ansible `command` module, I am not able to use `pyenv`, have to use `/root/.pyenv/bin/pyenv` and that is not working with activate.
comment on: http://stackoverflow.com/a/48288532
type: AnswerComment

simplehttpserver
tags question: http://stackoverflow.com/q/48308487
tag name: simplehttpserver
type: Tag

http://stackoverflow.com/comment/83375868
score: 0
type: AnswerComment
has text: Thanks! Although editing login() did not work, I decided to research command as you suggested and have got it working that way. Many thanks!
comment on: http://stackoverflow.com/a/48179848
type: Comment

http://stackoverflow.com/q/48216358
type: Question
has body: I have data that looks like this: import pandas as pd from sklearn_pandas import DataFrameMapper, CategoricalImputer from sklearn.preprocessing import StandardScaler, LabelBinarizer from sklearn.pipeline import make_pipeline from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier df = pd.DataFrame({ 'y': [0, 0, 0, 1, 1, 1, 1], 'a': [2, 1, 2, 7, 8, 8, 9], 'b': ['a', 'a', 'a', 'b', None, 'b', 'c'] }) y = df['y'] X = df.drop('y', axis=1) I want to use DataFrameMapper to pre-process and KerasClassifier to predict. All within a convenient make_pipeline... The DataFrameMapper part is simple: mapper = DataFrameMapper([ (['a'], StandardScaler()), ('b', [CategoricalImputer(), LabelBinarizer()]), ]) And defining the net is easy enough: def model(): model = Sequential() model.add(Dense(10, activation='relu', input_dim= **4** )) model.add(Dense(10, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) return model kc = KerasClassifier(build_fn=model, epochs=5, verbose=2) Putting it all in a make_pipeline is simple too: pipe = make_pipeline(mapper, kc) pipe.fit(X, y) pipe.predict_proba( pd.DataFrame({ 'y': [0], 'a': [2], 'b': ['b'] }) ) But here's the rub... I hardcoded the input_dim for the Classifier... and I can't in production, because I don't necessarily know what dimensions the DataFrameMapper will spit out... might be 4 might be 5 might be 11... So my real question: How can I pass the shape/output_dim of DataFrameMapper to the input_dim of KerasClassifier in the make_pipeline flow? Thanks!
type: UnansweredQuestion
downvote count: 0
tagged with: scikit-learn
tagged with: python
tagged with: keras
linked to: http://stackoverflow.com/q/46234722
score: 3
answer count: 0
tagged with: pandas
upvote count: 3
has comment: http://stackoverflow.com/comment/83415209
has title: Keras + DataFrameMapper + make_pipeline, input_dim dilemma
favorite count: 0

http://stackoverflow.com/q/48291093
has title: ignore "blank" (unfilled) row with python csv reader
has body: everybody. I can't find a pythonic way to ignore "blank" lines in a CSV. I use quotes because I'm talking about lines that look like '','','','','' Here is a CSV (blank lines could be random): id,name,age 1,alex,22 3,tiff,42 ,, ,, 4,john,24 Here is the code: def getDataFromCsv(path): dataSet = [] with open(unicode(path), 'r') as stream: reader = csv.reader(stream, delimiter=',') reader.next() # ignoring header for rowdata in reader: # how to check here? dataSet.append(rowdata) return dataSet Here is similar questions that I've been reading, but different to this in particular: python csv reader ignore blank row
has answer: http://stackoverflow.com/a/55243655
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/31508832
has answer: http://stackoverflow.com/a/55384852
answer count: 5
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/48291126
tagged with: reader
tagged with: python
has comment: http://stackoverflow.com/comment/83567448
has answer: http://stackoverflow.com/a/48291127
accepted answer: http://stackoverflow.com/a/48291127
has comment: http://stackoverflow.com/comment/83570075
upvote count: 2
has comment: http://stackoverflow.com/comment/83567378
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/68069088
has comment: http://stackoverflow.com/comment/83570050
downvote count: 0
has answer: http://stackoverflow.com/a/68069088

http://stackoverflow.com/q/48176348
has body: I have a Dataset API doohickey which is part of my tensorflow graph. How do I swap it out when I want to use different data? dataset = tf.data.Dataset.range(3) iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() variable = tf.Variable(3, dtype=tf.int64) model = variable*next_element #pretend like this is me training my model, or something with tf.Session() as sess: sess.run(variable.initializer) try: while True: print(sess.run(model)) # (0,3,6) except: pass dataset = tf.data.Dataset.range(2) iterator = dataset.make_one_shot_iterator() next_element = iterator.get_next() ### HOW TO DO THIS THING? with tf.Session() as sess: sess.run(variable.initializer) #This would be a saver restore operation, normally... try: while True: print(sess.run(model)) # (0,3)... hopefully except: pass
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: tensorflow-datasets
linked to: http://stackoverflow.com/q/34235225
has answer: http://stackoverflow.com/a/48177844
has title: tensorflow how to change dataset
tagged with: python
has answer: http://stackoverflow.com/a/53283743
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/53283743
answer count: 2
downvote count: 0
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48177844

http://stackoverflow.com/comment/83515111
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48265902
has text: Why do you need it based on flask? You could use a front end material bundle and split the views yourself.

http://stackoverflow.com/a/48303216
has comment: http://stackoverflow.com/comment/83592453
has comment: http://stackoverflow.com/comment/83591189
score: 3
has body: The basic problem is you have too many levels of loop. If you want to do it as a list comprehension, you only need one level: dict((position, token) for token, position in total_leftover) Note this can be further simplified into a dict comprehension: {position: token for token, position in total_leftover}
answers question: http://stackoverflow.com/q/48303079
type: Answer
has comment: http://stackoverflow.com/comment/83591377
upvote count: 3
downvote count: 0

raspberry-pi
tags question: http://stackoverflow.com/q/48213499
tags question: http://stackoverflow.com/q/48224865
tags question: http://stackoverflow.com/q/48290873
tags question: http://stackoverflow.com/q/48190530
type: Tag
tags question: http://stackoverflow.com/q/48190862
tags question: http://stackoverflow.com/q/48191975
tags question: http://stackoverflow.com/q/48316117
tags question: http://stackoverflow.com/q/48266063
tags question: http://stackoverflow.com/q/48175726
tags question: http://stackoverflow.com/q/48260058
tags question: http://stackoverflow.com/q/48295950
tags question: http://stackoverflow.com/q/48242515
tags question: http://stackoverflow.com/q/48257446
tags question: http://stackoverflow.com/q/48303969
tags question: http://stackoverflow.com/q/48191985
tags question: http://stackoverflow.com/q/48267533
tags question: http://stackoverflow.com/q/48249498
tag name: raspberry-pi
tags question: http://stackoverflow.com/q/48291217
tags question: http://stackoverflow.com/q/48205406
tags question: http://stackoverflow.com/q/48235012
tags question: http://stackoverflow.com/q/48313388
tags question: http://stackoverflow.com/q/48231926
tags question: http://stackoverflow.com/q/48321492
tags question: http://stackoverflow.com/q/48227104

http://stackoverflow.com/comment/83534796
type: QuestionComment
comment on: http://stackoverflow.com/q/48275648
has text: try to clear browser cache or check in incognito window.
type: Comment
score: 0

http://stackoverflow.com/a/48211847
score: 0
answers question: http://stackoverflow.com/q/48209293
has body: I suspect you need to wrap your uploaded file in an io.BytesIO. Here's a complete example showing how to open an uploaded PDF using PyPDF2 -- https://colab.research.google.com/notebook#fileId=1XlmXcp4xnrUGMUArevxiGNlrbMOMECO1 The key bit is: pdf = PdfFileReader(io.BytesIO(uploaded['abc123.pdf']))
type: Answer

http://stackoverflow.com/a/57415946
upvote count: 1
answers question: http://stackoverflow.com/q/48215969
type: Answer
has body: This small snippet works: def get_results(data,other_tensor): pooled_data, indices = tf.nn.max_pool_with_argmax(data,ksize=[1,ksize,ksize,1],strides=[1,stride,stride,1],padding='VALID',include_batch_in_index=True) b,w,h,c = other_tensor.get_shape.as_list() other_tensor_pooled = tf.gather(tf.reshape(other_tensor,shape= [b*w*h*c,]),indices) return other_tensor_pooled The above indices can be used to index the tensor. This function actually returns flattened indices and to use it with anything with batch_size &gt; 1 you need to pass include_batch_in_index as True in-order to get proper results. I am assuming here that othertensor you has the same batch size as data.
score: 1
downvote count: 0

http://stackoverflow.com/q/48176564
has comment: http://stackoverflow.com/comment/83334202
tagged with: parsing
has comment: http://stackoverflow.com/comment/83342024
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: 0
answer count: 0
has body: I'm trying to get information from email message about Subject, From, To, Date and this is done, also I need get all span from HTML which is in the same email, I tried to use Soup, but I did it wrong. So how I can get the only span from HTML? Thanks for any help, my code below: import imaplib import email import mimetypes from email import header from bs4 import BeautifulSoup def decodeHeader(headerMsg): L = header.decode_header(headerMsg) s = '' for s1, chset in L: if type(s1) == bytes: s += s1.decode(chset) if chset else s1.decode() else: s += s1 return s host = 'imap.yandex.ru' userid = 'myid' passwd = 'mypass' imap = imaplib.IMAP4_SSL(host) imap.login(userid, passwd) imap.select('INBOX') status, email_ids = imap.search(None, '(ALL)') for num in email_ids[0].split(): type1, data = imap.fetch(num, '(RFC822)') raw_email = data[0][1] email_msg = email.message_from_bytes(raw_email) if email_msg.is_multipart(): for payload in email_msg.get_payload(): # if payload.is_multipart(): ... doc = (payload.get_payload()) source_code = doc soup = BeautifulSoup(source_code, 'lxml') print(soup.find('span', {'class': 'mail-ThreadSidebar-List-Item_content'}).text) else: doc = (email_msg.get_payload()) source_code = doc soup = BeautifulSoup(source_code, 'lxml') print(soup.find('span', {'class': 'mail-ThreadSidebar-List-Item_content'})) print('Subject: ', decodeHeader(email_msg['Subject'])) print('From: ', decodeHeader(email_msg['From'])) print('To: ', decodeHeader(email_msg['To'])) print('Date: ', decodeHeader(email_msg['Date'])) type1, data = imap.fetch(num, '(UID BODY[TEXT])') raw_email = str(data[0][1]) # print('contents: ', raw_email) print('----\n\n')
tagged with: email
has comment: http://stackoverflow.com/comment/83334023
has title: How to parse HTML in email message
has comment: http://stackoverflow.com/comment/83334250

http://stackoverflow.com/a/48197477
has body: list(map(lambda l: list(map(float, l)), a)) if you do not want to use list comprehensions
answers question: http://stackoverflow.com/q/48197398
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/83447153
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48232372
has text: @unutbu litterally just saw that as i stared at it for the 15th time. This link is also a really great resource though thank you. Can I put your "comment" as a solution to my question?

http://stackoverflow.com/comment/83488714
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48252914
has text: What comprises the set of "special characters"? What was unsuccessful about your attempt to replace `'\xa0'`.
score: 0

http://stackoverflow.com/comment/83583999
comment on: http://stackoverflow.com/q/48298833
score: 0
has text: U haven’t tried but maybe it is possible? Or is there anyone that can tell me it is not possible? :/
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48289039
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48288699
has body: List traversal baby steps For traversing lists using recursion, there's only 3 things that matter the empty list - always check if your list is empty before anything! the head of the list – the first item the tail of the list – the entire list except the first item Ok, and here's the functions we'll use to write our programs def is_empty (ls): return ls == [] def head (ls): return ls[0] def tail (ls): return ls[1:] Usage of the functions is straightforward is_empty ([]) # =&gt; True is_empty ([ 1, 2, 3 ]) # =&gt; False head ([ 1, 2, 3 ]) # =&gt; 1 tail ([ 1, 2, 3 ]) # =&gt; [2,3] Ok, so let's write our list_sum function – I think you'll agree that we ended up with a very readable program thanks to the list helpers we defined def list_sum (ls): if is_empty (ls): return 0 else: return head (ls) + list_sum (tail (ls)) print (list_sum ([ 1, 2, 3, 4, 5, 6, 7 ])) # =&gt; 28 But you tagged this with tail recursion, so with the help of an optional parameter and a default value, we can move the recursive call into tail position. Changes in bold def list_sum (ls, acc = 0): if is_empty (ls): return acc else: return list_sum (tail (ls), head (ls) + acc) print (list_sum ([ 1, 2, 3, 4, 5, 6, 7 ])) # => 28 But Python doesn't really have tail-call elimination, so you'd still have to do something else to ensure stack-safety. Smoke higher-order functions every day Using head and tail relieved us from the tedium (and ugliness) of [0] and [1:], but this pattern of list traversal is so common that we can relieve ourselves from even thinking at this level altogether! Let's look back at our function, list_sum. This function traverses a list and performs addition using the built-in + function. What if instead of + we wanted to multiply all the elements using *? def list_sum (ls): if is_empty (ls): return 0 else: return head (ls) + list_sum (tail (ls)) def list_product (ls): if is_empty (ls): return 1 else: return head (ls) * list_product (tail (ls)) print (list_product ([ 1, 2, 3, 4, 5, 6,…
type: Answer

http://stackoverflow.com/q/48251068
tagged with: django-templates
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/8948430
accepted answer: http://stackoverflow.com/a/48253529
has answer: http://stackoverflow.com/a/48253529
has comment: http://stackoverflow.com/comment/83485857
has title: forloop.counter numbers not resetting when using nested for loops
tagged with: for-loop
type: Question
has comment: http://stackoverflow.com/comment/83484592
answer count: 2
linked to: http://stackoverflow.com/q/2376511
tagged with: django
tagged with: python
has body: I have a need for counting the standings of a sport team based on the total points they have their division. Each team has a total points and division assigned to them. views.py def seasonstandings(request): divisions = Team.objects.order_by().values_list('division__name',flat=True).distinct() stats = WeeklyStats.objects.values('player__team__team_name').annotate( team=F('player__team__team_name'), points = Sum('finishes'), division = F('player__team__division__name') ).order_by('division','-points') return render(request, 'website/seasonstandings.html', { 'divisions_and_stats': [[division, [stat for stat in stats if stat.division == division]] for division in divisions] }) My Django template code is as follows: seasonstandings.html {% for division in divisions %} {{ division }} Place Team Points {% for stat in stats %} {% if stat.division == division %} {{ forloop.counter}} {{ stat.team }} {{ stat.points }} {% endif %} {% endfor %} {% endfor %} The problem right now is that say I have 6 teams and 3 are in Division A and 3 are in Division B. Because it is separating the teams based on division it is showing the forloop.counter as 1 through 6 on the first forloop for divisions. What I want it to do is only do the forloop counter for the nested forloop ( the second one for stats) so that it shows places 1 through 3 for Division A and 1 through 3 for Division B. The results I am getting are: Division A Place Team Points 1 Timberlea Beverage Room 1 7 3 Lakeside Legion 1 4 4 Bedford Legion 3 Division B Place Team Points 2 Lakeside Legion 2 4 5 Purcells Cove Club 1 2 6 Army Navy Air-Force Club None When I am hoping to get get the results to look like this: Division A Place Team Points 1 Timberlea Beverage Room 1 7 2 Lakeside Legion 1 4 3 Bedford Legion 3 Division B Place Team Points 1 Lakeside Legion 2 4 2 Purcells Cove Club 1 2 3 Army Navy Air-Force Club None After some more looking into this, I think it is my IF Statement causing the issue where it will skip a record if…
possible better answer: http://stackoverflow.com/a/48251725
has comment: http://stackoverflow.com/comment/83485421
has answer: http://stackoverflow.com/a/48251725

http://stackoverflow.com/a/52962124
score: 2
answers question: http://stackoverflow.com/q/48302295
upvote count: 2
downvote count: 0
has body: I tried this sudo -H pip install --ignore-installed python-dateutil Post that the following sudo pip install boto3 Thanks
type: Answer

http://stackoverflow.com/comment/83567084
comment on: http://stackoverflow.com/a/48290933
has text: How did you format that? I tried pasting it with an 8 space indent but it just becomes one block of code..
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83334809
comment on: http://stackoverflow.com/q/48175102
score: 0
has text: No. Please put any code updates in the question by clicking the [edit] link. Code in the comment section is impossible to read.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48190218
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
answer count: 0
has title: Numpy: Walk along vector within 2d matrix
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has body: Consider a function A(x(z, y), y(z)). I want to start at arbitrary (x, y), and walk along z. I have dy/dz = 1 dx/dz = z y(1-x)/(y(y+z)). For epsilon z, this gives y(1-x)/(yy) Now, take the following discretization: import numpy as np x = np.linspace(0.01, 0.99, 100) y = np.linspace(0.5, 2, 50) X, Y = np.meshgrid(x, y, indexing='ij') A = X*Y d = Y*(1-X)/(Y*Y) Now, A is a 2d function in (x, y): A.shape Out[25]: (100, 50) which is increasing in both dimensions by construction. Now, from each starting point in A, I want to walk along the (d, 1) vector, until I reach a value above 1.5. My resulting matrix R with the same shape as A should contain the number of grid points in y dimension that it took to get there. If I never arrive at that value (that is, the corresponding boundary of A &lt; 1.5), any distinguishable output (eg nan) would be great. Since this is difficult to do manually, I cannot give an exact expected output. But for example, take the grid point (85, 20). Let's say that in that neighborhood, d=0.1 roughly (it is actually 0.13). That'd mean that I would want to move along the (1, 10) diagonal locally, until I reach A : A &gt;= 1.5. In this case, I want to walk from A[85, 20] up to A[85+2, 20+20], the first point above 1.5, with value of A[85+2, 20+20] Out[51]: 1.5023964131106988 So, I walked 20 grid points along z. This means that my resulting matrix R has R[85, 20] == 20. I'm both interested in high efficiency ways of doing this, as well as worse performing but more precise solutions. In any case, my solution has to build on the given matrices. To provide some more intuition about what I'm trying to achieve, consider dx/dz = 0. In that case, I could simply positive = A &gt; 1.5 iX, iY = np.meshgrid(np.arange(100), np.arange(50), indexing='ij') gridsMove = positive.argmax(axis=1)[:, np.newaxis] R = np.maximum(gridsMove-iY, 0).astype(float) # prune those here where we never arrive (argmax yields `0`, non robust test but works here) R[gridsMove.repeat(50, a…
score: 1

http://stackoverflow.com/q/48311704
tagged with: import
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83611091
accepted answer: http://stackoverflow.com/a/48312048
has comment: http://stackoverflow.com/comment/83610123
has comment: http://stackoverflow.com/comment/83609313
has comment: http://stackoverflow.com/comment/83609809
has title: Errno 2 file not found when calling a function from a different .py file
tagged with: python
tagged with: module
has body: I made a function that reads from a file and saves it's data in an array. This function is in Posts.py: index = 'Forum/Topics/index.txt' def loadTopicNames(): with open(index, 'r') as file: data = file.readlines() for row in data: row = row.replace('\n', '') topicNames.append(row) This function works, doesn't have problems with the file location. But when I import the Posts.py module in my Forum.py module, and execute it from Forum.py, I get this error: with open(index, 'r') as file: FileNotFoundError: [Errno 2] No such file or directory: 'Forum/Topics/index.txt' Here is the relevant code from Forum.py: import Posts Posts.loadTopicNames() Note: I found some solutions on stackoverflow already, but they mostly include making the path absolute, which is not an option here. Posts.py and Forum.py are in the same folder. This is sort of a representation of where the files are in the project: Project/Forum.py Project/Posts.py Project/Forum/Topics/index.txt Project/otherStuff... Edit: found the problem... The working directory for the Forum.py wasn't right, and that was the reason it messed everything up. It had wrong working directory because when I first made the module, I made it in a wrong folder. Then when I realized my mistake, I just copied it to the right place, but the working directory stayed the same...
has comment: http://stackoverflow.com/comment/83609718
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/48312048
downvote count: 0
possible better answer: http://stackoverflow.com/a/48312887
score: 1
has comment: http://stackoverflow.com/comment/83621746
upvote count: 1
tagged with: ioerror
has comment: http://stackoverflow.com/comment/83609477
has answer: http://stackoverflow.com/a/48312887

http://stackoverflow.com/q/48251292
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/41155985
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86743339
has body: I'm trying to install TA-Lib on Python, i'm using a x64 version so i can't install Ta-Lib using pip. I'm following these steps to run it but i have not clear the step 4: "Build the library nmake". I have opened the prompt but i don't really know how to build nmake, can anyone help me?
has answer: http://stackoverflow.com/a/48251569
tagged with: ta-lib
has title: Installing TA-Lib on python x64
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/59757015
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/q/48193436
type: Question
tagged with: cron
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83374947
has comment: http://stackoverflow.com/comment/83374846
tagged with: python
tagged with: google-bigquery
has title: Step by Step on cronjobs in Bigquery to adjust partitions of a table
has body: I need to systematically adjust the data in a bigquery table, keeping its partitions, which means that for each partition I will run a query and replace this partition in the bigquery table with the query result. However, I need to do that regularly. I was wondering if it is possible for me to write a cronjob that will allow me to replace the table partition with its queries results on a daily basis. I know how to replace specific partitions with query results through command line, but I need to implement this on a cron job for it to be ran on a daily basis. If I could do that in Python, it would be awesome!
tagged with: replace
score: 0
has comment: http://stackoverflow.com/comment/84014581
answer count: 0
linked to: http://stackoverflow.com/q/42874629
upvote count: 1
tagged with: partition
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83368525

http://stackoverflow.com/q/48304718
answer count: 1
favorite count: 0
tagged with: sikuli
type: Question
score: 1
has title: How to run a PyCharm project while passing environment variables from command line
has answer: http://stackoverflow.com/a/48324014
tagged with: pycharm
tagged with: jython
has body: I have an automation test framework built using Jython intertpreter in Pycharm. I'm using Sikuli and Selenium in this framework and I want to eventually start running this project from Jenkins. In order to do that, I want to get this running via command line first. But when I try running this via command line, I get this error. Does anyone know how to pass in environment variables via command line? Debug config screenshot &amp; running via command line
downvote count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/a/48320832
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83626910
has body: Your ListHigh and ListLow variables contain a scalar and a Series. That might be why max fails, it tries to compare that scalar with that Series. By the way, in Python, usually variables are not capitalized.
has comment: http://stackoverflow.com/comment/83636725
answers question: http://stackoverflow.com/q/48320339
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/83627468
accepted answer of: http://stackoverflow.com/q/48320339
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/48322166
score: 0
answers question: http://stackoverflow.com/q/48322019
type: AcceptedAnswer
has body: Well apparently the FAST descriptor is not implemented like for the STAR descriptor. Only the detection works : How to use STAR detector in openCV 3 with python?
accepted answer of: http://stackoverflow.com/q/48322019
type: Answer

http://stackoverflow.com/q/48217040
tagged with: ui-automation
answer count: 0
type: UnansweredQuestion
score: 1
has body: I am running UI automation test with Appium. But it is does not recognize my elements on the screen. I added Debug messages to the source code and built new apk with those messages. What i need to do next is start UI test and at same time grab logfile --> read from log for Debug message i added and if my text string is displayed --> assert and mark as pass. Example: 1. Start Test "launch app" 2. Verify that text "hello world" is displayed on first load page But appium does not see this text due to my app complexity, so, to assert the correct text string i need to look from realtime logs and than put results in my unittest Pass or Fail 3. And if i need to make any logic in the app(go to settings, go to profile page etc) i have to wait for specific Text string, even if i have time.sleep, it is not guarantee that text will be displayed. Is there an appropriate way to do this? Thanks.
downvote count: 0
has comment: http://stackoverflow.com/comment/83416501
has comment: http://stackoverflow.com/comment/83416123
upvote count: 1
has title: How to parse android log in realtime while running unittest with Appium?
favorite count: 0
type: Question
tagged with: appium
tagged with: android
tagged with: python

http://stackoverflow.com/comment/83459658
score: 0
has text: In this day and age, I would say that using CGI is probably a bad idea, maybe even a terrible idea. Then again, I don't know what you're doing, so maybe not. Using a framework like Django, Pyramid, or Flask is almost certainly a better way to go.
type: Comment
comment on: http://stackoverflow.com/q/48238452
type: QuestionComment

http://stackoverflow.com/a/48184690
answers question: http://stackoverflow.com/q/48183804
downvote count: 0
score: 3
has body: As @usr2564301 said getHistory gives you good explanation in human language Returns the number of last frames that affect the background model. If you need a mathematical explanation of what it is - I would recommend you to read An improved adaptive background mixture model for real-time tracking with shadow detection paper which this algorithm is based on. As you can see from sources (1, 2) history is used to calculate learningRate which is essentially alpha in that paper
upvote count: 3
type: Answer

http://stackoverflow.com/comment/83486875
type: QuestionComment
comment on: http://stackoverflow.com/q/48250311
type: Comment
has text: But then stretching won't be able anymore
score: 0

http://stackoverflow.com/comment/83337069
has text: Can you edit your question to include the errors, and code with them?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48178424

http://stackoverflow.com/q/48219222
answer count: 2
has body: I am trying to update Bokeh DataTable by selecting a plot.Not sure why it's not getting updated?In the code below,source_devon is ColumnDataSource for the plot- I wanted Datatable to get updated when we select a particular portion.Currently DataTable is created(initialization),but it doesn't changes on selection from bokeh.io import curdoc from bokeh.layouts import layout,row from bokeh.models import CDSView,HoverTool,GroupFilter,ColumnDataSource,Button,Select,TextInput,Slider,DataTable,TableColumn,DateFormatter,LinearAxis,Range1d,CustomJS,Rect from bokeh.plotting import figure,output_file,show from datetime import datetime, timedelta from bokeh.client import push_session import pandas as pd import numpy as np TOOLS='pan,wheel_zoom,box_zoom,reset,tap,save,lasso_select,xbox_select' # Select widget ccy_options = ['AUDUSD', 'USDJPY'] menu = Select(options=['AUDUSD','USDJPY'], value='AUDUSD') slider = Slider(start=-1000, end=10000, step=1000, value=-1000, title='Volume Cutoff') # Function to get Order/Trade/Price Datasets def get_combined_dataset(src,name): df = src[(src.CCYPAIR == name)].copy() return ColumnDataSource(data=df) # Function to Make Plots def make_plot(source_order): x = 'DATE' y = 'PRICE' y1 = 'Volume' size = 10 alpha = 0.5 hover = HoverTool( tooltips = [ ('OrderId', '@ORDER_ID_108'), ('Volume', '@Volume'), ('Price', '@PRICE') ] ) view1 = CDSView(source=source_order, filters=[GroupFilter(column_name='TYPE',group='ORDER'),GroupFilter(column_name='SIDE',group='B')]) view2 = CDSView(source=source_order, filters=[GroupFilter(column_name='TYPE',group='ORDER'),GroupFilter(column_name='SIDE',group='S')]) view3 = CDSView(source=source_order, filters=[GroupFilter(column_name='TYPE',group='TRADE'),GroupFilter(column_name='SIDE',group='B')]) view4 = CDSView(source=source_order, filters=[GroupFilter(column_name='TYPE',group='TRADE'),GroupFilter(column_name='SIDE',group='S')]) view5 = CDSView(source=source_order, filters=[GroupFilter(column_name='TYPE',group='DevonTra…
tagged with: python
has title: Refreshing Bokeh DataTable through Selection of Plots
tagged with: datatable
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48259938
accepted answer: http://stackoverflow.com/a/48259938
tagged with: widget
possible better answer: http://stackoverflow.com/a/48331294
has answer: http://stackoverflow.com/a/48331294
tagged with: bokeh
tagged with: callback
type: Question

http://stackoverflow.com/q/48303498
score: 0
accepted answer: http://stackoverflow.com/a/48304827
has answer: http://stackoverflow.com/a/48304827
answer count: 1
has title: TypeError: product.product(3,) is not JSON serializable
has body: I'm having so much issues with this code now. Here is my function : def _get_invoice_lines(self): self.cr.execute("SELECT inv.number,l.price_subtotal_taxed,l.name,inv.maitre_ouvrage,m.type_paiement,m.ref,m.date FROM product_product p,account_invoice inv, account_invoice_line l,account_move ml where p.id = l.product_id and inv.id= l.invoice_id and ml.invoice_id=inv.id and ml.type_paiement is not null and inv.journal_id = 1 and ml.type_paiement = '%s' and inv.date_invoice =DATE '%s' and p.id = %d "%(self.datas['type_paiement'],self.datas['date_invoice'],self.datas['product_id'].id)) return self.cr.fetchall() When I print my report I get this error : File "/usr/lib/python2.7/dist-packages/simplejson/encoder.py", line 239, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: product.product(3,) is not JSON serializable
type: Question
tagged with: odoo
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/83478901
score: 0
type: AnswerComment
has text: OK, what is source of data? `xlsx`, file? Or json?
comment on: http://stackoverflow.com/a/48188082
type: Comment

sqlalchemy
tags question: http://stackoverflow.com/q/48262260
tags question: http://stackoverflow.com/q/48190346
tags question: http://stackoverflow.com/q/48248771
tags question: http://stackoverflow.com/q/48242324
tags question: http://stackoverflow.com/q/48243602
tags question: http://stackoverflow.com/q/48330727
tags question: http://stackoverflow.com/q/48307008
tags question: http://stackoverflow.com/q/48187843
tags question: http://stackoverflow.com/q/48218869
tags question: http://stackoverflow.com/q/48260679
tags question: http://stackoverflow.com/q/48197972
tags question: http://stackoverflow.com/q/48174575
tags question: http://stackoverflow.com/q/48230018
tags question: http://stackoverflow.com/q/48317409
tags question: http://stackoverflow.com/q/48261173
tags question: http://stackoverflow.com/q/48208959
tags question: http://stackoverflow.com/q/48219143
tags question: http://stackoverflow.com/q/48299282
tags question: http://stackoverflow.com/q/48252564
tags question: http://stackoverflow.com/q/48232222
tags question: http://stackoverflow.com/q/48265532
tags question: http://stackoverflow.com/q/48214327
tags question: http://stackoverflow.com/q/48213032
tags question: http://stackoverflow.com/q/48216520
tags question: http://stackoverflow.com/q/48240437
tags question: http://stackoverflow.com/q/48274553
tags question: http://stackoverflow.com/q/48178805
tags question: http://stackoverflow.com/q/48320370
tags question: http://stackoverflow.com/q/48313934
tags question: http://stackoverflow.com/q/48320834
tags question: http://stackoverflow.com/q/48188660
tags question: http://stackoverflow.com/q/48258674
tags question: http://stackoverflow.com/q/48244563
tags question: http://stackoverflow.com/q/48177952
tags question: http://stackoverflow.com/q/48266472
tags question: http://stackoverflow.com/q/48250008
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/48188881
type: Tag
tags question: http://stackoverflow.com/q/48206047
tags question: http://stackoverflow.com/q/48298857
tags question: http://stackoverflow.com/q/48215592

http://stackoverflow.com/q/48328572
has answer: http://stackoverflow.com/a/48329424
tagged with: conditional-statements
tagged with: pandas
has answer: http://stackoverflow.com/a/48328593
score: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/48328619
has title: How to update np.array conditionally?
has answer: http://stackoverflow.com/a/48328619
type: Question
tagged with: numpy
has body: I got two numpy arrays: Out[23]: a = np.array([3, 7, 8, 9, 2], dtype=float) Out[24]: b = np.array([5, 6, 7, 10, 3], dtype=float) I need to compare a and b, and update array b so that its elements will contain the higher value or np.nan Example code: for i in range(len(b)): b[i] = b[i] if b[i] &gt; a[i] else np.nan Result: b Out[33]: array([ 5., nan, nan, 10., 3.]) Is there a way to do this without using a for loop? Thanks in advance.
answer count: 3
tagged with: arrays
downvote count: 0
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48328593
type: AnsweredQuestion

http://stackoverflow.com/comment/83642191
type: QuestionComment
comment on: http://stackoverflow.com/q/48325676
score: 0
has text: Automatic -1 for useless title. Edit to retrieve.
type: Comment

http://stackoverflow.com/a/48283058
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48282894
type: Answer
has body: Depends on what you intend to do with the data, how you want to Access it and whether it is static, or not. One of the easiest and most flexible way is a dictionary with tuples: dic = {"file1": (1, 4, 10), "file2": (99, 400)} If you need to Change the line numbers, you can use lists: dic = {"file1": [1, 4, 10], "file2": [99, 400]} And in very specific cases, you could use sets to ensure the lines appear only once and if you want to make use of the sets' methods to create difference, Union or intersections: dic = {"file1": set((1, 4, 10)), "file2": set((99, 400))} [edit] Btw: to access the data, you can get it by file name from dic dic["file1"] or key = "file2" dic[key] dic.get(key) # optionally using the .get method, which allows for Default values [/edit] Does it help? Otherwise, please explain the purpose. BR
accepted answer of: http://stackoverflow.com/q/48282894
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/83525434
has text: What made you think your class can have two methods with the same name?
comment on: http://stackoverflow.com/q/48270857
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/48243877
tagged with: python-3.6
has answer: http://stackoverflow.com/a/48417092
tagged with: apache-spark
score: 7
has comment: http://stackoverflow.com/comment/83478265
has comment: http://stackoverflow.com/comment/83474909
upvote count: 7
has title: IllegalArgumentException thrown when count and collect function in spark
tagged with: macos
has answer: http://stackoverflow.com/a/49304275
has comment: http://stackoverflow.com/comment/83471840
favorite count: 0
type: Question
answer count: 2
has body: I tried to load a small dataset on local Spark when this exception is thrown when I used count() in PySpark (take() seems working). I tried to search about this issue but got no luck in figuring out why. It seems something is wrong with the partition of RDD. Any ideas? Thank you in advance! sc.stop() sc = SparkContext("local[4]", "temp") testfile1 = sc.textFile(localpath('part-00000-Copy1.xml')) testfile1.filter(lambda x: x.strip().encode('utf-8').startswith(b'&lt;row')).take(1) ## take function seems working and this is what the data looks like: [' &lt;row AcceptedAnswerId="15" AnswerCount="5" Body="&amp;lt;p&amp;gt;How should I elicit prior distributions from experts when fitting a Bayesian model?&amp;lt;/p&amp;gt;&amp;#10;" CommentCount="1" CreationDate="2010-07-19T19:12:12.510" FavoriteCount="17" Id="1" LastActivityDate="2010-09-15T21:08:26.077" OwnerUserId="8" PostTypeId="1" Score="26" Tags="&amp;lt;bayesian&amp;gt;&amp;lt;prior&amp;gt;&amp;lt;elicitation&amp;gt;" Title="Eliciting priors from experts" ViewCount="1457" /&gt;'] this is the problem: test1 = testfile1.filter(lambda x: (x.strip().encode('utf-8').startswith(b'&lt;row'))).filter(lambda x: x is not None) test1.count() here is the exception: --------------------------------------------------------------------------- Py4JJavaError Traceback (most recent call last) &lt;ipython-input-34-d7626ed81f56&gt; in &lt;module&gt;() ----&gt; 1 test1.count() /usr/local/lib/python3.6/site-packages/pyspark/rdd.py in count(self) 1039 3 1040 """ -&gt; 1041 return self.mapPartitions(lambda i: [sum(1 for _ in i)]).sum() 1042 1043 def stats(self): /usr/local/lib/python3.6/site-packages/pyspark/rdd.py in sum(self) 1030 6.0 1031 """ -&gt; 1032 return self.mapPartitions(lambda x: [sum(x)]).fold(0, operator.add) 1033 1034 def count(self): /usr/local/lib/python3.6/site-packages/pyspark/rdd.py in fold(self, zeroValue, op) 904 # zeroValue provided to each partition is unique from the one provided 905 # to the final reduce call --&…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83475315
downvote count: 0
tagged with: pyspark
tagged with: python

http://stackoverflow.com/a/48293693
answers question: http://stackoverflow.com/q/48292152
score: 1
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48292152
has body: It is better to use currently recommended subprocess.Popen ( https://docs.python.org/3.6/library/subprocess.html ), for example as: def rnsystem (cmd, showoutput=True): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True) (out, err) = p.communicate() ret = p.wait() out = out.split('\n') err = err.split('\n') ret_tf = True if ret == 0 else False if showoutput: if ret_tf: for o in out: print(o) else: for e in err: print(e) return {'output': out, 'error': err, 'status': ret, 'status_tf': ret_tf}
type: AcceptedAnswer
type: Answer
upvote count: 1

http://stackoverflow.com/comment/83398039
has text: What happens with the second value? It's not added for `phone`, and the value for `camera` is different than the one in the list.
type: Comment
comment on: http://stackoverflow.com/q/48207313
type: QuestionComment
score: 0

http://stackoverflow.com/q/48241838
tagged with: python
has title: Working around AWS Lambda space limitations
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/83483328
upvote count: 2
score: 2
answer count: 2
tagged with: amazon-s3
has body: I am doing an example of a Simple Linear Regression in Python and I want to make use of Lambda functions to make it work on AWS so that I could interface it with Alexa. The problem is my Python package is 114 MB. I have tried to separate the package and the code so that I have two lambda functions but to no avail. I have tried every possible way on the internet. Is there any way I could upload the packages on S3 and read it from there like how we read csv's from S3 using boto3 client?
has answer: http://stackoverflow.com/a/48242033
downvote count: 0
has comment: http://stackoverflow.com/comment/83473074
has answer: http://stackoverflow.com/a/50647228
favorite count: 0
tagged with: aws-lambda
type: Question
has comment: http://stackoverflow.com/comment/83483620
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83490570
has comment: http://stackoverflow.com/comment/83476998

http://stackoverflow.com/comment/83494282
type: AnswerComment
comment on: http://stackoverflow.com/a/48255716
score: 1
has text: Thank you so much for your great explanation I had it mixed up was stuck on this for the past hour.
type: Comment

http://stackoverflow.com/comment/108115368
comment on: http://stackoverflow.com/a/61112297
type: Comment
score: 5
type: AnswerComment
has text: While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply.

http://stackoverflow.com/comment/83353076
comment on: http://stackoverflow.com/q/48185575
has text: @data 1,5,?,?,?,40,?,?,2,?,11,'average',?,?,'yes',?,'good' 2,4.5,5.8,?,?,35,'ret_allw',?,?,'yes',11,'below_average',?,'full',?,'full','good'
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83601018
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48307855
has text: For that matter, any number less than `-len(s)` will work.

http://stackoverflow.com/a/48206612
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/48206443
type: Answer
has body: for loops and the range(..) object If you write for i in range(..): Python does not translate this into something like for(int i = 0; i &lt; n; i++) (in the C-programming language family). Furthermore the range object is constructed once, before the for loop. The range(..) object, does not know which variables have been used to construct it. Once constructed, the range is fixed. It sees range(..) as an iterable object, and each iteration, it takes the next item the iterable yields. So whether you set the variable or not in the for loop, has no effect for the next iteration. In python-2.x, range(..) is not a specific object, but a call to construct a list. So if you call range(10) (without the for loop), you get [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. Why it does not work? So then why does the examples do not work? a=5 for i in range(1,a): print(i) a=a+1 Here we construct range(..) once. After that, the variables based on which it was constructed can change, since the range(..) object does change anymore. Incrementing a thus will not mean the range object will get larger. for i in range(1,4): print(i) i=i-1 The for loop each time takes the next item of the iterable. So if we first have collected 1 from the range loop, the next iteration, we collect 2. This is regardless what the value of i is. for i in range(1,4): print(i) i=1 For the very same reason: for does not take into account the previous value of i. It only fetches the next item the iterable (here range(..) yields). Since range(..) is fixed, it will simply feed the for loop the next item. Emulating an infinite loop So we need to construct an iterable that keeps yielding elements. A way to do this is itertools.count: from itertools import count for i in count(): # ... pass Or in case you are not interested in any value, we can use repeat as well: from itertools import repeat for _ in repeat(None): # ... pass
upvote count: 2

http://stackoverflow.com/comment/83605395
has text: @AndreyKravtsun 1) Even though the drawing is 2D, it still should be relevant. If you look at the contents of the `depth_data`, you can see both the background depth and the triangle depth. I just chose a 2D triangle since that was a simple shape to render in a very minimal amount of lines. Feel free to change the z-indices of the triangle and see the values in the depth texture. 2) Model should work just fine too, just have not installed the `Assimp` library on my laptop. 3) Using LinuxMint 18.3 on my laptop.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48243123
type: AnswerComment

http://stackoverflow.com/comment/83392240
has text: @Sushruth: well the `operator` package is usually faster, since usually it reduces the amount of code that has to be interpreted. A quick check says ~10-15% faster. Furthermore it *can* be dangerous (although as well wanted behavior) to sort *inplace*. The memory usage is less, but it means that other items refering to the list are now sorted as well, which can have some consequences). A final reason why `sorted(..)` can be useful over `.sort()` is that we do not always have guarantees that it is a list. We can not sort a `set` for instance, whereas `sorted` works with every iterable.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48205474
type: Comment

http://stackoverflow.com/a/48194681
has comment: http://stackoverflow.com/comment/83437016
score: 1
has comment: http://stackoverflow.com/comment/83734128
type: Answer
has comment: http://stackoverflow.com/comment/83734150
has comment: http://stackoverflow.com/comment/83407317
has comment: http://stackoverflow.com/comment/83401867
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83373579
has comment: http://stackoverflow.com/comment/83373451
answers question: http://stackoverflow.com/q/48193010
has body: This may work. I haven't tested it out to full completion since I'm at work but it should be a starting point for you. import bs4 as bs import requests import re def is_number(s): try: int(s) return True except ValueError: return False def main(): url = 'https://www.nga.org/cms/FormerGovBios?inOffice=Any&amp;state=Any&amp;party=&amp;lastName=&amp;firstName=&amp;nbrterms=Any&amp;biography=&amp;sex=Any&amp;religion=&amp;race=Any&amp;college=&amp;higherOfficesServed=&amp;militaryService=&amp;warsServed=&amp;honors=&amp;birthState=Any&amp;submit=Search' sauce = requests.get(url).text soup = bs.BeautifulSoup(sauce, "html.parser") finished = False csv_data = open('Govs.csv', 'a') csv_data.write('Name,Address,OfficeDates,Success,Address,Phone,Fax,Born,BirthState,Party,Schooling,Email') try: while not finished: #dl links to each gov table = soup.find('table', 'table table-striped table-striped') links = table.findAll('a') for link in links: info_array = [] gov = {} name = link.string gov_sauce = requests.get(r'https://nga.org'+link.get('href')).text gov_soup = bs.BeautifulSoup(gov_sauce, "html.parser") #print(gov_soup) office_and_stuff_info = gov_soup.findAll('address') for address in office_and_stuff_info: infos = address.findAll('p') for info in infos: tex = re.sub('[^a-zA-Z\d:]','',info.text) tex = re.sub('\\s+',' ',info.text) tex = tex.strip() if tex: info_array.append(tex) info_array = list(set(info_array)) gov['Name'] = name secondarry_address = '' gov['Address'] = '' for line in info_array: if 'OfficeDates:' in line: gov['OfficeDates'] = line.replace('OfficeDates:','').replace('-','') elif 'Succ' or 'Fail' in line: gov['Success'] = line elif 'Address' in line: gov['Address'] = line.replace('Address:','') elif 'Phone:' or 'Phone ' in line: gov['Phone'] = line.replace('Phone ','').replace('Phone: ','') elif 'Fax:' in line: gov['Fax'] = line.replace('Fax:','') elif 'Born:' in line: gov['Born'] = line.replace('Born:','') elif 'Birth State:' in line: gov['BirthState'] = l…

http://stackoverflow.com/q/48288553
has answer: http://stackoverflow.com/a/48289286
score: -3
has comment: http://stackoverflow.com/comment/83562176
has comment: http://stackoverflow.com/comment/83562130
favorite count: 0
has comment: http://stackoverflow.com/comment/83562246
has body: I'm trying to create a program on python that will take 3 integers and convert them into letter's using their ASCII but I'm not sure what is wrong with this program. Can you help me? num = [] letter = [] x = 0 numx = 0 for x in range(0,3): numx = int(input('Enter an integer')) num.append(numx) letter.append(str(chr(num[x])) print(letter)
has comment: http://stackoverflow.com/comment/83561963
has comment: http://stackoverflow.com/comment/83561979
has answer: http://stackoverflow.com/a/48288619
downvote count: 3
has comment: http://stackoverflow.com/comment/83563145
tagged with: python
has comment: http://stackoverflow.com/comment/83561969
has title: Integer to letters with a loop
type: Question
has comment: http://stackoverflow.com/comment/83562344
answer count: 2
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48199312
tagged with: python
tagged with: django-rest-framework
type: AnsweredQuestion
score: 0
has title: Customize the nested data in Serializer
has body: I have a ModelSerializer: class WorkOrderRetrieveSerializer(ModelSerializer): workordercomments = WorkOrderCommentForWorkOrderSerializer(many=True, read_only=True) class Meta: model = WorkOrder fields = "__all__" The JSON data is bellow: { "id": 1, "workordercomments": [ ..... { "id": 21, "content": "test files", "files": "[71]", "ctime": "2018-01-11T11:03:17.874268+08:00", "uptime": "2018-01-11T11:03:17.874362+08:00", "workorder": 1, "comment_user": { "id": 5, "username": "test03", "is_admin": true } } ], "workorder_num": "WON15118747168252", "name": "order01", "content": "first conntetn", "workordertype": "teck", "workorder_status": "created", "user_most_use_email": "lxas@128.com", "server_id": null, "public_ip": null, "belong_area": null, "files": null, "ctime": "2017-11-28T21:11:56.826971+08:00", "uptime": "2017-11-28T21:11:56.827064+08:00", "to_group": 3, "user": 2 } The "files": "[71]", in my JSON is a string of a group contains file ids. workordercomments is the related-name of the workorder. I want in the JSON workordercomments shows the files like this: { "id": 21, "content": "test files", "files": "['/media/images/xxxxx.png']", "ctime": "2018-01-11T11:03:17.874268+08:00", "uptime": "2018-01-11T11:03:17.874362+08:00", "workorder": 1, "comment_user": { "id": 5, "username": "test03", "is_admin": true } } The "files" value I want to is the link rather than its id. "files": "['/media/images/xxxxx.png']", or "files": ['/media/images/xxxxx.png'], Is it possible to customize the format? should I come true what function in serializer ?
accepted answer: http://stackoverflow.com/a/48199523
type: Question
has answer: http://stackoverflow.com/a/48199523
answer count: 1
tagged with: django

http://stackoverflow.com/q/48204861
has body: I'm using AWS Lex to generate a response to my sound (http://boto3.readthedocs.io/en/latest/reference/services/lex-runtime.html). The response audioStream is a StreamingBody object from boto3 (https://botocore.readthedocs.io/en/latest/reference/response.html#botocore.response.StreamingBody). The question is how can I turn the returned byte array to a wav file that I can play with sox? I have tried the following: audio_stream = response['audioStream'].read() f = open('response.wav', 'wb') f.write(audio_stream) f.close() But then I get an error with sox and aplay that the format is invalid (RIFF header was not found) I also tried to use the wave library with the following code audio_stream = response['audioStream'].read() f = wave.open('response.wav', 'wb') f.setnchannels(1) f.setsampwidth(2) f.setframerate(16000) f.writeframesraw(audio_stream) f.close() But then I only get white noise when I play the file and the length is very short.
tagged with: python
tagged with: wav
tagged with: boto3
tagged with: amazon-web-services
score: 2
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/48222392
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48222392
tagged with: amazon-lex
favorite count: 0
type: Question
has title: Python3 boto3 response to wav

http://stackoverflow.com/comment/83643483
has text: Well, didn't expect it to be this easy... :) Thanks!
type: Comment
comment on: http://stackoverflow.com/a/48328852
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83646719
type: Comment
has text: Its actually the other way round. I have a dense representation and want to create a sparse representation. I need to do this so that I can make a scatter plot out of it
comment on: http://stackoverflow.com/a/48330125
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83468533
score: 0
type: Comment
type: QuestionComment
has text: `output = ["".join([string,str(i)]) for i in List1]`
comment on: http://stackoverflow.com/q/48243018

http://stackoverflow.com/q/48298009
type: Question
upvote count: 22
has title: Can I give a click option another name?
accepted answer: http://stackoverflow.com/a/48298230
tagged with: python
has answer: http://stackoverflow.com/a/48298230
type: AnsweredQuestion
has body: I use click like this: import click @click.command(name='foo') @click.option('--bar', required=True) def do_something(bar): print(bar) So the name of the option and the name of the function parameter is the same. When it is not the same (e.g. when you want --id instead of --bar), I get: TypeError: do_something() got an unexpected keyword argument 'id' I don't want the parameter to be called id because that is a Python function. I don't want the CLI parameter to be called different, because it would be more cumbersome / less intuitive. How can I fix it?
tagged with: python-click
score: 21
answer count: 1
downvote count: 1
tagged with: command-line-interface
favorite count: 0

http://stackoverflow.com/q/48277886
has body: I want to connect to an SMB server and browse through its files, and for a given path, to be able to retrieve a list of files and folders, with the names and permissions. I need to support all SMB dialects, and to be able to do it from my code. The code would like roughly as follows: smbClient.connect(serverInfo); info = smbClient.getShare(shareName); for(File file : info.getFiles) { List&lt;permission&gt; permissions = file.getPermissions(); //do something } I've tried a few options such as smbj, impacket, nmap, samba but none of them seem to fill my requirements above. Is there any way to achieve the above, using Java, Python, or any linux CLI which i can call from my Java code?
has comment: http://stackoverflow.com/comment/85143733
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48467145
has comment: http://stackoverflow.com/comment/83542873
tagged with: smb
has title: Get SMB Shared Files Name and Permissions In Java
tagged with: python
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/48285858
answer count: 4
has answer: http://stackoverflow.com/a/48397051
has comment: http://stackoverflow.com/comment/83574871
downvote count: 0
has answer: http://stackoverflow.com/a/48280178
type: UnansweredQuestion
tagged with: java

http://stackoverflow.com/q/48290671
has comment: http://stackoverflow.com/comment/83566905
tagged with: export-to-csv
has comment: http://stackoverflow.com/comment/83592518
has body: I'm running a Python 2.7.12 program to process a lot of data and one of the strings I create stores a lot of data, but I have noticed that it is capped at 32,758 characters when I output the string as a CSV. I'm running my script on a development server on an Ubuntu-16.04 VM with access to 20GB of RAM Why is my one of my strings capped at 32,758? Is there a work around or way to fix this so that I am able to store more in my string? import os import pdfkit import re import requests import urllib2 #pdfminer from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage from cStringIO import StringIO #Opening my files #with open("GoodData.csv", 'w') as output: this does the same thing as what I have currently output = open("GoodData.csv", 'w') output.write("Company|Classification|ID Number|Incorporation State/Country|Address|Link to Metadata|Link to Data|Data" + '\n') count = 0 counter = 0 archive = open("archive.txt", 'w') qwerty = open("ProblemLinks.txt", 'r') for item in qwerty: #for item in linkList: print(" ") print("Number of documents parsed: " + str(count)) #This loop is for testing, to go to a specific link if counter == 0: #So I get the links out of this meta = metaData(item) pdfkit.from_url(meta[0], 'out.pdf') file = "/home/project/out.pdf" holder = convert_pdf_to_txt(file) if holder == None: output.write(''.join(['|'.join([str(meta[3]), str(meta[1]), str(meta[2]), str(meta[4]), str(meta[5]), str(item).rstrip(), str(meta[0]), "No risk data found"]), '\n'])) else: output.write(''.join(['|'.join([str(meta[3]), str(meta[1]), str(meta[2]), str(meta[4]), str(meta[5]), str(item).rstrip(), str(meta[0]), holder]), '\n'])) count = count + 1 else: counter = counter + 1 I am able to print holder before parsing is done and the entire document is stored there.
has title: Why is my string capped at 32,758 characters when outputting to CSV?
upvote count: 2
score: 2
downvote count: 0
tagged with: python
tagged with: string
has comment: http://stackoverflow.com/comment/83589828
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83592412
answer count: 1
tagged with: ubuntu-16.04
accepted answer: http://stackoverflow.com/a/48306250
has comment: http://stackoverflow.com/comment/83567647
has comment: http://stackoverflow.com/comment/83568333
has answer: http://stackoverflow.com/a/48306250
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83594974

http://stackoverflow.com/comment/91098199
score: 0
has text: Apologies for getting back on this so late: this works like a charm!
type: Comment
comment on: http://stackoverflow.com/a/48334723
type: AnswerComment

http://stackoverflow.com/comment/83334414
has text: Perhaps you haven't saved your file or restarted your server after making the changes.
comment on: http://stackoverflow.com/a/48175011
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48231273
has title: Too many values to unpack python gbf file
type: Question
has answer: http://stackoverflow.com/a/48235545
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83444869
downvote count: 1
has answer: http://stackoverflow.com/a/48231411
has answer: http://stackoverflow.com/a/48231416
has body: Hello i got python error too many values to unpack on python when i run my script Traceback: File "C:\Python27.1\perpetuum.py", line 193, in __init__ header_offset, header_length = struct.unpack('8sii', f.read(16)) ValueError: too many values to unpack. Code: class DataFile(object): """GBF file reader""" def __init__(self, filename): self.filename = filename with open(filename, 'rb') as f: header_offset, header_length = struct.unpack('8sii', f.read(16)) if magic != 'GXYDATA\x1a': raise Exception('Invalid data file (wrong magic)', magic) header = self._get_record(header_offset, header_length) self._records = self._parse_header(header) def _decode(self, data): try: import numpy as np i = np.arange(len(data), dtype=np.byte) buf = np.frombuffer(data, np.byte) ^ ((i + 1) * (i ^ -54) - 84) return buf.tostring() except ImportError: buf = array.array('B', data) for i in xrange(len(data)): buf[i] = 0xff &amp; (buf[i] ^ ((i + 1) * (i ^ 0xca) - 84)) return buf.tostring() def _get_record(self, offset, length): with open(self.filename, 'rb') as f: f.seek(offset) data = f.read(length) return self._decode(data) def _parse_header(self, header): """ header record format: int numRecords for each record: char[nameLen] nameSZ, 0 int offset int length int unkLength """ records = {} num_records = struct.unpack_from('i', header)[0] pos = 4 for i in xrange(num_records): name_end = header.find('\0', pos) name = header[pos:name_end] pos = name_end + 1 offset, length, unkLength = struct.unpack_from('iii', header, pos) pos += 12 # f1Length = min(13, unkLength) # f1 = header[pos:pos+f1Length] pos += unkLength records[name] = (offset, length) return records PREFIX_MAP = {'\x89PNG': '.png', 'DDS ': '.dds', 'A3MF': '.a3m', '#': '.txt', '=': '.txt', 'Extended Module': '.xm', 'RIFF': '.wav', 'OggS': '.ogg'} def _guess_ext(self, name, data): for prefix, ext in self.PREFIX_MAP.iteritems(): if data.startswith(prefix): return ext return '.bin' CATEGORY_MAP = OrderedDict([ ('def*.png', 'icons'), ('icon*.…
tagged with: python
has answer: http://stackoverflow.com/a/48236251
favorite count: 0
score: -1
answer count: 4

http://stackoverflow.com/comment/83625896
has text: @cᴏʟᴅsᴘᴇᴇᴅ I have got it, thx
comment on: http://stackoverflow.com/q/48319827
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83481709
comment on: http://stackoverflow.com/q/48249613
has text: Have you ran python manage.py collectstatic ?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48274050
has comment: http://stackoverflow.com/comment/83531695
score: 0
answers question: http://stackoverflow.com/q/48273907
has body: Does this get the output you looking for: import pandas as pd df=pd.DataFrame({'A':[1,2],'B':[3,4],'C':[5,6]}) Output : A B C 0 1 3 5 1 2 4 6
upvote count: 1
type: Answer
downvote count: 1

http://stackoverflow.com/comment/83369958
score: 0
has text: I was just doing the same observation, +1 `>>> import numpy as np >>> np.isnat <ufunc 'isnat'> >>> np.isnat(np.datetime64("NaT")) True >>> nat = np.datetime64("NaT") >>> nat numpy.datetime64('NaT') >>>` @OP Just convert them using `np.datetime64`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48194615

http://stackoverflow.com/comment/83647758
type: Comment
score: 0
type: AnswerComment
has text: Thank you, that worked. Wow that is a lot of quotes. I'll up vote and accept your answer shortly when SO lets me.
comment on: http://stackoverflow.com/a/48330878

http://stackoverflow.com/a/48222087
answers question: http://stackoverflow.com/q/48221710
downvote count: 1
type: Answer
upvote count: 0
score: -1
has body: import numpy as np import pandas as pd Veh_reg = np.array(['0001','0100']) date_array = np.array(['date1', 'date2']) df = pd.DataFrame({'Veh_reg':Veh_reg, 'date_array':date_array})

http://stackoverflow.com/comment/83591287
type: Comment
type: AnswerComment
has text: A new "problem" occurs ... https://stackoverflow.com/questions/48303309/use-cv2-connectedcomponents-and-eliminate-elements-with-a-small-number-of-pixels
score: 0
comment on: http://stackoverflow.com/a/48282585

http://stackoverflow.com/comment/83583651
comment on: http://stackoverflow.com/q/48296063
type: Comment
type: QuestionComment
has text: So, was `pip install inception` that gave you problems? Try reinstalling whatever you canceled adding the `--ignore-installed` flag
score: 0

http://stackoverflow.com/comment/83435288
comment on: http://stackoverflow.com/q/48226647
type: Comment
score: 1
has text: There's nothing in your detail view that mentions categories. You have `get_object.comment_set.all` but you have not set `get_object` in the template context. Did you mean to use `object.comment_set.all` instead? However, that would presumably return comments, so `{% for comment in object.commend_set.all %}` would make more sense.
type: QuestionComment

http://stackoverflow.com/comment/83605024
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48308858
has text: @juanpa.arrivillaga converted it to use `csv` - it is memory wise the smarter overall move - thanks for tipping me that way - most ppl here use huge files and data - I am C# and just pythonic in my freetime so I can get away with using list comprehensions most of the time. the ones asking questions having 1millions rows to do, may not be so fortunate

http://stackoverflow.com/comment/83811303
type: Comment
type: AnswerComment
score: 4
has text: I don't agree that you would *very likely* end in a deadlock. It might happen in some cases where the task being run uses *the same threadpool instance* to run another task.
comment on: http://stackoverflow.com/a/48327162

http://stackoverflow.com/comment/83797617
comment on: http://stackoverflow.com/a/48403961
has text: I had forgotten that context by the end of the next sentence - or it may have not registered for stating the "obvious".
type: Comment
score: 0
type: AnswerComment

dataframe
tags question: http://stackoverflow.com/q/48258994
tags question: http://stackoverflow.com/q/48252470
tags question: http://stackoverflow.com/q/48302781
tags question: http://stackoverflow.com/q/48243028
tags question: http://stackoverflow.com/q/48254436
tags question: http://stackoverflow.com/q/48285893
tags question: http://stackoverflow.com/q/48272452
tags question: http://stackoverflow.com/q/48273315
tags question: http://stackoverflow.com/q/48211095
tags question: http://stackoverflow.com/q/48290834
tags question: http://stackoverflow.com/q/48218455
tags question: http://stackoverflow.com/q/48250655
tags question: http://stackoverflow.com/q/48261358
tags question: http://stackoverflow.com/q/48220423
tags question: http://stackoverflow.com/q/48252757
tags question: http://stackoverflow.com/q/48189835
tags question: http://stackoverflow.com/q/48233746
tags question: http://stackoverflow.com/q/48263454
tags question: http://stackoverflow.com/q/48196381
tags question: http://stackoverflow.com/q/48274344
tags question: http://stackoverflow.com/q/48199806
tags question: http://stackoverflow.com/q/48195032
tags question: http://stackoverflow.com/q/48240369
tags question: http://stackoverflow.com/q/48310230
tags question: http://stackoverflow.com/q/48270609
tags question: http://stackoverflow.com/q/48275733
tags question: http://stackoverflow.com/q/48176949
tags question: http://stackoverflow.com/q/48186199
tags question: http://stackoverflow.com/q/48325935
tags question: http://stackoverflow.com/q/48198953
tags question: http://stackoverflow.com/q/48252601
tags question: http://stackoverflow.com/q/48207115
tags question: http://stackoverflow.com/q/48218037
tags question: http://stackoverflow.com/q/48246955
tags question: http://stackoverflow.com/q/48288164
tags question: http://stackoverflow.com/q/48312529
tags question: http://stackoverflow.com/q/48202955
tags question: http://stackoverflow.com/q/48196497
tags question: http://stackoverflow.com/q/48253360
tags question: http://stackoverflow.com/q/48220643
tags question: http://stackoverflow.com/q/48234092
tags question: http://stackoverflow.com/q/48211344
tags question: http://stackoverflow.com/q/48216114
tags question: http://stackoverflow.com/q/48227902
tags question: http://stackoverflow.com/q/48260848
tags question: http://stackoverflow.com/q/48280793
tags question: http://stackoverflow.com/q/48295624
tags question: http://stackoverflow.com/q/48232567
tags question: http://stackoverflow.com/q/48270953
tags question: http://stackoverflow.com/q/48199383
tags question: http://stackoverflow.com/q/48272201
tags question: http://stackoverflow.com/q/48251562
tags question: http://stackoverflow.com/q/48273713
tags question: http://stackoverflow.com/q/48313828
tags question: http://stackoverflow.com/q/48184930
tags question: http://stackoverflow.com/q/48328468
tags question: http://stackoverflow.com/q/48310207
tags question: http://stackoverflow.com/q/48179297
tags question: http://stackoverflow.com/q/48299312
tags question: http://stackoverflow.com/q/48286199
tags question: http://stackoverflow.com/q/48313045
tags question: http://stackoverflow.com/q/48299353
tags question: http://stackoverflow.com/q/48269844
tags question: http://stackoverflow.com/q/48204558
tags question: http://stackoverflow.com/q/48318858
tags question: http://stackoverflow.com/q/48290687
tags question: http://stackoverflow.com/q/48253759
tags question: http://stackoverflow.com/q/48276837
tags question: http://stackoverflow.com/q/48211358
tags question: http://stackoverflow.com/q/48235286
tags question: http://stackoverflow.com/q/48294273
tags question: http://stackoverflow.com/q/48254555
tags question: http://stackoverflow.com/q/48213149
tags question: http://stackoverflow.com/q/48235420
tags question: http://stackoverflow.com/q/48302066
tags question: http://stackoverflow.com/q/48197234
tags question: http://stackoverflow.com/q/48318578
tags question: http://stackoverflow.com/q/48175172
tags question: http://stackoverflow.com/q/48174398
tags question: http://stackoverflow.com/q/48304927

http://stackoverflow.com/q/48270742
has body: I am trying to web scrape the website fairygodboss.com and having trouble retrieving the reviews date... When I run the following under the rvest package: url<-read_html('https://fairygodboss.com/company-reviews/boston-consulting-group') Review<-url %>% html_nodes(xpath ='//p[@class="textColor6 w-700 p-b-10"]')%>% html_text() I should get the different dates as 2017/2016, but instead I get all dated as January 1970. Please can you help me identify the issue. I also tried on Python with bs4 as follows, I still have 1970 everywhere: import urllib r = urllib.urlopen('https://fairygodboss.com/company-reviews/boston-consulting-group').read()
upvote count: 0
answer count: 2
tagged with: web-scraping
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/48405078
has title: R/Python Webscraping - Date issue 1970
has answer: http://stackoverflow.com/a/75912703
has comment: http://stackoverflow.com/comment/83526994
type: Question
has comment: http://stackoverflow.com/comment/83550827
tagged with: python
type: UnansweredQuestion
tagged with: rvest
score: -1
tagged with: http://stackoverflow.com/tag/r

http://stackoverflow.com/a/67296867
has comment: http://stackoverflow.com/comment/124073591
type: Answer
has comment: http://stackoverflow.com/comment/119116615
score: 0
has body: Disclaimer: I was a contributor to pywindsorai. Assuming you just need the clicks (or spend) data, you can do this using windsor.ai as well, which is a bit simpler to use. You just have to connect your Twitter account to windsor.ai, and then use their Python SDK (pywindsorai) to load the data into pandas. import pandas as pd from pywindsorai.client import Client from pywindsorai.enums import LAST_7D from pywindsorai.enums import FIELD_SOURCE, FIELD_CAMPAIGN, FIELD_CLICKS api_key = 'xxx' # Get this from your windsor.ai account client = Client(api_key) campaign_clicks = client.connectors(date_preset=LAST_7D, fields=[FIELD_SOURCE, FIELD_CAMPAIGN, FIELD_CLICKS]) df = pd.DataFrame(campaign_clicks['data'])
answers question: http://stackoverflow.com/q/48319170

http://stackoverflow.com/q/48219191
upvote count: 1
has comment: http://stackoverflow.com/comment/83420786
has comment: http://stackoverflow.com/comment/83420214
has comment: http://stackoverflow.com/comment/83420610
has answer: http://stackoverflow.com/a/48219204
has body: How do I criss cross two lists together in python? Example: list_1 = [1, 2, 3] list_2 = [4, 5, 6] Expected Outcome: combined_list = [1, 4, 2, 5, 3, 6]
linked to: http://stackoverflow.com/q/11125212
has comment: http://stackoverflow.com/comment/83420242
has comment: http://stackoverflow.com/comment/83420451
has comment: http://stackoverflow.com/comment/83420672
favorite count: 0
accepted answer: http://stackoverflow.com/a/48219216
type: Question
has comment: http://stackoverflow.com/comment/83420221
possible better answer: http://stackoverflow.com/a/48219204
has comment: http://stackoverflow.com/comment/83420765
has comment: http://stackoverflow.com/comment/83420468
has comment: http://stackoverflow.com/comment/83420430
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83420208
has comment: http://stackoverflow.com/comment/83420201
has title: How do I criss cross two lists together in python?
has answer: http://stackoverflow.com/a/48219216
has answer: http://stackoverflow.com/a/48219217
has comment: http://stackoverflow.com/comment/83420339
has comment: http://stackoverflow.com/comment/83420465
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/11125212
has comment: http://stackoverflow.com/comment/83420367
tagged with: list
downvote count: 2
answer count: 3

http://stackoverflow.com/comment/83330939
type: AnswerComment
has text: @aspiring That might work but do you really want to track them manually? If these correspond to a piece of data you're picking up from somewhere else, you might want to set them manually and shouldn't rely on Django to set them for you. In most cases, however, the ID is meaningless - it's just a way to find a particular record and, as such, what the number is shouldn't matter.
score: 3
type: Comment
comment on: http://stackoverflow.com/a/48175419

http://stackoverflow.com/comment/83541211
type: QuestionComment
score: 2
has text: Looks like that you want to call `SignIn.login()`.
comment on: http://stackoverflow.com/q/48278832
type: Comment

http://stackoverflow.com/comment/84438207
has text: But one of the questions remains, how does that happen that pixel reading functions return wrong dimensions (width and height are swapped?). For example, in your code snippet `depth_str = glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_FLOAT)` depth_str.shape == (800, 600), according to debug output.
comment on: http://stackoverflow.com/a/48243123
score: 1
type: Comment
type: AnswerComment

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/48292298
tags question: http://stackoverflow.com/q/48241660
tags question: http://stackoverflow.com/q/48224063
tags question: http://stackoverflow.com/q/48306896
tags question: http://stackoverflow.com/q/48176403
tags question: http://stackoverflow.com/q/48224201
tag name: kivy-language
tags question: http://stackoverflow.com/q/48245794
tags question: http://stackoverflow.com/q/48259400
tags question: http://stackoverflow.com/q/48325676
tags question: http://stackoverflow.com/q/48287204
tags question: http://stackoverflow.com/q/48307543
tags question: http://stackoverflow.com/q/48307305

http://stackoverflow.com/comment/83450802
type: Comment
type: QuestionComment
has text: Can you show what your input and output are supposed to look like? I am having trouble seeing exactly what you want.
score: 0
comment on: http://stackoverflow.com/q/48234088

http://stackoverflow.com/q/48280197
has comment: http://stackoverflow.com/comment/83544022
has answer: http://stackoverflow.com/a/48280657
type: Question
has body: I have been given this as a list of lists each containing either a number 1 2 3 and 0 (0 is repeated twice). Depending on the number and the position I would like a corresponding variable to get added 1 time for each occurrence. ballots = [['1', '2', '3', '0', '0'], ['1', '3', '0', '2', '0'], ['1', '2', '3', '0', '0'], ['0', '3', '2', '0', '1'], ['1', '3', '0', '2', '0'], ['2', '0', '3', '1', '0'], ['0', '0', '2', '1', '3'], ['0', '1', '2', '3', '0'], ['0', '1', '0', '2', '3'], ['2', '3', '1', '0', '0'], ['3', '2', '0', '0', '1'], ['0', '1', '3', '2', '0'], ['0', '0', '1', '2', '3'], ['0', '0', '3', '2', '1'], ['1', '2', '3', '0', '0'], ['2', '1', '3', '0', '0'], ['0', '3', '2', '1', '0'], ['0', '2', '3', '0', '1'], ['1', '2', '3', '0', '0'], ['1', '0', '0', '3', '2'], ['2', '1', '3', '0', '0'], ['3', '1', '2', '0', '0'], ['2', '3', '0', '1', '0'], ['0', '0', '3', '1', '2'], ['0', '3', '1', '0', '2'], ['2', '1', '0', '0', '3'], ['2', '0', '0', '1', '3'], ['2', '0', '0', '1', '3'], ['3', '0', '1', '0', '2']] For example, for the first list: the 1 in position 1 would mean that candidate1vote1 += 1 the 2 in the 2nd position would mean that candidate2vote2 += 1 the 3 in the 3rd position would mean that candidate3vote3 += 1 All 0's are ignored but still counted as a space. For the second list: the 1 in the first position would mean that candidate1vote1 += 1 the 3 in the 2nd position would mean that candidate3vote2 += 1 the 2 in the 4th position would mean that candidate4vote2 += 1 Basically the position corresponds to candidate1/2/3/4/5 and the value corresponds to either a 1st preference vote, 2nd preference vote or a 3rd preference vote. Does anyone know how I'd be able to sort through the lists using for/while loops so that it goes through each ballot and each individual vote doing the corresponding sum?
answer count: 2
has answer: http://stackoverflow.com/a/48280553
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83544943
downvote count: 2
has comment: http://stackoverflow.com/comment/83544212
tagged with: python
has comment: http://stackoverflow.com/comment/83545562
tagged with: sorting
favorite count: 0
has title: Python 2d array issues
tagged with: list
linked to: http://stackoverflow.com/q/240178
has comment: http://stackoverflow.com/comment/83544270
has comment: http://stackoverflow.com/comment/83544502
score: -2

http://stackoverflow.com/a/48318566
has comment: http://stackoverflow.com/comment/98099855
has comment: http://stackoverflow.com/comment/97883804
has comment: http://stackoverflow.com/comment/98104960
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48318417
has body: Seems like ps.Spatial_Markov wants a numpy array, while you pass a pandas data frame. Try extracting the array from the data frame by modifying this line pci = f[list(map(str,range(1, 1096)))].as_matrix() Update Indeed, the docs are quit specific about that: pysal.spatial_dynamics.markov.Spatial_Markov(y, w, k=4, permutations=0, fixed=False, variable_name=None) Parameters: - y (array) – (n,t), one row per observation, one column per state of each observation, with as many columns as time periods. ...
has comment: http://stackoverflow.com/comment/97922675
answers question: http://stackoverflow.com/q/48318417
has comment: http://stackoverflow.com/comment/98049280
type: Answer

http://stackoverflow.com/q/48195549
has body: [UPDATED: 'fix' is disable SMT in BIOS; i.e. something very ugly is going on: FreeBSD vs Ryzen] This one has me scratching my head. The following code intermittently fails on FreeBSD 11.1 + python 3.6.4 + postgresql 10.1 + Ryzen 1600x. This is all happening inside of a Flask app, but I do not think that that is relevant. The problem does not occur with this code with macOS + python 3.6.4 + postgresql 10.1. The code does not seem to fail ever if workers &lt;= 4. It will fail randomly if workers &gt;= 5. It will take &lt; 20 tries to induce a failure. Success will yield the list of finds, of course. You will also see a copy of finished search for every worker: 4x, 6x, 10x, ... You will also see a single RETURNED FROM SEARCH. Failure means you never get the list returned. But you will see a copy of finished search for every worker: 4x, 6x, 10x, ... And so workonsearch() really does seem to have completely finished. Nevertheless you will not see RETURNED FROM SEARCH as the result returns to threadedsearcher() A stripped down version of the code in question: def threadedsearcher(searchobject): managedlistoffinds = manager.list() searchlist = manager.list(searchobject.tosearch) workers = 6 jobs = [Process(target=workonsearch, args=(managedlistoffinds, searchlist, lookingfor)) for i in range(workers)] for j in jobs: j.start() for j in jobs: j.join() print('RETURNED FROM SEARCH') return managedlistoffinds def workonsearch(managedlistoffinds, searchlist, lookingfor): dbconnection = setconnection() curs = dbconnection.cursor() so = searchobject while searchlist: try: table = searchlist.pop() except IndexError: table = None searchlist = None if table: newfinds = mysearch(lookingfor, table) managedlistoffinds += newfinds dbconnection.commit() curs.close() print('finished search') return managedlistoffinds
has title: FreeBSD + multithreaded python = *intermittent* failures to return from function [Ryzen incompatibility?]
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84263536
has comment: http://stackoverflow.com/comment/83374443
answer count: 0
tagged with: hardware
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83491622
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84263664
has comment: http://stackoverflow.com/comment/83442853
tagged with: freebsd
type: UnansweredQuestion
tagged with: multithreading

http://stackoverflow.com/comment/83578372
score: 0
has text: Sorry, forgot to do so! Edited the post accordingly, its for Python.
comment on: http://stackoverflow.com/q/48296778
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48262492
upvote count: 7
linked to: http://stackoverflow.com/q/6413441
favorite count: 0
has answer: http://stackoverflow.com/a/68297024
type: Question
has comment: http://stackoverflow.com/comment/83508619
has body: I want to convert JSON data to PDF which is getting from API. example JSON data { "data": [ { "state": "Manchester", "quantity": 20 }, { "state": "Surrey", "quantity": 46 }, { "state": "Scotland", "quantity": 36 }, { "state": "Kent", "quantity": 23 }, { "state": "Devon", "quantity": 43 }, { "state": "Glamorgan", "quantity": 43 } ] } I found this script: http://code.activestate.com/recipes/578979-convert-json-to-pdf-with-python-and-xtopdf/ but getting error no module PDFWriter Is there any another way to convert JSON Data PDF. PLEASE HELP.
has title: How to convert JSON data to PDF using python script
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48265741
linked to: http://stackoverflow.com/q/42753745
has comment: http://stackoverflow.com/comment/83510508
answer count: 3
score: 7
tagged with: http://stackoverflow.com/tag/pdf
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/71819215
tagged with: python
linked to: http://stackoverflow.com/q/7771011

http://stackoverflow.com/a/48285522
answers question: http://stackoverflow.com/q/48279740
type: Answer
has body: You can try this regex : import re pattern=r'(?:\/\/)(\w+)|(?&lt;=\.)(\w+)' string='http://news.bbc.co.uk/foo/bar/xyzzy.html' result=[] match=re.finditer(pattern,string) for i in match: if i.group(1)!=None: result.append(i.group(1)) elif i.group(2)!=None and i.group(2)!='html': result.append(i.group(2)) print(result) output: ['news', 'bbc', 'co', 'uk'] But Cool thing is you can do this thing in one line: import tldextract result=tldextract.extract("http://news.bbc.co.uk/foo/bar/xyzzy.html") print([i.split('.') for i in result]) output: [['news'], ['bbc'], ['co', 'uk']]
score: 0

http://stackoverflow.com/comment/83359872
type: Comment
type: QuestionComment
has text: Define your `migrate`. Generally write ones' code by the format of the line, then put them into the contrib directory, add some cmake file, re-cmake.
comment on: http://stackoverflow.com/q/48188940
score: 1

http://stackoverflow.com/q/48198030
tagged with: docker
tagged with: docker-volume
has title: Returning log file from process run in docker
answer count: 2
score: 1
downvote count: 0
upvote count: 1
has body: I'm a total newbie to docker, and am having trouble on how to approach this problem. Consider this super simplified cli tool that produces a log when ran with docker run. import click import logging logging.basicConfig(filename='log.log') logger = logging.getLogger(__name__) @click.group() @click.version_option('1.0') def cli(): '''docker_cli with docker test''' @cli.command('run') @click.argument('name', default='my name') def run(name): logger.info("running 'run' within docker") print('Hello {}'.format(name)) And my dockerfile is as follows: FROM python:3.5-slim LABEL maintainer="Boudewijn Aasman" LABEL version="1.0" ENV config production RUN mkdir /docker_cli COPY docker_cli ./docker_cli COPY setup.py . RUN python setup.py install CMD ["cli", "run"] If I execute the container using: docker run cli_test cli run world how do I retrieve the log file that gets created during the process? The container exits immediately after the command print out 'Hello world'. My assumption is using a volume, but not sure how to make it work.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48198103
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48198174
tagged with: python

http://stackoverflow.com/comment/83435823
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48214470
has text: Fixed the defaults. @Paul there must be a notion of confidence - if I parse '11/12/2017' then I'm approx. 50% confident that the result is correct. Perhaps you could elaborate on some of the pitfalls you envisage?
score: 0

http://stackoverflow.com/comment/83613092
type: QuestionComment
comment on: http://stackoverflow.com/q/48313674
has text: c = math.log10(i/1024) is a float object. You cannot iterate over this object.
score: 0
type: Comment

http://stackoverflow.com/comment/83334059
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48176954
has text: Thanks @piRSquared ! This works, and deals fine with NaNs (which I have in my actual dataframe).
score: 0

http://stackoverflow.com/comment/83421041
score: 0
type: Comment
type: QuestionComment
has text: Yes, the XML has an encoding declaration that claims UTF-8. I've tried smaller data sets, but I can't get them to fail.
comment on: http://stackoverflow.com/q/48219469

http://stackoverflow.com/q/48216574
score: 1
answer count: 1
downvote count: 1
tagged with: machine-learning
tagged with: scikit-learn
tagged with: keras
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83416399
accepted answer: http://stackoverflow.com/a/48217900
has body: I don't know the reason why the results I have obtained aren't scale well. As you can see on the pictures bellow, there is a problem with scaling. There are two issues: There are no negative values There is problem with maximum values prediction I don't have idea why I have those problems. Do you have any idea's how I can fix this issue? I would be very grateful for your help CODE: # Read inputs X = dataset.iloc[0:20000, [1, 4, 10]].values # Read output y = dataset.iloc[0:20000, 5].values # Splitting the dataset into the Training set and Test set from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # Output matrix conversion y_train = y_train.reshape(-1, 1) y_test = y_test.reshape(-1, 1) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) y_train = sc.fit_transform(y_train) y_test = sc.transform(y_test) # Import the Keras libraries and package from keras.models import Sequential from keras.layers import Dense # building model classifier = Sequential() classifier.add(Dense(activation="sigmoid", input_dim=3, units=64, kernel_initializer="uniform")) classifier.add(Dense(activation="sigmoid", units=32, kernel_initializer="uniform")) classifier.add(Dense(activation="sigmoid", units=16, kernel_initializer="uniform")) classifier.add(Dense(activation="sigmoid", units=1, kernel_initializer="uniform")) classifier.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy']) # Fitting the ANN to the training set results = classifier.fit(X_train, y_train, batch_size=16, epochs=25) # Predicting the Test set results y_pred = classifier.predict(X_test)
tagged with: neural-network
tagged with: python
has title: ANN: keras/sklearn doesn't scale well
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48217900
has comment: http://stackoverflow.com/comment/83416211

http://stackoverflow.com/comment/83540187
has text: like @Daniel said, you can do it this way and access it with new[0].parent_order.ticker . Or you can do it like i said, step by step
comment on: http://stackoverflow.com/a/48278267
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/48207685
upvote count: 1
has answer: http://stackoverflow.com/a/48208084
favorite count: 0
type: Question
tagged with: numpy
tagged with: multidimensional-array
has answer: http://stackoverflow.com/a/48208088
tagged with: python
accepted answer: http://stackoverflow.com/a/48210054
has title: Advanced Integer slicing when slicing object is an ndarray tuple
has answer: http://stackoverflow.com/a/48210054
has body: I understand how x=np.array([[1, 2], [3, 4], [5, 6]] y = x[[0,1,2], [0,1,0]] Output gives y= [1 4 5] This just takes the first list as rows and seconds list and columns. But how does the the below work? x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]]) rows = np.array([[0,0],[3,3]]) cols = np.array([[0,2],[0,2]]) y = x[rows,cols] This gives the output of : [[ 0 2] [ 9 11]] Can you please explain the logic when using ndarrays as slicing object? Why does it have a 2d array for both rows and columns. How are the rules different when the slicing object is a ndarray as opposed to a python list?
type: AnsweredQuestion
answer count: 3
tagged with: numpy-indexing
tagged with: matrix
score: 1
possible better answer: http://stackoverflow.com/a/48208084
downvote count: 0

http://stackoverflow.com/q/48211344
has answer: http://stackoverflow.com/a/48211735
has body: I am very new to programming languages. I am trying pandas and python. I have a csv file that I want to turn the table. The original table looks like: W0 W1 W2 P1 11 12 10 P2 7 6 3 P3 7 11 8 P4 12 8 13 P5 8 5 13 I want to turn the table so that the P1-Pn would be my first row and W0-Wn be my column. I tried several codes but none worked.
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/83404669
score: 0
has comment: http://stackoverflow.com/comment/83404130
has comment: http://stackoverflow.com/comment/83404733
has comment: http://stackoverflow.com/comment/83404990
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/83405023
has title: How to unstack a dataframe in pandas?
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/83376480
type: QuestionComment
comment on: http://stackoverflow.com/q/48197549
has text: @sKwa There are no generators here...
score: 0
type: Comment

http://stackoverflow.com/comment/94688260
type: Comment
comment on: http://stackoverflow.com/a/53923249
type: AnswerComment
has text: Hi, thanks for your kind sharing, but it seems that custom configuration has priority over system wide config?
score: 1

http://stackoverflow.com/a/48227083
has body: Your problem doesn't appear to be any extra newlines, it's simply that you configured it to show 7 lines but you're only inserting 6. If you set the height to 6 you won't see this blank line.
downvote count: 0
has comment: http://stackoverflow.com/comment/137248642
type: Answer
answers question: http://stackoverflow.com/q/48220788
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/137248600

http://stackoverflow.com/a/48302487
has comment: http://stackoverflow.com/comment/83663556
has comment: http://stackoverflow.com/comment/83666155
has comment: http://stackoverflow.com/comment/83737939
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/83663419
has body: Without altering your code too much (and without testing), an easy way to get what you want is to add another condition to your key checks. If you alter the relevant code section as follows, all should be fine: for event in pygame.event.get(): # eventHandler for keyboard events during game if event.type == pygame.QUIT: gameExit = True if event.type == pygame.KEYDOWN: if (event.key == pygame.K_LEFT or event.key == pygame.K_a) and direction != "right": # Each of these handles either arrow keys or WASD key events. lead_x_change = -blockSize lead_y_change = 0 direction = "left" elif (event.key == pygame.K_RIGHT or event.key == pygame.K_d) and direction != "left": lead_x_change = blockSize lead_y_change = 0 direction = "right" elif (event.key == pygame.K_UP or event.key == pygame.K_w) and direction != "down": lead_y_change = -blockSize lead_x_change = 0 direction = "up" elif (event.key == pygame.K_DOWN or event.key == pygame.K_s) and direction != "up": lead_y_change = blockSize lead_x_change = 0 direction = "down" elif event.key == pygame.K_ESCAPE: pauseGame() Mind the parentheses around the or'd key checks!
score: 2
answers question: http://stackoverflow.com/q/48301798
downvote count: 0

http://stackoverflow.com/comment/83355237
type: Comment
type: QuestionComment
has text: It's not exactly clear what you're asking. Do you just want any values from the json response? If yes, just access them via their keys. `json.loads() `returns a dictionary. You can use all methods of `dict` then.
comment on: http://stackoverflow.com/q/48187790
score: 0

http://stackoverflow.com/comment/83593909
comment on: http://stackoverflow.com/q/48303969
score: 0
type: Comment
has text: Does this page have any documentation? Is it your personal page?
type: QuestionComment

http://stackoverflow.com/a/48264852
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48263802
score: 3
accepted answer of: http://stackoverflow.com/q/48263802
has body: you can parse the geojson and extract the points / coordinates import json data = json.loads(datastring) data['features'][0]['geometry'] #Your first point ( How can I parse GeoJSON with Python ) When you load a GeoJSON file using the json library, you get a dict that contains an entry features, which contains the list of features. Each feature in turn consists of a dict, which, among other things, contains an entry geometry. The geometry is a dict containing the entries type and coordinates. So you can traverse your GeoJSON file like this: import json with open('test.json') as f: data = json.load(f) for feature in data['features']: print feature['geometry']['type'] print feature['geometry']['coordinates'] ( https://gis.stackexchange.com/questions/73768/how-to-convert-geojson-to-python-objects ) now that you have the coordinates / points create a polygon in shapely with it to get a geometric representation of the city boundaries : How to create a Polygon given its Point vertices? Point-in-Polygon Now that you have a polygon, determining whether a point is inside it is very easy. There’s 2 ways to do it. `point.within(polygon)` `polygon.contains(point)` point should be an instance of the Point class, and poly is of course an instance of Polygon. within and contains are the converse of each other, so whichever method you use is entirely up to you. https://streamhacker.com/2010/03/23/python-point-in-polygon-shapely/ in shapely is a specific class to handle points and only points that are represented in this class will work in the point.within(polygon) and polygon.contains(point) functions. The point type is implemented by a Point class; curve by the LineString and LinearRing classes; and surface by a Polygon class. Shapely implements no smooth (i.e. having continuous tangents) curves. All curves must be approximated by linear splines. All rounded patches must be approximated by regions bounded by linear splines. ( https://toblerity.org/shapely/manual.html ) so you have …
has comment: http://stackoverflow.com/comment/83512956

http://stackoverflow.com/q/48307919
tagged with: python
tagged with: boto3
tagged with: amazon-web-services
has title: Unknown service error botocore
type: AnsweredQuestion
tagged with: botocore
has body: I'm trying to use the recent Amazon transcribe service with: transcribe = boto3.client('transcribe') and I get the following error: botocore.exceptions.UnknownServiceError: Unknown service: 'transcribe'. Valid service names are: ... I've tried upgrading boto3 and botocore using: pip install botocore --upgrade pip install boto3 --upgrade
favorite count: 0
has comment: http://stackoverflow.com/comment/83601109
has comment: http://stackoverflow.com/comment/133437540
type: Question
score: 5
accepted answer: http://stackoverflow.com/a/48307993
upvote count: 5
downvote count: 0
answer count: 1
tagged with: aws-sdk
has answer: http://stackoverflow.com/a/48307993

http://stackoverflow.com/q/48258864
score: 0
type: UnansweredQuestion
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/48259184
has body: I am trying to build a wheel and source distribution on windows 10 for a project of mine, but the build freezes at removing 'release-exporter-1.0' (and everything under it) for sdist and creating build\bdist.win-amd64\wheel\release_exporter-1.0.dist-info\WHEEL for bdist_wheel. Following is my setup.py setup( name='release-exporter', version=version(), install_requires=get_requirements('requirements.txt'), packages=find_packages(), url='https://github.com/akshaybabloo/release-exporter', license='MIT', author='Akshay Raj Gollahalli', author_email='akshay@gollahalli.com', description='Release exporter for GitHub and GitLab.', keywords="changelog releases", classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Intended Audience :: Developers', 'Environment :: Console', 'Development Status :: 5 - Production/Stable', 'Topic :: Utilities' ], entry_points={ 'console_scripts': [ 'rex = release_exporter:main' ] }, ) I have tried to manually give the package name from ['release_exporter'] to using find_packages() of setup tools. I also thought the keyword should be a string, so I changed it from ['changelog', 'releases'] to "changelog releases". But still no luck. Also, I have tried to set --verbose flag by doing python setup.py sdist --verbose, but it doesn't work. I think the bug is not rectified yet -> https://bugs.python.org/issue7202 Any help would be appreciated. Update I am using Python 3.6.3
has title: sdist and bdist_wheel freezes at build
tagged with: python

http://stackoverflow.com/comment/83442913
has text: ` An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module: if __name__ == '__main__': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce an executable.`
type: Comment
comment on: http://stackoverflow.com/a/48217551
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83451254
score: 3
comment on: http://stackoverflow.com/q/48234274
has text: `idx` is the primary key, therefore it is indexed. Presumably `prop_link` is not indexed, which explains the difference in speed.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48191362
has body: You can use UtilityInfo.index.names=['Date'] to give a name to the index. You could also create a column from this index using df.reset_index() Good ref : Rename Pandas DataFrame Index
answers question: http://stackoverflow.com/q/48177087
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48177087

http://stackoverflow.com/comment/83416003
has text: @Rawing Code Review cannot magically fix that. It's not on topic there, either. Is it?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48216921

http://stackoverflow.com/a/48188317
upvote count: 1
has body: You need a random timer variable which you can decrement by the dt (delta time) each frame. When it's below zero, create a bullet instance, add it to the group and reset the timer. I use the random.uniform function here which gives you a float, but you could also use random.randrange or randint if you want ints. To get the delta time (the time since the last tick) just assign the value that clock.tick(fps) returns to a variable. # The timer is the time in seconds until the enemy shoots. timer = random.uniform(2, 6) # Random float between 2 and 6. dt = 0 running = True while True: # Event handling omitted. # Decrease the timer by the delta time. timer -= dt if timer &lt;= 0: # Ready to fire. # Pick a random enemy to get the x and y coords. random_enemy = random.choice(enemy.sprites()) enemy_x, enemy_y = random_enemy.rect.center # Create a bullet and add it to the sprite groups. bullet = BulletEnemy(enemy_x, enemy_y) allSprites.add(bullet) enemy.add(bullet) timer = random.uniform(2, 6) # Reset the timer. # Collision detection and drawing omitted. # clock.tick returns the time that has passed since the last frame. dt = clock.tick(60) / 1000 # / 1000 to convert it to seconds.
answers question: http://stackoverflow.com/q/48187816
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/q/48239021
tagged with: python-2.7
score: 0
has body: I have problem to use function for Pandas DataFrame, only 1st column result calculated. Problem seem coming out when I extract value from df2, as it was OK when I give direct value to G and H, but I really need to extract from df2 DataFrame import pandas as pd import numpy as np def mmInch(x): return(x/25.4) def Inchmm(x): return(x*25.4) def PsiBarg(x): return(x/14.5) def MB31G(L,W,T,S,D,P): Z=(mmInch(L))**2/(D*(mmInch(T))) M=np.where(Z&gt;50,0.032*0.032*Z+3.3,(1+0.6275*Z-0.003375*Z**2)**(1/2)) F=P*((1-0.85*W)/(1-0.85*W/M)) I=2*F*mmInch(T)/D return(PsiBarg(I*S)) raw_data = {'L': [2,4,5,6,4], 'W':[0.1,0.12,0.15,0.3,0.4],'T': [12,12,12,15,15], 'S':[0.72,0.72,0.72,0.5,0.5]} df1 = pd.DataFrame(raw_data, columns = ['L', 'W', 'T', 'S',]) df2 = pd.DataFrame({'a':[28], 'b': [75000]}) G=df2['a'] H=df2['b'] df1['Result']=MB31G(df1['L'],df1['W'],df1['T'],df1['S'],G,H) df1
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/83460712
has title: Pandas DataFrame Function
has comment: http://stackoverflow.com/comment/83460549
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83460520
has comment: http://stackoverflow.com/comment/83460346
tagged with: python

http://stackoverflow.com/q/48314325
tagged with: python
has title: Concurrent Futures and the correct number of threads to use.
score: 2
has comment: http://stackoverflow.com/comment/83614310
has comment: http://stackoverflow.com/comment/84350323
answer count: 0
has comment: http://stackoverflow.com/comment/83614409
tagged with: concurrent.futures
has body: I'm developing a webscraping tool and I am using concurrent processes. I want to know if there is a general rule for the number of threads you need to use. Currently, I have it set for 10, but I've noticed that I get a lot more missing data values when I push the number past the amount of threads. URLs = loadit() start = time.time() with ThreadPoolExecutor(max_workers=10) as executor: # start the load operations and mark each future with its URL future_to_url = {executor.submit(load_url, url): url for url in URLs} for future in concurrent.futures.as_completed(future_to_url): url = future_to_url[future] try: data = future.result() print(data.values()) # scraped_data = restaurant_parse(link) # time.sleep(random.randrange(3, 5)) writeit(outName, data.values()) except Exception as exc: print('%r generated an exception: %s' % (url, exc)) end = time.time() print(end - start) lscpu on a ubuntu linux box shows ubuntu-dev@ubuntu:~$ lscpu Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian CPU(s): 3 On-line CPU(s) list: 0-2 Thread(s) per core: 1 Core(s) per socket: 3 Socket(s): 1 NUMA node(s): 1 Vendor ID: GenuineIntel CPU family: 6 Model: 61 Model name: Intel(R) Core(TM) i7-5557U CPU @ 3.10GHz Stepping: 4 CPU MHz: 3100.000 BogoMIPS: 6200.00 Hypervisor vendor: KVM Virtualization type: full L1d cache: 32K L1i cache: 32K L2 cache: 256K L3 cache: 4096K NUMA node0 CPU(s): 0-2 Thank you!
favorite count: 0
has comment: http://stackoverflow.com/comment/83615685
tagged with: multiprocessing
type: Question
tagged with: linux
has comment: http://stackoverflow.com/comment/83679471
upvote count: 2
type: UnansweredQuestion
tagged with: multithreading
downvote count: 0

http://stackoverflow.com/comment/83495891
score: 0
comment on: http://stackoverflow.com/q/48256557
has text: @schwobaseggl Yep, I don't think there's a way around the O(N) without replicating data.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48257072
has comment: http://stackoverflow.com/comment/83496940
has answer: http://stackoverflow.com/a/48257149
possible better answer: http://stackoverflow.com/a/48257183
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/48257149
has body: I hope the title wasn't too confusing, but you'll see what I meant by that in a bit. In the meantime, some backstory-- I'm working on a function that generates random usernames and passwords and writes them in a text file as username:password for another program that collects the username:password line as: string = line.split(":") username = string[0] pwd = string[1] Why does this matter? Well, when I run my function: Code: # To generate users and passwords for the password file: """ Usage: count-- how many accounts to generate file-- where to dump the accounts method-- dict is where it loops through words and chooses random ones as users and passwords, and brute (not implemented yet) is where it chooses random characters and strings them together as users and passwords. users-- if you want any filled in users, put them in here. passes-- if you want any filled in passes, put them in here. """ def genAccts(count, file, method="dict", users=[], passes=[]): try: f = open(file, "w") if method == "dict": dictionary = "Dictionary.txt"#input("[*] Dictionary file: ") d = open(dictionary, "r") words = d.readlines() d.close() accts = [] for b in range(0, count): global user global pwd user = random.choice(words) pwd = random.choice(words) if b < len(users)-1: user = users[b] if b < len(passes)-1: pwd = passes[b] acct = [user, pwd] accts.append(acct) print("[+] Successfully generated",count,"accounts") for acct in accts: combined = acct[0]+":"+acct[1] print(combined) f.write(combined) f.close() print("[+] Successfully wrote",count,"accounts in",file+"!") except Exception as error: return str(error) genAccts(50, "brute.txt") In my password file brute.txt, I get an output like quainter :slightest litany :purples reciprocal :already delicate :four and so I'm wondering why is a \n added after the username?
downvote count: 0
has comment: http://stackoverflow.com/comment/83496913
upvote count: 1
has answer: http://stackoverflow.com/a/48257183
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48257439
has comment: http://stackoverflow.com/comment/83496836
has title: In python, newStr+":"+otherStr becomes newStr+"\n"+":"+otherStr
answer count: 3
score: 1

http://stackoverflow.com/comment/83603432
type: QuestionComment
type: Comment
has text: _could not bind on port_ - make sure that ports are accessible or set free port manually (`spark.ui.port`) and see if it resolves the problem.
score: 0
comment on: http://stackoverflow.com/q/48308586

http://stackoverflow.com/q/48304675
has body: I know other people went through this kind of problem but I still can't fix the problem. I just began to programming. I use spyder IDE and get the following error when I run the code. File "C:\Users\kaany\AppData\Roaming\Python\Python36\site-packages\matplotlib\path.py", line 25, in &lt;module&gt; from . import _path, rcParams ImportError: cannot import name '_path' When I remove 'import matplotlib as plt' from my code everything goes fine. I have numpy 1.13.3 and matplotlib 2.1.0 I'd appreciate if someone provided any solution to this.
answer count: 0
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83594726
favorite count: 0
type: Question
tagged with: importerror
has comment: http://stackoverflow.com/comment/83595195
type: UnansweredQuestion
tagged with: matplotlib
tagged with: spyder
tagged with: python
has title: Import Error: Cannot import name '_path' PYTHON
has comment: http://stackoverflow.com/comment/83595059

http://stackoverflow.com/comment/83353180
comment on: http://stackoverflow.com/q/48186011
type: QuestionComment
score: 0
type: Comment
has text: I ran your code with `my_data = pd.DataFrame([[1, 2], [3, 4]])` and it worked as expected, both tables were created and populated.

http://stackoverflow.com/comment/83451328
type: AnswerComment
comment on: http://stackoverflow.com/a/48233912
has text: @Turn when i m using fun at the place of a in filter ,then while printing valid i getting an empty list..can u please fix the code.
type: Comment
score: 0

http://stackoverflow.com/q/48243283
has title: TypeError: must be str, not bytes in IBM Watson
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83469235
has comment: http://stackoverflow.com/comment/83469035
tagged with: typeerror
tagged with: ibm-cloud
tagged with: watson
has comment: http://stackoverflow.com/comment/83469290
tagged with: python
has comment: http://stackoverflow.com/comment/83468997
has body: I just finished the CodeAcademyIBM Watson course, and they programmed in python 2, when I brought the file over in python 3, I kept getting this error. The file script and all the credentials worked fine in CodeAcademy. Is this because I'm working in Python 3, or is it because of an issue in the code. Traceback (most recent call last): File "c:\Users\Guppy\Programs\PythonCode\Celebrity Match\CelebrityMatch.py", line 58, in &lt;module&gt; user_result = analyze(user_handle) File "c:\Users\Guppy\Programs\PythonCode\Celebrity Match\CelebrityMatch.py", line 22, in analyze text += status.text.encode('utf-8') TypeError: must be str, not bytes Does anyone know whats wrong, the code is below: import sys import operator import requests import json import twitter from watson_developer_cloud import PersonalityInsightsV2 as PersonalityInsights def analyze(handle): twitter_consumer_key = '&lt;key&gt;' twitter_consumer_secret = '&lt;secret&gt;' twitter_access_token = '&lt;token&gt;' twitter_access_secret = '&lt;secret&gt;' twitter_api = twitter.Api(consumer_key=twitter_consumer_key, consumer_secret=twitter_consumer_secret, access_token_key=twitter_access_token, access_token_secret=twitter_access_secret) statuses = twitter_api.GetUserTimeline(screen_name = handle, count = 200, include_rts = False) text = "" for status in statuses: if (status.lang =='en'): #English tweets text += status.text.encode('utf-8') #The IBM Bluemix credentials for Personality Insights! pi_username = '&lt;username&gt;' pi_password = '&lt;password&gt;' personality_insights = PersonalityInsights(username=pi_username, password=pi_password) pi_result = personality_insights.profile(text) return pi_result def flatten(orig): data = {} for c in orig['tree']['children']: if 'children' in c: for c2 in c['children']: if 'children' in c2: for c3 in c2['children']: if 'children' in c3: for c4 in c3['children']: if (c4['category'] == 'personality'): data[c4['id']] = c4['percentage'] if 'children' not in c3: if (c3['catego…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83469071
accepted answer: http://stackoverflow.com/a/48243537
score: 1
has answer: http://stackoverflow.com/a/48243537
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83598242
comment on: http://stackoverflow.com/q/48306299
type: Comment
type: QuestionComment
score: 0
has text: @jbch : does the library works too with the Scanner i'm working with ? ( TTL (GT-511C3) )

http://stackoverflow.com/comment/83501258
has text: @NiemaMoshiri Yeah, `check_output` is similiar to `run`, it return until subprocess terminate.
score: 0
comment on: http://stackoverflow.com/q/48259183
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48176007
answers question: http://stackoverflow.com/q/48175801
has body: As Mr. Gordon pointed out in his comment the REPL will print the object, but in the script it won't print it out unless you tell it to do so. If you want the same type of behavior as the REPL you can do: print(repr(f)) That should give you: repr[1234] Is that what you are looking for?
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48175801
has comment: http://stackoverflow.com/comment/83355167

http://stackoverflow.com/comment/83476727
type: QuestionComment
has text: Did you try to solve the problem on your own? What resources did you use? If you've written code, did it return any errors?
comment on: http://stackoverflow.com/q/48246875
score: 2
type: Comment

http://stackoverflow.com/comment/90903850
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48291478
has text: Why doesn't calling `a, c = sympy.symbols('a c', commutative=False)` later work? It seems expressions involving those symbols are set in stone (as `subs` doesn't work on them).
type: Comment

http://stackoverflow.com/comment/83643545
has text: Wydaje mi się, że tak, chociaż operacja funkcji `c` poprzez połączenie z bazy danych `[G]` jest ryzykowna i bez warunku wynik może nie być poprawny. Ale musiałbym sprawdzić gotowe rozwiązanie, wtedy byłbym pewien, czy to możliwe, czy nie. Ponieważ trudno sobie wyobrazić wszystko. Ale sam pomysł jest na razie interesujący :)
type: QuestionComment
comment on: http://stackoverflow.com/q/48327672
type: Comment
score: 0

http://stackoverflow.com/q/48288492
has title: Split string with Regex on variable pattern
type: Question
has comment: http://stackoverflow.com/comment/83562238
has comment: http://stackoverflow.com/comment/83562039
tagged with: python
tagged with: regex
tagged with: python-3.x
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48289369
has body: I'm going crazy over a fairly simple problem: I have a list of list that i want to split. There's a fairly easy pattern, but with a variation that I can't seem to capture: [['XXOOY00 100.00–200.00 300.000 -1.000 XX0IY00 300.00–400.00 500.000 +10.000 XX2IY00 600.00–700.00 800.00 0.000'], ['XXOOY00 100.00–200.00 300.000 -1.000 XX0IY00 300.00–400.00 500.000 XX2IY00 600.00–700.00 800.00 0.000']] The general pattern in the list éléments is code, range, value, change. As you can see there's a variation in the pattern in the second list, because the second element only had code,range, value. In order to split these lists, I use this regex: for element in list: final_list.append(re.split('([A-Z]{2}[A-Z0-9]{1}[A-Z]{2}[A-Z0-9]{2}\s\S*\s\S*\s\S*)\s', element)) However, this fails on the second list because I have: [['XXOOY00 100.00–200.00 300.000 -1.000, XX0IY00 300.00–400.00 500.000 +10.000, XX2IY00 600.00–700.00 800.00 0.000'], ['XXOOY00 100.00–200.00 300.000 -1.000, XX0IY00 300.00–400.00 500.000 XX2IY00, 600.00–700.00 800.00 0.000']] While the expected result is: [['XXOOY00 100.00–200.00 300.000 -1.000, XX0IY00 300.00–400.00 500.000 +10.000, XX2IY00 600.00–700.00 800.00 0.000'], ['XXOOY00 100.00–200.00 300.000 -1.000, XX0IY00 300.00–400.00 500.000, XX2IY00 600.00–700.00 800.00 0.000']] Which regex patter would allow me to do this? To clarify: I want a list so that if I read the content of the list element wise I have: XXOOY00 100.00–200.00 300.000 -1.000 XX0IY00 300.00–400.00 500.000 +10.000 XX2IY00 600.00–700.00 800.00 0.000 XXOOY00 100.00–200.00 300.000 -1.000 XX0IY00 300.00–400.00 500.000 XX2IY00 600.00–700.00 800.00 0.000 Thank you.
answer count: 1
has comment: http://stackoverflow.com/comment/83564039
has comment: http://stackoverflow.com/comment/83562043
accepted answer: http://stackoverflow.com/a/48289369

http://stackoverflow.com/comment/83420765
score: 0
comment on: http://stackoverflow.com/q/48219191
type: Comment
type: QuestionComment
has text: I'm sorry, that is not my intent

http://stackoverflow.com/a/48193413
has comment: http://stackoverflow.com/comment/83367995
answers question: http://stackoverflow.com/q/48192862
type: Answer
has comment: http://stackoverflow.com/comment/83368310
has body: #Opens the text document file=open("Old.txt", "r") #Reads the text document and splits it into a list with each line being an element lines=file.read().split("\n") new_lines=[] #Iterate over list of lines for line in lines: #If line is not in the empty list of lines( i.e the list that will contain unique lines) add the line to it #This makes sure that no line exists twice in the list if line not in new_lines: new_lines.append(line) #Open a new text file file_new=open("New.txt","w") #Add each line of our new unique lines list to the text file file_new.write("\n".join(new_lines)) file_new.close() file.close()
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48192862
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/83444298
has text: Thanks ,that works, also a variation of the above comment worked too: `[x.strip() for x in str.splitlines() if x]`
type: Comment
comment on: http://stackoverflow.com/a/48231027
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83585652
has text: the reason its not working for you is, you have a list of list , and a list cannot be added to a set because lists are not hashable .
comment on: http://stackoverflow.com/q/48300501
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48191878
has comment: http://stackoverflow.com/comment/83365138
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83365161
has comment: http://stackoverflow.com/comment/83381810
has comment: http://stackoverflow.com/comment/83376858
accepted answer of: http://stackoverflow.com/q/48191484
downvote count: 0
score: 7
upvote count: 7
type: Answer
answers question: http://stackoverflow.com/q/48191484
has body: "something that has to be named 'id'" Why? Anyway, that aside, have you tried simply moving the call to values ahead of the call to annotate? i.e. item_list = MyTable.objects.values('Name').annotate(id=Concat(F('id'), F('Code'), output_field=CharField())) This is predicated on the Name field also being unique. EDIT: If the Name field is not unique, then you can do it with an extra call to values and annotate. i.e. item_list = MyTable.objects.values( 'Name', 'id' ).annotate( id_dummy=Concat(F('id'), F('Code'), output_field=CharField()) ).values( 'id_dummy', 'Name' ).annotate( id=F('id_dummy') ) EDIT from question owner: Finally, I used this code to avoid unintentionally group_by: item_list = MyTable.objects.annotate( OriginalId=F('id') ).values( 'Name', 'OriginalId' ).annotate( id=Concat(F('id'), F('Code'), output_field=CharField() ))

http://stackoverflow.com/a/57263692
has comment: http://stackoverflow.com/comment/111638568
type: Answer
has body: The styling of the input field should be done in the frontend. For example, you would have: class CheckBoxWidget(Form): box1 = BooleanField() box2 = BooleanField() ... widget = FormField(CheckBoxWidget) And then in your html file you would have something like: &lt;div&gt; form.widget.label("checkbox-class") form.widget("other-checkbox-class") &lt;/div&gt; wrapped inside of your form.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48262191
score: 1

http://stackoverflow.com/q/48252853
has comment: http://stackoverflow.com/comment/83489166
has comment: http://stackoverflow.com/comment/83512419
has comment: http://stackoverflow.com/comment/83488547
has comment: http://stackoverflow.com/comment/83489559
tagged with: python
has comment: http://stackoverflow.com/comment/83500516
tagged with: theory
has comment: http://stackoverflow.com/comment/83493713
type: Question
score: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/83491400
has comment: http://stackoverflow.com/comment/83512511
has comment: http://stackoverflow.com/comment/83489719
upvote count: 1
has comment: http://stackoverflow.com/comment/83693414
has answer: http://stackoverflow.com/a/48254183
has comment: http://stackoverflow.com/comment/83494667
has body: In Python you can declare a function that doesn't explicitly return a value. For example, you can write: def launch_aborted(): call_KimJongUn() # oops we forget to return a value and then successfully use it in an if statement, for example: if not launch_aborted(): launch_ballistic_missile() In a similar situation, the use of uninitialized variables, Python recognizes an error and throws an exception. Python doesn't treat uninitialized variables as None by default as it does with function return value. # if the variable launch_aborted wasn't assigned yet # interpreter throws NameError or UnboundLocalError here if not launch_aborted: # this code will not be exceuted launch_ballistic_missile() This behavior masks errors. If a function has a bug in its declaration, if not all its control paths return a value, it will be difficult to find this bug because by default it returns None and None is also a valid value in boolean expressions and assignments. I am looking for any justification of this design decision other than simplicity of implementation. I understand that it would need additional check in a caller to track this error and it may degrade performance slightly, but this doesn't look like a reasonable argument here, the similar check for a variable state has also introduce a delay.
downvote count: 1
has comment: http://stackoverflow.com/comment/83489455
favorite count: 0
has comment: http://stackoverflow.com/comment/83488912
has comment: http://stackoverflow.com/comment/83512346
has title: What was the rational to make None a default return value in python instead of checking it as it is done to uninitialized variables
has comment: http://stackoverflow.com/comment/83494664

typeerror
tags question: http://stackoverflow.com/q/48218505
tags question: http://stackoverflow.com/q/48253225
tags question: http://stackoverflow.com/q/48230846
tags question: http://stackoverflow.com/q/48271543
tags question: http://stackoverflow.com/q/48271838
tags question: http://stackoverflow.com/q/48253723
tag name: typeerror
tags question: http://stackoverflow.com/q/48243283
tags question: http://stackoverflow.com/q/48294919
tags question: http://stackoverflow.com/q/48252809
tags question: http://stackoverflow.com/q/48258144
tags question: http://stackoverflow.com/q/48180718
tags question: http://stackoverflow.com/q/48256956
type: Tag
tags question: http://stackoverflow.com/q/48179778
tags question: http://stackoverflow.com/q/48217583
tags question: http://stackoverflow.com/q/48234833
tags question: http://stackoverflow.com/q/48269859
tags question: http://stackoverflow.com/q/48270363

http://stackoverflow.com/comment/83336201
type: Comment
has text: you are calling it inside the suite, reduce the indentation of the those line `h = HeadlineRetriever()` so that its outside the indentation of the class declaration
score: 2
comment on: http://stackoverflow.com/q/48178002
type: QuestionComment

http://stackoverflow.com/comment/83506952
type: Comment
score: 0
type: AnswerComment
has text: did you bother READING the question ??? "I know there is already zip and dict to do this job, but I am wondering why this code went wrong and where."
comment on: http://stackoverflow.com/a/48261929

http://stackoverflow.com/comment/97492187
score: 1
type: Comment
comment on: http://stackoverflow.com/a/55384852
type: AnswerComment
has text: Hi, welcome to Stack Overflow. When answering a question that already has many answers, please be sure to add some additional insight into why the response you're providing is substantive and not simply echoing what's already been vetted by the original poster. This is especially important in "code-only" answers such as the one you've provided.

http://stackoverflow.com/a/66984088
has comment: http://stackoverflow.com/comment/124935155
upvote count: 2
type: Answer
has body: I tried to edit the accepted answer so it would actually run, but this was rejected for some reason. However, here is a working/simpler version of the accepted answer (corrected indentation, corrected Queue.Queue to queue.Queue, simplified unnecessarily verbose super call, added imports): from concurrent import futures import queue class ThreadPoolExecutorWithQueueSizeLimit(futures.ThreadPoolExecutor): def __init__(self, maxsize=50, *args, **kwargs): super().__init__(*args, **kwargs) self._work_queue = queue.Queue(maxsize=maxsize)
has comment: http://stackoverflow.com/comment/137634874
answers question: http://stackoverflow.com/q/48263704
score: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/124826113

http://stackoverflow.com/q/48209383
has body: I have different tables : A,B,C ... And I want to select a number given of rows from each table and make an union I used this query (number given = 100) : sql_query = ''' SELECT * FROM A ORDER BY RANDOM() LIMIT 100 UNION SELECT * FROM B ORDER BY RANDOM() LIMIT 100 ''' but when I try to read the DataFrame : df=pd.read_sql(sql_query, con) I have an error : DatabaseError: Execution failed on sql : LIMIT clause should come after UNION not before If I use the LIMIT clause after UNION, it would return only the number given of rows but I don't know how many rows from each table were extracted. Example : if I want 100 rows from A and 100 rows from B, using the LIMIT 200 Clause after the UNION, I will have 200 rows but I don't know how many rows were extracted from A and from B Thank you for help,
tagged with: pandas
tagged with: sql
tagged with: sqlite
tagged with: python
type: Question
has title: SELECT UNION query with random rows from multiple tables
answer count: 2
upvote count: 3
accepted answer: http://stackoverflow.com/a/48209728
downvote count: 0
has answer: http://stackoverflow.com/a/48209728
favorite count: 0
possible better answer: http://stackoverflow.com/a/48209797
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48209797

http://stackoverflow.com/comment/83501665
comment on: http://stackoverflow.com/a/48254231
score: 0
type: Comment
has text: Damn, i meant `self + other`, so `__add__` is called.
type: AnswerComment

http://stackoverflow.com/comment/83642959
score: 0
type: Comment
has text: [It seems](https://stackoverflow.com/a/48328717/1422096) that it dosn't ignore them @unutbu, it does process them by jumping back the timestamp of 1 second when it appears.
type: AnswerComment
comment on: http://stackoverflow.com/a/48328495

http://stackoverflow.com/comment/83644981
comment on: http://stackoverflow.com/q/48313021
score: 0
type: Comment
type: QuestionComment
has text: I wrote a framework for selenium in python that takes care of tedious tasks like these, the official bindings are a bit funky in that they feel a bit dated in terms of workflow with larger sites/apps. If you wanted to check it out you can view it https://github.com/neetjn/py-component-controller

http://stackoverflow.com/q/48194777
type: Question
has title: Django permission to create a folder when being served by Apache2
tagged with: wsgi
has body: I am serving a Django site using Apache2 and mod_wgsi on a Debian 8 machine. I have correctly set the permissions to access the database and static file directories and the directory my_site/media. However, the site needs to create a directory in my_site/media (i.e. my_site/media/another_directory) and I can't seem to give apache2 permission to do this. The permission for media are: drwxrwxrwx 2 scamp www-data 4096 Jan 10 03:09 media The Django error I get is Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: 'media/new_folder' This is my django.conf: Alias /robots.txt /home/scamp/trcalc_django/static/robots.txt Alias /favicon.ico /home/scamp/trcalc_django/static/favicon.ico Alias /media/ /home/scamp/trcalc_django/media/ Alias /static /home/scamp/trcalc_django/static &lt;Directory /home/scamp/trcalc_django/static&gt; Require all granted &lt;/Directory&gt; &lt;Directory /home/scamp/trcalc_django/media&gt; Require all granted &lt;/Directory&gt; WSGIScriptAlias / /home/scamp/trcalc_django/wsgi.py &lt;Directory /home/scamp/trcalc_django&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; Is there something else I need to put in the apache conf? or some other permissions that need to be set?
tagged with: django
tagged with: apache2
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48194959
tagged with: mod-wsgi
has answer: http://stackoverflow.com/a/48194959
answer count: 1
tagged with: python

http://stackoverflow.com/q/48219852
type: AnsweredQuestion
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/83421538
answer count: 1
has body: output= Sign in to Twitter Visit someone's profile Saved search Promote this Tweet Block Tweet with location Spread the Location Your list Create a new list Copy Tweet link Embed this Tweet and i want make to one variable="Sign in to Twitter,Visit someone's profile,Saved search,Promote this Tweet,Block,Tweet with location,Spread the Location,Your list,Create a new list,Copy Tweet link,Embed this Tweet"
favorite count: 0
has comment: http://stackoverflow.com/comment/83421441
type: Question
has title: how to make new variable in python while output print
has comment: http://stackoverflow.com/comment/83421384
accepted answer: http://stackoverflow.com/a/48220025
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/48220025
tagged with: python-2.7

http://stackoverflow.com/comment/83515221
has text: You mean you want to split each line on the space?
type: QuestionComment
comment on: http://stackoverflow.com/q/48266087
score: 1
type: Comment

http://stackoverflow.com/q/48224572
type: UnansweredQuestion
tagged with: django
favorite count: 0
has body: I want to create a select field that displays a list of records from a column that is not a foreign key. I am able to do it using widget=ForeignKeyRawIdWidget(rel=Slum._meta.get_field('electoral_ward').rel where 'electoral_ward' is a foreign key in 'Slum' model. But, I wish to have the same behavior for a field ('name') which is just a char field in 'Slum' model. EDIT: I have a custom form (not a model form). In that form, I wish to have a selection field which will have slum names in the list. Instead of having a simple drop-down I need to have a raw field widget which will show a pop-up for selection. How do I achieve this? Thank you!
has comment: http://stackoverflow.com/comment/83431739
tagged with: modelchoicefield
score: 1
has title: Djaongo: ModelChoiceField and Widget - Could not display non-foreign key field
tagged with: python
tagged with: django-forms
type: Question
answer count: 0
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83522819
type: AnswerComment
has text: I've tried this method before, but it didn't work for me.
comment on: http://stackoverflow.com/a/48220095
type: Comment
score: 0

http://stackoverflow.com/a/48420568
type: Answer
score: 0
has body: I have gone through the code of pproxy source repository. @Alex If you can make some changes to the code. I think it works. Following are the changes I suggest. In core.py In ProxyHandler Class init method change the peer initialization From self.peer = False to self.peer = True Please resolve the certificate issue by creating a pem file of your target application. place it in certs directory. {{This point I am not clear about how to do it.}}. Kindly check with @Homewrecker. Reason for failure: peer value is harcoded with false. So every time it tries to make a httpConnection what ever you provide.
answers question: http://stackoverflow.com/q/48317624

http://stackoverflow.com/a/56023186
downvote count: 1
has body: The premise on assign is that it returns: A new DataFrame with the new columns in addition to all the existing columns. And also you cannot do anything in-place to change the original dataframe. The callable must not change input DataFrame (though pandas doesn't check it). On the other hand df['ln_A'] = np.log(df['A']) will do things inplace. So is there a reason I should stop using my old method in favour of df.assign? I think you can try df.assign but if you do memory intensive stuff, better to work what you did before or operations with inplace=True.
type: Answer
answers question: http://stackoverflow.com/q/48177914
upvote count: 10
score: 9

http://stackoverflow.com/comment/83580641
has text: possible duplicate of [importing modules from parent folder](https://stackoverflow.com/questions/714063/importing-modules-from-parent-folder) and [import file from parent directory](https://stackoverflow.com/questions/16780014/import-file-from-parent-directory/30536516)
type: Comment
comment on: http://stackoverflow.com/q/48298077
type: QuestionComment
score: 0

http://stackoverflow.com/a/48177389
answers question: http://stackoverflow.com/q/48177247
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: You cannot get the filename from the array. The variable im1 = cv2.imread(...) only stores the array values. It is stored as a standard numpy ndarray object and there is no attribute referencing the filenames. However, there are a lot of options here to do what you want, some that are very typical patterns for Python. Generally, you're looking to store two pieces of information: the filename and the image array. One option is just to have two lists, one being the filenames and the other the images: &gt;&gt;&gt; filename_list = ['im1.jpg', 'im2.jpg', ...] &gt;&gt;&gt; im_list = [cv2.imread(filename) for filename in filename_list] Another way is to store these as pairs: &gt;&gt;&gt; filename1 = 'im1.jpg' &gt;&gt;&gt; filename2 = 'im2.jpg' &gt;&gt;&gt; im1 = cv2.imread(filename1) &gt;&gt;&gt; im2 = cv2.imread(filename2) &gt;&gt;&gt; im_pairs = [(filename1, im1), (filename2, im2), ...] or if you already have the filenames and images as lists (as in the first case) you can use a list comprehension to build the pairs: &gt;&gt;&gt; im_pairs = [(filename, im) for filename, im in zip(filename_list, im_list)] A better option (in terms of code reuse in actual projects) with the same idea as above is to create a namedtuple so it's more explicit what each item is: &gt;&gt;&gt; from collections import namedtuple &gt;&gt;&gt; Img = namedtuple('Img', ['name', 'data']) &gt;&gt;&gt; im1 = Img('im1.jpg', np.array([5, 4, 3, 2, 1])) &gt;&gt;&gt; im1.name 'im1.jpg' &gt;&gt;&gt; im1.data array([5, 4, 3, 2, 1]) And here you can just create a list of Img objects. A fourth option is to use a Python dictionary with the key being the name and the value being the arrays: &gt;&gt;&gt; filename1 = 'im1.jpg' &gt;&gt;&gt; filename2 = 'im2.jpg' &gt;&gt;&gt; im1 = cv2.imread(filename1) &gt;&gt;&gt; im2 = cv2.imread(filename2) &gt;&gt;&gt; im_pairs = {filename1: im1, filename2: im2, ...} or again with a dictionary comprehension: &gt;&gt;&gt; im_pairs = {filename: im for filename, im in zip(filename_li…

http://stackoverflow.com/comment/83337135
type: AnswerComment
score: 0
has text: separately from your question, and as cricket_007 points out in his answer, you shouldn't be naming things like `x1`, `x2`, `x3` etc in 95% of circumstances. You should prefer a list `xs = [x1, x2, x3]`
type: Comment
comment on: http://stackoverflow.com/a/48178518

http://stackoverflow.com/a/48270765
answers question: http://stackoverflow.com/q/48270745
type: AcceptedAnswer
downvote count: 0
score: 3
has body: If they're in a list (e.g. called vars), you can use the all function: if all([v &gt; 0 for v in vars]): do something EDIT: @EliKorvigo made a good point about not needing to allocate the space for a list. You could just do this instead: if all(v &gt; 0 for v in vars): do something which works equivalently to the first code block, but without allocating the list
has comment: http://stackoverflow.com/comment/83525321
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/83525292
accepted answer of: http://stackoverflow.com/q/48270745
has comment: http://stackoverflow.com/comment/83525391

http://stackoverflow.com/a/48302002
has comment: http://stackoverflow.com/comment/83594403
score: 0
answers question: http://stackoverflow.com/q/48301542
accepted answer of: http://stackoverflow.com/q/48301542
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83614219
has comment: http://stackoverflow.com/comment/83604094
has comment: http://stackoverflow.com/comment/83629001
has body: Install the sh package: pip install sh. Then do: from sh import git commit_messages = git.log( pretty='format:"%h - %an, %ar : %s"', n=50, _tty_out=False ) Or, using only built-in modules: from subprocess import Popen with Popen(['git', 'log', '--pretty=format:"%h - %an, %ar : %s"']) as proc: commit_messages = proc.stdout.read()
has comment: http://stackoverflow.com/comment/83592446
has comment: http://stackoverflow.com/comment/83592905
type: Answer
has comment: http://stackoverflow.com/comment/83618877

http://stackoverflow.com/q/48240341
tagged with: python
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48240525
has title: My Rock Paper Scissors doesn't work (Python 2)
score: -1
has body: So basicly it just keeps repeating the chose question no matter what you put in. Is it a variable mistake or just a looping error? Its really annoying so could someone please help me I would be much appreciated. import time from random import randint #Variable List # computer - the computer status (choice changes) # player - the player # score - the points # ques - the question # status - either yes to continue loop no to stop the loop # ran - the number generated by randint # cmd - Keeps the config loaded (so keep yes or game will break) #cactive - allows the randomiser to run and set comp status status = 'yes' score = 0 rock = 'r' paper = 'p' scissor = 's' cmd = 'yes' cmdx = 'yes' computer = 'cactive' ran = ["rock", "paper", "scissors"] #Intro print "===================================" time.sleep(1) print "Welcome To Rock, Paper, Scissors!" time.sleep(1) print "Please use lowercase for awnsers." time.sleep(1) print "===================================" time.sleep(1) raw_input("Are you ready to start? ") #Awnser Feedback * * * * * * * * * * * while status=='yes': ques = input('Chose Rock, Paper, Scissor, Score Or Exit: ') if computer==0 and ques=='rock': #rock argument print 'Tie!' elif computer==0 and ques=='paper': print 'You Won!' score = score+1 elif computer==0 and ques=='scissors': print 'You Lost To Rock' score = score-1 if computer==1 and ques=='rock': #paper argument print 'You Lost To Paper' score = score-1 elif computer==1 and ques=='paper': print 'Tie!' elif computer==1 and ques=='scissors': print 'You Won!' score = score+1 if computer==2 and ques=='rock': #Scissors Argument print 'You Won!' score = score+1 elif computer==2 and ques=='paper': print 'You Lost To Scissors' score = score-1 elif computer==2 and ques=='scissors': print 'Tie!' #The Game while status=='yes': print ques if ques=='': print "Please Enter A Command" if ques=='score': #Score Choice print "You Have", score, "Points!" if ques=='cheat': #Score Cheat score = score+9999999999 print "Ch…
type: Question
has comment: http://stackoverflow.com/comment/83463581
upvote count: 0
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/48230022
answers question: http://stackoverflow.com/q/48202943
has body: A simple approach would be something like this: first=[[8,8,8,8,0,0,0,0,6,6,5,5],[8,8,8,8,0,0,0,0,6,6,5,5],[8,8,8,8,0,0,0,0,6,6,5,5],[8,8,8,8,0,0,0,0,6,6,5,5]] second = [[9,9,6,7,3,6,5,0,6,4,3,4], [9,9,6,7,3,6,5,0,6,4,3,4], [9,9,6,7,3,6,5,0,6,4,3,4], [9,9,6,7,3,6,5,0,6,4,3,4]] for first_1,second_1 in zip(first,second): for index,value in enumerate(first_1): if value==0: try: if first_1[index-1]==0 and first_1[index+1]==0: second_1[index]=0 second_1[index-1]=0 second_1[index+1]=0 except IndexError: pass print(second) output: [[9 9 6 7 0 0 0 0 6 4 3 4] [9 9 6 7 0 0 0 0 6 4 3 4] [9 9 6 7 0 0 0 0 6 4 3 4] [9 9 6 7 0 0 0 0 6 4 3 4]]
type: Answer
score: 0

google-calendar-api
tags question: http://stackoverflow.com/q/48305449
type: Tag
tag name: google-calendar-api

http://stackoverflow.com/q/48174361
favorite count: 0
accepted answer: http://stackoverflow.com/a/48174402
has body: I am running into some issues with my prediction service where I am getting the error SSLError: ('The read operation timed out',) -- I am able to see from the code that the current num_retries is set to 0. Can anybody help me understand how I can update the num_retries so that more than 1 will be attempted? I am making my calls by following predict_json from this example. Further, is there any way for me to understand if this read operation timeout is being caused by me (ie. something I am sending) or if it is caused by something on Google's side?
has answer: http://stackoverflow.com/a/48174402
type: Question
tagged with: google-cloud-ml
tagged with: python
has title: Cloud ML Engine Prediction Service 'Read Operation Timed Out'
tagged with: google-cloud-platform
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/a/48192207
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83365366
answers question: http://stackoverflow.com/q/48192168
has body: You are looking for shift index.shift(1) Out[336]: DatetimeIndex(['2012-01-06', '2012-01-09', '2012-01-10', '2012-01-11'], dtype='datetime64[ns]', freq='B') Also BDay will do that too from pandas.tseries.offsets import BDay index + BDay(1) Out[340]: DatetimeIndex(['2012-01-06', '2012-01-09', '2012-01-10', '2012-01-11'], dtype='datetime64[ns]', freq='B')
type: Answer

http://stackoverflow.com/comment/83490839
type: AnswerComment
score: 1
has text: I put also these lines to avoid to have wrong the first part : if (opt1[0] != opt2[0]) : sys.exit( ). Thanks again, the fact is I clicked the up arrow to accept it as a a solution but ignores me ( I'll try again ). I'm a new member, that's why..
comment on: http://stackoverflow.com/a/48253646
type: Comment

http://stackoverflow.com/a/48257864
upvote count: 1
score: 1
type: Answer
has body: Turns out that I can change permissions on script files and commit them on github. Their permission will hold in other machines.
answers question: http://stackoverflow.com/q/48189649
downvote count: 0

scons
tag name: scons
type: Tag
tags question: http://stackoverflow.com/q/48224513

http://stackoverflow.com/comment/83589015
score: 1
comment on: http://stackoverflow.com/q/48299396
type: Comment
type: QuestionComment
has text: your EXE file is self-uncompressing ZIP file - when you start program then system uncompresses it to random folder and it doesn't have to run it in this folder but it uses full path to run it from different folder - and then program can search other files in wrong folder. There were questions/answers how to use `sys.argv[0]` to get full path to folder with script - and then you can use `os.path.join()` to create full path to other files.

http://stackoverflow.com/a/48178963
answers question: http://stackoverflow.com/q/48178884
score: 38
upvote count: 38
accepted answer of: http://stackoverflow.com/q/48178884
type: Answer
type: AcceptedAnswer
downvote count: 0
has body: Referring to this Cross Validated Link, How to normalize data to 0-1 range?, it looks like you can perform min-max normalisation on the last column of foo. v = foo[:, 1] # foo[:, -1] for the last column foo[:, 1] = (v - v.min()) / (v.max() - v.min()) foo array([[ 0. , 0. ], [ 0.13216 , 0.06609523], [ 0.25379 , 1. ], [ 0.30874 , 0.09727968]]) Another option for performing normalisation (as suggested by OP) is using sklearn.preprocessing.normalize, which yields slightly different results - from sklearn.preprocessing import normalize foo[:, [-1]] = normalize(foo[:, -1, None], norm='max', axis=0) foo array([[ 0. , 0.2378106 ], [ 0.13216 , 0.28818769], [ 0.25379 , 1. ], [ 0.30874 , 0.31195614]])

http://stackoverflow.com/comment/83454434
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48235869
has text: `while number != guess:` repeats until that condition is no longer true. But since you never change the values of those variables inside the loop, the condition never changes, so it repeats forever.
score: 1

http://stackoverflow.com/a/48230432
has comment: http://stackoverflow.com/comment/83449140
score: 0
answers question: http://stackoverflow.com/q/48230210
type: Answer
has body: from PIL import ImageGrab, Image im = ImageGrab.grab() im.save('photo.png') #Saving the image img = Image.open('photo.jpg') img.show() This differs from the OP because I am using the Image library of PIL to open and show the image. The OP originally tried to display the image using the ImageGrab.grab() function. This was incorrect. The image needs to be opened first and then shown.

http://stackoverflow.com/q/48238432
type: UnansweredQuestion
has title: What is meaning of _ in python
linked to: http://stackoverflow.com/q/5893163
tagged with: python
has answer: http://stackoverflow.com/a/48238449
tagged with: python-2.7
score: 0
duplicate of: http://stackoverflow.com/q/5893163
tagged with: openai-gym
answer count: 1
type: Question
has body: While taking outputs from step function of openAI gym environment _ used as the fourth variable.Is it to just for the values which we don't want to use? is there any kind of advantage for using _ instead of any other name? import gym env = gym.make('CartPole-v0') for i_episode in range(20): observation = env.reset() for t in range(100): env.render() print(observation) action = env.action_space.sample() observation, reward, done, _ = env.step(action) if done: print("Episode finished after {} timesteps".format(t+1)) break

http://stackoverflow.com/a/48237751
type: Answer
has body: An approach different in a lot of the details but primarily in its use of circle() to more rapidly draw the hexagons: from turtle import Turtle, Screen # force object-oriented turtle hex_count = 0 # global to count all hexagons drawn by all routines def hexagons(turtle): global hex_count # needed as this function *changes* hex_count for _ in range(24): # don't need explicit iteration variable turtle.circle(100, steps=6) # use circle() to draw hexagons turtle.left(15) # 24 hexagons offset by 15 degrees = 360 hex_count += 1 # increment global hexagon count print(hex_count) screen = Screen() yertle = Turtle(visible=False) # keep turtle out of the drawing yertle.speed('fastest') # ask turtle to draw as fast as it can hexagons(yertle) screen.exitonclick() # allow dismiss of window by clicking on it
score: 0
answers question: http://stackoverflow.com/q/48236516

jquery
tags question: http://stackoverflow.com/q/48309523
tags question: http://stackoverflow.com/q/48197996
tags question: http://stackoverflow.com/q/48239116
tags question: http://stackoverflow.com/q/48311151
type: Tag
tag name: jquery
tags question: http://stackoverflow.com/q/48176377
tags question: http://stackoverflow.com/q/48202737
tags question: http://stackoverflow.com/q/48198882
tags question: http://stackoverflow.com/q/48257519
tags question: http://stackoverflow.com/q/48181511
tags question: http://stackoverflow.com/q/48195813

http://stackoverflow.com/a/48262837
has comment: http://stackoverflow.com/comment/83512021
accepted answer of: http://stackoverflow.com/q/48261969
score: 0
has comment: http://stackoverflow.com/comment/83510235
answers question: http://stackoverflow.com/q/48261969
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83511197
has body: Here: class IssueUpdateView(UpdateView): # ... def get_object(self): return self.request.user I don't know why you're returning request.user here (could it be a copy-paste from some example you didn't fully understand ?) - but anyway: UpdateView.get_object() is supposed to return the object to edit. You usually get this object from some unique id passed as argument from the url to the view: url(regex=r'^issues/edit/(?P&lt;issue_id&gt;\d+)/$', view= IssueUpdateView.as_view(), name='issue-update') class IssueUpdateView(UpdateView): # ... def get_object(self, queryset=None): return Issue.objects.get(id=self.kwargs["issue_id"])
type: Answer

http://stackoverflow.com/comment/83640768
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48327371
has text: @NiemaMoshiri - So pop one at a time from both keys (within the key key doesnt have to be ordered) :

http://stackoverflow.com/a/48228231
has comment: http://stackoverflow.com/comment/83439121
has comment: http://stackoverflow.com/comment/83439432
has comment: http://stackoverflow.com/comment/83439495
has body: You can use BeautifulSoup to read the meta tag in the header of the HTML page and get the redirect URL e.g. &gt;&gt;&gt; import requests &gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; a = requests.get("http://www.vbb.de/de/datei/GTFS_VBB_Nov2015_Dez2016.zip") &gt;&gt;&gt; soup = BeautifulSoup(a.text, 'html.parser') &gt;&gt;&gt; soup.find_all('meta', attrs={'http-equiv': lambda x:x.lower() == 'refresh'})[0]['content'].split('URL=')[1] '/de/download/GTFS_VBB_Nov2015_Dez2016.zip' This URL would be relative to the original URL's domain, making the new URL http://www.vbb.de/de/download/GTFS_VBB_Nov2015_Dez2016.zip. Downloading this appears to download the ZIP file for me: &gt;&gt;&gt; a = requests.get("http://www.vbb.de/de/download/GTFS_VBB_Nov2015_Dez2016.zip", stream=True) &gt;&gt;&gt; with open('test.zip', 'wb') as f: ... a.raw.decode_content = True ... shutil.copyfileobj(a.raw, f) ... $ unzip -l test.zip Archive: test.zip Length Date Time Name --------- ---------- ----- ---- 5554 2015-11-20 15:17 agency.txt 2151517 2015-11-20 15:17 calendar_dates.txt 71731 2015-11-20 15:17 calendar.txt 65424 2015-11-20 15:17 routes.txt 816498 2015-11-20 15:17 stops.txt 196020096 2015-11-20 15:17 stop_times.txt 365499 2015-11-20 15:17 transfers.txt 11765292 2015-11-20 15:17 trips.txt 113 2015-11-20 15:17 logging --------- ------- 211261724 9 files It is on this redirect that there is a 301 status returned: &gt;&gt;&gt; a.history [&lt;Response [301]&gt;] &gt;&gt;&gt; a &lt;Response [200]&gt; &gt;&gt;&gt; a.history[0] &lt;Response [301]&gt; &gt;&gt;&gt; a.history[0].url 'http://www.vbb.de/de/download/GTFS_VBB_Nov2015_Dez2016.zip' &gt;&gt;&gt; a.url 'http://images.vbb.de/assets/ftp/file/286316.zip'
has comment: http://stackoverflow.com/comment/83440286
has comment: http://stackoverflow.com/comment/83439439
has comment: http://stackoverflow.com/comment/83438958
type: Answer
answers question: http://stackoverflow.com/q/48227100
score: 0

http://stackoverflow.com/a/48330053
accepted answer of: http://stackoverflow.com/q/48329778
answers question: http://stackoverflow.com/q/48329778
has comment: http://stackoverflow.com/comment/83646263
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84261115
score: 1
has body: Create virtual environment on a machine that has internet access and use the --copies option to ensure files are not symlinked. Afterwards copy the whole environment to the target machine and use it there. # create the environement python3 -m venv venvfoldername --copies # activate the environment . venvfoldername/bin/activate # install your requirements together with their dependencies pip install -r requirements.txt # copy everything to target machine scp -r venvfoldername labhostname:/path/on/the/server # connect there and activate the environment ssh labhostname cd /path/on/the/server/ . venvfoldername/bin/activate # you can also use it like that /path/on/the/server/venvfoldername/bin/python foobar.py You should have everything at hand now.
has comment: http://stackoverflow.com/comment/84261060
type: Answer

http://stackoverflow.com/a/48220996
type: Answer
upvote count: 1
has body: You need to make key=lambda k, v: property_sort_order.index(k) into key=lambda k_v:property_sort_order.index(k_v[0]) - the lambda is getting passed a single tuple, which you can't destructure in python3.6.
has comment: http://stackoverflow.com/comment/83444637
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48220862
score: 1
has comment: http://stackoverflow.com/comment/83426186
accepted answer of: http://stackoverflow.com/q/48220862
has comment: http://stackoverflow.com/comment/83424488
has comment: http://stackoverflow.com/comment/83425014
downvote count: 0

http://stackoverflow.com/comment/83497557
has text: No screenshots please. Post the full text of the traceback instead.
type: Comment
comment on: http://stackoverflow.com/q/48256956
type: QuestionComment
score: 2

forms
tags question: http://stackoverflow.com/q/48266273
tags question: http://stackoverflow.com/q/48292771
tags question: http://stackoverflow.com/q/48236529
type: Tag
tags question: http://stackoverflow.com/q/48309478
tags question: http://stackoverflow.com/q/48231934
tags question: http://stackoverflow.com/q/48187696
tag name: forms
tags question: http://stackoverflow.com/q/48273530
tags question: http://stackoverflow.com/q/48199162
tags question: http://stackoverflow.com/q/48206719
tags question: http://stackoverflow.com/q/48310912
tags question: http://stackoverflow.com/q/48273687
tags question: http://stackoverflow.com/q/48190604
tags question: http://stackoverflow.com/q/48186625

http://stackoverflow.com/comment/83544852
type: Comment
type: QuestionComment
has text: @user202729, I would like to return 'N/A' string, assigned to a variable.
comment on: http://stackoverflow.com/q/48280586
score: 0

http://stackoverflow.com/q/48320942
tagged with: java
type: Question
tagged with: python-3.x
answer count: 0
upvote count: 2
type: UnansweredQuestion
has title: Error seen while calling Java file from Python script
downvote count: 0
tagged with: python
tagged with: java-8
has body: Below is the Java program which I want to execute using Python script from Pycharm: public class ExampleWithField { public int member = 1; public String member() { return "Hello World"; } } Below is the Python code from py4j.java_gateway import JavaGateway gateway = JavaGateway() example = gateway.jvm.ExampleWithField() c = example.member() print c And I am getting error like File "C:/Users/pmevega/PycharmProjects/untitled1/First.py", line 16, in &lt;module&gt; example = gateway.jvm.ExampleWithField() TypeError: 'JavaPackage' object is not callable
favorite count: 0
score: 2
tagged with: python-2.7

http://stackoverflow.com/q/48236181
duplicate of: http://stackoverflow.com/q/36250353
type: UnansweredQuestion
answer count: 1
has title: Discord import for python not working
downvote count: 0
tagged with: python
favorite count: 0
score: 3
upvote count: 3
linked to: http://stackoverflow.com/q/36250353
has comment: http://stackoverflow.com/comment/83455325
has answer: http://stackoverflow.com/a/48236339
has comment: http://stackoverflow.com/comment/83455336
tagged with: discord
type: Question
has body: import discord import random import asyncio import pickle import os client = discord.Client() @client.event async def on_ready(): print('logged in as') print(client.user.name) print(client.user.id) print('------') @client.event async def on_message(message): if message.content.startswith('!hello'): await client.send_message(message.channel,'sample text') client.run(MY_TOKEN) when i run it it prints the following message : Traceback (most recent call last): File "C:/Users/Tommy/PycharmProjects/discord/discord.py", line 1, in &lt;module&gt; import discord File "C:\Users\Tommy\PycharmProjects\discord\discord.py", line 8, in &lt;module&gt; client = discord.Client() AttributeError: module 'discord' has no attribute 'Client' not sure what to do here, i already set the paths in the interpreter but it still prints this message, i got all this code from a youtube video and it is verbatim so i dont know why it is not working

http://stackoverflow.com/comment/83413319
type: QuestionComment
comment on: http://stackoverflow.com/q/48214884
score: 0
has text: @DanielRoseman correct. :) I'm not sure how that happens on Heroku. But I can confirm that the default database is using the DATABASE_URL on heroku. I would assume that since the 'default' database name is a reserved, special name on Django and DATABASE_URL is always the name of your main DB on heroku, that the two are automatically connected unless told to do otherwise. Probably in the django-heroku buildpack.
type: Comment

http://stackoverflow.com/a/48285706
type: Answer
answers question: http://stackoverflow.com/q/48284642
score: 1
has body: This is how split can use a regular expression for its split-on argument. For this simple case it has no obvious advantages over a plain split, other than you don't need a separate strip to remove the whitespace around the |. import re str = "2 | 848 | Seconds | 660.00 | 900.00 | OK" result = re.split(r'\s*\|\s*', str) Result: ['2', '848', 'Seconds', '660.00', '900.00', 'OK']
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/83553966
type: Comment
comment on: http://stackoverflow.com/q/48284853
type: QuestionComment
score: 5
has text: Please don't post error messages or code as a screenshot. Nobody wants to type anything from a picture and you limit the help you can get here on SO. Please edit your question.

http://stackoverflow.com/a/48266333
score: 0
has body: Probably not a full answer, but I expect it gives some hints and it is far too long for a comment. You should think twice about your requirements, because it will probably not be that easy depending on your proficiency in C and what OS you are using. If I have correctly understood, you have a sensor that sends data (which is already weird unless the sensor is an intelligent one). You want to write a C program that will read that data and either buffer it, and retain only last (you did not say...) and at the same time will wait for requests from a Python script to give it back what it has received (and kept) from the sensor. That probably means a dual thread program with quite a bit of synchronization. You will also need to specify the communication way between C and Python. You can certainly use the subprocess module, but do not forget to use unbuffered output in C. But you could also imagine an independant program that uses a FIFO or a named piped with a well defined protocol for external requests, in order to completely separate both problems. So my opinion is that this is currently too broad for a single SO question...
has comment: http://stackoverflow.com/comment/83516013
has comment: http://stackoverflow.com/comment/83515759
answers question: http://stackoverflow.com/q/48265821
type: Answer
has comment: http://stackoverflow.com/comment/83515951

http://stackoverflow.com/a/48203163
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48202943
has body: A simple solution with a list comprehension: &gt;&gt;&gt; old_arr=[9,9,6,7,3,6,5,0,6,4,3,4] &gt;&gt;&gt; new_arr=[8,8,8,8,0,0,0,0,6,6,5,5] &gt;&gt;&gt; [new_arr[i] if old_arr[i] else 0 for i in range(len(new_arr))] [9, 9, 6, 7, 0, 0, 0, 0, 6, 4, 3, 4]
type: Answer

http://stackoverflow.com/q/48236890
favorite count: 0
has title: Nested Function calling in Python
type: AnsweredQuestion
score: 3
tagged with: python
accepted answer: http://stackoverflow.com/a/48236941
type: Question
has answer: http://stackoverflow.com/a/48236941
has body: def f1(): X = 88 def f2(): print(X) return f2 action = f1() action() Since f1 is returning f2 so it seems fine when I call f2 as (f1())(). But when I call f2 directly as f2(), it gives error. Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'f2' is not defined Can someone explain what is the difference between the function calling of f2 using above 2 ways.
upvote count: 3
tagged with: function
answer count: 1
downvote count: 0
tagged with: nested

http://stackoverflow.com/q/48220688
linked to: http://stackoverflow.com/q/48200064
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/83423009
type: Question
tagged with: opencv
score: 0
has comment: http://stackoverflow.com/comment/83422936
tagged with: opencv3.0
has title: How to generate a mp4(not a avi) file from a number of frames using Python OpenCV?
tagged with: python
has answer: http://stackoverflow.com/a/48221611
tagged with: python-3.x
has body: I am unable to generate a mp4 file from a number of frames, although I can generate avi file. How to get mp4 file instead of avi file # Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file. import cv2 out = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height)) out.write(frame) out.release()
has comment: http://stackoverflow.com/comment/83423082

http://stackoverflow.com/q/48251646
has answer: http://stackoverflow.com/a/48251818
accepted answer: http://stackoverflow.com/a/48251818
tagged with: shell
has comment: http://stackoverflow.com/comment/83486730
has answer: http://stackoverflow.com/a/48251694
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48251651
possible better answer: http://stackoverflow.com/a/48251651
has body: sample.py is an existing python file. Command to run that python file : &gt;&gt;&gt; python sample.py Error message: SyntaxError: invalid syntax How to create and run a python file in a Python 2.7.14 shell.
upvote count: 3
linked to: http://stackoverflow.com/q/11744181
linked to: http://stackoverflow.com/q/6513967
downvote count: 0
tagged with: python
answer count: 6
has title: Creating and running a python file
favorite count: 0
has answer: http://stackoverflow.com/a/48251970
type: AnsweredQuestion
score: 3
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48252332
has answer: http://stackoverflow.com/a/48253523

http://stackoverflow.com/comment/83565764
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48290329
has text: Thank you. The actual situation is a little more complex, and I wanted to avoid the list construction. I will add that fact to the original question.
score: 0

http://stackoverflow.com/comment/83366911
has text: @PatrickArtner fixed it. But how do you move a Question?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48192862

http://stackoverflow.com/q/48244232
answer count: 4
has answer: http://stackoverflow.com/a/48244374
type: AnsweredQuestion
has body: I have a Windows service named Tor Win32 Service that was installed by the Tor installer today but does not start. I get the message Windows could not start the Tor Win32 Service service on Local Computer. Error 1064: An exception occurred in the service when handling the control request. The service is installed with this path to the executable "E:\...\tor browser\browser\torbrowser\tor\tor.exe" --nt-service "-f" "e:\...\tor browser\browser\torbrowser\data\tor\torrc" This post https://tor.stackexchange.com/questions/15207/problems-with-starting-the-tor-service-on-windows-10-error-1064 suggests that the problem (when running the service for a Tor relay) is the log file path in torrc. But (a) I fixed that and it did not solve the problem and (b) I don't want to run a Tor relay anyway, I need the service to provide a proxy for my Python program.
score: 0
has answer: http://stackoverflow.com/a/57741080
tagged with: tor
upvote count: 1
tagged with: windows
has answer: http://stackoverflow.com/a/48272648
downvote count: 1
accepted answer: http://stackoverflow.com/a/48272648
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/57741080
has title: Tor Win32 Service doesn't start
has answer: http://stackoverflow.com/a/52770100
tagged with: python

http://stackoverflow.com/comment/83528058
type: QuestionComment
score: 0
has text: @KlausD. Actually, even with 1 sec I get the same traceback...it is breaking anyway.
comment on: http://stackoverflow.com/q/48271573
type: Comment

http://stackoverflow.com/comment/83558335
score: 0
has text: Thank you so much that's perfect! One question - can you clarify what '.idxmax(1)' does exactly? reading that line it seems like if it sums to 1, it prints the name of the column but I'm not sure how
type: Comment
comment on: http://stackoverflow.com/a/48286570
type: AnswerComment

http://stackoverflow.com/a/48316702
upvote count: 6
answers question: http://stackoverflow.com/q/48315955
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 6
has body: Yes, it handles DST natively. Check this: import pandas as pd df = pd.DataFrame({'date': pd.to_datetime(['2017-08-30 12:00:00', '2017-12-30 12:00:00'])}) df['date'].dt.tz_localize('Europe/Brussels').dt.tz_convert('UTC').dt.strftime('%Y-%m-%d %H:%M:%S') I picked one date with DST, i.e. UTC+1+1 and the other is only UTC+1 (where +1 is for Brussels). The output shows, that first date is converted as minus 2 hours, while the second date is minus 1 hour. 0 2017-08-30 10:00:00 1 2017-12-30 11:00:00
accepted answer of: http://stackoverflow.com/q/48315955

http://stackoverflow.com/comment/83630711
type: AnswerComment
has text: Yes in that case to switch the values `d[sublist[-1]] += sublist[1::-1]`
comment on: http://stackoverflow.com/a/48321326
score: 0
type: Comment

http://stackoverflow.com/comment/83446093
comment on: http://stackoverflow.com/q/48231893
score: 7
type: Comment
type: QuestionComment
has text: You may want to drop the trailing `+ os.sep` from the expression.

http://stackoverflow.com/comment/83546677
type: QuestionComment
score: 0
has text: I have successfully parsed the link of image from the webpage, using the BeautifulSoup I cant name the site as it is rated NSFW for testing purpose just let the image link be https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png
comment on: http://stackoverflow.com/q/48268516
type: Comment

http://stackoverflow.com/q/48220845
tagged with: shared-memory
tagged with: multiprocessing
type: Question
tagged with: numpy
answer count: 2
upvote count: 3
downvote count: 0
has title: Sharing and editing numpy array in python multiprocessing
has answer: http://stackoverflow.com/a/48238614
possible better answer: http://stackoverflow.com/a/48238614
favorite count: 0
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48239079
accepted answer: http://stackoverflow.com/a/48239079
tagged with: python
has body: I was experimenting on numpy with multiprocessing in python I've read numerous tutorials and stackoverflow answers. I wrote a code : from multiprocessing import Process, Array import numpy as np def main(): im_arr = np.array([[1,2,3],[4,6,7]]) print('Array in main before process:',im_arr) shape = im_arr.shape size = im_arr.size im_arr.shape = size arr = Array('B', im_arr) p = Process(target=fun, args=(arr,shape)) p.start() p.join() arr = np.frombuffer(arr.get_obj(), dtype=np.uint8) arr.shape = shape print('Array in main after process:',arr) def fun(a, shape): a = np.frombuffer(a.get_obj(), dtype=np.uint8) a.shape = shape a[0][0] = 10 a = np.array([[0,0,0],[0,0,0]]) a[0][0] = 5 print('Array inside function:',a) a.shape = shape[0]*shape[1] if __name__ == '__main__': main() What i hoped to do was to share a numpy array and to edit the array in another process while the change can also be observed in main program. But the output i get is as follows ('Array in main before process:', array([[1, 2, 3], [4, 6, 7]])) ('Array inside function:', array([[5, 0, 0], [0, 0, 0]])) ('Array in main after process:', array([[10, 2, 3], [ 4, 6, 7]], dtype=uint8)) it seems like 'a' in the function behaves like a new independent object after the numpy array is saved to it. Please correct what i'm doing wrong.

http://stackoverflow.com/q/48285048
has answer: http://stackoverflow.com/a/48285109
has answer: http://stackoverflow.com/a/48285480
downvote count: 0
favorite count: 0
has title: Is there a shorthand initializer in Python?
has comment: http://stackoverflow.com/comment/83554475
has comment: http://stackoverflow.com/comment/87747015
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/9728243
score: 14
linked to: http://stackoverflow.com/q/28345780
tagged with: python
has answer: http://stackoverflow.com/a/48285139
has body: I have found no reference for a short constructor call that would initialize variables of the caller's choice. I am looking for class AClass: def __init__(self): pass instance = AClass(var1=3, var2=5) instead of writing the heavier class AClass: def __init__(self, var1, var2): self.var1 = var1 self.var2 = var2 or the much heavier instance = AClass() instance.var1 = 3 instance.var2 = 5 Am I missing something?
has answer: http://stackoverflow.com/a/48285357
answer count: 4
type: Question
linked to: http://stackoverflow.com/q/35190877
upvote count: 14
accepted answer: http://stackoverflow.com/a/48285480
possible better answer: http://stackoverflow.com/a/48285139

http://stackoverflow.com/comment/83611039
type: Comment
type: QuestionComment
has text: Have you used `AUTH_USER_MODEL` in `settings.py`?
comment on: http://stackoverflow.com/q/48312224
score: 0

http://stackoverflow.com/a/48330473
has comment: http://stackoverflow.com/comment/83708740
upvote count: 2
has body: this small change will do it: for line in inFile: line.rstrip('\n') for i in range(0,len(line),1): linsiz.append(line[i:i+2])
accepted answer of: http://stackoverflow.com/q/48330400
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48330400
has comment: http://stackoverflow.com/comment/83708622
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83647205

http://stackoverflow.com/comment/83403582
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48211136
has text: please also share what your final list should look like?
score: 0

http://stackoverflow.com/a/48254151
accepted answer of: http://stackoverflow.com/q/48254115
upvote count: 5
type: Answer
has body: Map with multiple iterators: Given your desired intermediate output I'd say that map isn't the right tool to get a j containing the integers 1-9. That's because map with multiple iterators goes through the iterators simultaneously: It doesn't repeat, that's just because it's a gif file. The problem(s) in your approaches: In the first iteration it will return "1", "4", "7" (the first elements of each iterable) the next iteration will return "2", "5", "8" and the last iteration "3", "6", "9". On each of these returns it will apply the function, in your first example in the first iteration that's int("1") and int("4") and int("7") which evaluates to 7 because that's the last truthy value of the chained ands: &gt;&gt;&gt; int("1") and int("4") and int("7") 7 That also explains why the result is 24 because the results of the other iterations are 8 and 9: &gt;&gt;&gt; int("2") and int("5") and int("8") 8 &gt;&gt;&gt; int("3") and int("6") and int("9") 9 &gt;&gt;&gt; 7 + 8 + 9 24 In your second example you added the strings (which concatenates the strings) and then converted it to an integer: &gt;&gt;&gt; "1" + "4" + "7" "147" &gt;&gt;&gt; int("147") 147 The solution: So, you need the addition from your second approach but apply the int to each variable like you did in the first example: j = list(map(lambda x, y, z: int(x)+int(y)+int(z), num, num2, num3)) A better solution: But for that problem I would probably use a different approach, especially if you want the "desired" j. To get that you need to chain the iterables: import itertools chained = itertools.chain(num, num2, num3) Then convert all of them to integers: chained_integers = map(int, chained) This chained_integers is the iterator-equivalent to the [1, 2, 3, 4, 5, 6, 7, 8, 9] list you wanted as j. You could also use chained_integers = list(map(int, chained)) and print the chained_integers before proceeding if you want to double-check that. And finally to reduce it I would actually use the built-in sum function: re…
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48254115
score: 5

http://stackoverflow.com/comment/83470108
type: QuestionComment
score: 2
has text: Do you have to use regular expression? If not you could just iterate over the file and start saving if the line contains the ' {"befor " 17}, {"androidID' and stop if the line contains the end value.
comment on: http://stackoverflow.com/q/48243658
type: Comment

http://stackoverflow.com/q/48290879
tagged with: pandas
tagged with: amazon-s3
has title: AWS Lambda and S3 and Pandas - Load CSV into S3, trigger Lambda, load into pandas, put back in bucket?
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/37703634
has comment: http://stackoverflow.com/comment/83567104
has comment: http://stackoverflow.com/comment/83567425
linked to: http://stackoverflow.com/q/38154040
favorite count: 0
tagged with: aws-lambda
type: Question
has body: I'm a noob to AWS and lambda, so I apologize if this is a dumb question. What I would like to be able to do is load a spreadsheet into an s3 bucket, trigger lambda based on that upload, have lambda load the csv into pandas and do stuff with it, then write the dataframe back to a csv into a second s3 bucket. I've read a lot about zipping a python script and all the libraries and dependencies and uploading that, and thats a separate question. I've also figured out how to trigger lambda upon uploading a file to an S3 bucket and to automatically copy that file to a second s3 bucket. The part I'm having trouble finding any information on is that middle part, the loading the file into pandas and manipulating the file within pandas all inside the lambda function. First question: Is something like that even possible? Second question: how do I "grab" the file from the s3 bucket and load it into pandas? would it be something like this? import pandas as pd import boto3 import json s3 = boto3.resource('s3') def handler(event, context): dest_bucket = s3.Bucket('my-destination-bucket') df = pd.read_csv(event['Records'][0]['s3']['object']['key']) # stuff to do with dataframe goes here s3.Object(dest_bucket.name, &lt;code for file key&gt;).copy_from(CopySource = df) ? I really have no idea if that's even close to right and is a complete shot in the dark. Any and all help would be really appreciated, because I'm pretty obviously out of my element!
type: UnansweredQuestion
score: 6
has comment: http://stackoverflow.com/comment/83569241
has answer: http://stackoverflow.com/a/48293440
tagged with: python
tagged with: amazon-web-services
upvote count: 6
has comment: http://stackoverflow.com/comment/83567346

http://stackoverflow.com/a/48264126
downvote count: 0
upvote count: 7
answers question: http://stackoverflow.com/q/48262273
score: 7
type: Answer
has body: You could use functools.lru_cache: from functools import lru_cache from operator import attrgetter def cached_property_depends_on(*args): attrs = attrgetter(*args) def decorator(func): _cache = lru_cache(maxsize=None)(lambda self, _: func(self)) def _with_tracked(self): return _cache(self, attrs(self)) return property(_with_tracked, doc=func.__doc__) return decorator The idea is to retrieve the values of tracked attributes each time the property is accessed, pass them to the memoizing callable, but ignore them during the actual call. Given a minimal implementation of the class: class A: def __init__(self, b, c): self._b = b self._c = c @property def b(self): return self._b @b.setter def b(self, value): self._b = value @property def c(self): return self._c @c.setter def c(self, value): self._c = value @cached_property_depends_on('b', 'c') def a(self): print('Recomputing a') return self.b + 2 * self.c a = A(1, 1) print(a.a) print(a.a) a.b = 3 print(a.a) print(a.a) a.c = 4 print(a.a) print(a.a) outputs Recomputing a 3 3 Recomputing a 5 5 Recomputing a 11 11
has comment: http://stackoverflow.com/comment/83522871
has comment: http://stackoverflow.com/comment/83523300

http://stackoverflow.com/comment/83558290
type: AnswerComment
comment on: http://stackoverflow.com/a/48286528
has text: Great, thank you. Is it possible to add something to this one liner that will return the unique column and value combinations?
type: Comment
score: 0

http://stackoverflow.com/comment/83356481
type: QuestionComment
has text: @tripleee I guess there are various ways to deal with the variable-naming problem. At least for me, I have no ground to comment on the _style_ of others, in my code they would probably be called `qs`, `std`, `splt` and similar mutilations. :P
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48187556

ocr
tags question: http://stackoverflow.com/q/48324203
tags question: http://stackoverflow.com/q/48197934
tag name: ocr
type: Tag
tags question: http://stackoverflow.com/q/48193947

http://stackoverflow.com/a/48239907
score: 0
has comment: http://stackoverflow.com/comment/83462176
has body: Try this one: div.find_element_by_xpath('p/span[contains(text(), "Who")]/following-sibling::text()').text.strip()
answers question: http://stackoverflow.com/q/48239842
type: Answer

http://stackoverflow.com/a/48259562
has comment: http://stackoverflow.com/comment/83504085
upvote count: 2
score: 2
downvote count: 0
type: Answer
has body: Your time_from and time_to default is wrong. You should provide a default value not a format. If your model is new remove the migration file (I think dev_app.0016_auto_20180112_0630) change default values and run manage.py makemigrations again.
answers question: http://stackoverflow.com/q/48258696
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83507647
accepted answer of: http://stackoverflow.com/q/48258696

http://stackoverflow.com/comment/83512738
score: 0
has text: Welcome to Stack Overflow! When you created your account here, it was suggested you take the [tour](https://stackoverflow.com/tour) and read the [help center pages](https://stackoverflow.com/help) in order to familiarize yourself with the site. Specific pages that you should read include [How Do I Ask a Good Question?](https://stackoverflow.com/help/how-to-ask) and [How to Create a Minimal, Complete, and Verifiable Example](https://stackoverflow.com/help/mcve). Please take these introductory steps and then edit your post accordingly.
comment on: http://stackoverflow.com/q/48264822
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83338329
comment on: http://stackoverflow.com/q/48179010
type: Comment
type: QuestionComment
score: 0
has text: @NiyamatUllah Yes I have. It doesn't even seem to recognise the try/except, and won't continue to the except after the try has failed. I have tried just "except:" as well and still throwing the same error.

http://stackoverflow.com/q/48290566
type: Question
accepted answer: http://stackoverflow.com/a/48293183
score: 1
tagged with: python
type: AnsweredQuestion
has title: Problems using `scale_size_manual` in plotnine
tagged with: plotnine
has answer: http://stackoverflow.com/a/48293183
tagged with: categorical-data
answer count: 1
downvote count: 0
upvote count: 1
has body: I'm trying to use plotnine to build a plot with points sized based on their a classification 1-4. In the MWE below, I've constructed a test dataset that matches mine. from plotnine import * import pandas as pd import numpy as np a = pd.DataFrame(data={'a':4*list(range(4)), 'x':np.random.random(16), 'y':np.random.random(16)}) ggplot(a, aes(x='x', y='y', size='a')) + geom_point() + scale_size_manual(values=(3,3,3,3)) However, when I run the code, I get the following message: TypeError: Continuous value supplied to discrete scale Thinking that the problem was that the a column was non-categorical, I tried the following MWE: from plotnine import * import pandas as pd import numpy as np a = pd.DataFrame(data={'a':4*list(range(4)), 'x':np.random.random(16), 'y':np.random.random(16)}) a['a'] = a['a'].astype('category') ggplot(a, aes(x='x', y='y', size='a')) + geom_point() + scale_size_manual(values=(3,3,3,3)) However, this gives the error message: ValueError: cannot convert float NaN to integer In R's ggplot (which plotnine attempts to mirror), the following library(ggplot2) a = data.frame(a=rep(1:4,4), x=runif(16), y=runif(16)) ggplot(a, aes(x=x, y=y, size=a)) + geom_point() + scale_size_manual(values=c(3,3,3,3)) gives the familiar message Error: Continuous value supplied to discrete scale Introducing a factor solves the issue: library(ggplot2) a = data.frame(a=rep(1:4,4), x=runif(16), y=runif(16)) a$a = factor(a$a) ggplot(a, aes(x=x, y=y, size=a)) + geom_point() + scale_size_manual(values=c(3,3,3,3)) So plotnine seems to be treating categorical information slightly differently from ggplot. How can I get plotnine to do what I want?
favorite count: 0

http://stackoverflow.com/comment/83379764
score: 0
comment on: http://stackoverflow.com/q/48198810
type: Comment
type: QuestionComment
has text: @ScottHunter I looked through several threads that were similar or related. I honestly was just not getting/understanding the correlation in my head between others questions and my own. I apologize if this is an issue, I am working on an open source project and figured this would be a chance to get familiar with using stackoverflow. When I say new this is literally my first project.

http://stackoverflow.com/q/48282748
score: 4
upvote count: 4
tagged with: numpy
has comment: http://stackoverflow.com/comment/83549634
has answer: http://stackoverflow.com/a/48283240
has comment: http://stackoverflow.com/comment/83553248
has comment: http://stackoverflow.com/comment/83553847
has comment: http://stackoverflow.com/comment/83549733
answer count: 1
has comment: http://stackoverflow.com/comment/83549582
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/83549866
linked to: http://stackoverflow.com/q/47125697
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83549278
has title: numpy - use arrays as start and end of range
has comment: http://stackoverflow.com/comment/83559130
duplicate of: http://stackoverflow.com/q/47125697
tagged with: python
has body: This is a simplified array of what I have: a = np.array([ 1, 12, 60, 80, 90, 210]) b = np.array([11, 30, 79, 89, 99, 232]) How can I get a result that uses a as the start range, and b as the end of the range, that can compute a list of numbers (quickly). so, c would look like: c = np.array([1,2,3,...,11, 12,13,14,...,29,30, 60,61,62,...79, ..., 210,211,...,231,232]) Ideally, this would be done in a vectorised way (using numpy/pandas) rather than python.
has comment: http://stackoverflow.com/comment/83550059
has comment: http://stackoverflow.com/comment/83549804
accepted answer: http://stackoverflow.com/a/48283240
has comment: http://stackoverflow.com/comment/83550456
type: Question

http://stackoverflow.com/a/48260773
has comment: http://stackoverflow.com/comment/100800292
has body: You should set the following environment variables in $SPARK_HOME/conf/spark-env.sh: export PYSPARK_PYTHON=/usr/bin/python export PYSPARK_DRIVER_PYTHON=/usr/bin/python If spark-env.sh doesn't exist, you can rename spark-env.sh.template
score: 32
upvote count: 32
type: Answer
has comment: http://stackoverflow.com/comment/83519497
answers question: http://stackoverflow.com/q/48260412
downvote count: 0
has comment: http://stackoverflow.com/comment/83518911
has comment: http://stackoverflow.com/comment/130528404

http://stackoverflow.com/comment/83337912
has text: All objects are stored by reference in Python, even integers.
comment on: http://stackoverflow.com/a/48178887
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48198383
has comment: http://stackoverflow.com/comment/83378074
has answer: http://stackoverflow.com/a/48198408
has title: Must all attributes of an object be in the objects __hash__ function?
type: AnsweredQuestion
tagged with: hash
has comment: http://stackoverflow.com/comment/83378137
has body: Using python 3.6 I have read the docs. When implementing __hash__ Must all attributes of an object be in the objects __hash__ function? So would this example be ok? class Foo(object): def __init__(self, value): self.value = value self.not_important = 'irrelevant' def __hash__(self): return hash((self.value,)) def __eq__(self, other): if self.value == other.value: return True return False foo.not_important is modified while being a key in a dictionary &gt;&gt;&gt; foo = Foo(1) &gt;&gt;&gt; d = {foo:'foo is in d'} &gt;&gt;&gt; foo.not_important = 'something else' &gt;&gt;&gt; d[foo] 'foo is in d' &gt;&gt;&gt; bar = Foo(1) &gt;&gt;&gt; foo == bar True &gt;&gt;&gt; d[bar] 'foo is in d' But foo.not_important isn't used by it's __hash__ implementation. Is this perfectly okay? Or can this go horribly wrong?
has comment: http://stackoverflow.com/comment/83378006
has comment: http://stackoverflow.com/comment/83378025
tagged with: python
accepted answer: http://stackoverflow.com/a/48198470
type: Question
has answer: http://stackoverflow.com/a/48198470
score: 0
has comment: http://stackoverflow.com/comment/83378925
answer count: 2
possible better answer: http://stackoverflow.com/a/48198408

http://stackoverflow.com/comment/83557821
type: QuestionComment
comment on: http://stackoverflow.com/q/48286520
score: 1
has text: You never modify f_x, so why should it be anything other than 0?
type: Comment

http://stackoverflow.com/comment/83365527
type: Comment
type: QuestionComment
has text: In an interactive python session I can import lxml, but I can't import mdfreader which needs the pip installed lxml version and causes the exception.
score: 0
comment on: http://stackoverflow.com/q/48191933

http://stackoverflow.com/a/56043773
has body: Set use_multiprocessing=False in fit_generator, this somehow allows to walk-around the problem.
downvote count: 1
type: Answer
score: -1
answers question: http://stackoverflow.com/q/48185746
has comment: http://stackoverflow.com/comment/132463071
upvote count: 0

http://stackoverflow.com/q/48254454
has comment: http://stackoverflow.com/comment/83491550
has comment: http://stackoverflow.com/comment/83491607
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48254508
score: 3
possible better answer: http://stackoverflow.com/a/48254509
has title: How to groupby a row/horizontally (Pandas)
has body: Say one has a dataframe df = pd.DataFrame([['a','a','b','b','c','d', 'c'], [1, 3, 5, 7, 9, 2, 4]], index=["alpha", "val"]) 0 1 2 3 4 5 6 alpha a a b b c d c val 1 3 5 7 9 2 4 Would we be able to group the data by alpha? What I currently see from the documentation most examples are grouping by column labels. Still, there are lines like pandas objects can be split on any of their axes. # default is axis=0 grouped = obj.groupby(key) grouped = obj.groupby(key, axis=1) &lt;- seems to be what we want grouped = obj.groupby([key1, key2]) I tried with df.groupby("alpha", axis=1), but it gave me KeyError: 'alpha' What is the correct way to do so? This was one step in my another problem. In the problem, I tried to create a b c d 1 5 9 2 3 7 4
has comment: http://stackoverflow.com/comment/83491663
has answer: http://stackoverflow.com/a/48254509
tagged with: python
has comment: http://stackoverflow.com/comment/83491579
has comment: http://stackoverflow.com/comment/83491525
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/48254508
answer count: 2
tagged with: pandas-groupby
downvote count: 0
tagged with: pandas

http://stackoverflow.com/comment/83587367
comment on: http://stackoverflow.com/a/48301096
score: 0
type: Comment
has text: I changed my code into this.. basically added '[[' brackets instead on '[' "onehotencoder=OneHotEncoder() df['info.venue']=onehotencoder.fit_transform(df'info.venue')"
type: AnswerComment

http://stackoverflow.com/comment/83478822
has text: Your methods work. It seems `/following-sibling` or `//following-sibling` does not matter.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48248042

http://stackoverflow.com/comment/83533426
type: AnswerComment
score: 0
has text: @Friender0140 What doctest? Please include all relevant information in your question.
comment on: http://stackoverflow.com/a/48274948
type: Comment

http://stackoverflow.com/comment/83562160
has text: so if i create a simple python django project and start the server using the python3 interpreter then it will show me 3.5.x version right?.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48288341

http://stackoverflow.com/comment/83833522
comment on: http://stackoverflow.com/q/48265583
has text: you asked https://stackoverflow.com/help/mcve and I added the complete code. You solution does not fix the issues. Why? This is a very good question. Basically looking for this answer is what this whole issue is about. Don't know how to be more explicit without reposting the whole question, sorry.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/55243655
downvote count: 1
answers question: http://stackoverflow.com/q/48291093
type: Answer
score: -1
has body: You can use the built-in function any: for rowdata in reader: # how to check here? if not any(row): continue dataSet.append(rowdata)
upvote count: 0

http://stackoverflow.com/comment/83612694
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48313258
type: Comment
has text: Thank you this is fantastic. I appreciate it.

psycopg2
tags question: http://stackoverflow.com/q/48176567
tags question: http://stackoverflow.com/q/48267879
tags question: http://stackoverflow.com/q/48206900
type: Tag
tags question: http://stackoverflow.com/q/48326859
tags question: http://stackoverflow.com/q/48255941
tags question: http://stackoverflow.com/q/48177324
tags question: http://stackoverflow.com/q/48247365
tag name: psycopg2

http://stackoverflow.com/comment/83359996
comment on: http://stackoverflow.com/q/48189694
type: Comment
type: QuestionComment
has text: Questions usually benefit from sample input and expected output.
score: 0

http://stackoverflow.com/comment/83364899
score: 0
type: Comment
type: AnswerComment
has text: One thing that I noticed in the `try-except` block above is that the exception should be `IOError`, right?
comment on: http://stackoverflow.com/a/48176727

http://stackoverflow.com/comment/83764857
has text: Hey, just to wrap it up - in each of the ImageDataGenerator instances I had to include the normlization - "samplewise_center=True, samplewise_std_normalization=True" - I had to include it in the constructor of each of the ImageDataGenerator objects.The thing is without having the data normalized it tends to mistaken the learning procedure (yes, now it's obvious :) ). So the correct answer is two folded: You answered the first part and @Marcin Mozejko had a point as well :). You can update your answer if you'd like to, will accept it as a correct one.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48223921
type: Comment

http://stackoverflow.com/q/48221727
has answer: http://stackoverflow.com/a/48222686
downvote count: 0
has answer: http://stackoverflow.com/a/52490953
favorite count: 0
has body: I'm trying to make CNN for my image classification. Before start that, I'm trying to make one simple neural net model. but I have error massage that "Cannot feed value of shape (1, 224, 224, 3) for Tensor 'Placeholder_30:0', which has shape '(1, 150528)'" my image's size are all different... so I resized all image size to 224*224*3 and made model to classify 7labels.. but I met that error and I don't know what to do. Here is my code please help # -*- coding: utf-8 -*- """ Created on Fri Jan 12 14:46:07 2018 @author: Yoon seock ju """ #clear all the variable in spyder %reset #import packages import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from scipy import misc import glob import random from numpy import array #InteractiveSession ready sess = tf.InteractiveSession() #size for resize image data size = 224,224 #train, test image list trainset = [] trainlabel = [] testset = [] testlabel = [] #read train_image data for i in range(7): path = "C:/Users/user/Desktop/향수이미지/train/"+str(i)+"/*.jpg" for image_path in glob.glob(path): image = misc.imread(image_path) print(image.shape) if (image.shape[0] &gt;224) and (image.shape[1] &gt; 224): print("resize start") image = misc.imresize(image,size) image = array(image).reshape(1, 224,224,3) trainset.append(image) trainlabel.append(i) print("resize image= ",image.shape) print(image.dtype) print(i," is done") #read test_image data for i in range(7): path = "C:/Users/user/Desktop/향수이미지/test/"+str(i)+"/*.jpg" for image_path in glob.glob(path): image = misc.imread(image_path) print(image.shape) if (image.shape[0] &gt;224) and (image.shape[1] &gt; 224): print("resize start") image = misc.imresize(image,size) image = array(image).reshape(1,224,224,3) testset.append(image) testlabel.append(i) print("resize image= ",image.shape) print(image.dtype) print(i," is done") #set placeholder x = tf.placeholder(tf.float32, shape = [1, 150528])#Our images 224*224*3 y_ = tf.placeholder(tf.float32, shape = [None, 7])#Our ta…
answer count: 3
has answer: http://stackoverflow.com/a/48222217
score: 1
tagged with: python
type: Question
has title: Cannot feed value of shape (1, 224, 224, 3) for Tensor 'Placeholder_30:0', which has shape '(1, 150528)'
upvote count: 1
type: UnansweredQuestion

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/48242761
tag name: google-oauth

http://stackoverflow.com/comment/83520970
type: QuestionComment
comment on: http://stackoverflow.com/q/48266472
has text: [This Q/A](https://stackoverflow.com/questions/34009296/using-sqlalchemy-session-from-flask-raises-sqlite-objects-created-in-a-thread-c) answers the root cause of your problems in this case. In short, sharing a `Session` between 2 threads is a recipe for disaster. A `Session` [is not thread-safe](http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#is-the-session-thread-safe). A `Session` is also lazy and requests a connection only when needed. The 1st function emits no queries, the 2nd does due to the manual flush, so the 1st thread creates no SQLite resources, 2nd does.
score: 1
type: Comment

http://stackoverflow.com/q/48200075
answer count: 2
tagged with: nameko
has comment: http://stackoverflow.com/comment/83381175
downvote count: 0
tagged with: mysql
upvote count: 1
accepted answer: http://stackoverflow.com/a/48201370
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48201370
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83381264
possible better answer: http://stackoverflow.com/a/48200238
score: 1
has answer: http://stackoverflow.com/a/48200238
has body: I try to use a nameko rpc server to read data from mysql. here is the server code. class SendService: name = 'url_feature_rpc_service' def __init__(self): print('new connection') self.db = MySQLdb.connect(host="localhost", user="user", passwd="123456", db="today_news", charset='utf8') self.cursor = self.db.cursor() @rpc def get_feature(self, url): sql = 'select title_seg, entity_seg, title_entity_vec from article_feature where url_md5 = md5(\'{}\')'.format(url) self.cursor.execute(sql) result = self.cursor.fetchone() if result == None: return '' return '\t'.join(result) and here is the client code: with ClusterRpcProxy(config) as cluster_rpc: for line in sys.stdin: line = line.strip() try: result = cluster_rpc.url_feature_rpc_service.get_feature(line) except Exception as e: print(e) my question is every time I call the rpc service, it will set up a new connection. and I sometimes get the mysql error(99)"cannot connect mysql server". can I use only one connection?
tagged with: python
has title: python3 nameko RPC server with mysql connection
type: AnsweredQuestion

http://stackoverflow.com/comment/88690508
type: QuestionComment
has text: @Eric, the error arises with numpy 1.14.0. In numpy 1.14.x, where x ≥ 1, a FutureWarning is triggered instead.
score: 0
comment on: http://stackoverflow.com/q/48267058
type: Comment

encoder-decoder
type: Tag
tags question: http://stackoverflow.com/q/48283120
tag name: encoder-decoder

http://stackoverflow.com/q/48193308
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has body: Hi I am working with python. I am working with a list of numbers A = [7,9,6,8] I want to get the permutations of the numbers that are in a sequential manner. Desired output is as below: [(6), (7), (8), (9), (6, 7), (7, 8), (8, 9), (6, 7, 8), (7, 8, 9)] My code is as below: &gt;&gt;&gt; import itertools &gt;&gt;&gt; A = [6,8,7,9] &gt;&gt;&gt; def comb(myc: list): retcol = [] for i in range(1,len(myc)): retcol += list(itertools.combinations(myc,i)) return retcol &gt;&gt;&gt; S = sorted(A, key=int) &gt;&gt;&gt; comb(S) [(6,), (7,), (8,), (9,), (6, 7), (6, 8), (6, 9), (7, 8), (7, 9), (8, 9), (6, 7, 8), (6, 7, 9), (6, 8, 9), (7, 8, 9)] &gt;&gt;&gt; [(6,), (7,), (8,), (9,), (6, 7), (6, 8), (6, 9), (7, 8), (7, 9), (8, 9), (6, 7, 8), (6, 7, 9), (6, 8, 9), (7, 8, 9)] I have 2 questions: How can I get only the combinations that are in a sequence like shown in the desired output above. Is there a better way to get such kinda result without putting in an explicit for loop? maybe a list comprehension
has answer: http://stackoverflow.com/a/48193445
tagged with: python
has title: Get combinations of a list of number in a sequence
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48193445
upvote count: 2

http://stackoverflow.com/q/48319723
accepted answer: http://stackoverflow.com/a/48319872
type: Question
tagged with: python-3.x
upvote count: 2
downvote count: 0
answer count: 1
tagged with: selenium
has body: I'm trying to access hyperlink texts that will always be stored as the last hyperlink tag nested in 100 div tags on a certain website. In the below example, "00A17" would be what I'm trying to extract from a single tag. HTML Code: &lt;div class="headlineText"&gt; &lt;a class="mrnum" title="Full MathSciNet Item" href="/mathscinet/search/publdoc.html?arg3=&amp;amp;co4=AND&amp;amp;co5=AND&amp;amp;co6=AND&amp;amp;co7=AND&amp;amp;dr=all&amp;amp;extend=1&amp;amp;l=100&amp;amp;pg4=AUCN&amp;amp;pg5=TI&amp;amp;pg6=PC&amp;amp;pg7=ALLF&amp;amp;pg8=ET&amp;amp;review_format=html&amp;amp;s4=&amp;amp;s5=&amp;amp;s6=&amp;amp;s7=%22Featured%20Review%22&amp;amp;s8=Journals&amp;amp;sort=Newest&amp;amp;vfpref=html&amp;amp;yearRangeFirst=&amp;amp;yearRangeSecond=&amp;amp;yrop=eq&amp;amp;r=9&amp;amp;mx-pid=2650657"&gt;&lt;strong&gt;MR2650657&lt;/strong&gt;&lt;/a&gt; &lt;a class="item_status" href="/mathscinet/help/fullitem_help_full.html#indexed"&gt;&lt;span&gt;Indexed&lt;/span&gt;&lt;/a&gt; &lt;a href="/mathscinet/search/author.html?mrauthid=115370"&gt;Logan, J. David&lt;/a&gt; &lt;span class="title"&gt;&lt;span class="searchHighlight"&gt;Featured review&lt;/span&gt;: &lt;span class="it"&gt;Introduction to the foundations of applied mathematics&lt;/span&gt; [&lt;a href="/mathscinet/search/publdoc.html?pg1=MR&amp;amp;s1=2526777&amp;amp;loc=fromrevtext"&gt;MR2526777&lt;/a&gt;].&lt;/span&gt; &lt;a href="/mathscinet/search/journaldoc.html?id=5174"&gt; &lt;em&gt;SIAM Rev.&lt;/em&gt;&lt;/a&gt; &lt;a href="/mathscinet/search/publications.html?pg1=ISSI&amp;amp;s1=281478"&gt; 52 &lt;/a&gt; &lt;a href="/mathscinet/search/publications.html?pg1=ISSI&amp;amp;s1=281478"&gt; (2010), &lt;/a&gt; &lt;a href="/mathscinet/search/publications.html?pg1=ISSI&amp;amp;s1=281478"&gt; no. 1,&lt;/a&gt; 173–178. &lt;a href="/mathscinet/search/mscdoc.html?code=00A17"&gt;00A17&lt;/a&gt; &lt;/div&gt; The code I wrote to attempt this is basically a mess Python Code for remote access: headlineTexts = [] mscLinks = [] fo…
favorite count: 0
tagged with: selenium-webdriver
score: 2
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/83627473
tagged with: python
has title: Getting text from the last hyperlink tag
has answer: http://stackoverflow.com/a/48319872

http://stackoverflow.com/comment/83566337
has text: Thanks! Installed libxml2-dev and libxslt1-dev, and found lxml in the apt repos. Pip version wouldn't install properly.
comment on: http://stackoverflow.com/a/48289476
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48233402
possible better answer: http://stackoverflow.com/a/48242519
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48242519
type: Question
tagged with: numpy
answer count: 2
has title: How to swap array's columns if condition is satisfied
tagged with: multidimensional-array
has comment: http://stackoverflow.com/comment/83449316
tagged with: arrays
accepted answer: http://stackoverflow.com/a/48233479
has body: I have an Nx3 numpy array: A = [[01,02,03] [11,12,13] [21,22,23]] I need an array where the second and third columns are swapped if the sum of the second and third numbers is greater then 20: [[01,02,03] [11,13,12] [21,23,22]] Is it possible to achieve this without a loop? UPDATE: So, the story behind this is that I want to swap colors in a RGB image, namely green and blue, but not yellow - this is my condition. Empirically I found out it is abs(green - blue) &gt; 15 &amp;&amp; (blue &gt; green) swapped = np.array(img).reshape(img.shape[0] * img.shape[1], img.shape[2]) idx = ((np.abs(swapped[:,1] - swapped[:,2]) &lt; 15) &amp; (swapped[:, 2] &lt; swapped[:, 1])) swapped[idx, 1], swapped[idx, 2] = swapped[idx, 2], swapped[idx, 1] plt.imshow(swapped.reshape(img.shape[0], img.shape[1], img.shape[2])) this actually works, but partially. The first column will be swapped, but the second one will be overwritten. # tested in pyton3 a = np.array([[1,2,3],[11,12,13],[21,22,23]]) a[:,1], a[:,2] = a[:,2], a[:,1] array([[ 1, 3, 3], [11, 13, 13], [21, 23, 23]])
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48233479
has comment: http://stackoverflow.com/comment/83465562
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83449397
tagged with: image-processing

http://stackoverflow.com/q/48264619
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83512503
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83512515
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/83514056
has comment: http://stackoverflow.com/comment/83512847
has comment: http://stackoverflow.com/comment/83512290
has comment: http://stackoverflow.com/comment/83512183
tagged with: intersection
has body: I have what I believe is a rather basic issue, to which I cannot find an elegant solution. Imagine I have two rather complex lines (e.g. B-splines) in 2-D space spanned up by two matrices of dimensions (n,2), where n (the rows) are the number of points along the lines, and the two columns correspond to x and y coordinate respectively. Further information: The distance between two sequential points is similar, but not constant. The point of intersection may not necessarily be a point that spans up the lines. there may be (theoretically) any number of intersections I want to find the point(s) at which these lines intersect. For my purposes it is sufficient to take the lines as linear between each two sequential points. Unfortunately, every solution I can come up with so far is incredibly inefficient (e.g. using two nested for-loops and checking each segment of two points on one line vs each segment on the other line). There has to be a more elegant way of doing this. Is there any kind of function that may ease an implementation of such a routine? P.S.: Below you can find an illustration of the system I described above.
has comment: http://stackoverflow.com/comment/83512776
tagged with: python
has comment: http://stackoverflow.com/comment/83513951
tagged with: linear-algebra
has answer: http://stackoverflow.com/a/48266969
has comment: http://stackoverflow.com/comment/83512872
has title: Python - Find intersection between lines spanned by several points
has answer: http://stackoverflow.com/a/48265128
possible better answer: http://stackoverflow.com/a/48265128
has comment: http://stackoverflow.com/comment/83512781
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83512423
accepted answer: http://stackoverflow.com/a/48266969
has comment: http://stackoverflow.com/comment/83512579

http://stackoverflow.com/comment/83548226
comment on: http://stackoverflow.com/a/48277234
score: 0
type: AnswerComment
has text: Looks like i was mistaken about sorting being more computationally intensive than the algorithm. We seem to have a similar idea for the algorithm to work with a presorted array
type: Comment

http://stackoverflow.com/a/48320451
has comment: http://stackoverflow.com/comment/83627426
has comment: http://stackoverflow.com/comment/83627026
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83628169
has comment: http://stackoverflow.com/comment/83627380
accepted answer of: http://stackoverflow.com/q/48320432
has comment: http://stackoverflow.com/comment/83627117
answers question: http://stackoverflow.com/q/48320432
has comment: http://stackoverflow.com/comment/83626815
has comment: http://stackoverflow.com/comment/83626950
score: 10
type: Answer
has comment: http://stackoverflow.com/comment/83627081
has comment: http://stackoverflow.com/comment/83626853
upvote count: 10
has body: There's no need for regex here. Just convert your array to a 1 byte string, using astype - v = np.array(['abc', 'def', 'ghi']) &gt;&gt;&gt; v.astype('&lt;U1') array(['a', 'd', 'g'], dtype='&lt;U1') Alternatively, you change its view and stride. Here's a slightly optimised version for equal sized strings. - &gt;&gt;&gt; v.view('&lt;U1')[::len(v[0])] array(['a', 'd', 'g'], dtype='&lt;U1') And here's the more generalised version of .view method, but this works for arrays of strings with differing length. Thanks to Paul Panzer for the suggestion - &gt;&gt;&gt; v.view('&lt;U1').reshape(v.shape + (-1,))[:, 0] array(['a', 'd', 'g'], dtype='&lt;U1') Performance y = np.array([x * 20 for x in v]).repeat(100000) y.shape (300000,) len(y[0]) # they're all the same length - `abcabcabc...` 60 Now, the timings - # `astype` conversion %timeit y.astype('&lt;U1') 100 loops, best of 3: 5.03 ms per loop # `view` for equal sized string arrays %timeit y.view('&lt;U1')[::len(y[0])] 100000 loops, best of 3: 2.43 µs per loop # Paul Panzer's version for differing length strings %timeit y.view('&lt;U1').reshape(y.shape + (-1,))[:, 0] 100000 loops, best of 3: 3.1 µs per loop The view method is faster by a huge margin. However, use with caution, as the memory is shared. If you're interested in a more general solution that finds you the first letter (regardless of where it may be), I'd say the fastest/easiest way would be using the re module, compiling a pattern and searching inside a list comprehension. &gt;&gt;&gt; p = re.compile('[a-zA-Z]') &gt;&gt;&gt; [p.search(x).group() for x in v] ['a', 'd', 'g'] And, its performance on the same setup above - %timeit [p.search(x).group() for x in y] 1 loop, best of 3: 320 ms per loop

http://stackoverflow.com/a/48236251
answers question: http://stackoverflow.com/q/48231273
score: 0
has body: drhagen stupidity of human take -1 and no answer at all get my skill at photoshop and I could laugh of you any time
type: Answer

http://stackoverflow.com/q/48245239
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/4383571
answer count: 2
has body: I wrote a python code and saved it (let's say I saved it in (C:\Users\MyCode\Code1.py) ) and I'm writing a new python code, and I would like to copy everything from Code1. I just opened Code1.py and copied and pasted it, but is there a smarter way to do it? (thanks for the answers so far, but let's assume that the code that I'm trying to copy and the code that I'm writing are not in the same directory)
has title: Importing the entire python code that I have written previously
possible better answer: http://stackoverflow.com/a/48245266
upvote count: 0
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83473484
type: Question
accepted answer: http://stackoverflow.com/a/48245264
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48245264
has answer: http://stackoverflow.com/a/48245266

http://stackoverflow.com/q/48177087
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/19851005
tagged with: api
answer count: 1
has body: I have some data that cant be replecated but I am doing an API request to an energy management system to build a simple pandas data frame... When the data request comes back, I do a write to pd_to.CSV for the data, and then do a read_CSV with index_col='Date', parse_dates=True How do I incorporate this to my API request labeling the time stamp as 'Date' and as well as the parse_dates=True? (Skip the read/write data to CSV...) from pyhaystack.client.niagara import NiagaraHaystackSession import pandas as pd session = NiagaraHaystackSession(uri='http://192.x.x.x', username='username', password='password', pint=True) op = session.nav() op.wait() nav = op.result print(nav) #Get Data for the OSA-T &amp; convert to Pandas series: oat = session.find_entity(filter_expr='outsideAir').result oat_df = session.his_read_frame(oat, rng= '2017-10-01,2018-01-01').result oat_df = pd.Series(oat_df[oat_df.columns[0]]) #Get Data for the electrical energy kWh &amp; convert to Pandas series: elecMeter = session.find_entity(filter_expr='elecMeter').result elecMeter_df = session.his_read_frame(elecMeter, rng= '2017-10-01,2018-01-01').result elecMeter_df = pd.Series(elecMeter_df[elecMeter_df.columns[0]]) #Get Data for the natural gas energy therms &amp; convert to Pandas series: gasMeter = session.find_entity(filter_expr='gasMeter').result gasMeter_df = session.his_read_frame(gasMeter, rng= '2017-10-01,2018-01-01').result gasMeter_df = pd.Series(gasMeter_df[gasMeter_df.columns[0]]) UtilityInfo = pd.DataFrame({'oat' : oat_df, 'kWh' : elecMeter_df, 'therms' : gasMeter_df}) This is where I am read/write to CSV that I am hoping to incorporate into the API request... Unless this is just best practices doing the read/write???.. Basically in between the read/write steps below I have to cheat and open up Excel to label the timestampt column 'Date' which I am hoping to avoid!!! UtilityInfo.to_csv('C:\\Python Scripts\\UtilityInfo.csv', sep=',', header=True, index=True, na_rep='N/A') UtilityInfo = pd.r…
has comment: http://stackoverflow.com/comment/83375497
has comment: http://stackoverflow.com/comment/83368706
has comment: http://stackoverflow.com/comment/83363022
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83363347
has title: API time series data
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: data-science
has answer: http://stackoverflow.com/a/48191362
accepted answer: http://stackoverflow.com/a/48191362

http://stackoverflow.com/comment/83647852
type: Comment
type: AnswerComment
has text: @ZuhaibAsad, please consider adding a __reproducible__ sample data set to your question and your desired data set. My solution doesn't need any loops...
score: 0
comment on: http://stackoverflow.com/a/48329811

http://stackoverflow.com/q/48252601
downvote count: 0
has title: Subtract 2 values from one another within 1 column after groupby
has body: I am very sorry if this is a very basic question but unfortunately, I'm failing miserably at figuring out the solution. I need to subtract the first value within a column (in this case column 8 in my df) from the last value &amp; divide this by a number (e.g. 60) after having applied groupby to my pandas df to get one value per id. The final output would ideally look something like this: id 1 1523 2 1644 I have the actual equation which works on its own when applied to the entire column of the df: (df.iloc[-1,8] - df.iloc[0,8])/60 However I fail to combine this part with the groupby function. Among others, I tried apply, which doesn't work. df.groupby(['id']).apply((df.iloc[-1,8] - df.iloc[0,8])/60) I also tried creating a function with the equation part and then do apply(func)but so far none of my attempts have worked. Any help is much appreciated, thank you!
favorite count: 0
has answer: http://stackoverflow.com/a/48252639
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/48252639
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
tagged with: dataframe
tagged with: python
type: Question
upvote count: 3

http://stackoverflow.com/a/48213604
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/83415861
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83415713
accepted answer of: http://stackoverflow.com/q/48213509
has body: You could embed the bit that you want to repeat in a while True block that you break out of? For example: while True answer = input("What is the correct answer, a, b, or c? ") check = input("Are you sure (y/n)? ") if check=="y" or check=="Y": break
answers question: http://stackoverflow.com/q/48213509
type: Answer

http://stackoverflow.com/comment/83510934
type: Comment
comment on: http://stackoverflow.com/q/48262966
type: QuestionComment
has text: Yes, exactly - I want the GUI to remain responsive (e.g. no spinning ball on a Mac), but the dialog window should be modal - so the only possible user interaction is either wait until `time.sleep(10)` has finished or cancel `time.sleep(10)`.
score: 0

http://stackoverflow.com/a/48220838
upvote count: 1
has body: Just try this one : fc = Fc.objects.all().values_list('operator_priority', flat=True) seen_values = set() new_list = [] for x in fc: if x not in seen_values: new_list.append(fc) seen_values.add(fc) or else try this one also: fc = Fc.objects.all().values_list('operator_priority', flat=True) new_dict = dict() for obj in fc: if obj not in new_dict: new_dict[obj] = obj
has comment: http://stackoverflow.com/comment/83423296
type: Answer
has comment: http://stackoverflow.com/comment/83423348
score: 1
answers question: http://stackoverflow.com/q/48220570
downvote count: 0

http://stackoverflow.com/q/48262991
score: 3
upvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/48263259
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83509132
has title: Counter in BruteForce while-loop; Out of memory with yield?
type: UnansweredQuestion
has body: I'm starting to learn basic programming with python, and as I encountered permutations, I wanted to see if I could (for fun) brute force a userinput.. It seems to work for short PW's, but my counter seems to have a flaw, or do I miss something about permutations nature? ...the counter shows the same number each time, for any PW of the same length... Also, there's a memory error for longer PW's, but I thought I ruled that out by using a generator(yield) instead of a list.. or didn't I? Thanks for your Help import string from itertools import permutations characters = string.ascii_letters user_pw = input('Set your PW') attempts = 0 done = False while True: def Generator(): guess_storage = [''.join(p) for p in permutations(characters, len(user_pw))] for current in guess_storage: yield current for guess in Generator(): attempts += 1 if guess == user_pw: print('SUCESS: ') print('Password: ', guess) done = True if done == True: break print('Attempts: ', attempts)
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83510052

http://stackoverflow.com/a/48278043
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: To optimize the code, based on @COLDSPEED's suggestion I used: df_min = grouped.agg({'Aduration': 'sum', 'type': 'count', 'Astart': 'min'}).reset_index() df_min.rename(columns={'Aduration': "Used", 'type': 'Count', 'Astart': 'min'}, inplace=True) df_with_proc = df_t1[df_t1['type'] == "Process"].groupby(["CPU", "index"]).agg({'type': 'count'}).reset_index() df_with_proc.rename(columns={'type': 'CSwitch'}, inplace=True) df_t1 = pd.merge(df_with_proc, df_t1, how="right", on=['CPU', 'index']) df_t1 = pd.merge(df_min, df_t1, how="right", on=['CPU', 'index']) This can compute in 0.2 sec on same dataframe.
answers question: http://stackoverflow.com/q/48273294

http://stackoverflow.com/comment/83481599
type: Comment
type: QuestionComment
has text: @timgeb: What about `'Leonardo Da Vinci'`?
comment on: http://stackoverflow.com/q/48249512
score: 0

http://stackoverflow.com/comment/83479828
has text: You're welcome. And no, you won't be able to upload the debug version. It will ask you to create a Release version.
comment on: http://stackoverflow.com/a/48228135
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/65828968
has body: If you are using Pycharm , Got to Run - &gt; Edit Configurations and click on Environment variables to add as below(basically the PYSPARK_PYTHON and PYSPARK_DRIVER_PYTHON should point to the same version of Python) . This solution worked for me .Thanks to the above posts.
score: 1
answers question: http://stackoverflow.com/q/48260412
downvote count: 0
upvote count: 1
type: Answer

boto3
tags question: http://stackoverflow.com/q/48296084
tags question: http://stackoverflow.com/q/48204861
tags question: http://stackoverflow.com/q/48297096
tag name: boto3
tags question: http://stackoverflow.com/q/48209678
tags question: http://stackoverflow.com/q/48262698
tags question: http://stackoverflow.com/q/48196784
tags question: http://stackoverflow.com/q/48307919
tags question: http://stackoverflow.com/q/48310785
tags question: http://stackoverflow.com/q/48256007
tags question: http://stackoverflow.com/q/48323239
type: Tag
tags question: http://stackoverflow.com/q/48302295
tags question: http://stackoverflow.com/q/48298295
tags question: http://stackoverflow.com/q/48317116
tags question: http://stackoverflow.com/q/48250068
tags question: http://stackoverflow.com/q/48221591
tags question: http://stackoverflow.com/q/48175271
tags question: http://stackoverflow.com/q/48209088

http://stackoverflow.com/comment/135021800
type: Comment
has text: Adding those 2 as env vars (to bash_profile.sh) solved my problem!
type: AnswerComment
comment on: http://stackoverflow.com/a/58268006
score: 0

http://stackoverflow.com/q/48290068
has comment: http://stackoverflow.com/comment/83566222
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: data-science
linked to: http://stackoverflow.com/q/45182397
tagged with: data-science-experience
has body: Is there any way to enable Jupyter-dashboard extensions on IBM DSX service? Righ below is the extension I'm trying to install: http://jupyter-dashboards-layout.readthedocs.io/en/latest/index.html According to the documentation, the following commands should be executed on Jupyter to enable the extension: pip install jupyter_dashboards jupyter dashboards quick-setup --sys-prefix jupyter nbextension install --py jupyter_dashboards --sys-prefix jupyter nbextension enable jupyter_dashboards --py --sys-prefix I've installed the Jupyter extension through the notebook itself with pip install, as shown right below: However, when I've tried the next command required for the install I receive the following error: I've initially though that it could be an issue regarding jupyter path, and tried the same command on the different jupyter binaries that are found on the container, but I still couldn't figure out why the install seems to not be working so far. Is there any procedure in particular I should follow to install / enable extensions on IBM DSX? In case this extension can'tbe installed, do you guys indicate any alternative for Jupyter-Dashboards extension that can be used to improve the notebook presentation? Thanks in advance! Felipe Silveira
type: Question
accepted answer: http://stackoverflow.com/a/48294817
has title: Is it possible to install Jupyter Dashboard extension on IBM DSX?
tagged with: python
tagged with: jupyter
has answer: http://stackoverflow.com/a/48294817
has comment: http://stackoverflow.com/comment/83568732
tagged with: jupyter-notebook

http://stackoverflow.com/a/48213935
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83410729
type: Answer
has body: I'm interpreting your question as "I have a string ending in a digit sequence, for example "item_01". I want to get a string with the same form as the original string, but with the digit incremented by one, for example "item_02"." You could use re.sub to replace the digit sequence with a new one: &gt;&gt;&gt; import re &gt;&gt;&gt; &gt;&gt;&gt; s = "item_01" &gt;&gt;&gt; result = re.sub( ... r"\d+$", #find all digits at the end of the string, ... lambda m: str( #replacing them with a string ... int(m.group())+1 #equal to one plus the original value, ... ).zfill(len(m.group())), #with at least as much padding as the original value. ... s ... ) &gt;&gt;&gt; &gt;&gt;&gt; print(result) item_02 In one line, that would be result = re.sub(r"\d+$", lambda m: str(int(m.group())+1).zfill(len(m.group())), s) Note that the resulting string may be longer than the original string, if the original value is all nines: &gt;&gt;&gt; re.sub(r"\d+$", lambda m: str(int(m.group())+1).zfill(len(m.group())), "item_99") 'item_100' And it will only increment the digit sequence at the very end of the string, and not any intermediary sequences. &gt;&gt;&gt; re.sub(r"\d+$", lambda m: str(int(m.group())+1).zfill(len(m.group())), "item_23_42") 'item_23_43' And if the string has no suffix digit sequence, it will simply return the original value unaltered. &gt;&gt;&gt; re.sub(r"\d+$", lambda m: str(int(m.group())+1).zfill(len(m.group())), "item_foobar") 'item_foobar'
accepted answer of: http://stackoverflow.com/q/48213646
answers question: http://stackoverflow.com/q/48213646
downvote count: 0

http://stackoverflow.com/q/48245765
favorite count: 0
tagged with: ode
has answer: http://stackoverflow.com/a/60267581
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48999583
has answer: http://stackoverflow.com/a/48999583
tagged with: python
answer count: 6
score: 22
has answer: http://stackoverflow.com/a/58281925
has answer: http://stackoverflow.com/a/55720088
has body: For solving simple ODEs using SciPy, I used to use the odeint function, with form: scipy.integrate.odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0, ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0, hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12, mxords=5, printmessg=0)[source] where a simple function to be integrated could include additional arguments of the form: def dy_dt(t, y, arg1, arg2): # processing code here In SciPy 1.0, it seems the ode and odeint funcs have been replaced by a newer solve_ivp method. scipy.integrate.solve_ivp(fun, t_span, y0, method='RK45', t_eval=None, dense_output=False, events=None, vectorized=False, **options) However, this doesn't seem to offer an args parameter, nor any indication in the documentation as to implementing the passing of args. Therefore, I wonder if arg passing is possible with the new API, or is this a feature that has yet to be added? (It would seem an oversight to me if this features has been intentionally removed?) Reference: https://docs.scipy.org/doc/scipy/reference/integrate.html
type: Question
tagged with: numpy
upvote count: 22
accepted answer: http://stackoverflow.com/a/48245935
has title: Pass args for solve_ivp (new SciPy ODE API)
downvote count: 0
has answer: http://stackoverflow.com/a/48245935
has answer: http://stackoverflow.com/a/57016523
tagged with: odeint
tagged with: scipy

http://stackoverflow.com/q/48326732
has body: So I have successfully put together a lovely program that counts the total unread messages from inside a category within a Gmail account, and posts the data in realtime into a tkinter text box - all seems to work, apart from one really annoying aspect... The only issue I am having is that the code seems to be counting blank inside Gmail where there are actually 0 messages, trash included. I want the readout to be 0 submission[s], instead of submission[s]. How can I get the code below to see no messages as 0? When 1 unread message is in there however it tells me that 1 message is in there, when there are 2, it says 2. But when there are 0 it returns a blank space followed by the else statement as if it were counting at least one message in the inbox. Frustrating right? Here is the code that I am using to delve into the Gmail account and count the 'unreads' - hopefully I have just done something stupid... #! /usr/bin/env python3.4 import imaplib import email import tkinter as tk mail=imaplib.IMAP4_SSL('imap.gmail.com', 993) mail.login('mygmail@gmail.com','mypassword') mail.select("myinboxlabel") typ, messageIDs = mail.search(None, "UNSEEN") memberships = str(messageIDs[0], encoding='utf8') if memberships == 0: info2['text'] = 'no memberships' else: info2['text'] = '{} membership[s]'.format(memberships)
has comment: http://stackoverflow.com/comment/83648416
has title: imap returing "blank" unseen message, from an inbox containing no messages
type: Question
has comment: http://stackoverflow.com/comment/83641493
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83640292
tagged with: imap
tagged with: python
tagged with: gmail
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83641277
tagged with: gmail-imap

http://stackoverflow.com/comment/83543007
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48278967
score: 0
has text: Cheers :) btw, I don't know what code is in that method, but django provides the fk id directly in `project.projectLeader_id`

http://stackoverflow.com/q/48190158
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/68645
tagged with: python
score: -1
duplicate of: http://stackoverflow.com/q/41881061
has body: I'm new to writing python test code and am currently dabbling with unittest. Why is this complaining: class MyTestClass(unittest.TestCase): testdata = "somefile.json" def testparse(self): data = json.loads(open(testdata).read()) Traceback (most recent call last): File "test.py", line 14, in test_instantiation data = json.loads(open(testdata).read()) NameError: global name 'testdata' is not defined
has answer: http://stackoverflow.com/a/48190250
has answer: http://stackoverflow.com/a/48190246
tagged with: python-2.7
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/83361528
tagged with: python-unittest
downvote count: 1
has title: Why is it complaining about variable not being defined
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83360371

http://stackoverflow.com/a/48233593
type: Answer
has body: When you do: bin_out.append(bins1) bin_mean.append(bins1) bin_bd.append(bins1) all three lists contain references to the same bins1 lists. Then later you do: for i in bin_mean: binn1.append(i) so binn1 also contains references to the same lists. Finally, you do: binn1[i][j]=p[i] This modifies the lists that all 4 variables refer to. You should make copies of the lists: bin_out.append(bins1[:]) bin_mean.append(bins1[:]) bin_bd.append(bins1[:]) ... for i in bin_mean: binn1.append(i[:]) BTW, that loop can be done with a list comprehension: binn1 = [i[:] for i in bin_mean]
score: 2
answers question: http://stackoverflow.com/q/48232674
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/83424983
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48219223
type: Comment
has text: I have tried the looping solution, and it work because I only have one model only in a relation from the Django user with the userProfile, so good, but what if I want to access directly to this user profile or any **object** doing something like: {{ object_list.portfolio }}, or {{ objectt_list.carousel }} ?

http://stackoverflow.com/a/48188939
accepted answer of: http://stackoverflow.com/q/48177039
has body: I performed a re-flash of Raspbian on the belligerent little thing. It appears to work now. The odd thing is that the image is the 2019-11-29 version. Weird.
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/48177039
type: Answer

http://stackoverflow.com/comment/83365208
type: AnswerComment
comment on: http://stackoverflow.com/a/48192272
has text: @KennyOstrom there will *never* be more than one match. A key is either in the dictionary or not. They are NOT the same at all. One is constant time and the other is linear. These are basic facts about dictionaries
score: 0
type: Comment

http://stackoverflow.com/q/48173798
answer count: 3
downvote count: 0
has title: additional row colors in seaborn cluster map
has answer: http://stackoverflow.com/a/48175227
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83329739
has answer: http://stackoverflow.com/a/58520672
has answer: http://stackoverflow.com/a/55736346
has comment: http://stackoverflow.com/comment/83328090
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83330149
accepted answer: http://stackoverflow.com/a/48175227
possible better answer: http://stackoverflow.com/a/58520672
tagged with: seaborn
has comment: http://stackoverflow.com/comment/83329827
has body: I am currently generating clustermaps in seaborn and labeling the row colors as below. matrix = pd.DataFrame(np.random.random_integers(0,1, size=(50,4))) labels = np.random.random_integers(0,5, size=50) lut = dict(zip(set(labels), sns.hls_palette(len(set(labels)), l=0.5, s=0.8))) row_colors = pd.DataFrame(labels)[0].map(lut) g=sns.clustermap(matrix, col_cluster=False, linewidths=0.1, cmap='coolwarm', row_colors=row_colors) plt.show() I have a second annotation column similar to the labels data I would also like to add to the plot. The seaborn API doesn't support adding a second row_colors column, which is fine, but I am struggling in finding a workaround using matplotlib to add this annotation column to the clustering. If I cannot use seaborn to do this and have to generate all of this manually using matplotlib that would be fine, I just can't figure that out either. Thanks for your help!
tagged with: python
has comment: http://stackoverflow.com/comment/83329492
score: 14
upvote count: 14
type: AnsweredQuestion

http://stackoverflow.com/a/48246381
downvote count: 0
upvote count: 7
has body: You can create an entry manually by triggering the request_success event. from locust import events events.request_success.fire( request_type="task", name="my_task", response_time=1337, response_length=0, ) You could also create a decorator that automatically fires the above event and tracks the execution time for the tasks that it's applied to.
score: 7
type: Answer
answers question: http://stackoverflow.com/q/48233961
has comment: http://stackoverflow.com/comment/136025719

http://stackoverflow.com/comment/83515081
type: QuestionComment
has text: MatLab function or matplotlib??
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48265933

http://stackoverflow.com/q/48247648
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83483296
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has body: I use aiomysql. I access mysql with asynchronous. SO I use aiomysql. But running time(when aiomysql doesn't use) is same running time when aimysql uses. from sqlalchemy import create_engine import pymysql pymysql.install_as_MySQLdb() import pandas as pd engine = create_engine("mysql+mysqldb://root:"+"qhdks12#$"+"@localhost/stock", encoding='utf-8') conn = pymysql.connect(host='localhost', user='root', password="qhdks12#$", db='stock', charset='utf8') cursor = conn.cursor() def test(): for i in range(10): sql = "select * from test;" data = pd.read_sql(sql, conn, index_col=None) %timeit test() Above Code, aiomysql not use. In Jupyter Notebook, test() function running time is "3.1 s ± 39.3 ms" import asyncio import aiomysql as aiomysql import pandas as pd async def main(loop): pool = await aiomysql.create_pool(host='127.0.0.1', port=3306, user='root', password='qhdks12#$', db='stock', loop=loop) for i in range(2): await test(pool, loop) async def test(pool, loop): async with pool.acquire() as conn: async with conn.cursor() as cur: await cur.execute("select * from test;") rows = () rows = await cur.fetchall() result = pd.DataFrame.from_records(list(rows)) loop = asyncio.get_event_loop() %timeit loop.run_until_complete(main(loop)) Above Code, aiomysql use. In Jupyter Notebook, main(loop) function running time is "3.05 s ± 107 ms per loop " Running time is same. I think above code doesn't connect db with asynchronous. So, I don't know aiomysql normally. How do I connect db with asynchronous???
tagged with: python-asyncio
has title: I don't know using python aiomysql normally. running time (when aiomysql doesn't use) is same running time when aiomysql uses
score: 1
tagged with: mysql
has comment: http://stackoverflow.com/comment/83479318
has answer: http://stackoverflow.com/a/54618874
tagged with: asynchronous

http://stackoverflow.com/a/50999075
answers question: http://stackoverflow.com/q/48230370
score: 3
type: Answer
has body: Go to http://chromedriver.chromium.org/downloads copy the download link according to your OS wget -N paste_the_link_you_copied unzip it using below command unzip chromedriver_linux64.zip Give the permission by the below command chmod +x chromedriver Then follow the below commands, if it says already exists (probabily old version) then go to that path (/usr/local/bin/chromedriver and /usr/bin/chromedriver) and delete chromedriver and run the commands again sudo mv -f chromedriver /usr/local/share/chromedriver sudo ln -s /usr/local/share/chromedriver /usr/local/bin/chromedriver sudo ln -s /usr/local/share/chromedriver /usr/bin/chromedriver Hope this helps. Thanks
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/48263314
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48263858
score: 0
has body: Hello I would like to loop through a list of datetimes obtained from an Excel file and check if the timedifference between the current iteration and previous iterations > 10 minutes and if so then the current iteration should be previous iteration + 10 minutes. This is list of dates that I got, and I would like index 4 to be index 3 + 10 minutes instead of NaT ex. 0 2014-11-01 00:00:00 1 2014-11-01 00:10:00 2 2014-11-01 00:20:00 3 2014-11-01 00:30:00 4 NaT 5 2014-11-01 00:50:00 6 2014-11-01 01:00:00 7 2014-11-01 01:10:00 8 2014-11-01 01:20:00 9 2014-11-01 01:30:00 10 2014-11-01 01:40:00 11 2014-11-01 01:50:00 12 2014-11-01 02:00:00 13 NaT 14 2014-11-01 02:20:00 15 2014-11-01 02:30:00 16 2014-11-01 02:40:00 17 2014-11-01 02:50:00 18 2014-11-01 03:00:00 Name: Timestamp, dtype: datetime64[ns] import pandas as pd import os import matplotlib.pyplot as plt import numpy as np import time import datetime os.chdir('C:\Users\NIK\.spyder2\PythonScripts') file = 'FilterDataTest.xlsx' data = pd.read_excel(file, sheetname='Ark1') dato = data['Timestamp'] for i in range(0,len(dato)): if dato[i].minute - dato[i-1].minute &gt; 10: dato_old = dato[i-1] dato[i] = dato_old + minute(10) This is the code that I have made so far, I know that it would not work especially the last part with old value + minute(10) this is only to highlight what I am trying to do.
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/83509617
has title: Loop through dates in pandas datetime object and compare timedifference
type: Question
accepted answer: http://stackoverflow.com/a/48263858
tagged with: datetime
tagged with: python
tagged with: timestamp

http://stackoverflow.com/q/48184668
type: Question
tagged with: debugging
tagged with: pycharm
tagged with: python
has title: PyCharm + IPython debug in external terminal
type: AnsweredQuestion
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48200287
has body: I am wondering is it possible to attach process of debugging in PyCharm IDE to external IPython terminal. Here is a picture which would describe this scenario: Here are steps how I would like to reproduce this scenario: 1.) Set breakpoint at any line of code in PyCharm IDE. 2.) When IDE encounters line of code where breakpoint is located, it should open terminal, start ipython and load all variables / modules as if normal debugging would occur. 3.) Continue and step into / out should be reflected in terminal Any help would be greatly appreciated!
accepted answer: http://stackoverflow.com/a/48200287
tagged with: ipython

http://stackoverflow.com/a/48337177
type: Answer
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83816855
has comment: http://stackoverflow.com/comment/83818857
answers question: http://stackoverflow.com/q/48245651
has body: If your code is assuming that you'll fill in w_att and w_r later with the correct values, then it should do what you think: produce a TensorArray in which each element is calculated across a psuedo-batch. You'll have to think pretty hard and carefully to make sure these are filled the right way. It is quite inefficient since you are doing multiple (potentially very large/sparse) matrix multiplies. If you know ahead of time exactly how many pseudo-batches you will have, then you should use tf.dynamic_partition with your group_num_list x_partitions = tf.dynamic_partition(x, group_num_list, pseudo_batch_size) x_partitions is then a python list of Tensors where x_partitions[0] is a stack of the vectors from x for which the index of group_num_list was 0. e.g. (not actually code) given x.shape == [5, 100] and group_num_list == [0,0,0,1,1], then len(x_partitions) == 2 and x_partitions[0].shape == [3, 100] x_partitions[1].shape == [2, 100] You can then do whatever else you were going to do on just one partition on all of the partitions with a native python loop (although this creates a bunch of extra nodes in your graph, there's very little computation overhead). I'm going to modify your get_attention_weighted_rep, mostly assuming different names and feeding in all of the components. I'm going to call it x_to_s def x_to_s(x, A, r): e = tf.matmul(tf.matmul(x, A), r) alpha = tf.softmax(e) return tf.reduce_sum(x * e, 0, keep_dims=True) Once this has been done per partition, you can concatenate them back together to get an s across all pseudo-batches: # following on from our example earlier, let's use x_to_s # which takes an x with x.shape = [None, 100] # and returns a tensor with shape = [1, 100] s_parts = [] for p in x_partitions: # calculate/find A and r for this x s_parts.append(x_to_s(p, A, r)) s = tf.concat(s_parts) # this makes s.shape = [2, 100] If you want a dynamic number of pseudo batches at run time; then I don't think there's a simple way. I didn't read enough of t…

http://stackoverflow.com/comment/83476441
has text: I can't install, because it Lambda(serverless from AWS)
comment on: http://stackoverflow.com/a/48244447
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83548538
score: 0
has text: Well you need some way to map which key corresponds with what value.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48282388

http://stackoverflow.com/q/48237735
has comment: http://stackoverflow.com/comment/83458067
downvote count: 0
has answer: http://stackoverflow.com/a/48237799
possible better answer: http://stackoverflow.com/a/48237799
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83458126
has comment: http://stackoverflow.com/comment/83457981
upvote count: 2
has comment: http://stackoverflow.com/comment/83458057
has comment: http://stackoverflow.com/comment/83458191
tagged with: arrays
has answer: http://stackoverflow.com/a/48237822
tagged with: python
accepted answer: http://stackoverflow.com/a/48237822
has comment: http://stackoverflow.com/comment/83458085
score: 2
type: AnsweredQuestion
has body: I have two arrays (a,b) of different mXn dimensions I need to know that how can I roll these two arrays into a single one dimensional array I used np.flatten() for both a,b array and then rolled them into a single array but what i get is an array containg two one dimensional array(a,b) a = np.array([[1,2,3,4],[3,4,5,6],[4,5,6,7]]) #3x4 array b = np.array([ [1,2],[2,3],[3,4],[4,5],[5,6]]) #5x2 array result = [a.flatten(),b.flatten()] print(result) [array([1, 2, 3, 4, 3, 4, 5, 6, 4, 5, 6, 7]), array([1, 2, 2, 3, ... 5, 6])] In matlab , I would do it like this : res = [a(:);b(:)] Also, how can I retrieve a and b back from the result?
answer count: 2
has title: how to roll two arrays of diffeent dimesnions into one dimensional array in python

http://stackoverflow.com/comment/83495497
type: QuestionComment
has text: Welcome to Stack Overflow! You can [take the tour](http://stackoverflow.com/tour) first and learn [How to Ask a good question](http://stackoverflow.com/help/how-to-ask) and create a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example. That makes it easier for us to help you.
score: 0
comment on: http://stackoverflow.com/q/48256374
type: Comment

http://stackoverflow.com/a/48260980
type: Answer
answers question: http://stackoverflow.com/q/48258463
has body: Try with: Go to Window → Preferences. Open PyDev and select Editors (actually click on 'Editors', don't just expand it). In the Appearance Color Options dropdown menu, select what you want to change. I took this tip from this link https://www.rose-hulman.edu/class/csse/resources/Eclipse/eclipse-python-configuration.htm
score: 0

http://stackoverflow.com/comment/83436905
type: AnswerComment
comment on: http://stackoverflow.com/a/48227450
has text: anyway I'm keeping this Q&A for my future training sessions :) a good example of complex loop turned into ... a complex list comprehension :)
score: 0
type: Comment

http://stackoverflow.com/comment/83418522
type: AnswerComment
has text: I tried this way but I get the error 'can't multiply sequence by non-int of type 'str''
score: 0
comment on: http://stackoverflow.com/a/48216977
type: Comment

http://stackoverflow.com/q/48176420
type: Question
has body: Wagtail claims to work with django 2.0 on their website but when I install it via pip install wagtail uninstalls django 2.0 and installs 1.11. Is there a way to have it work smoothly with new django? Updating django back to 2.0 ends up breaking the site. Here is the code when I attempt to run the server: Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x1061e58c8&gt; Traceback (most recent call last): File "/Users/johnbriggs/.virtualenvs/py1/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/johnbriggs/.virtualenvs/py1/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/Users/johnbriggs/.virtualenvs/py1/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Users/johnbriggs/.virtualenvs/py1/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/Users/johnbriggs/.virtualenvs/py1/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/johnbriggs/.virtualenvs/py1/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/johnbriggs/.virtualenvs/py1/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Users/johnbriggs/.virtualenvs/py1/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Users/johnbriggs/.virtualenvs/py1/lib/python3.6/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 "&…
score: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/48541367
has title: Using Wagtail with django 2.0
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/48176541
accepted answer: http://stackoverflow.com/a/48176541
downvote count: 0
upvote count: 1
tagged with: wagtail
tagged with: pip
has answer: http://stackoverflow.com/a/48541367
favorite count: 0

http://stackoverflow.com/a/48226178
type: AcceptedAnswer
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/83434208
answers question: http://stackoverflow.com/q/48226109
downvote count: 0
has body: You could just switch the ' and " to achieve your goal: print(' ' + eachP + ' ' + ' ') However, a more readable way for you would be this: print(' {} '.format(arr14.index(eachP), eachP)
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48226109

http://stackoverflow.com/a/48298230
score: 27
upvote count: 27
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48298009
accepted answer of: http://stackoverflow.com/q/48298009
type: Answer
has body: You just need to add a non-option (doesn't start with -) argument in the click.option decorator. Click will use this as the name of the parameter to the function. This allows you to use Python keywords as option names. Here is an example which uses id_ inside the function: import click @click.command(name='foo') @click.option('--id', 'id_', required=True) def do_something(id_): print(id_) There is an official example here in the --from option.

relative-path
type: Tag
tags question: http://stackoverflow.com/q/48324056
tag name: relative-path

http://stackoverflow.com/q/48274695
tagged with: pyserial
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/83533043
has answer: http://stackoverflow.com/a/48274933
has comment: http://stackoverflow.com/comment/83532923
has body: I am attempting to read serial values from an Arduino using Python. &gt;&gt;&gt; ser.read() '2' &gt;&gt;&gt; a = ser.readLine() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'Serial' object has no attribute 'readLine' Why do I get an error with readLine, but not with read()? Or read(10)? The complete code I'm using: &gt;&gt;&gt; import serial &gt;&gt;&gt; ser = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=10) &gt;&gt;&gt; ser.read() '\n' &gt;&gt;&gt; ser.readLine() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'Serial' object has no attribute 'readLine' &gt;&gt;&gt; ser.read() '2' &gt;&gt;&gt; ser.readLine() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'Serial' object has no attribute 'readLine'
has comment: http://stackoverflow.com/comment/83533084
has comment: http://stackoverflow.com/comment/83533027
answer count: 1
tagged with: arduino
favorite count: 0
type: Question
tagged with: serialization
has title: ser.read() works, but ser.readLine() throws error

http://stackoverflow.com/a/75186633
type: Answer
answers question: http://stackoverflow.com/q/48256395
has body: The only thing I know is that categorical dtypes use less data because sometimes object dtypes are encoded and thus have more characters in the encoding, where as categorical are encoded only if necessary.
score: 0

http://stackoverflow.com/q/48178204
has body: I'm working on a Django project in which settings such as SECRET_KEY are defined in a .env file, and manage.py sets the environment variable using python-dotenv as follows: from dotenv import load_dotenv, find_dotenv if __name__ == "__main__": load_dotenv(find_dotenv()) # usual manage.py code Then settings.py simply defines module-level settings from environment variables, for example, SECRET_KEY = os.environ['SECRET_KEY'] I'm now in the process of switching to pytest-django for unit testing. The problem, however, is that without running python manage.py first, the environment variables don't get set, so I end up with E KeyError: 'SECRET_KEY' The way I'm now thinking of working around this is to define a custom action to register with manage.py to run pytest (following https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/). This seems a bit like using a sledgehammer to crack a nut, though. Any suggestions of more elegant ways to go about this problem?
type: Question
has title: How to run django-pytest on a project which imports settings from environment variables defined in manage.py
has answer: http://stackoverflow.com/a/48178690
score: 5
upvote count: 5
tagged with: django
tagged with: python
tagged with: pytest-django
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: pytest
has answer: http://stackoverflow.com/a/48178666
accepted answer: http://stackoverflow.com/a/48178666
possible better answer: http://stackoverflow.com/a/48178690
favorite count: 0

http://stackoverflow.com/a/48245099
has comment: http://stackoverflow.com/comment/83900264
has body: I usually use openpyxl when working with Excel files and bulk_create to insert into database with 1 query. Below is a code example. import openpyxl, datetime file = uploadform.cleaned_data['docfile'] workbook = openpyxl.load_workbook(file, read_only=True) # Get name of the first sheet and then open sheet by name first_sheet = workbook.get_sheet_names()[0] worksheet = workbook.get_sheet_by_name(first_sheet) data = [] for row in worksheet.iter_rows(row_offset=1): # Offset for header stock = Stocks() stock.user = request.user stock.name = row[0].value stock.number = row[1].value stock.suffix = row[2].value stock.brand = row[3].value stock.comment = row[4].value stock.price = row[5].value stock.date = datetime.datetime.utcnow() stock.confirm = 'approved' stock.seller = row[6].value data.append(stock) # Bulk create data Stocks.objects.bulk_create(data) bulk_create has some caveats so do read documentation before using it.
answers question: http://stackoverflow.com/q/48244679
has comment: http://stackoverflow.com/comment/83915352
has comment: http://stackoverflow.com/comment/83915978
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83919821
has comment: http://stackoverflow.com/comment/83915258
has comment: http://stackoverflow.com/comment/83910801
score: 0
accepted answer of: http://stackoverflow.com/q/48244679
has comment: http://stackoverflow.com/comment/83553418
type: Answer

http://stackoverflow.com/comment/83394499
has text: I get `ValueError: cannot reshape array of size 8 into shape (1000,newaxis)` on line 4
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48206754
type: Comment

http://stackoverflow.com/comment/83467454
type: AnswerComment
comment on: http://stackoverflow.com/a/48242499
score: 0
has text: As the documentation you link warns right at the start, the sets module has been deprecated since Python 2.6, which was released almost ten years ago (1 October 2008), and doesn't even exist in modern Python.
type: Comment

http://stackoverflow.com/comment/83494464
type: QuestionComment
comment on: http://stackoverflow.com/q/48253800
has text: in python's `matplotlib` there are 2d histograms, hexbin... https://python-graph-gallery.com/2d-density-plot/ and https://python-graph-gallery.com/heatmap/
type: Comment
score: 0

http://stackoverflow.com/a/48263391
has comment: http://stackoverflow.com/comment/83512121
type: Answer
has comment: http://stackoverflow.com/comment/83512629
has comment: http://stackoverflow.com/comment/83513127
downvote count: 0
answers question: http://stackoverflow.com/q/48259089
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83513820
has comment: http://stackoverflow.com/comment/83511841
has body: Trivia Your problem stems from these lines of code: on_off.write(b"S00QLE\n") sleep(4) especially from sleep. It's very weak pattern, because you're expecting a completion of S00QLE in four seconds. No more and no less! And while telnet actually works for these four seconds, the GUI sleeps. Therefore your GUI is in unresponsive state and can't redraw the relief of the button. The good alternative to sleep is the after - so you can schedule an execution: # crude and naive fix via closure-function and root.after def Power_On_Off (PowerSwitchPort, Action): ... def write_switch_port_and_close(): on_off.write(StringDict[PowerSwitchPort]) on_off.close() on_off.write(b"S00QLE\n") # sleep(4) root.after(4000, write_switch_port_and_close) ... Solution To overcome this problem, you can use generic after self-sheduling loop. In my example I connect to public telnet server, which broadcasts Star Wars Episode IV (not an add!), to simulate a long-running process. Of course, your execute (write) two commands in telnet, to represent this behaviour we recive a telnet broadcast until the famous "Far away" line is found (first long-run operation (write)). After that, we update the label-counter and then we connect to the broadcast again (second long-run operation (write)). Try this code: import tkinter as tk import telnetlib class App(tk.Tk): def __init__(self): super().__init__() # store telnet client without opening any host self.tn_client = telnetlib.Telnet() # label to count "far aways" self.far_aways_encountered = tk.Label(text='Far aways counter: 0') self.far_aways_encountered.pack() # start button - just an open telnet command ("o towel.blinkenlights.nl 23") self.button_start = tk.Button(self, text='Start Telnet Star Wars', command=self.start_wars) self.button_start.pack() # start button - just an close telnet command ("c") self.button_stop = tk.Button(self, text='Stop Telnet Star Wars', command=self.close_wars, state='disabled') self.button_stop.pack() # simple counter self.cou…
has comment: http://stackoverflow.com/comment/83512748

http://stackoverflow.com/comment/83546118
type: QuestionComment
comment on: http://stackoverflow.com/q/48280807
has text: This is __not__ json indeed, this is a Python `dict`.
score: 1
type: Comment

http://stackoverflow.com/comment/83476159
score: 0
has text: Suppose I am testing an apple. One test would test if it is red. Another one would test if it is edible. If the edible test fails, I know what is wrong with the apple. On the other hand, if I put all asserts into the same test, then it takes a while to read the output, figure out which assert fail, and what does that means.
comment on: http://stackoverflow.com/q/48246674
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48292804
type: AnsweredQuestion
tagged with: tkinter
score: 2
answer count: 1
downvote count: 0
duplicate of: http://stackoverflow.com/q/1101750
favorite count: 0
type: Question
has title: How to delete label generated from loop in tkinter?
tagged with: attributeerror
upvote count: 2
accepted answer: http://stackoverflow.com/a/48292833
tagged with: python
has answer: http://stackoverflow.com/a/48292833
has body: So I'm trying to delete labels when a button is clicked, but I get an error on doing so. This is a loop that generates labels based on the list that I have declared earlier. t = 150 i = 0 for p in products_list: self.pr1 = Label(self.right, text=str(products_list[i]), font=('arial 16 bold'), bg='steelblue', fg='white').place(x=0, y=t) self.pr2 = Label(self.right, text=(str(quantity_list[i])), font=('arial 16 bold'), bg='steelblue', fg='white').place(x=130, y=t) self.pr3 = Label(self.right, text=(str(price_list[i])), font=('arial 16 bold'), bg='steelblue', fg='white').place(x=240, y=t) t += 40 i += 1 Now I'm trying to delete those labels when I click a button. I have created a print_bill function which has to delete the labels. I tried: def print_bill(self): f = open(str(date), "w+") f.write("Bill Bill Bill") f.close() tkinter.messagebox.showinfo("Bill", "Bill Generated Successfully") self.pr1.destroy()
linked to: http://stackoverflow.com/q/1101750

http://stackoverflow.com/comment/83536033
comment on: http://stackoverflow.com/q/48276017
score: 0
type: Comment
type: QuestionComment
has text: @ReblochonMasque I added the traceback

http://stackoverflow.com/comment/83434252
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48226225
has text: In your `comment.indent =` line.... Shouldn't you be looking up by ID of the replied comment, not the comment itself? Eg `Comment.objects.get(id=comment.replyto.id).indent + 1;`

http://stackoverflow.com/comment/83577470
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48296063
has text: try to delete all files/folders already downloaded (e.g. bottleneck_dir, model_dir, ...) and then run again

http://stackoverflow.com/q/48214014
favorite count: 0
type: Question
has title: counting returned values of unique( )
accepted answer: http://stackoverflow.com/a/48214096
possible better answer: http://stackoverflow.com/a/48214055
has answer: http://stackoverflow.com/a/48214096
has answer: http://stackoverflow.com/a/48214055
tagged with: python
has body: I have a dataframe,df1 Date inp name 0 2017-08-07 2.3.6 ABC 1 2017-08-07 2.3.6 ABC 2 2017-08-08 2.3.6 TAC 3 2017-08-22 2.5.9 TTT 4 2017-09-23 0.8.0 TAC 5 2017-10-09 2.3.6 ABC 6 2017-10-09 2.3.6 TAC 7 2017-10-09 2.3.6 TAC 8 2017-10-23 0.8.0 TAC 9 2017-11-08 6.2.6 ABC then another dataframe,df2 2.3.6ABC 2.3.6TAC 2.5.9TTT August 2 1 0 September 0 0 0 October 1 2 0 November 0 0 1 another dataframe,df3 2.3.6ABC 2.3.6TAC August 2 1 September 0 0 October 1 2 November 0 0 I want to get the distinct values in column: 'inp' of df1 which in this case is 4. Then, number of columns of df2 and df3 which is 3 and 2 in this case. How can I store the number of columns of the 2 dataframes,df2 and df3 in a new dataframe by renaming the index, then getting the percentage df2 and df3 in df1. It should look like this: noOfColumn pct df2 as sat 3 3/4=75 df3 as nath 2 2/4=50 I have not been able to go past this point st=pd.Dataframe(df1) st=df['inp'].unique() st2=st.count() because I keep getting this: AttributeError: 'numpy.ndarray' object has no attribute 'count'
has comment: http://stackoverflow.com/comment/83409754
type: AnsweredQuestion
answer count: 2
tagged with: pandas
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/48246958
has body: I want that when the turtle reaches a certain position, I use a command to move it to another position. The turtle walks a floating point plane so doing exact (integer) position comparisons is problematic. Instead, calculate the distance between the turtle and its target. If that distance is less than some small value (say the radius of the turtle cursor) consider it having hit the target and then take action: if turtle.distance(-25, 50) &lt; 5: # turtle is upon the target turtle.goto(100, 100)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48242213

http://stackoverflow.com/q/48209817
has title: FreeCADCmd export calculation
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83421245
has body: my goal ist to calculate the volume of a solid from a STEP file. Within the python console inside the FreeCAD GUI it is no problem. But I need to do it on the command line with a python script. The problem is, how can I export my result??? I tried to figure out how to export a simple text or whatever from a python script run by FreeCADCmd for a while now. I found no way to export anything ... A simple print("Hello world") doesn't work. Also writing a file doesn't work. The log file is clean, just saying executed test.py-. I hope anyone can help me on this!!! Thanks, Andi
tagged with: freecad
tagged with: export
score: 0
has comment: http://stackoverflow.com/comment/87230172
type: Question

http://stackoverflow.com/comment/88720926
type: Comment
type: AnswerComment
has text: I have edited my question by adding the code that I am using. @ Rene B.
comment on: http://stackoverflow.com/a/50833860
score: 0

http://stackoverflow.com/a/48238627
score: 0
has comment: http://stackoverflow.com/comment/83477651
has body: If you have access to python from java android app. You can write python output in file, then in java code read that file. Or if python output is in web, you will need some web service that provides json/xml output, and then in java code you should call that web service.
answers question: http://stackoverflow.com/q/48237510
type: Answer

http://stackoverflow.com/q/48312205
has comment: http://stackoverflow.com/comment/83610942
accepted answer: http://stackoverflow.com/a/48319998
linked to: http://stackoverflow.com/q/1401712
has title: find the k nearest neighbours of a point in 3d space with python numpy
linked to: http://stackoverflow.com/q/48126771
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/83610549
type: AnsweredQuestion
has body: I have a 3d point cloud of n points in the format np.array((n,3)). e.g This could be something like: P = [[x1,y1,z1],[x2,y2,z2],[x3,y3,z3],[x4,y4,z4],[x5,y5,z5],.....[xn,yn,zn]] I would like to be able to get the K-nearest neighbors of each point. so for example the k nearest neighbors of P1 might be P2,P3,P4,P5,P6 and the KNN of P2 might be P100,P150,P2 etc etc. how does one go about doing that in python?
answer count: 2
upvote count: 7
downvote count: 3
linked to: http://stackoverflow.com/q/4350215
favorite count: 0
type: Question
tagged with: knn
tagged with: numpy
has answer: http://stackoverflow.com/a/58719633
possible better answer: http://stackoverflow.com/a/58719633
has answer: http://stackoverflow.com/a/48319998

http://stackoverflow.com/comment/83456270
has text: According to the [`csv` docs](https://docs.python.org/3/library/csv.html#id3), `newline=''` allows `csv` to do it's internal newline handling correctly.
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/48236818

http://stackoverflow.com/a/48249538
has comment: http://stackoverflow.com/comment/83504580
answers question: http://stackoverflow.com/q/48249512
score: 1
type: Answer
has body: You can use slicing: def split_name(name, last_field=2): return name.split()[last_field-1:last_field] split_name("Matt Damon") # =&gt; ["Damon"] split_name("Madonna") # =&gt; []
has comment: http://stackoverflow.com/comment/83503298
has comment: http://stackoverflow.com/comment/83498686
has comment: http://stackoverflow.com/comment/83483140
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83483070

http://stackoverflow.com/q/48273921
score: -3
has comment: http://stackoverflow.com/comment/83531789
has comment: http://stackoverflow.com/comment/83531431
upvote count: 0
answer count: 2
downvote count: 3
has answer: http://stackoverflow.com/a/48274012
favorite count: 0
has comment: http://stackoverflow.com/comment/83531541
tagged with: python-3.x
has body: Example: unique_dig(123456) All unique 6 I'm trying to write code to have a function return how many unique numbers there are in a positive integer. count = 0 for i in unique_digits: if count.has_key(i): count[i] += 1 else: count[i] = count + 1
type: Question
has comment: http://stackoverflow.com/comment/83531960
has comment: http://stackoverflow.com/comment/83531383
has answer: http://stackoverflow.com/a/48274120
has title: How do I return the number of unique digits in a positive integer
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48257301
downvote count: 0
has comment: http://stackoverflow.com/comment/83498061
has body: I am trying to extract file name from file pointer without extension. My file name is as follows: this site:time.list,this.list,this site:time_sec.list, that site:time_sec.list and so on. Here required file name always precedes either whitespace or dot. Currently I am doing this to get file from file name preceding white space and dot in file name. search_term = os.path.basename(f.name).split(" ")[0] and search_term = os.path.basename(f.name).split(".")[0] Expected file name output: this, this, this, that. How can i combine above two into one liner kind and pythonic way? Thanks in advance.
has comment: http://stackoverflow.com/comment/83497244
favorite count: 0
has comment: http://stackoverflow.com/comment/83497356
type: Question
has comment: http://stackoverflow.com/comment/83497386
answer count: 3
has answer: http://stackoverflow.com/a/48257978
has comment: http://stackoverflow.com/comment/83497349
has comment: http://stackoverflow.com/comment/83497318
tagged with: python
has answer: http://stackoverflow.com/a/48257417
has comment: http://stackoverflow.com/comment/83497371
has comment: http://stackoverflow.com/comment/83497452
accepted answer: http://stackoverflow.com/a/48257978
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48257560
has comment: http://stackoverflow.com/comment/83497411
upvote count: 2
has title: How to split a string on multiple pattern using pythonic way (one liner)?
has answer: http://stackoverflow.com/a/48257560

http://stackoverflow.com/q/48269223
favorite count: 0
type: Question
tagged with: interpolation
tagged with: currying
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83521833
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83522746
has body: I'm trying to write a function that returns an interpolating function that linearly extrapolates outside of the interpolating range. After looking at the posts on currying, I can't figure out why what I have doesn't work. I have: def interpolation(X_list,a_list): A1=scipy.interpolate.UnivariateSpline( np.asarray(X_list), np.asarray(a_list), k=3, s=0, check_finite=True) m=(((a_list[-1])-(a_list[-2])) / ((X_list[-1])-(X_list[-2]))) A1ext= m*X+a_list[-1]-m*X_list[-1] def a(X): if X_list[-1]&gt;=X: return A1 if X&gt;X_list[-1]: return A1ext return a(X)
score: 1
has answer: http://stackoverflow.com/a/48269684
has comment: http://stackoverflow.com/comment/83521842
has comment: http://stackoverflow.com/comment/83522336
has title: Defining a function that returns an (interpolated) function
has comment: http://stackoverflow.com/comment/83521721

http://stackoverflow.com/q/48273491
favorite count: 0
type: Question
has body: I am trying to automate a website that opens only in IE. Manually i am able to add the IE extension to chrome and run the website. But is it possible with selenium to automatically open the website in chrome?
has comment: http://stackoverflow.com/comment/83533111
has title: Can I open an IE instance in chrome automatically
linked to: http://stackoverflow.com/q/34222412
upvote count: 0
linked to: http://stackoverflow.com/q/18994519
answer count: 1
linked to: http://stackoverflow.com/q/34194674
tagged with: python
downvote count: 1
tagged with: selenium-webdriver
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48273680
has answer: http://stackoverflow.com/a/48273680
score: -1

http://stackoverflow.com/comment/83490712
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48254058
score: 0
has text: Can you reword your question or provide some clarification? I'm not quite sure what you're looking for

http://stackoverflow.com/comment/83514383
type: QuestionComment
comment on: http://stackoverflow.com/q/48265397
has text: However, @g.lahlou it would help if you properly format your query
score: 0
type: Comment

http://stackoverflow.com/q/48298619
tagged with: lda
has comment: http://stackoverflow.com/comment/88187460
has title: Predict new text using Python Latent Dirichlet Allocation (LDA) model
score: 1
tagged with: python
tagged with: topic-modeling
has comment: http://stackoverflow.com/comment/88143443
has comment: http://stackoverflow.com/comment/88193460
type: Question
has comment: http://stackoverflow.com/comment/83583260
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
tagged with: predict
has comment: http://stackoverflow.com/comment/83582741
has body: I use LDA package to model topics with a large set of text documents. A simplified(!) example (I removed all other cleaning steps, lemmatization, biograms etc.) of my code is below and I'm happy with the results so far. But now I struggle to write a code to predict a new text. I can't find any reference in LDA's documentation about save/loading/predict options. I can add a new text to my set and fit it again but it is an expensive way of doing it. I know I can do it with gensim. But somehow the results from the gensim model are less impressive so I'd stick to my initial LDA model. Will appreciate any suggestions! My code: import lda from sklearn.feature_extraction.text import CountVectorizer import numpy as np import nltk from nltk.corpus import stopwords stops = set(stopwords.words('english')) # nltk stopwords list documents = ["Liz Dawn: Coronation Street's Vera Duckworth dies at 77", 'Game of Thrones stars Kit Harington and Rose Leslie to wed', 'Tony Booth: Till Death Us Do Part actor dies at 85', 'The Child in Time: Mixed reaction to Benedict Cumberbatch drama', "Alanna Baker: The Cirque du Soleil star who 'ran off with the circus'", 'How long can The Apprentice keep going?', 'Strictly Come Dancing beats X Factor for Saturday viewers', "Joe Sugg: 8 things to know about one of YouTube's biggest stars", 'Sir Terry Wogan named greatest BBC radio presenter', "DJs celebrate 50 years of Radio 1 and 2'"] clean_docs = [] for doc in documents: # set all to lower case and tokenize tokens = nltk.tokenize.word_tokenize(doc.lower()) # remove stop words texts = [i for i in tokens if i not in stops] clean_docs.append(texts) # join back all tokens to create a list of docs docs_vect = [' '.join(txt) for txt in clean_docs] cvectorizer = CountVectorizer(max_features=10000, stop_words=stops) cvz = cvectorizer.fit_transform(docs_vect) n_topics = 3 n_iter = 2000 lda_model = lda.LDA(n_topics=n_topics, n_iter=n_iter) X_topics = lda_model.fit_transform(cvz) n_top_words = 3 topic_summari…
favorite count: 0

http://stackoverflow.com/comment/83568293
type: Comment
has text: this is useful but a couple of issues: (1) Performance very sensitive to n and # of unique values, e.g. I see your method 3x slower for n = 15,000 and 200 unique values. (2) Operations such as ~A are not as easy. I would probably have to store a full set of all coordinates [or cycle through them all] and exclude items in set(a_). But cf https://github.com/scipy/scipy/issues/1166.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48280229

http://stackoverflow.com/a/54701671
answers question: http://stackoverflow.com/q/48198770
type: Answer
upvote count: 8
score: 8
has comment: http://stackoverflow.com/comment/96190807
downvote count: 0
has body: I have tried adding the following line below. tf.app.flags.DEFINE_string('f', '', 'kernel') This solution is different from others in that it is simple and easy to try. You just need to add this into your code, and it doesn't change your system. Please let me know if this solution helps solve other people's problems. The reference for this solution is from a Chinese website: https://blog.csdn.net/qq_39956625/article/details/80500291

http://stackoverflow.com/q/48211037
tagged with: string
has comment: http://stackoverflow.com/comment/83403638
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48211597
has comment: http://stackoverflow.com/comment/83403358
score: 3
has comment: http://stackoverflow.com/comment/83403275
tagged with: algorithm
tagged with: python
has title: Not Understanding Essence of "Longest Substring with At Least K Repeating Characters"
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48211597
has body: This is a question regarding question #395 on LeetCode, entitled "Longest Substring with At Least K Repeating Characters." Someone posted a remarkably concise solution (in Python), and I am having trouble understanding the idea at the core of this approach. I can follow the code (reproduced below) mechanically, but I can't quite grasp the core idea here. For instance, I see that it counts the characters in the string and recursively splits the string at characters for which the count is less than the prescribed maximum number of characters (k). def longestSubstring(self, s, k): for c in set(s): if s.count(c) &lt; k: return max(self.longestSubstring(t, k) for t in s.split(c)) return len(s) The author says (emphasis added), "If every character appears at least k times, the whole string is ok. Otherwise split by a least frequent character (because it will always be too infrequent and thus can’t be part of any ok substring) and make the most out of the splits." Why is it that when a character is too infrequent, it necessarily cannot be part of any valid substring?
upvote count: 3
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83403223

http://stackoverflow.com/comment/83565515
score: 0
comment on: http://stackoverflow.com/a/48286118
has text: I like this answer because it maintains the `float` datatype for the values. Using `'{:.3f}'.format()` converts the numbers to strings, and consequently, they will be written to the file with quotes around the numbers.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48186194
score: 1
tagged with: pygame
has answer: http://stackoverflow.com/a/48186278
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83352435
has body: I am making the game space invaders in pygame and I managed to collide the enemybullet with the player. But i cannot collide the playerbullet with the enemy. I am doing exactly the same, I think. But it gives the error below. At this moment the enemy shoots with the button TAB, when I got this working I want to let the enemy to shoot the randomly. line 148, in hitenemy = pygame.sprite.spritecollide(enemy, bulletsPlayer, True) line 1513, in spritecollide spritecollide = sprite.rect.colliderect AttributeError: 'Group' object has no attribute 'rect' import pygame, sys from pygame.locals import * import random screenWidth = 800 screenHeight = 600 FPS = 60 pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((screenWidth,screenHeight)) pygame.display.set_caption("Space Invaders") clock = pygame.time.Clock() shipWidth = 78 #colors black=(0,0,0) blue=(0,0, 255) green=(0,128,0) red=(255,0,0) white=(255,255,255) yellow=(255,255,0) def app_quit(): pygame.quit() sys.exit("System exit.") class Player(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("spaceship7.png").convert() self.image.set_colorkey(white)#make white transparant self.rect = self.image.get_rect() self.rect.centerx = screenWidth / 2 self.rect.bottom = screenHeight - 10 self.speedx = 0 def update(self): self.speedx = 0 if event.type == KEYDOWN and event.key == K_LEFT: self.speedx = -2 elif event.type == KEYDOWN and event.key == K_RIGHT: self.speedx = 2 self.rect.x += self.speedx if self.rect.right &gt; screenWidth: self.rect.right = screenWidth if self.rect.left &lt; 0: self.rect.left = 0 def shootPlayer(self): bulletPlayer = BulletPlayer(self.rect.centerx, self.rect.top) allSprites.add(bulletPlayer) bulletsPlayer.add(bulletPlayer) class Enemy(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("enemy.png").convert() self.image.set_colorkey(white) self.rect = self.image.get_rect() se…
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48186278
has title: Space Invaders - Pygame - Collision
upvote count: 1
tagged with: python
tagged with: collision
type: AnsweredQuestion

http://stackoverflow.com/a/48330493
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48330389
answers question: http://stackoverflow.com/q/48330389
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/83647114
has comment: http://stackoverflow.com/comment/83651324
has comment: http://stackoverflow.com/comment/83647372
score: 3
upvote count: 3
has body: Here's one way based on np.maximum.reduceat - def grouby_maxY(a): b = a[a[:,0].argsort()] # if first col is already sorted, skip this grp_idx = np.flatnonzero(np.r_[True,(b[:-1,0] != b[1:,0])]) grp_maxY = np.maximum.reduceat(b[:,1], grp_idx) return np.c_[b[grp_idx,0], grp_maxY] Alternatively, if you want to bring np.unique, we can use it to find grp_idx with np.unique(b[:,0], return_index=1)[1]. Sample run - In [453]: np.random.seed(0) In [454]: arr = np.random.randint(0,5,(10,2)) In [455]: arr Out[455]: array([[4, 0], [3, 3], [3, 1], [3, 2], [4, 0], [0, 4], [2, 1], [0, 1], [1, 0], [1, 4]]) In [456]: grouby_maxY(arr) Out[456]: array([[0, 4], [1, 4], [2, 1], [3, 3], [4, 0]])

http://stackoverflow.com/a/48190109
has comment: http://stackoverflow.com/comment/83360309
upvote count: 0
has comment: http://stackoverflow.com/comment/83360301
downvote count: 1
answers question: http://stackoverflow.com/q/48189736
has comment: http://stackoverflow.com/comment/83360387
has comment: http://stackoverflow.com/comment/83360419
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/83360961
has comment: http://stackoverflow.com/comment/83361211
has body: See if this below code will work for you. This code will go through all the working folders, find only the files, rename and move those renamed files to the superseded folder import os import shutil working_folders = [f'C:\working_folders\{x}' for x in ['Property','Ownership','Sold','Lease']] for wf in working_folders: for f in os.listdir(wf): if os.path.isfile(os.path.join(wf, f)): os.rename(os.path.join(wf, f), os.path.join(wf, f'2018010_Property_Export.dfb_{f}')) shutil.move(os.path.join(wf, f'2018010_Property_Export.dfb_{f}'), os.path.join(wf, 'superseded', f'2018010_Property_Export.dfb_{f}'))

http://stackoverflow.com/comment/83490276
type: AnswerComment
comment on: http://stackoverflow.com/a/48253792
has text: @cᴏʟᴅsᴘᴇᴇᴅ Yes, it does. Any operation leading to a race condition produces side-effects by definition. CPython's GIL just makes it easy to forget about that.
type: Comment
score: 0

http://stackoverflow.com/q/48312508
tagged with: python
tagged with: dictionary
score: 2
has answer: http://stackoverflow.com/a/48312532
has title: How do you create nested dictionaries in Python?
favorite count: 0
has comment: http://stackoverflow.com/comment/83612203
type: Question
has body: I am having difficulty to create nested dictionary from the below mentioned list: student = ['Mike','Frank'] Type = ['Midterm1','Midterm2','Final'] Scores = [[10,20,30],[40,50,60]] I am looking for following dictionary: Scorecard = {'Mike':'Midterm':10,'Midterm2':20,'Final':30},'Frank': {'Midterm':40,'Midterm2':50,'Final':60}} I was able to create student and type combination but having difficultly to nest the type and values at the student level. The output would be scorecard['Mike']['Midterm'] = 10 ['Mike']['Midterm2'] = 20
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83613660
downvote count: 0
answer count: 1

http://stackoverflow.com/q/48318221
has answer: http://stackoverflow.com/a/48318348
possible better answer: http://stackoverflow.com/a/48318348
has body: I need to open an URL in Chromedriver using Python. If I use: driver.get('https://google.com'); everything is ok. But if I try opening my URL: driver.get('https://banana.deer:6969/app/banana#/virtualize/reddit/Rainbowdash?_g=(refreshingWhale:(display:HD,breakpause:!f,value:42),timespy:(from:now-420,mode:superfast,to:now))&amp;_a=(airfilters:!(),linked:!f,raspberry:(raspberry_string:(analyze_wildlife:!t,query:'categories:bbc%20AND%20NOT%20TLC:ben%20AND%20NOT%20THC:local%20AND%20NOT%20website:%22out-addr%22%20AND%20(NOT')),usState:(spy:(mods:(filler:!f,name:tabletennis))),bib:(aggrs:!((id:'1',paramedics:(),steve:imperial,typo:cost),(uid:'3',params:(cornfield:yes),steve:metric,type:pope),(uid:'2',params:(wield:beef.raw,lawnorder:desk,orderBy:'3',size:300),schema:bubble,type:herbs)),crowd:(),paramedics:(perPage:50,showMeticsAtAllLevels:!f,showAll:!t),title:Banana-Pie,type:rainforest))'); I get SyntaxError: invalid syntax Screenshot of the popup I think this is caused by me not knowing how to properly escape the URL. I've tried a few things, but I think I need your help.
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83622100
accepted answer: http://stackoverflow.com/a/48318307
type: Question
tagged with: escaping
has title: Chromedriver Python Long URL invalid Syntax
has answer: http://stackoverflow.com/a/48318307
tagged with: python

http://stackoverflow.com/comment/83574471
has text: Thanks @jezrael , the general solutions makes it more robust
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48294752
score: 0

http://stackoverflow.com/a/48325563
downvote count: 0
type: Answer
has body: Okay after looking a bit more. I believe it is impossible to do it directly with JSON There is a solution here about getting the full tweet. you can see it here The problem with the answer above is that full_text turn the object into a string. if you need the object in its initial state to use it later with json to get other info. do the following: use tweet_mode="extended" in user_timeline() and save it in tweet_list. eg: tweet_list = api.user_timeline("user", count=10, tweet_mode="extended") take one tweet only like this: tweet=tweet_list[0] if you want the full text tweet, do this: tweet.full_text if you need a json version of the object do this jtweet = tweet._json or just access the key like this tweet._json['id'] Hope that helps
accepted answer of: http://stackoverflow.com/q/48324771
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48324771
score: 5
upvote count: 5

http://stackoverflow.com/a/48206067
has body: data = [ ['1', '-160'], ['2', '-3000'], ['4', '-2'], ['5', '0.27'], ] print [[int(i), float(j)] for i, j in data] Result: [[1, -160.0], [2, -3000.0], [4, -2.0], [5, 0.27]]
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48205972

http://stackoverflow.com/comment/83628055
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48321066
has text: Do you want it in this format in order for it to be presentable? or do you want to do further processing/analysis on it after?
type: QuestionComment

http://stackoverflow.com/q/48232072
has comment: http://stackoverflow.com/comment/83446435
has comment: http://stackoverflow.com/comment/83446582
has answer: http://stackoverflow.com/a/48233641
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: javascript
has comment: http://stackoverflow.com/comment/83446536
tagged with: flask
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83446564
has title: Return list of list from Python to JS
has body: I am doing some calculation on my python code. As a result, I get list of list similar to what I have here data = [ [{"Count": 33874, "range": "-10"}, {"Count": 19961, "range": "-9"}], [{"Count": 46831, "range": "8"}, {"Count": 62326, "range": "9"}] ] I want to return this to my JS? I am currently using jsonify({"list":data}) but this does not work. My python code @app.route('/readRatingFiles', methods = ['POST']) def get_post_MlModel(): data = compute() return jsonify({"list":data}) My JS code $.post("/readRatingFiles", { }).done(function(data) { indexGot = data.index textDict[indexGot] = data.results; });
has comment: http://stackoverflow.com/comment/83446527
has comment: http://stackoverflow.com/comment/83446457
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83446461

http://stackoverflow.com/q/48328481
type: Question
has answer: http://stackoverflow.com/a/48329041
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has title: Matplotlib xticks values irregular size
tagged with: plot
type: AnsweredQuestion
score: 1
tagged with: matplotlib
has body: I am making a plot with matplotlib and I need irregular values for the xtick labels. I know there is parameter size. However, I would like to have values on my x-axis that are two times greater than the values of the labels on the y-axis. With size parameter I can only change the font size of the values, but the actual numeric values will still be in proportion 1:1. Is it possible to make xtick label values in proportion 2:1 with the ytick label values?
accepted answer: http://stackoverflow.com/a/48329041
favorite count: 0

http://stackoverflow.com/comment/83628538
comment on: http://stackoverflow.com/q/48319706
type: Comment
has text: The result to my code is that it's counting the number of rows with due_date 15 days before each specified date. I need it to sum the amounts instead of count the rows
type: QuestionComment
score: 0

http://stackoverflow.com/a/48280215
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48280153
has comment: http://stackoverflow.com/comment/83553922
score: 0
has comment: http://stackoverflow.com/comment/83553566
answers question: http://stackoverflow.com/q/48280153
has body: use os.chdir to move to the file path and try to write the files to zip. import datetime import os import zipfile path = '/Users/xxxx/reports/xxxx/monthly' month = datetime.datetime.now().strftime('%G'+'-'+'%B') zf = os.path.join(path, '{}.zip'.format(month)) z = zipfile.ZipFile(zf, 'w') os.chdir(path) #Change DIR for i in os.listdir(path): if i.endswith('.xml'): z.write(i) z.close() Without changing DIR: z = zipfile.ZipFile(zf, 'w') for i in os.listdir(path): if i.endswith('.xml'): z.write(os.path.join(path, i)) z.close()
type: Answer

http://stackoverflow.com/q/48266387
has title: Python Structured arrays instead of many single arrays
tagged with: python
tagged with: numpy
has body: I am new to structured arrays, but I think it is that what I need. I have a numpy array which contains for every entry a minus counter and one array that contains a plus counter. They are filled within a process. At the end of this process I want to divide all plus counter cell per cell through the minus counter and save it in an array with the result of this calculation in every entry. So I think there is a better way to create three different arrays with the same size. Lets assume my arrays are in this form: import numpy as np import itertools plusArr = np.ones((20 ,39, 90)) minusArr = np.ones((20 ,39, 90)) resultArr = np.zeros((20 ,39, 90)) Then the cells are filled with numbers. At the end I doing something like: for i in itertools.product(np.arange(0,20,1),np.arange(0,39,1),np.arange(0,90,1)): resultArr[i[0]][i[1]][i[2]] = plusArr[i[0]][i[1]][i[2]]/minusArr[i[0]][i[1]][i[2]] print(resultArr) This works but in the filling process it is very time consuming to look up the same entry location for both, minus and plus array. So I thought maybe to have a structured array with a triple instead of i int entries. In every triple the first entry is the plus counter, the second is the minus counter, and the last entry is 0 until the filling process is finished and it can be filled with the result of the division of plus and minus entry. As a small side question. If one of my counter entries is 0, then i want to fill the result cell of the entry of the array which has no zero entry at this location. Is there a smart numpy way to do that or just an if condition?
type: UnansweredQuestion
answer count: 1
tagged with: arrays
has comment: http://stackoverflow.com/comment/83521359
tagged with: scipy
type: Question
has answer: http://stackoverflow.com/a/48268387
score: 0

http://stackoverflow.com/comment/83523174
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48269756
type: QuestionComment
has text: It seems like a known [issue](https://github.com/sammchardy/python-binance/issues)

http://stackoverflow.com/comment/83446702
score: 0
type: AnswerComment
has text: Worked perfectly. Thank you very much!
type: Comment
comment on: http://stackoverflow.com/a/48231697

http://stackoverflow.com/q/48270469
tagged with: django
type: Question
has body: I'm new to DJango and I have some doubts about forms. Here is the code, I would appreciate your help :D This is the error that appears to me: enter image description here directories and files: blog |--_pycachce_ |--migrations |--static |--templates |--blog |--base.html |--forms.py |--post_bio.html |--post_detail.html |--post_edit.html |--post_list.html |--models.py |--tests.py |--urls.py |--views.py |--_init_.py |--admin-py templates/post_edit.html code: {% extends 'blog/base.html' %} {% block content %} New post {% csrf_token %} {{ form.as_p }} Save {% endblock %} urls.py code: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list), url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'), url(r'^post/new/$', views.post_new, name='post_new'), ] views.py code: from django.shortcuts import render from django.utils import timezone from django.shortcuts import render, get_object_or_404 from .models import Post from .forms import PostForm from .models import Post from .forms import PostForm def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts' : posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) def post_new(request): form = PostForm() return render(request, 'blog/post_edit.html', {'form': form})
type: AnsweredQuestion
score: 0
has title: ImportError at post/new al crear un formulario con Django
tagged with: python
tagged with: django-forms
has answer: http://stackoverflow.com/a/48270803
accepted answer: http://stackoverflow.com/a/48270803
answer count: 1

http://stackoverflow.com/comment/83585056
score: 1
type: QuestionComment
has text: `selenium` and `requests` don't share resources, but perhaps you could get cookies from `selenium` and pass it to `requests`
comment on: http://stackoverflow.com/q/48300303
type: Comment

http://stackoverflow.com/comment/83639515
type: QuestionComment
has text: Why not just configure your proxy?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48327054

http://stackoverflow.com/a/48197832
answers question: http://stackoverflow.com/q/48197383
type: Answer
has body: There's a few things you need to understand here: on_message() is an event that simply passes you the entire Message object. Secondly, it's message.content for the string of the message. Don't use a function call (). Third, you shouldn't be creating a new async def inside of on_message. If you really just want to respond to a message that says "buy me," here is an example of responding to someone who starts their message with "buy me." Since I'm not 100% sure what exactly your end goal is, I'm simply going to give you an example you can build off of: @client.event async def on_message(msg): if msg.content.startswith("buy me"): responses = ['meh', 'no thanks brudda'] choice = random.choice(responses) await client.send_message(msg.channel, choice) On a side note: This seems like you're using the "async" version of discord.py. You should think about moving to the "rewrite" library which is going to change a lot of these API calls. Also, you should be using commands.ext, but considering you don't have a good grasp on Python yet, using on_message() should be good enough. There's a lot more to say about your code in its current state, but this should be enough to push you in the right direction.
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/48220939
type: Question
has comment: http://stackoverflow.com/comment/98436190
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48222669
tagged with: python
has body: I have validate the start_date and end_date. I need to set null end date field while raising the error. Here is my code: @api.onchange('end_date') def onchange_end_date(self, end_date, start_date): if (start_date and end_date) and (start_date &lt; end_date): raise exceptions.except_orm(_('Warning!'),_('The start date must be less than to the end date.'))
has answer: http://stackoverflow.com/a/48232258
score: 0
answer count: 3
tagged with: odoo-10
has answer: http://stackoverflow.com/a/49550944
has title: Set null the date field while raising exception in odoo

http://stackoverflow.com/q/48243018
score: 7
tagged with: string
tagged with: string-concatenation
downvote count: 1
favorite count: 0
type: AnsweredQuestion
upvote count: 8
has answer: http://stackoverflow.com/a/48243085
has answer: http://stackoverflow.com/a/48243065
has comment: http://stackoverflow.com/comment/83468533
has answer: http://stackoverflow.com/a/48243089
has answer: http://stackoverflow.com/a/78188500
has comment: http://stackoverflow.com/comment/83468769
has comment: http://stackoverflow.com/comment/83468832
tagged with: python
accepted answer: http://stackoverflow.com/a/48243085
type: Question
possible better answer: http://stackoverflow.com/a/48243065
has answer: http://stackoverflow.com/a/48592379
has body: I would like to know how to concatenate a string to the end of all elements in a list. For example: List1 = [ 1 , 2 , 3 ] string = "a" output = ['1a' , '2a' , '3a']
answer count: 8
tagged with: list
tagged with: concatenation
has answer: http://stackoverflow.com/a/48243078
has title: Concatenate string to the end of all elements of a list in python
has answer: http://stackoverflow.com/a/48243064
has answer: http://stackoverflow.com/a/48243236

http://stackoverflow.com/q/48261783
answer count: 1
has comment: http://stackoverflow.com/comment/83506293
has comment: http://stackoverflow.com/comment/83506611
has answer: http://stackoverflow.com/a/48265470
has body: I'm trying to iterate over a df to calculate values for a new column, but it's taking too long. Here is the code (it's been simplified for brevity): def calculate(row): values = [] weights = [] continued = False df_a = df[((df.winner_id == row['winner_id']) | (df.loser_id == row['winner_id']))].loc[row['index'] + 1:] if len(df_a) &lt; 30: df.drop(row['index'], inplace = True) continued = True ##if we dropped the row, we don't want to calculate it's value if continued == False: for match in zip(df_a['winner_id'],df_a['tourney_date'],df_a['winner_rank'],df_a['loser_rank'], df_a['winner_serve_pts_pct']): weight = time_discount(yrs_between(match[1],row['tourney_date'])) ##calculate individual values and weights values.append(match[4] * weight * opp_weight(match[3])) weights.append(weight) ##return calculated value return sum(values)/sum(weights) df['new'] = df.apply(calculate, axis = 1) My dataframe is not too large (60,000 by 35), but it's taking about 40 minutes for my code to run. I originally used iterrows(), but people suggested that I use zip() and apply - but it's still taking very long. Any help will be greatly appreciated. Thank you
tagged with: iteration
type: Question
type: UnansweredQuestion
has title: Iterating over Pandas dataframe using zip and df.apply()
tagged with: dataframe
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/83507814
tagged with: pandas
linked to: http://stackoverflow.com/q/2232362

http://stackoverflow.com/comment/83546432
score: 0
type: AnswerComment
has text: Ah, in that case you are going to need: driver.find_elements_by_xpath("//input[contains(@class, 'button')]")
type: Comment
comment on: http://stackoverflow.com/a/48280649

http://stackoverflow.com/comment/83587047
comment on: http://stackoverflow.com/q/48301044
score: 0
has text: No need for it at all in this particular case ;-)
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83436272
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48227090
score: 0
has text: @yudongshen why are you offering him a "ultra fast" decoder if his problem is with memory? ujson may be more memory efficient, Im not sure about that, but then thats is what you should say about ujson and not it being ultra fast. Your comment looks like just merchandising of a certain package.

http://stackoverflow.com/comment/83369889
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48194545
has text: @COLDSPEED, if I do that I get this error: `*** KeyError: 'Crop'`

http://stackoverflow.com/comment/83581747
has text: This gives only latest commits in all the branches of a repository. What I want if i pass say December 2017 how will i get all the activity list on that repo
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48298319

http://stackoverflow.com/comment/83410948
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48214327
score: 0
has text: @felipsmartins bah! I guess i had to move onto Python 3 eventually. Thanks!

http://stackoverflow.com/q/48309478
has comment: http://stackoverflow.com/comment/83628985
tagged with: django
upvote count: 1
tagged with: django-forms
has comment: http://stackoverflow.com/comment/83605225
has comment: http://stackoverflow.com/comment/83604625
has answer: http://stackoverflow.com/a/48310007
favorite count: 0
type: Question
has body: I have a django template in which I'm dynamically rendering multiple fields (using ajax) Below is a Django form (which has been rendered in a template) whose fields have same names. I want to use the cleaned_data method to clean form data in views.py before storing them in the database. index.html Submit {% csrf_token %} Add item forms.py class ItemForm(forms.Form): this_field = forms.CharField() urls.py urlpatterns = [ url(r'^newPickupOrder/$', views.pickup_order_view, name='new_pickup_order'), ] views.py def add_item(request): if request.method == 'POST': itemForm = ItemForm() return HttpResponse(itemForm.as_p()) def pickup_order_view(request): if request.method == 'POST': form = ItemForm(request.POST) same_name_fields = request.POST.getlist('this_field') # WANT TO CLEAN DATA IN same_name_fields if form.is_valid(): print(form.cleaned_data) # ONLY PRINTS THE LAST FIELD's DATA return HttpResponseRedirect('/viewPickupRequests') The problem I'm facing is that if I use form.cleaned_data['this_field'], only the last field's data is fetched i.e. in this example, the field with value anotherTestValue is fetched and cleaned. If I fetch the data using request.POST.getlist('this_field'), all the fields' data is fetched and stored as a list, but, I don't know how to clean it using cleaned_data method. Is there a way to apply the cleaned_data method to the list of field data?
has title: Clean Django form fields with same name
accepted answer: http://stackoverflow.com/a/48310007
possible better answer: http://stackoverflow.com/a/48322274
tagged with: python
tagged with: forms
has answer: http://stackoverflow.com/a/48322274
type: AnsweredQuestion
tagged with: django-views
answer count: 2
score: 1
downvote count: 0

http://stackoverflow.com/a/48466289
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48299353
upvote count: 1
has body: The error is misleading because it says __init__ takes 1 positional argument (which is the self from the object of the class Chromosome). Secondly, what you are getting from the operation on df in tester is actually a DataFrame indexed as df with one column of Gene values. To solve this you would have to change the code along these lines: class Chromosome(object): def __init__(self, df): self.port = [Gene() for id in range(20)] self.xxx = list(df)
type: Answer

http://stackoverflow.com/q/48266788
upvote count: 1
tagged with: python
has body: I'd like to calculate the percentile of each value in a list (or numpy array), weighted by weights in another list. For example, given some f I'd like: x = [1, 2, 3, 4] weights = [2, 2, 3, 3] f(x, weights) to yield [20, 40, 70, 100]. I can calculate the unweighted percentile for a single item using from scipy import stats stats.percentileofscore(x, 3) # 75.0 Per Map each list value to its corresponding percentile I can also calculate this for each using [stats.percentileofscore(x, a, 'rank') for a in x] # [25.0, 50.0, 75.0, 100.0] And per Weighted version of scipy percentileofscore I can calculate a single item's weighted percentile using: def weighted_percentile_of_score(x, weights, score, kind='weak'): npx = np.array(x) npw = np.array(weights) if kind == 'rank': # Equivalent to 'weak' since we have weights. kind = 'weak' if kind in ['strict', 'mean']: indx = npx &lt; score strict = 100 * sum(npw[indx]) / sum(weights) if kind == 'strict': return strict if kind in ['weak', 'mean']: indx = npx &lt;= score weak = 100 * sum(npw[indx]) / sum(weights) if kind == 'weak': return weak if kind == 'mean': return (strict + weak) / 2 Called as: weighted_percentile_of_score(x, weights, 3)) # 70.0 as desired. How do I do this (efficiently) for each item in the list?
linked to: http://stackoverflow.com/q/12414043
has answer: http://stackoverflow.com/a/48267063
favorite count: 0
accepted answer: http://stackoverflow.com/a/48267063
possible better answer: http://stackoverflow.com/a/48266789
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/21844024
tagged with: scipy
has answer: http://stackoverflow.com/a/48266789
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/48252282
answer count: 2
downvote count: 0
has title: Map each value of a list to its weighted percentile

http://stackoverflow.com/a/48217414
type: AcceptedAnswer
type: Answer
has body: As always, the docs are useful here. Simply specify the row you want to use as the header row, and the start of your data: pricing = pd.read_csv(io.StringIO(pricing_r.decode('utf-8')), header=5)
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48217392
downvote count: 0
answers question: http://stackoverflow.com/q/48217392

http://stackoverflow.com/comment/83462224
comment on: http://stackoverflow.com/q/48239714
type: Comment
type: QuestionComment
score: 0
has text: [A tutorial](https://www.w3schools.in/python-tutorial/loops/) might help you understand the logic of Python loops. You can visualise the execution of your Python program [on Pythontutor](http://pythontutor.com/visualize.html#mode=edit). This allows you to observe intermediate variables and execute your program step by step.

http://stackoverflow.com/a/48209753
answers question: http://stackoverflow.com/q/48209673
downvote count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/83400521
type: Answer
has body: Exploit the Fact that Python set may not contain duplicates. The has_duplicate() Function takes care of determining if a list contains duplicates. def has_duplicates(listObj): return len(listObj) != len(set(listObj)) print(has_duplicates([1, 2, 1, 1, 4, 7])) ## PRINTS: True print(has_duplicates([9, 2, 5, 4, 7])) ## PRINTS: False
score: 8

http://stackoverflow.com/a/48389099
answers question: http://stackoverflow.com/q/48217449
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/83958951
score: 22
upvote count: 23
accepted answer of: http://stackoverflow.com/q/48217449
has comment: http://stackoverflow.com/comment/83960050
has comment: http://stackoverflow.com/comment/83962351
has comment: http://stackoverflow.com/comment/83959103
type: Answer
has body: The worker process within multiprocessing.Pool is an instance of Process, it keeps an internal counter to identify itself, you could use this counter along with OS process id: import os from multiprocessing import current_process, Pool def x(a): p = current_process() print('process counter:', p._identity[0], 'pid:', os.getpid()) if __name__ == '__main__': with Pool(2) as p: r = p.map(x, range(4)) p.join() yields: process counter: 1 pid: 29443 process counter: 2 pid: 29444 process counter: 2 pid: 29444 process counter: 1 pid: 29443

http://stackoverflow.com/comment/83568691
type: QuestionComment
has text: @Tai sorry , not title , so i fixed it sorry
comment on: http://stackoverflow.com/q/48286364
score: 0
type: Comment

http://stackoverflow.com/a/54230990
has body: You can also do this using the following: import site # if outside of a sublime text plugin class all_views = sublime.active_window().views() # or if inside use the 'view' variable, skip to line 9 and change # all_views[0].settings to view.settings if len(all_views) &gt; 0: external_python_path = all_views[0].settings().get("external_python_path") sp = site.getsitepackages(external_python_path) sp = [x for x in sp if "site-packages" in x.lower()] sys.path.append(sp) then in your Preferences.sublime-settings file, you add a key:value like { "somekey": "somevalue", ..., "external_python_path": "path_to_python folder excluding the python.exe" }
has comment: http://stackoverflow.com/comment/95287045
answers question: http://stackoverflow.com/q/48276861
score: 1
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83386809
has text: I keep getting 'dict' `object has no attribute 'iteritems'` i have been trying it from examples I seen on other pages.
type: Comment
comment on: http://stackoverflow.com/a/48202092
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83430481
type: QuestionComment
comment on: http://stackoverflow.com/q/48223504
has text: Should it also remove numbers like `1976` or leave them in the string?
score: 0
type: Comment

http://stackoverflow.com/comment/83415958
comment on: http://stackoverflow.com/q/48216856
has text: Maybe the question should be instead why does `a = foo(BAR)` work! But yeah, the scoping here is a little different than other languages.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83522864
comment on: http://stackoverflow.com/q/48269295
type: Comment
score: 0
has text: I have a comment section which fills userid when user is submittin comment post. So it's not foreignkey it is an integerfield. How do we do exatly? i didn't get it. Sorry im too new on django. I've added comment model
type: QuestionComment

http://stackoverflow.com/a/48302649
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83644264
score: 1
type: Answer
has body: The code you created tries to follow the same follows the same philosophy that the example you found. But you're destroying the sequence too soon (and you ended up using an extra RepeatVector because of that). To avoid this, you can use return_sequences=True in all encoder layers, except for the last. This keeps the sequence as a sequence allowing a greater interpretation power because you're not collapsing your data too soon. #add return_sequences=True to all layers except for the last encoded = LSTM(4, return_sequences=True)(inputs) #do not use RepeatVector, you've got your sequences preserved with their length #the last encoder layer is the only one that collapses the sequence encoded = LSTM(2)(encoded) #this RepeatVector is the only that is needed, to restore the sequence length decoded = RepeatVector(timesteps)(encoded) #the rest is the same decoded = LSTM(4,return_sequences = True)(encoded) decoded = LSTM(input_dim,return_sequences = True)(decoded)
has comment: http://stackoverflow.com/comment/83633276
answers question: http://stackoverflow.com/q/48299833
has comment: http://stackoverflow.com/comment/83642975
has comment: http://stackoverflow.com/comment/83635081

http://stackoverflow.com/comment/83548761
has text: Why do you have the lines `import tkinter.ttk as ttk` and `from tkinter import *` ?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48282550

http://stackoverflow.com/q/48287670
tagged with: sql-server
score: 1
has body: I have moved the codebase for a large existing Python 2 project from pymssql to pyodbc. The move was easy, everything builds, and runs fine, except that pyodbc returns SQL Server columns of type time as datetime.time, where pymssql (as well as the PostgreSQL native drivers) return strings. Meaning, I receive a datetime.time(11, 54, 13, 161000) object instead of 11:54:13.161000. Is there any way I can change this behavior globally without resorting to a stored procedure of some sort? Handling a returned object instead of a returned string will involve several days worth of refactoring and testing.
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48291723
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48291723
has title: How to change datetime.time return type to string under pyodbc?
downvote count: 0
upvote count: 1
tagged with: pyodbc
type: AnsweredQuestion

http://stackoverflow.com/comment/83416987
type: QuestionComment
has text: @PatrickHaugh that's pretty neat but for this case such magic functions are restricted.
score: 0
comment on: http://stackoverflow.com/q/48217471
type: Comment

http://stackoverflow.com/q/48187966
has comment: http://stackoverflow.com/comment/83355639
tagged with: google-app-engine
tagged with: python
accepted answer: http://stackoverflow.com/a/48188062
has answer: http://stackoverflow.com/a/48188062
tagged with: google-cloud-python
type: AnsweredQuestion
tagged with: python-2.7
linked to: http://stackoverflow.com/q/67631
score: 1
has title: How to import modules when modules have same folder names,
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83357466
upvote count: 1
linked to: http://stackoverflow.com/q/41399303
has body: I'm facing an issue where google.appengine and google.cloud python modules are under different directories named google Their following paths are as below: 1st Path: C:\Users\MohammedT\Desktop\dsapp\sitepackages\dev\google_appengine api_server.py appcfg.py backends_conversion.py BUGS bulkloader.py bulkload_client.py demos dev_appserver.py download_appstats.py endpointscfg.py gen_protorpc.py google --&gt; Directory 1 where appengine module resides lib LICENSE new_project_template php php_cli.py README RELEASE_NOTES remote_api_shell.py run_tests.py 2nd Path: C:\Users\MohammedT\Desktop\datastore\dsenv\Lib\site-packages enum enum34-1.1.6.dist-info future future-0.16.0.dist-info futures-3.2.0.dist-info gapic_google_cloud_datastore_v1-0.15.3-py2.7-nspkg.pth gapic_google_cloud_datastore_v1-0.15.3.dist-info gapic_google_cloud_error_reporting_v1beta1-0.15.3-py2.7-nspkg.pth gapic_google_cloud_error_reporting_v1beta1-0.15.3.dist-info gapic_google_cloud_logging_v2-0.91.3-py2.7-nspkg.pth gapic_google_cloud_logging_v2-0.91.3.dist-info google ------------&gt; Directory 2 where other other modules resides googleapiclient googleapis_common_protos-1.5.3-py2.7-nspkg.pth googleapis_common_protos-1.5.3.dist-info google_api_core-0.1.3-py3.6-nspkg.pth google_api_core-0.1.3.dist-info google_api_python_client-1.6.4.dist-info Can I achieve this without moving them to a common directory? I have set the python path to point at both of these directories. I'm currently able to import from Directory 2 but cannot import from Directory 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/83442867
comment on: http://stackoverflow.com/a/48229937
score: 0
has text: But those aren't the names of your fields - those are `clientAccNum`, `clientSubacc` etc.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48204128
score: 0
type: Answer
has body: The problem here is z()['data']['children'] in the method reddit(subreddit) z is a string and you are using it as a callable object. From what I understand what you need to do is, z = todayilearned.json() If you are able to get the data from the url and the if the json has data and children attribute and also x should be initialized, this should work
answers question: http://stackoverflow.com/q/48203819

http://stackoverflow.com/comment/83422089
comment on: http://stackoverflow.com/q/48218263
score: 1
type: Comment
type: QuestionComment
has text: Thank you @sid8491. That answer gave much more clarity. I had been following the steps right but was using anaconda to do the pip install of twilio. I instead used powershell and that worked.

http://stackoverflow.com/comment/83588425
type: Comment
score: 0
type: AnswerComment
has text: @RoadRunner: `most_common()` uses a heap queue to produce the order when N < K (length of the counter), which is O(KlogN) solution. Sorting is O(NlogN). So yes, sorting would be *slower* here, because you are doing way more work than is needed (you don't need to order all K elements, only the top N).
comment on: http://stackoverflow.com/a/48301632

http://stackoverflow.com/q/48197234
has answer: http://stackoverflow.com/a/60334984
has answer: http://stackoverflow.com/a/48197299
tagged with: dataframe
tagged with: python
has body: I have: df = pd.DataFrame({'col1': ['asdf', 'xy', 'q'], 'col2': [1, 2, 3]}) col1 col2 0 asdf 1 1 xy 2 2 q 3 I'd like to take the "combinatoric product" of each letter from the strings in col1, with each elementwise int in col2. I.e.: col1 col2 0 a 1 1 s 1 2 d 1 3 f 1 4 x 2 5 y 2 6 q 3 Current method: from itertools import product pieces = [] for _, s in df.iterrows(): letters = list(s.col1) prods = list(product(letters, [s.col2])) pieces.append(pd.DataFrame(prods)) pd.concat(pieces) Any more efficient workarounds?
has answer: http://stackoverflow.com/a/48201433
has comment: http://stackoverflow.com/comment/83375731
upvote count: 15
score: 15
linked to: http://stackoverflow.com/q/53218931
has answer: http://stackoverflow.com/a/48197321
has comment: http://stackoverflow.com/comment/94307226
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83376013
has answer: http://stackoverflow.com/a/48197395
has answer: http://stackoverflow.com/a/48197300
downvote count: 0
has answer: http://stackoverflow.com/a/48197296
has title: Unnest (explode) a Pandas Series
favorite count: 0
has comment: http://stackoverflow.com/comment/83375760
accepted answer: http://stackoverflow.com/a/48197395
type: Question
possible better answer: http://stackoverflow.com/a/48197299
answer count: 8
has answer: http://stackoverflow.com/a/56979753

http://stackoverflow.com/q/48215884
duplicate of: http://stackoverflow.com/q/12595051
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48216021
tagged with: python
tagged with: regex
has title: Using regex in Python if statement
accepted answer: http://stackoverflow.com/a/48215949
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/12595051
answer count: 2
has answer: http://stackoverflow.com/a/48215949
has answer: http://stackoverflow.com/a/48216021
upvote count: 2
linked to: http://stackoverflow.com/q/45740182
downvote count: 2
has body: I am trying to figure out how to incorporate regex into a python if statement. I have a pandas dataframe where I am iterating over the rows and want to perform an action every time the row has a specific combination of text. The regex should match any 7 character string that begins with a capital letter followed by 6 numbers (ie. R142389) for index, row in df1.iterrows(): if row[4] == REGEX HERE: Perform Action Am I going about this the right way? Any help would be greatly appreciated!

http://stackoverflow.com/q/48309776
tagged with: modular
has body: Edited Question: I guess I worded my previous question improperly, I actually want to get away from "unit tests" and create automated, modular system tests that build off of each other to test the application as whole. Many parts are dependent upon the previous pages and subsequent pages cannot be reached without first performing the necessary steps on the previous pages. For example (and I am sorry I cannot give the actual code), I want to sign into an app, then insert some data, then show that the data was sent successfully. It is more involved than that, however, I would like to make the web driver portion, 'Module 1.x'. Then the sign in portion, 'Module 2.x'. The data portion, 'Module 3.x'. Finally, success portion, 'Module 4.x'. I was hoping to achieve this so that I could eventually say, "ok, for this test, I need it to be a bit more complicated so let's do, IE (ie. Module 1.4), sign in (ie. Module 2.1), add a name (ie Module 3.1), add an address (ie. Module 3.2), add a phone number (ie Module 3.3), then check for success (ie Module 4.1). So, I need all of these strung together. (This is extremely simplified and just an example of what I need to occur. Even in the case of the unit tests, I am unable to simply skip to a page to check that the elements are present without completing the required prerequisite information.) The issue that I am running into with the lengthy tests that I have created is that each one requires multiple edits when something is changed and then multiplied by the number of drivers, in this case Chrome, IE, Edge and Firefox (a factor of 4). Maybe my approach is totally wrong but this is new ground for me, so any advice is much appreciated. Thank you again for your help! Previous Question: I have found many answers for creating unit tests, however, I am unable to find any advice on how to make said tests sequential. I really want to make modular tests that can be reused when the same action is being performed repeatedly. I have tried vari…
has title: Is it possible to make sequential tests in Python-Selenium tests?
linked to: http://stackoverflow.com/q/47861813
tagged with: python
has comment: http://stackoverflow.com/comment/83605356
type: Question
has answer: http://stackoverflow.com/a/48311473
score: 0
tagged with: automated-tests
type: UnansweredQuestion
answer count: 1
tagged with: selenium

http://stackoverflow.com/q/48208370
tagged with: module
linked to: http://stackoverflow.com/q/3365740
accepted answer: http://stackoverflow.com/a/48208997
type: AnsweredQuestion
has title: Python: How do I import modules without python-filename as submodule?
score: 7
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48208997
type: Question
tagged with: python-3.x
tagged with: python-import
has body: Description Assume, I have a package with the following structure: package-folder |_ mypackage |_ __init__.py |_ module1.py setup.py Where __init__.py is empty and module1.py: def do_stuff(): print('Did stuff.') setup.py is containing the usual context for making a package out of this, which can be installed with pip install -e pkgpath on the local system. In a script.py, I would have to do: import mypackage as abbr abbr.module1.do_stuff() # output: Did stuff. My desired call would be: abbr.do_stuff() # output: Did stuff. Questions How can I 'organize' my package so that I can call functions, out of module1.py directly from abbr.function()? What code changes are required? Is this organization useful if the package grows? So that directories would act as the structure-element and python-files are just capsules to organize my functions within? What is the best way to organize functions in modules and sub-modules? Further thoughts Is there a good reason not to have just one function in each python-file which can be used from the module? (and has the same name as the file) I assume, I will have to modify my __init__.py-files, but I couldn't figure out how. Clarification on questions 2 package-folder |_ mypackage |_ __init__.py |_ module1.py #with function do_stuff1() |_ subpackage |_module2.py #with function do_stuff2() setup.py Calls should be: abbr.do_stuff1() abbr.subpackage.do_stuff2() And not: abbr.module1.do_stuff1() abbr.subpackage.module2.do_stuff2()
tagged with: python
upvote count: 7

http://stackoverflow.com/a/48210600
has comment: http://stackoverflow.com/comment/83403039
score: 2
upvote count: 2
has body: Setup It's always best to provide a definitive way to reconstruct your data. With this code, others can play with it to figure out stuff. a = pd.Series( [10, 9, 15, 25, 30], pd.date_range('2017-12-31', periods=5) ) Solution Use Pandas' pd.Series.ewm method with an alpha parameter set to .9 a.ewm(alpha=.9).mean() 2017-12-31 10.000000 2018-01-01 9.090909 2018-01-02 14.414414 2018-01-03 23.942394 2018-01-04 29.394294 Freq: D, dtype: float64 To more closely match what your code does, use the adjust=False option with alpha=.1 a.ewm(alpha=.1, adjust=False).mean() 2017-12-31 10.0000 2018-01-01 9.9000 2018-01-02 10.4100 2018-01-03 11.8690 2018-01-04 13.6821 Freq: D, dtype: float64
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48209497
answers question: http://stackoverflow.com/q/48209497
type: Answer

http://stackoverflow.com/comment/83488694
has text: subprocess.Popen waits for `second.py` to complete, this isnt what im looking for :/
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48252892
type: Comment

http://stackoverflow.com/comment/83378012
type: Comment
type: QuestionComment
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [on topic](http://stackoverflow.com/help/on-topic) and [how to ask](http://stackoverflow.com/help/how-to-ask) apply here. StackOverflow is not a design, coding, research, or tutorial service. http://idownvotedbecau.se/noresearch/
score: 0
comment on: http://stackoverflow.com/q/48198381

http://stackoverflow.com/comment/83394542
type: Comment
has text: Thanks,now on I will
score: 0
comment on: http://stackoverflow.com/q/48206013
type: QuestionComment

http://stackoverflow.com/a/48214458
upvote count: 1
answers question: http://stackoverflow.com/q/48214158
score: 1
type: Answer
has body: Using a shorter, though not as effecient, list comprehension: d = {} d['inds'] = [0, 3, 7, 3, 3, 5, 1] d['vals'] = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0] new_d = [0 if i not in d['inds'] else dict(zip(d['inds'], d['vals']))[i] for i in range(max(d["inds"])+1)] Output: [1.0, 7.0, 0, 5.0, 0, 6.0, 0, 3.0]
downvote count: 0

http://stackoverflow.com/q/48243820
tagged with: zenhub
tagged with: python
linked to: http://stackoverflow.com/q/47860744
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/48269380
accepted answer: http://stackoverflow.com/a/48269380
score: 1
answer count: 1
downvote count: 0
tagged with: github
has body: This is a follow up question to How to set an issue pipeline with zenhub. I'm attempting to convert an issue to an epic in a Python script. I can convert the issue to an Epic, but I get an error when I attempt to add issues when creating the epic. This works: zenhub_headers = {"X-Authentication-Token": "%s" % token} target_zh_issues_url = '%s/p1/repositories/%d/issues' % (zh_api_endpoint, target_repo_id) params = {} response = requests.post(target_zh_issues_url + '/%s/convert_to_epic' % issue, headers=zenhub_headers, data=params) The code also works when I set params = {"issues":[]} But when I attempt to add an issue with params = {"issues": [{"repo_id": 280565, "issue_number": 17}]} I get a 400 error, b'{"message":"Invalid Field for issues: [object Object],[object Object]"}' I then tried using the /update_issues API to add issues to the epics I'd created. target_zh_epics_url = '%s/p1/repositories/%d/epics' % (zh_api_endpoint, target_repo_id) params = {"add_issues": [{"repo_id": 280565, "issue_number": 17}]} response = requests.post(target_zh_epics_url + '/%s/update_issues' % issue, headers=zenhub_headers, data=params) This resulted in a 400 error, b'{"message":"Invalid Field for addIssues: repo_id,issue_number"}'. Those fields are as described in the API doc.
favorite count: 0
has title: Creating an Epic from a Github Issue with Zenhub API
type: Question

http://stackoverflow.com/comment/83519902
type: QuestionComment
comment on: http://stackoverflow.com/q/48268259
score: 0
has text: No,I didn't redefine the Conv2D definition
type: Comment

http://stackoverflow.com/comment/83379233
comment on: http://stackoverflow.com/a/48198605
score: 0
has text: If you meant to have something like `Q99MR6-3 NA` just add `+ ' NA'` after `else genename_id` and before the parenthesis like this: `else genename_id + ' NA'))`.
type: Comment
type: AnswerComment

knn
tags question: http://stackoverflow.com/q/48270363
tags question: http://stackoverflow.com/q/48312205
tags question: http://stackoverflow.com/q/48190843
tag name: knn
type: Tag

http://stackoverflow.com/comment/83598568
comment on: http://stackoverflow.com/q/48305898
has text: @Ev.Kounis why do you think it’s impossible to parse? Assuming the input is a string then it can be parsed although not elegantly I guess
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48306528
tagged with: network-programming
has answer: http://stackoverflow.com/a/48307480
tagged with: sockets
has title: Python - socket.error: Cannot assign requested address
linked to: http://stackoverflow.com/q/14471885
tagged with: python
upvote count: 6
linked to: http://stackoverflow.com/q/30992881
has body: I have written a chat server but I cannot bind my socket to an IP address: import sys import os import socket HOST = "194.118.168.131" SOCKET_LIST = [] RECV_BUFFER = 4096 PORT = 9009 def chat_server(): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind((HOST, PORT)) server_socket.listen(10) ... I get the following error: Traceback (most recent call last): File "server.py", line 83, in <module> sys.exit(chat_server()) File "server.py", line 20, in chat_server server_socket.bind((HOST, PORT)) File "/usr/lib/python2.7/socket.py", line 224, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 99] Cannot assign requested address What's wrong with my code? I didn't find an answer on: 'Connection aborted.', error(99, 'Cannot assign requested address') error in Python, socket.error[Errno 99] Cannot assign requested address, bind: cannot assign requested address Cannot assign requested address - possible causes?
type: AnsweredQuestion
answer count: 1
score: 6
downvote count: 0
linked to: http://stackoverflow.com/q/43460287
favorite count: 0
accepted answer: http://stackoverflow.com/a/48307480
type: Question
linked to: http://stackoverflow.com/q/7640619

http://stackoverflow.com/q/48249291
score: 2
possible better answer: http://stackoverflow.com/a/48250314
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has body: Performing sentence tokenizer using spaCy NLP and writing it to Pandas Dataframe. # -*- coding: utf-8 -*- #!/usr/bin/env python from __future__ import unicode_literals # Extraction import spacy,en_core_web_sm import pandas as pd # Read the text file nlp = en_core_web_sm.load() doc = nlp(unicode(open('o.txt').read().decode('utf8')) ) for idno, sentence in enumerate(doc.sents): print 'Sentence {}:'.format(idno + 1), sentence Sentences = list(doc.sents) df = pd.DataFrame(Sentences) print df output: Sentence 1: This is a sample sentence. Sentence 2: This is a second sample sentence. Sentence 3: This is a third sample sentence. 0 1 2 3 4 5 6 0 This is a sample sentence . None 1 This is a second sample sentence . 2 This is a third sample sentence . Expected output in Pandas 0 0 This is a sample sentence. 1 This is a second sample sentence. 2 This is a third sample sentence. How to achieve the expected output?
accepted answer: http://stackoverflow.com/a/61354658
favorite count: 0
type: Question
upvote count: 2
answer count: 2
tagged with: spacy
has title: Sentence tokenizer - spaCy to pandas
tagged with: python
has answer: http://stackoverflow.com/a/61354658
has answer: http://stackoverflow.com/a/48250314

http://stackoverflow.com/comment/83454025
type: QuestionComment
has text: Are you asking how to collect multiple branches in the result, if `GlossList` appears repeatedly?
score: 0
comment on: http://stackoverflow.com/q/48235431
type: Comment

http://stackoverflow.com/a/48184787
upvote count: 1
has body: Let's modify your data slightly. df = pd.DataFrame({ 'identifier': ['1', None, '2'], 'name': ['Tom', 'Peter', 'Peter'], 'registered': [True, False, True] }) df identifier name registered 0 1 Tom True 1 None Peter False 2 2 Peter True A "None" is the first identifier for "Peter". You can remedy this with a sort_values call, following which, you call groupby + agg. df.sort_values(['identifier'])\ .groupby('name', as_index=False)\ .agg({'identifier' : 'first', 'registered' : any}) name registered identifier 0 Peter True 2 1 Tom True 1
type: Answer
answers question: http://stackoverflow.com/q/48184524
score: 1
downvote count: 0

http://stackoverflow.com/comment/83368809
type: Comment
comment on: http://stackoverflow.com/a/48193453
type: AnswerComment
score: 0
has text: That's because you are basically saying `for each-one-of-these in this`. But `each-one-of-these` is a tuple (similar to a list), and so it's trying to fit that into the integer that you get from the range function, which doesn't make any sense.

http://stackoverflow.com/q/48269372
has body: I want to add some arguments to the function serving_input_receiver_fn, because the size of the feature array depends of the model. The problem is that the oficial definition of serving_input_receiver_fn is: serving_input_receiver_fn: A function that takes no argument and returns a ServingInputReceiver. Required for custom models. My implementation of this function is: def serving_input_receiver_fn(): serialized_tf_example = tf.placeholder(dtype=tf.string, shape=[None], name='input_tensors') receiver_tensors = {'inputs': serialized_tf_example} feature_spec = {'words': tf.FixedLenFeature([25],tf.int64)} features = tf.parse_example(serialized_tf_example, feature_spec) return tf.estimator.export.ServingInputReceiver(features, receiver_tensors) So, I want that the size ([25]), the name of the features ('words') and the name of the receiver ('inputs') can be variables. There is a chance to have arguments in this function? or another way to do this?
answer count: 1
tagged with: tensorflow
favorite count: 0
has title: Tensorflow serving_input_receiver_fn with arguments
type: Question
accepted answer: http://stackoverflow.com/a/50367084
tagged with: python
has answer: http://stackoverflow.com/a/50367084
type: AnsweredQuestion
downvote count: 0
upvote count: 1
tagged with: machine-learning
score: 1

http://stackoverflow.com/comment/83355682
has text: Is possible create sample data as plain text?
comment on: http://stackoverflow.com/q/48187724
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48368001
type: AcceptedAnswer
score: 6
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48282935
answers question: http://stackoverflow.com/q/48282935
type: Answer
upvote count: 6
has body: The difficulty you are having is that your homography matrix h does not correspond well with a projection obtained with a sensible perspective camera. I think there is a simpler approach. Fundamentally, you needed to be very clear about your technical goal, and separate this from your approach for solving it. Always do this whenever you tackle any vision problem. Technical goal So let's be clear about the technical goal. You have a top-down image of a planar surface (also called a rectified view). Normally you would call this surface the model, defined on the plane z=0. You want to render this model. Specifically you want to do the following; A virtual perspective camera is created that is looking at the model from a particular viewpoint. We define this model-to-camera rigid transform by R1, t1, with an intrinsic matrix K. The camera is moved by rotating it about its centre of projection. Let's denote this rotation by R2. The model is rendered using the view from 2. We will call this image I2 For simplicity I'm going to use T(R,t) to denote the 4x4 homogeneous rigid transform for some rotation R and translation t. The model-to-camera transform at stage 3 is therefore given by T=T(R2, (0,0,0)) x T(R1, t1). Rendering options There are two good ways to create I2 Use a rendering engine such as OpenGL or Ogre. The advantage of this is that it can be easy to make a GUI for changing the camera viewpoint and other complex rendering effects can be added. Determine the model-to-image homography matrix and render with OpenCV using warpPerspective. The advantage of this is that it can be done in a few lines without breaking into rendering software. The disadvantage is that you can get some strange effects if the homography has a vanishing point in the render (as you are observing). More on that point later. Definition of model-to-image homography To use the OpenCV approach we define the model-to-image homography as H2. This can be defined in terms of the camera parameters. Cons…

join
type: Tag
tags question: http://stackoverflow.com/q/48263454
tag name: join
tags question: http://stackoverflow.com/q/48232626
tags question: http://stackoverflow.com/q/48312567
tags question: http://stackoverflow.com/q/48312790
tags question: http://stackoverflow.com/q/48255079

http://stackoverflow.com/comment/90467005
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48249910
has text: If you do not want to filter your data on the basis of your instance, than you can pass filtered instances to you serializer. If tou want to pass data directly to your nested serialized, than that data must be part of your queryset.

http://stackoverflow.com/q/48255071
has body: I just setup a new server on Digital Ocean. Updated Django to 1.11, uploaded my project, ran collectstatic and I've made sure my settings match another project I have (which is live and works 100%). However, my static doesn't collect correctly into my static folder (which I have it set to do), any media I upload wont display, and the admin still has the all design from before I updated it to 1.11... Any thoughts? settings code below.. INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'listings', 'stats', 'users', 'allauth', 'allauth.account', 'allauth.socialaccount', ) ... STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ '/static/', ] #MEDIA MEDIA_ROOT = '/home/django/django_project/media/' MEDIA_URL = '/media/' Also here's a picture of my file structure: Note that admin did not collect in static
has comment: http://stackoverflow.com/comment/83493282
type: Question
has answer: http://stackoverflow.com/a/48258131
answer count: 2
has answer: http://stackoverflow.com/a/48256674
has title: Django admin not working?
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/83493304

http://stackoverflow.com/comment/83389901
type: Comment
type: QuestionComment
has text: Is the code indentation correct? Or did you make a mistake in this question?
comment on: http://stackoverflow.com/q/48203931
score: 0

http://stackoverflow.com/a/59160121
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/126824952
has body: If you're ok with installing a package, check out wcmatch. It can patch the Python PathLib so that you can run multiple matches in one go: from wcmatch.pathlib import Path paths = Path('path/to/dir').glob(['*.jl', '*.jsonlines'])
has comment: http://stackoverflow.com/comment/121921120
has comment: http://stackoverflow.com/comment/121883080
score: 5
downvote count: 1
answers question: http://stackoverflow.com/q/48181073

http://stackoverflow.com/a/48203354
type: Answer
answers question: http://stackoverflow.com/q/48202525
score: 2
downvote count: 0
upvote count: 2
has body: You can use NumPy broadcasting to vectorize your operation, avoiding the need for Python loops altogether: def computerCost(x, y, theta): return np.sum((x * theta - y) ** 2, axis=(0, 1)) / (2 * len(y)) m = 100 x = np.linspace(-5,10,m)[:, None, None] y = np.linspace(1,100,m)[:, None, None] theta_0 = np.linspace(-10,10,100) theta_1 = np.linspace(-1,4,100) X, Y = np.meshgrid(theta_0,theta_1) XY = np.stack((X.ravel(), Y.ravel()))[None, :, :] computerCost(x, y, XY) # array([ 7442.62878788, 7340.86628993, 7240.13955518, ..., 1322.02086831, # 1320.72740104, 1320.46969697])
has comment: http://stackoverflow.com/comment/83432954
has comment: http://stackoverflow.com/comment/83432481

timeit
tag name: timeit
tags question: http://stackoverflow.com/q/48205956
tags question: http://stackoverflow.com/q/48276339
type: Tag
tags question: http://stackoverflow.com/q/48269712

http://stackoverflow.com/a/48256724
answers question: http://stackoverflow.com/q/48256678
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83496092
has body: You should append \Z to the end of the regex, so the regex pattern is '\d+\Z'. Your code then becomes: &gt;&gt;&gt; import re &gt;&gt;&gt; pattern = re.compile(r'\d+\Z') &gt;&gt;&gt; string = u"1+*" &gt;&gt;&gt; bool(pattern.match(string)) False This works because \Z forces matching at only the end of the string. You may also use $, which forces a match at a newline before the end of the string or at the end of the string. If you would like to force the string to only contain numeric values (irrelevant if using re.match, but maybe useful if using other regular expression libraries), you may add a ^ to the front of the pattern, forcing a match at the start of the string. The pattern would then be '^\d+\Z'.
type: Answer

http://stackoverflow.com/a/48243071
score: 3
has body: You are storing classes in the river: random.choice([Bear,Fish]) So you get a list of classes: [&lt;class '__main__.Bear'&gt;, ... # ^^^^^ You'd have to call your randomly chosen class to create instances: random.choice([Bear, Fish])() # the () calls the class Now you have a new problem: &gt;&gt;&gt; random.choice([Bear, Fish])() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: __repr__ returned non-string (type Fish) because you are returing self from your __repr__ method. Return a string value; perhaps by using return str(self), but it is better to just implement only __repr__, because if __str__ is missing then Python falls back to __repr__ automatically. The following code works; note that I removed the __init__ methods for Fish and Bear, there is no point in using print() to output a newline when you create one of those: class Bear: def __repr__(self): return 'B' class Fish: def __repr__(self): return 'F' class River: #simulate based on river length INITIAL_RIVER_LENGTH=20 def __init__(self): self._river = [None] * self.INITIAL_RIVER_LENGTH def __repr__(self): return str(self._river) def fillRiver(self): self._river = [ random.choice([Bear,Fish])() for i in range(self.INITIAL_RIVER_LENGTH) ] Demo: &gt;&gt;&gt; riv = River() &gt;&gt;&gt; riv.fillRiver() &gt;&gt;&gt; riv [F, B, B, B, B, F, B, F, B, F, F, B, F, F, F, B, B, B, F, F]
answers question: http://stackoverflow.com/q/48242912
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48242912

http://stackoverflow.com/comment/83577121
has text: See the webhook will call the url when isMine is True.. in this case here, that is also True, I just put that line there to be sure.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48296262

http://stackoverflow.com/q/48182874
has comment: http://stackoverflow.com/comment/83346146
has comment: http://stackoverflow.com/comment/83345774
has comment: http://stackoverflow.com/comment/83346227
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83345677
tagged with: python
has comment: http://stackoverflow.com/comment/83345959
has comment: http://stackoverflow.com/comment/83355218
has comment: http://stackoverflow.com/comment/83346365
score: 0
tagged with: random
answer count: 0
has body: I am trying to write a python program to randomly read some tiff images from a large sample tiff images. Interestingly, I found that python tends to read the tiff images (with floating point values) much slower if we use random generator to generate indices and obtain the list of the image paths, as compared to use hard code random indices to obtain the image paths and read the tiff images. import datetime import matplotlib.pyplot as plt import numpy def read_in_seq(image_filenames, indices): return [ plt.imread(image_filenames[index]) for index in indices ] image_filenames = [] for index in range(15000): image_filenames.append("/tmp/%05d" % index + ".tiff") # This is generated from numpy.random.choice(15000, 100) but hard coded the values here indices=[ 3885, 901, 6233, 7234, 10195, 2204, 469, 2906, 12114, 13515, 12977, 5201, 8829, 11537, 5400, 9633, 10744, 12991, 2593, 3046, 5103, 1901, 8831, 12454, 9779, 4714, 10839, 8702, 8537, 2136, 5095, 9006, 13293, 9933, 3584, 10818, 8594, 11032, 3705, 435, 6679, 8349, 6930, 9741, 12933, 3231, 1849, 7871, 11752, 8361, 3094, 2229, 14303, 2006, 5554, 1492, 14817, 12690, 10648, 14631, 6401, 6181, 4401, 7222, 9881, 8381, 7603, 11374, 12702, 6881, 11868, 10967, 14508, 12930, 3542, 1197, 8387, 11253, 1802, 14732, 7419, 11994, 6083, 8846, 5370, 4276, 13953, 14409, 8197, 8956, 4717, 3262, 2314, 12527, 5394, 12495, 6708, 9724, 740, 10416] print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') + ": Normal input read started with size=" + str(len(indices))) output = read_in_seq(image_filenames, indices) # takes 0.8 seconds print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') + ": Normal input read completed with size=" + str(len(output))) indices = numpy.random.choice(15000, 100) print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') + ": Random input read started with size=" + str(len(indices))) output = read_in_seq(image_filenames, indices) # takes ~3 seconds print(datetime.datetime.now().strftime('%Y-%m-%d …
has comment: http://stackoverflow.com/comment/83345879
has comment: http://stackoverflow.com/comment/83345545
has title: Why python read tiff images slower when using random generator to retrieve the image paths
has comment: http://stackoverflow.com/comment/83346104
type: Question
tagged with: numpy
tagged with: tiff
has comment: http://stackoverflow.com/comment/83345838

http://stackoverflow.com/comment/105052011
comment on: http://stackoverflow.com/a/52812845
type: Comment
score: 7
type: AnswerComment
has text: Isn't the whole point of a context manager is you don't have to call close() or begin()?

http://stackoverflow.com/a/48309093
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/48309004
has body: First off, the filename function needs to return something. So the body of that function would need to look like: def filename(): filename = "inputs2.txt" return filename But the error message you are seeing is caused by trying to convert a function, readdata.filename, to a string. You need to call the function first to get the value: open(str(readdata.filename()), 'a') (note the open and close parentheses after filename) If readdata.filename is returning a string already though, you don't need to call str(), and can just open the file like so: open(readdata.filename(), 'a')
type: Answer

http://stackoverflow.com/q/48290616
tagged with: xlsxwriter
answer count: 1
favorite count: 0
has body: I am trying to find a solution how to substitute the following: worksheet = writer.sheets['Overview'] worksheet.write_formula('C4', '=MIN('Sheet_147_mB'!C2:C325)') with something like: for s in sheet_names: worksheet.write_formula(row, col, '=MIN(s +'!C2:C325')') row+=1 to iterate through all the existing sheets in the current xlsx book and write the function to the current sheet having an overview. After spending some hours I was not able to find any solution therefore it would be hihgly appriciated if someone could point me to any direction. Thank you!
type: Question
has answer: http://stackoverflow.com/a/48296764
accepted answer: http://stackoverflow.com/a/48296764
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
has title: xlsxwriter refer to sheets inside worksheet.write_formula()

http://stackoverflow.com/q/48277417
has title: Different ways to access tuples created with zip built-in function
tagged with: python
type: AnsweredQuestion
score: 0
has body: I want to sort a tuple of integers(in decreasing order) and I then want to save a tuple with the order of indices after sorting in a set. The following piece of code does the job: my_set = set() l = (1, 3, 6, 10, 15, 21) my_set.add(list(zip(*sorted(enumerate(l), key=lambda x: x[1], reverse=True)))[0]) If I evaluate my_set I now have {(5, 4, 3, 2, 1, 0)} I was trying to do the same with the following code(i for indices, v for values): my_set.add(i for i, v in zip(*sorted(enumerate(l), key=lambda x: x[1], reverse=True))) It doesn't work in the same way. The set becomes { &lt;generator object &lt;genexpr&gt; at 0x7f82e49ce360&gt;} Why is it that if I feed the zip result into a list I can access the tuples inside but I can't use the other syntax? Is there an alternative way of obtaining some tuple created by zip without having to feed into a list and then indexing into it?
accepted answer: http://stackoverflow.com/a/48277628
answer count: 1
has comment: http://stackoverflow.com/comment/83538204
upvote count: 1
has comment: http://stackoverflow.com/comment/83538642
has answer: http://stackoverflow.com/a/48277628
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83538352

http://stackoverflow.com/comment/83363481
type: QuestionComment
score: 0
has text: the variables you get are the ones passed in when the callback is executed... now to get around this issue sometimes you can use something like a closure
comment on: http://stackoverflow.com/q/48191589
type: Comment

http://stackoverflow.com/comment/83385712
score: 0
comment on: http://stackoverflow.com/a/48202138
type: Comment
type: AnswerComment
has text: Hi Rakesh, What library are you getting the `interitems` from?

http://stackoverflow.com/comment/83419457
score: 0
type: Comment
type: QuestionComment
has text: @James Is it possible to do this from shell? The reason is because script1 and script2 are located in different docker containers. Sorry to not include this in the question. I will update it now.
comment on: http://stackoverflow.com/q/48218601

http://stackoverflow.com/q/48194470
tagged with: pandas
score: 12
type: AnsweredQuestion
downvote count: 0
has title: Numpy isnat() returns value error on datetime objects
possible better answer: http://stackoverflow.com/a/48194615
accepted answer: http://stackoverflow.com/a/48194942
favorite count: 0
has answer: http://stackoverflow.com/a/48194615
linked to: http://stackoverflow.com/q/13703720
has answer: http://stackoverflow.com/a/48194942
type: Question
upvote count: 12
has body: Have been working through options listed in Converting between datetime, Timestamp and datetime64; however, numpy's isnat() seems to not recognize a datetime object, or I'm missing some other kind of datetime object that the function requires for input. Here's an overview of the dataframe: &gt;&gt;&gt; time_data.head() Date Name In AM Out AM \ 0 2017-12-04 AUSTIN LEWIS 1900-01-01 07:03:11 1900-01-01 12:01:50 1 2017-12-05 AUSTIN LEWIS 1900-01-01 05:24:07 1900-01-01 12:08:21 2 2017-12-06 AUSTIN LEWIS 1900-01-01 11:58:32 NaT 3 2017-12-07 AUSTIN LEWIS 1900-01-01 08:31:23 1900-01-01 12:49:51 4 2017-12-11 AUSTIN LEWIS 1900-01-01 06:55:21 1900-01-01 12:02:08 In PM Out PM Sick Time 0 1900-01-01 12:28:52 1900-01-01 17:34:53 NaT 1 1900-01-01 12:35:12 1900-01-01 16:15:17 NaT 2 NaT 1900-01-01 23:59:01 NaT 3 1900-01-01 13:18:34 1900-01-01 18:10:35 NaT 4 1900-01-01 12:30:49 1900-01-01 17:39:54 NaT &gt;&gt;&gt; time_data.dtypes Date object Name object In AM datetime64[ns] Out AM datetime64[ns] In PM datetime64[ns] Out PM datetime64[ns] Sick Time datetime64[ns] dtype: object &gt;&gt;&gt; type(time_data['In AM'][3]) &lt;class 'pandas._libs.tslib.Timestamp'&gt; &gt;&gt;&gt; type(time_data['In AM'][3].to_datetime()) &lt;type 'datetime.datetime'&gt; if np.isnat(time_data['Out AM'][row].to_datetime()) &amp; np.isnat(time_data['In PM'][row].to_datetime()): Throws "ValueError: ufunc 'isnat' is only defined for datetime and timedelta" What am I missing here?!
answer count: 2
tagged with: datetime
tagged with: python
tagged with: numpy

http://stackoverflow.com/q/48244923
has comment: http://stackoverflow.com/comment/83473027
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/773
has answer: http://stackoverflow.com/a/48245129
possible better answer: http://stackoverflow.com/a/48245129
has body: I have a string of A and B like this: "(BA)4B5A", and I want the output to be BABABABABBBBBA. But the code I have only works if I have the number 1 after A, like "(BA)4B5A1". For letters that don't have a number after it, I just want to repeat it once. I want this to work for any string of A and B def extensao(seq): new_seq = "" i = 0; while i &lt; len(seq): if seq[i] == '(': it = i + 1 exp = "" while seq[it]!= ')': exp += seq[it] it+=1 it+=1 num="" while it &lt; len(seq) and seq[it].isdigit() == True: num += seq[it] it+=1 x = 0 while x &lt; int(num): new_seq += exp x+=1 i = it else: char = seq[i] it=i+1 if(seq[it].isdigit()==True): num="" while it &lt; len(seq) and seq[it].isdigit() == True: num += seq[it] it+=1 x = 0 while x &lt; int(num): new_seq += char x+=1 i = it else: new_seq+=char i+=1 return new_seq def main(): seq = input("Escreva uma sequencia:") final_seq = extensao(seq) print(final_seq) main()
has title: expand a string of A and B that are compacted
type: Question
has answer: http://stackoverflow.com/a/48245030
has comment: http://stackoverflow.com/comment/83472696
has answer: http://stackoverflow.com/a/48268413
tagged with: python
accepted answer: http://stackoverflow.com/a/48245030
type: AnsweredQuestion

http://stackoverflow.com/comment/83384425
score: 1
type: QuestionComment
has text: To get a concrete answer you should probably provide the shapes of the input arrays. In general, what you see is that `np.sum` by default always sums over the whole input and returns a scalar. `np.dot` only sums over one axis (which in your case seems to be the only one) and preserves dimensions.
comment on: http://stackoverflow.com/q/48201729
type: Comment

http://stackoverflow.com/q/48263630
type: UnansweredQuestion
has body: Does anyone know of any Tensorflow code for undistorting images? (removing fisheye effects) Currently, I am undistorting images using OpenCV. However, I want to push that code inside of the net. Is there an open source code or Tensorflow function for doing this? I can't find anything via Google.
tagged with: python
tagged with: opencv
score: 0
linked to: http://stackoverflow.com/q/31089265
has answer: http://stackoverflow.com/a/54660611
has comment: http://stackoverflow.com/comment/83514890
answer count: 1
has title: Tensorflow function for undistorting images
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/83523633

http://stackoverflow.com/q/48273473
has comment: http://stackoverflow.com/comment/83571987
has comment: http://stackoverflow.com/comment/83530716
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83530710
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83530735
has comment: http://stackoverflow.com/comment/83530718
has title: Variable class reassignment not working
has comment: http://stackoverflow.com/comment/83530748
tagged with: python
score: -2
accepted answer: http://stackoverflow.com/a/48273523
has body: I am making an adventure game, and I have too check which class the player is, but the game does not reassign the character, so the player is still none type after being set to person. character = None def start(): characterchosen = False printslow("Welcome adventurer. Chose wisely.") sleep(2) charactername = input("What is your name? ") print("Characters:") print("1. Person") while characterchosen == False: character = input("Please chose a character: ") characterchosen = True if character == "1": character = person(charactername) else: characterchosen = False print("Invalid Response. Please try again.") print("Great! Now that you have chosen your class, your mission may begin.") gameone() def gameone(): if type(character) == "&lt;class 'person'&gt;": print("game here") start() When I used print(type(character)) I got &lt;class 'NoneType'&gt; UPDATE: I tried setting the check to NoneType, but I still get nothing, even though the function is being called.
has comment: http://stackoverflow.com/comment/83530719
has answer: http://stackoverflow.com/a/48273523
answer count: 1
downvote count: 3

http://stackoverflow.com/q/48241426
has comment: http://stackoverflow.com/comment/83479668
has answer: http://stackoverflow.com/a/48271650
favorite count: 0
has comment: http://stackoverflow.com/comment/83479599
type: Question
has body: import pygame as pg import sys pg.init() screen = pg.display.set_mode((800, 600)) clock = pg.time.Clock() screenGray = pg.Color('gray80') RotorFont = pg.font.SysFont("malgun gothic",17) textColour = pg.Color('navy') background = pg.Surface(screen.get_size()) background.fill(screenGray) ACTIONPRINT = False while True: for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit() if event.type == pg.MOUSEBUTTONDOWN: ACTIONPRINT = True screen.blit(background,(0,0)) rotorAA = ['G','N','Z','M','V','B','F','L','Q','R','Y','P','I','C','E','A','D','K','J','W','X','S','H','U','O','T']#2 rotorAB = ['L','Q','R','Y','D','K','J','W','X','S','H','U','O','P','I','C','F','A','G','N','Z','M','V','B','E','T']#3 rotorBA = ['Q','W','E','R','T','Y','U','I','O','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M']#4 rotorBB = ['Y','H','Q','V','L','T','C','W','K','P','S','N','X','E','O','M','B','U','G','F','A','J','D','R','Z','I']#5 rotorCA = ['D','F','P','A','N','E','Y','C','S','G','K','J','M','X','O','V','L','W','Q','H','T','U','B','R','Z','I']#6 rotorCB = ['Z','I','A','C','T','F','U','Q','N','V','P','B','D','O','L','R','S','X','M','G','H','J','W','E','K','Y']#7 rotorList = [rotorAA,rotorAB,rotorBA,rotorBB,rotorCA,rotorCB] count = 0 k = 0 if ACTIONPRINT == True: ACTIONPRINT = False for i in range(0,len(rotorList)): if count % 2 == 0 and count != 0: k += 25 for j in range(0,26): a = RotorFont.render(rotorList[i][j],1,textColour) background.blit(a,(25 + (i * 25) + k,90+(j * 16))) if rotorList[i][j] == letter and i + 2 &lt; 6: correspondingLetter = rotorList[i+1][(rotorList[i].index(letter))] pg.draw.line(background,black,(25 + (i * 25) + k,90+(j * 16)),(25 + (i + 1 * 25) + 25,90+(rotorList[i+1].index(correspondingLetter) * 16))) letter = rotorList[i+2][rotorList[i+1].index(correspondingLetter)] count += 1 pg.display.flip() clock.tick(60) The above code prints the rotors to the screens, in pairs. What I would like to happen is for a letter to be entered in an i…
has comment: http://stackoverflow.com/comment/83466308
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/83484210
accepted answer: http://stackoverflow.com/a/48271650
type: AnsweredQuestion
has title: How to draw lines between two lists in pygame?
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83484410
answer count: 1
has comment: http://stackoverflow.com/comment/83518804

http://stackoverflow.com/a/58883769
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48304792
answers question: http://stackoverflow.com/q/48304792
has body: SSH is not native as a windows command. In the following line map command to point to ssh which is located in C:\Windows\System32\OpenSSH. OpenSSH is now added to Windows 10 in System32. Try this, i think it may work for you. child = pexpect.popen_spawn.PopenSpawn('ssh pi@192.168.178.34') try this instead command = 'C:\Windows\system32\OpenSSH\ssh.exe pi@192.168.178.34' child = pexpect.popen_spawn.PopenSpawn(command) better yet, you can install the new Windows Subsystem for Linux and run your script with that. Windows Subsystem for Linux Installation Guide for Windows 10
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83442045
type: QuestionComment
comment on: http://stackoverflow.com/q/48229059
score: 0
has text: I may be looking at this incorrectly, but what is your expected result? Aren't both requests (curl and py) giving out 401 errors?
type: Comment

http://stackoverflow.com/a/48304132
downvote count: 0
has comment: http://stackoverflow.com/comment/83639468
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48302284
has comment: http://stackoverflow.com/comment/83638838
has body: To create HTML output in a Jupyter notebook you may use display(HTML(&lt;your html here&gt;)). Colorizing the single letters could be done by defining each within a &lt;span&gt; with the respective color. A solution could look like the following: import matplotlib.colors as mcolors from matplotlib import cm import numpy as np from IPython.core.display import display, HTML def format_chars(chars,numbers): numbers = np.array(numbers).astype(float) norm = mcolors.Normalize(vmin=-1, vmax=1) cmap = cm.RdYlGn colors = cmap(norm(numbers)) hexcolor = [mcolors.to_hex(c) for c in colors] letter = lambda (c,l): "&lt;span style='color:{};'&gt;{}&lt;/span&gt;".format(l,c) text = " ".join(list(map(letter, zip(chars,hexcolor)))) text = "&lt;div style='font-size:14pt;font-weight:bold;'&gt;" + text + "&lt;/div&gt;" display(HTML(text)) return colors chars = ['a', 'c', 'm', 'e', 't', 'e', 'l', 'l', 'm', 'e'] vals = ['0.17', '0.062', '0.26', '-0.0799', '-0.449', '-0.746', '-0.812', '-0.844', '-0.865','-0.87'] col = format_chars(chars,vals)
upvote count: 5
accepted answer of: http://stackoverflow.com/q/48302284
score: 5

http://stackoverflow.com/q/48308845
downvote count: 0
answer count: 1
has title: How to use python ctypes to define an undefined symbol
score: 4
has body: I would like to use a shared library (with python ctypes) which expects that some symbols are defined in the program that uses this shared library. In the following example, var is defined in test.c, while nm libadd.so shows that var is undefined; /* libadd.c */ #include &lt;stdio.h&gt; extern int var; int add(int a, int b) { return (a + b + var); } gcc -c -Wall -Werror -fpic libadd.c gcc -shared -o libadd.so libadd.o /* test.c */ #include &lt;stdio.h&gt; #include "libadd.h" int var = 1; int main(void) { printf("%d", add(1,2)); return 0; } gcc -L/path/to/libadd -Wall -o test test.c -ladd Similarly, how to do this with python ctypes; # test.py from ctypes import * #what to do to define var? sharedlib = CDLL("sharedlib/libadd.so", mode = RTLD_GLOBAL) print( sharedlib.add(1,2) ) OSError: sharedlib/libadd.so: undefined symbol: var
favorite count: 0
type: Question
tagged with: linker
tagged with: python
tagged with: shared-libraries
accepted answer: http://stackoverflow.com/a/48327494
upvote count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48327494
tagged with: ctypes
tagged with: extern

http://stackoverflow.com/a/48277174
answers question: http://stackoverflow.com/q/48275290
score: 0
has body: Use PyQuery to get jquery like querying on html content using python. from pyquery import PyQuery as pq scripttags = pq('src') ## will output a list of script tags print(scriptTags[0].src) Based on your content you can use Jquery like querying
type: Answer

fabric
tags question: http://stackoverflow.com/q/48285057
tags question: http://stackoverflow.com/q/48199586
tags question: http://stackoverflow.com/q/48217681
tags question: http://stackoverflow.com/q/48229312
tag name: fabric
type: Tag
tags question: http://stackoverflow.com/q/48273001

http://stackoverflow.com/comment/83348321
type: QuestionComment
comment on: http://stackoverflow.com/q/48183771
has text: yes my bad... I've corrected it..
score: 0
type: Comment

http://stackoverflow.com/comment/83543821
comment on: http://stackoverflow.com/a/48280051
score: 1
type: Comment
type: AnswerComment
has text: The result is perfect, thank you so much! I do not understand everything you did, so I will not be able to do it again by myself, but I know at least what functions I need to bone up.

http://stackoverflow.com/q/48199353
upvote count: 8
answer count: 3
has answer: http://stackoverflow.com/a/62808157
accepted answer: http://stackoverflow.com/a/48213129
has answer: http://stackoverflow.com/a/48213129
tagged with: nlp
has answer: http://stackoverflow.com/a/48203306
score: 8
type: Question
tagged with: spacy
has title: How to use spacy in large dataset with short sentences efficiently?
downvote count: 0
possible better answer: http://stackoverflow.com/a/48203306
tagged with: python
favorite count: 0
has body: I choose spacy to process kinds of text because of the performance of it's lemmatation compared with nltk. But When I process millions short text, it always consumed all of my memory(32G) and crashed. Without it just a few minutes and less than 10G mem is consumed. Is something wrong with the usage of this method? is there any better solution to improve the performance? Thanks! def tokenizer(text): try: tokens = [ word for sent in sent_tokenize(text) for word in word_tokenize(sent)] tokens = list(filter(lambda t: t.lower() not in stop_words, tokens)) tokens = list(filter(lambda t: t not in punctuation, tokens)) tokens = list(filter(lambda t: len(t) &gt; 4, tokens)) filtered_tokens = [] for token in tokens: if re.search('[a-zA-Z]', token): filtered_tokens.append(token) spacy_parsed = nlp(' '.join(filtered_tokens)) filtered_tokens = [token.lemma_ for token in spacy_parsed] return filtered_tokens except Exception as e: raise e Dask parrallel computing ddata = dd.from_pandas(res, npartitions=50) def dask_tokenizer(df): df['text_token'] = df['text'].map(tokenizer) return df %time res_final = ddata.map_partitions(dask_tokenizer).compute(get=get) Info about spaCy spaCy version 2.0.5 Location /opt/conda/lib/python3.6/site-packages/spacy Platform Linux-4.4.0-103-generic-x86_64-with-debian-stretch-sid Python version 3.6.3 Models en, en_default
type: AnsweredQuestion

http://stackoverflow.com/a/48218587
type: Answer
has body: Generally you want to build the entire dataset before passing it to the data frame constructor. Appending is very slow because it is creating a an entire new data frame from scratch on the backend. import xml.etree.cElementTree as ET import pandas as pd tree = ET.parse(path+xname) root = tree.getroot() data = [] for i in range(1, range(len(root[1])): data.append((root[1][i][0][0].attrib["value"], root[1][i][0][1].attrib["value"], root[1][i][0][2].attrib["value"], root[1][i][1][0].text, root[1][i][1][1].attrib["value"])) df = pd.DataFrame(data ,columns=["GEO","AGE","SEX","YEAR","VALUE"])
score: 2
accepted answer of: http://stackoverflow.com/q/48217974
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48217974
has comment: http://stackoverflow.com/comment/83419453

http://stackoverflow.com/q/48211945
downvote count: 0
upvote count: 1
has body: It is about metaclasses in Python2.7. To be clear, the code is like: class MetaC(type): def __new__(cls, name, bases, attrs): print "MetaC" return super(MetaC, cls).__new__(cls, name, bases, attrs) class MetaB(MetaC): def __new__(cls, name, bases, attrs): print "MetaB" return super(MetaB, cls).__new__(cls, name, bases, attrs) class MetaA(MetaB): def __new__(cls, name, bases, attrs): print "MetaA" return super(MetaA, cls).__new__(cls, name, bases, attrs) class A(object): __metaclass__ = MetaA print type(A) class B(A): __metaclass__ = MetaB print type(B) class C(B): __metaclass__ = MetaC print type(C) The results are like: MetaA MetaB MetaC &lt;class '__main__.MetaA'&gt; MetaB MetaC MetaA MetaB MetaC &lt;class '__main__.MetaA'&gt; MetaC MetaA MetaB MetaC &lt;class '__main__.MetaA'&gt; It seems that when creating the class C, MetaA.__new__ is called after MetaC.__new__. To figure it out, I looked into the source code and find in typeobject.c: static PyObject * type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds) { /* some code is omitted here */ for (i = 0; i &lt; nbases; i++) { tmp = PyTuple_GET_ITEM(bases, i); tmptype = tmp-&gt;ob_type; if (tmptype == &amp;PyClass_Type) continue; /* Special case classic classes */ if (PyType_IsSubtype(winner, tmptype)) continue; if (PyType_IsSubtype(tmptype, winner)) { winner = tmptype; continue; } PyErr_SetString(PyExc_TypeError, "metaclass conflict: " "the metaclass of a derived class " "must be a (non-strict) subclass " "of the metaclasses of all its bases"); return NULL; } if (winner != metatype) { if (winner-&gt;tp_new != type_new) /* Pass it to the winner */ return winner-&gt;tp_new(winner, args, kwds); metatype = winner; } /* some code is omitted here */ } The for loop finds the most deepest subclass winner(sorry for my poor english, the code may be much clearer than my words). If it is not metatype, winner-&gt;tp_new will be called. That's why I got the results from my code. So, what I am wondering is, why is it d…
favorite count: 0
type: Question
has title: How is everything happened when a class's metaclass is a subclass of its subclass's metaclass?
type: UnansweredQuestion
tagged with: cpython
tagged with: python
tagged with: inheritance
tagged with: metaclass
has comment: http://stackoverflow.com/comment/83408082
score: 1
has answer: http://stackoverflow.com/a/48213465
answer count: 1

http://stackoverflow.com/comment/83443768
comment on: http://stackoverflow.com/a/48230639
type: Comment
score: 0
has text: I think I understand.... But why is `localhost.localdomain` getting returned only when the fqdn of the main interface's IP address is appended to the 127.0.0.1 entry in the hosts file? I'm not passing in a value either time, so the "name is omitted or empty" on both runs.
type: AnswerComment

http://stackoverflow.com/comment/83555310
comment on: http://stackoverflow.com/q/48285286
has text: @ImportanceOfBeingErnest thank you for your suggestion. I already read examples about it. But I had issues trying to set it properly
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48292331
score: 2
type: UnansweredQuestion
has body: I am trying to post data using postman with x-www-form-urlencoded. When I send request an eroor is occuring saying- { "detail": "Missing filename. Request should include a Content-Disposition header with a filename parameter." } post data is contained {'name': 'hello'} this is my view: serializer = Web2TypeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) NOTE: Post data not containg any file.
answer count: 1
downvote count: 0
tagged with: django
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/49637007
has title: Django REST Framework form data no submit with x-www-form-urlencoded
tagged with: python
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/a/49806235
type: Answer
score: 0
has body: I encountered similar problem, when I was using mxnet with multiprocessing and OpenCV. I didn't use Tornado, but symptoms were same: a single process environment worked fine, but as soon as I set multiprocessing, I get segmentation faults. It turns out that my problem was related to this issue: https://github.com/opencv/opencv/issues/5150, and I fixed that by setting cv2.setNumThread(0) in the beginning of my code. Since you are using resnet, I assume that you also have a dependency on OpenCV. I also notice that there were quite a few Segmentation fault issues fixed in mxnet version 1.1, so if you are not using this version, I recommend to upgrade to it as it is much more stable.
answers question: http://stackoverflow.com/q/48316400

http://stackoverflow.com/comment/83348228
has text: `if Fries.get(): cof = float(Fries.get()) else: cof = 0`
comment on: http://stackoverflow.com/q/48184238
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/83678725
type: Comment
score: 0
type: AnswerComment
has text: @Reems yes there are several modules like [schedule](https://schedule.readthedocs.io/en/stable/) but they all require a daemon (permanent background process). Using the OS's task scheduler is much better.
comment on: http://stackoverflow.com/a/48332476

http://stackoverflow.com/a/48229469
has body: I guess the idea would be to create a contour plot outside the updating function once and give it a colorbar. The contour plot would then need to have defined levels and the colorrange needs to be defined. ax.contourf(..., levels=levels, vmin=zmin, vmax=zmax) where zmin and zmax are the minimum and maximum data to be shown, and levels is the list or array of levels to use. Then, inside the animating function, you would only create a new contour plot with those same parameters without touching the colorbar at all. import numpy as np import itertools import matplotlib.pyplot as plt import matplotlib.mlab as ml import matplotlib.animation as animation def f(x,y,a): return a*(x**2+y**2) avals = list(np.linspace(0,1,10)) xaxis = list(np.linspace(-2,2,9)) yaxis = list(np.linspace(-2,2,9)) xy = list(itertools.product(xaxis,yaxis)) xy = np.array(list(map(list,xy))) x = xy[:,0] y = xy[:,1] zlist = [] for a in avals: z = [] for i, xval in enumerate(x): z.append(f(x[i],y[i],a)) zlist.append(z) xi = np.linspace(min(x),max(x),len(x)) yi = np.linspace(min(y), max(y), len(y)) zmin = min([min(zl) for zl in zlist]) zmax = max([max(zl) for zl in zlist]) levels = np.linspace(zmin, zmax,41) kw = dict(levels=levels, cmap=plt.cm.hsv, vmin=zmin, vmax=zmax, origin='lower') fig,ax = plt.subplots() zi = ml.griddata(x, y, zlist[0], xi, yi, interp='linear') contourplot = ax.contourf(xi, yi, zi, **kw) cbar = plt.colorbar(contourplot) def animate(index): zi = ml.griddata(x, y, zlist[index], xi, yi, interp='linear') ax.clear() ax.contourf(xi, yi, zi, **kw) ax.set_title('%03d'%(index)) ani = animation.FuncAnimation(fig,animate,10,interval=200,blit=False) plt.show()
answers question: http://stackoverflow.com/q/48228692
downvote count: 0
type: AcceptedAnswer
upvote count: 6
type: Answer
score: 6
accepted answer of: http://stackoverflow.com/q/48228692

http://stackoverflow.com/q/48266247
has answer: http://stackoverflow.com/a/48267893
has comment: http://stackoverflow.com/comment/83518824
has answer: http://stackoverflow.com/a/48270683
has title: Solving rational inequalities in sympy
has body: I am new to sympy but want to solve the following problem: I have multiple inequality constraints of the form A &lt; f(x) &lt; B C &lt; g(x) &lt; D ... where A, B, C, D are just numbers. f and g are rational functions. For instance I can get the following to work: solve_rational_inequalities(((Poly(x-10000.00), Poly(1, x)), '&gt;'), ((Poly(x-100000.00), Poly(1, x)), '&lt;'), ((Poly((x/130000.00)-0.00), Poly(1, x)), '&gt;'), ((Poly((x/130000.00)-0.19), Poly(1, x)), '&lt;')) Interval.open(10000, 24700) Here, A = 10.000, B = 100.000, C = 0, D = 0.19, f(x) = x and g(x) = x/130.000. So this works. Now, for another case, I have the function f(x) = 10100.00 / x. If I just apply the recipe from above I get: solve_rational_inequalities(((Poly((10100.00/x)-0.00), Poly(1, x)), '&gt;'), ((Poly((10100.00/x)-0.19), Poly(1, x)), '&lt;')) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/oliverdemetz/Library/Python/2.7/lib/python/site-packages/sympy/solvers/inequalities.py", line 162, in solve_rational_inequalities numer_intervals = solve_poly_inequality(numer*denom, rel) File "/Users/oliverdemetz/Library/Python/2.7/lib/python/site-packages/sympy/solvers/inequalities.py", line 55, in solve_poly_inequality reals, intervals = poly.real_roots(multiple=False), [] File "/Users/oliverdemetz/Library/Python/2.7/lib/python/site-packages/sympy/polys/polytools.py", line 3454, in real_roots reals = sympy.polys.rootoftools.CRootOf.real_roots(f, radicals=radicals) File "/Users/oliverdemetz/Library/Python/2.7/lib/python/site-packages/sympy/polys/rootoftools.py", line 196, in real_roots return cls._get_roots("_real_roots", poly, radicals) File "/Users/oliverdemetz/Library/Python/2.7/lib/python/site-packages/sympy/polys/rootoftools.py", line 565, in _get_roots raise PolynomialError("only univariate polynomials are allowed") sympy.polys.polyerrors.PolynomialError: only univariate polynomials are allowed
type: Question
has comment: http://stackoverflow.com/comment/83518760
has comment: http://stackoverflow.com/comment/83515839
has comment: http://stackoverflow.com/comment/83516722
tagged with: python
linked to: http://stackoverflow.com/q/48284093
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: sympy
accepted answer: http://stackoverflow.com/a/48267893
possible better answer: http://stackoverflow.com/a/48270683

http://stackoverflow.com/comment/83391965
comment on: http://stackoverflow.com/a/48204975
type: Comment
has text: Thank you! I don't know itertools. I will try to learn this library.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83339837
comment on: http://stackoverflow.com/q/48179874
type: Comment
type: QuestionComment
has text: Okay, so instead of saying `se = set(l)` I can just directly create a list by doing `return list(set(l))` ? Thanks, I never knew that!
score: 0

http://stackoverflow.com/comment/83488020
type: Comment
type: QuestionComment
has text: @DYZ: It depends on how complex the language is of course. But the Equivalence problem of two Turing machines us undecidable (and even co-undecidable).
comment on: http://stackoverflow.com/q/48252649
score: 1

http://stackoverflow.com/q/48193704
upvote count: 2
type: UnansweredQuestion
score: 1
answer count: 1
has title: Python For Loop (Iterating Variable Name = List Name)
has comment: http://stackoverflow.com/comment/83368004
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83367892
has comment: http://stackoverflow.com/comment/83368641
has answer: http://stackoverflow.com/a/48193801
has comment: http://stackoverflow.com/comment/83368116
has comment: http://stackoverflow.com/comment/83368019
has body: I am running this Python code: numbers = [1, 2, 3] letters = ['a', 'b', 'c'] for numbers in numbers: print(numbers) for letters in letters: print(letters) and got this output: 1 a b c 2 c 3 c I do not understand why I got this output . What I am asking is what is the effect of using iterating variable with the same name with the sequence(list)?
tagged with: python
has comment: http://stackoverflow.com/comment/83367885
tagged with: list
tagged with: for-loop

http://stackoverflow.com/q/48298902
favorite count: 0
score: 2
has title: split a array columns into rows pyspark
type: AnsweredQuestion
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/83584479
accepted answer: http://stackoverflow.com/a/48299214
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48299214
upvote count: 2
downvote count: 0
tagged with: pyspark
answer count: 1
tagged with: python
has body: I have a DataFrame similar to following: new_df = spark.createDataFrame([ ([['hello', 'productcode'], ['red','color']], 7), ([['hi', 'productcode'], ['blue', 'color']], 8), ([['hoi', 'productcode'], ['black','color']], 7) ], ["items", "frequency"]) new_df.show(3, False) # +------------------------------------------------------------+---------+ # |items |frequency| # +------------------------------------------------------------+---------+ # |[WrappedArray(hello, productcode), WrappedArray(red, color)]|7 | # |[WrappedArray(hi, productcode), WrappedArray(blue, color)] |8 | # |[WrappedArray(hoi, productcode), WrappedArray(black, color)]|7 | # +------------------------------------------------------------+---------+ I need to generate a new DataFrame similar to following: # +------------------------------------------- # |productcode | color |frequency| # +------------------------------------------- # |hello | red | 7 | # |hi | blue | 8 | # |hoi | black | 7 | # +--------------------------------------------

http://stackoverflow.com/comment/83647416
score: 0
comment on: http://stackoverflow.com/a/48329937
has text: Just to be clear, the problem isn't with speed, it's with memory consumption (Since you said `apply` should be faster)
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83647448
comment on: http://stackoverflow.com/q/48266118
has text: Well, mass functions are definable on any countable set, and countable sets are isomorphic to the integers. Which is a long-winded way of saying it doesn't matter, just relabel your points 0, 1, 2, 3, ....
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48274129
linked to: http://stackoverflow.com/q/626759
has comment: http://stackoverflow.com/comment/83535912
has comment: http://stackoverflow.com/comment/83531755
has body: In following code, shape of size &amp; randm is same only, 1-D Array (3,) Then why size=(3, 3, 2) &amp; randm=[-1.10343097 -1.31819984 0.20597956] Q.1 Why different bracket () vs [] Q.2 What is significant of each bracket () &amp; [] image = np.array([[[ 0.67826139, 0.29380381], [ 0.90714982, 0.52835647], [ 0.4215251 , 0.45017551]], [[ 0.92814219, 0.96677647], [ 0.85304703, 0.52351845], [ 0.19981397, 0.27417313]], [[ 0.60659855, 0.00533165], [ 0.10820313, 0.49978937], [ 0.34144279, 0.94630077]]]) size = np.shape(image) print (str (size)) print (np.shape(size)) randm = np.random.randn(3) print (randm) print (np.shape(randm)) Output- (3, 3, 2) (3,) [-1.10343097 -1.31819984 0.20597956] (3,)
score: -6
favorite count: 0
downvote count: 6
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48274160
has answer: http://stackoverflow.com/a/48274153
upvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1983
has answer: http://stackoverflow.com/a/48275833
tagged with: python
has comment: http://stackoverflow.com/comment/83531888
has title: What is difference between (1,2,3) vs [1,2,3] in python ?
has comment: http://stackoverflow.com/comment/83531910
answer count: 3

permutation
tags question: http://stackoverflow.com/q/48192925
tags question: http://stackoverflow.com/q/48253730
type: Tag
tags question: http://stackoverflow.com/q/48234169
tag name: permutation
tags question: http://stackoverflow.com/q/48248076
tags question: http://stackoverflow.com/q/48222204
tags question: http://stackoverflow.com/q/48235938

http://stackoverflow.com/comment/83454443
type: AnswerComment
comment on: http://stackoverflow.com/a/48235894
type: Comment
has text: The nested `while`s should just be `if`.
score: 2

http://stackoverflow.com/comment/83362645
type: QuestionComment
has text: What errors are you getting?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48190949

http://stackoverflow.com/comment/106928845
comment on: http://stackoverflow.com/a/48213273
has text: it depends maybe on version of boto but for me the following code was returning an error, using session = boto3.Session( <--- Session (with Capital S) instead of session work better.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/72133154
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48226295
has body: This is the intended function of ax.get_ylim(). Without this function (and get_xlim) doing what it does, there would be no way to get the max and min values displayed on the chart. You can use the following to achieve what you want: max(df[df["columninquestion"] < ax.get_ylim()[1]]["columninquestion"])

http://stackoverflow.com/comment/83489608
comment on: http://stackoverflow.com/a/48253516
has text: sure thing. just made the changes. sorry for the inconvenience
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48278187
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83619850
has comment: http://stackoverflow.com/comment/83540096
has comment: http://stackoverflow.com/comment/83684072
tagged with: hierarchy
has comment: http://stackoverflow.com/comment/83540004
has answer: http://stackoverflow.com/a/48298613
tagged with: sys
has comment: http://stackoverflow.com/comment/83683394
has comment: http://stackoverflow.com/comment/83660172
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83539822
has title: Argparse: what is the difference between "sys.argv[1]" and "args.input"?
has comment: http://stackoverflow.com/comment/83558822
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48298613
tagged with: argparse
has comment: http://stackoverflow.com/comment/83539919
upvote count: 0
has body: I'm learning how to use argparse and it's a labyrinth for me. I have a code that works: if I run python Test.py . it prints all files in hierarchy using this code #!/usr/bin/env python # -*- coding: utf-8 -*- import os import argparse import sys import glob #parser = argparse.ArgumentParser() #parser.add_argument('-input', dest='input',help="input one or more files",nargs='+',metavar=None #args = parser.parse_args() def dirlist(path, c = 1): for i in glob.glob(os.path.join(path, "*")): if os.path.isfile(i): filepath, filename = os.path.split(i) print ('----' *c + filename) elif os.path.isdir(i): dirname = os.path.basename(i) print ('----' *c + dirname) c+=1 dirlist(i,c) c-=1 #path = os.path.normpath(args.input) path = os.path.normpath(sys.argv[1]) print(os.path.basename(path)) dirlist(path) But, as I want to understand how argparse works I want to run the code using python Test.py - input . But nothing works. I know I'm close, I have written a sort of Frankenstein code which is commented. Where am I wrong? I feel I'm so close to the solution...
answer count: 1
has comment: http://stackoverflow.com/comment/83581681
has comment: http://stackoverflow.com/comment/83651068
downvote count: 1
has comment: http://stackoverflow.com/comment/83545512
favorite count: 0

http://stackoverflow.com/comment/83565321
type: Comment
has text: https://stackoverflow.com/questions/48286251/windows-python-pygame-error-video-system-not-initialized-after-adding-mp3-file
comment on: http://stackoverflow.com/a/48287618
type: AnswerComment
score: 0

http://stackoverflow.com/a/48290839
answers question: http://stackoverflow.com/q/48290758
score: 6
upvote count: 6
type: Answer
has comment: http://stackoverflow.com/comment/83566981
has body: You can use the einsum expression to perform the transformation on each index: x = np.random.randn(n, n, n) ft3 = np.einsum('ijk,im-&gt;mjk', x, D) ft3 = np.einsum('ijk,jm-&gt;imk', ft3, D) ft3 = np.einsum('ijk,km-&gt;ijm', ft3, D) print(np.abs(ft3 - np.fft.fftn(x)).max()) 1.25571216554e-12 This can also be written as a single NumPy step: ft3 = np.einsum('ijk,im,jn,kl-&gt;mnl', ft3, D, D, D, optimize=True) Without the optimize argument (available in NumPy 1.12+) it will be very slow however. You can also do each of the steps using dot, but it requires a bit of reshaping and transposing. In NumPy 1.14+ the einsum function will automatically detect the BLAS operations and do this for you.
accepted answer of: http://stackoverflow.com/q/48290758
type: AcceptedAnswer
downvote count: 0

rx-py
tags question: http://stackoverflow.com/q/48293273
tag name: rx-py
type: Tag

http://stackoverflow.com/comment/83491192
has text: @mkl It is AcroForm (native Pdf)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48247361
type: Comment

http://stackoverflow.com/a/48263950
upvote count: 1
score: 1
type: Answer
has body: You just need a dict-comprehension that will re-built your dictionary with an if condition for the value part. my_dict = {1:5, 2:5, 3:5} arr = [1,2] my_dict = {k: (0 if k in arr else v+1) for k, v in my_dict.items()} print(my_dict) # {1: 0, 2: 0, 3: 6} Note that I have re-named the dictionary from dict to my_dict. That is because by using dict you are overwriting the Python built-in called dict. And you do not want to do that.
answers question: http://stackoverflow.com/q/48263875
downvote count: 0
has comment: http://stackoverflow.com/comment/83511538

http://stackoverflow.com/a/48195390
score: 0
has body: If memory is not a concern, you can store/restore state by saving/restoring the whole object. I am also considering that control of the target object outside its class is not a problem. I assume the object is not cancelling the last action itself, but some other code controls that. Otherwise you'll have to manage your class relation with the Stack class. In the below example I use deepcopy, but pickle.dumps can also be used. I choose to use a stack like structure, which allows the saving of whatever number of objects/states you want. But replacing with a rotating buffer would allow the storage of only the last n objects/states. The advantage I see over some of the other answers is not worrying about what methods were called or attributes had changed. It's also simple. Preserving states and frames/environments always remembers me of dicts and stacks: from copy import deepcopy class ObjectStack(): def __init__(self): self.objects = [] def push(self, obj): self.objects.append(deepcopy(obj)) def pop(self): return self.objects.pop() if self.objects else None #just an example class, not OP's original class class char(): def __init__(self, char): self.char = char stack = ObjectStack() c = char('C') stack.push(c) # save object c = char('D') # somehow object changes print(c.char) last = stack.pop() # restore last object/state if last is not None: c = last print(c.char) last = stack.pop() if last is None: print('No more objects/states saved')
answers question: http://stackoverflow.com/q/48173774
type: Answer

http://stackoverflow.com/a/70662040
has body: The data assigned to a column in the DataFrame must be a single dimension array. For example, consider a num_arr to be added to a DataFrame num_arr.shape (1, 126) For this num_arr to be added to a DataFrame column, It should be reshaped.... num_arr = num_arr.reshape(-1, ) num_arr.shape (126,) Now I could set this arr as a DataFrame column df = pd.DataFrame() df['numbers'] = num_arr
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48306694
score: 2

http://stackoverflow.com/a/48330304
has body: This is the solution I ended up using based on the answer above. import pandas as pd df= pd.DataFrame([12,11,4,15,6,12,4,7],columns=['foo']) # make a dict with counts count_dict = dict(df.foo.value_counts()) # assign that dict to a column df['temp_count'] = [count_dict[d] for d in df.foo] # loc in the 'pruned' tag df.loc[df.temp_count &lt; 2, 'foo']='pruned' df = df.drop(["temp_count"], axis=1)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48326897

http://stackoverflow.com/comment/83597676
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48306212
type: QuestionComment
has text: BTW, if you're asking about something you found in a different SO question or answer, it's courteous to link to that answer. (But *do* be sure your question actually contains a question -- a description of a specific problem, or exact steps to take to see something not work and a description of how to *tell* it's not working, etc).

http://stackoverflow.com/comment/83485189
type: AnswerComment
has text: Can you post the output of `df'Age', 'Sex', 'Days'.head().to_dict()`?
score: 0
comment on: http://stackoverflow.com/a/48251097
type: Comment

http://stackoverflow.com/a/48251159
answers question: http://stackoverflow.com/q/48251131
has body: This should work: if request.method == "POST": code = request.POST.get('code', False) fp = open('mp/somefile.txt', 'w') fp.write(str(code).replace("\n", '')) fp.close()
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48251131

http://stackoverflow.com/comment/83565183
type: QuestionComment
type: Comment
score: 2
has text: Algorithms are typically not tied to a specific language.
comment on: http://stackoverflow.com/q/48290057

http://stackoverflow.com/q/48269295
type: Question
has comment: http://stackoverflow.com/comment/83521950
has comment: http://stackoverflow.com/comment/83523332
accepted answer: http://stackoverflow.com/a/48270568
has comment: http://stackoverflow.com/comment/83522522
has comment: http://stackoverflow.com/comment/83523801
has answer: http://stackoverflow.com/a/48270568
has title: xDjango Inner Join tables with queryset
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83523122
score: 0
has comment: http://stackoverflow.com/comment/83523038
has body: I'm trying to INNER join 2 tables: Comments and Auth. So I store userid in Comments table and I need to pair it with the Auth. I did with .raw(), but I don't want to do with the raw(), I have tried also other like get_objects_or_404 but that does not work either because of multiple queries. Here is my query, works as excepted. SELECT * FROM index_comment INNER JOIN auth_user WHERE index_comment.userid=auth_user.id And here is my Comment model: class Comment(models.Model): content = models.TextField() userid = models.IntegerField() published = models.DateField(default=timezone.now) postid = models.IntegerField() Views.py def readPost(request, postName): content = get_object_or_404(Post, link=postName) kategori = get_object_or_404(Category, id=content.category_id) user = get_object_or_404(User, id=content.username_id) if request.method == "POST": form = sendComment(request.POST) if form.is_valid: formContent = strip_tags(request.POST["content"]) newComment = Comment() newComment.content = formContent newComment.postid = content.id newComment.save() return redirect('post',content.link) else: form = sendComment args = { "content": content, "kategori": kategori, "user":user, "commentForm": form, } # return HttpResponse("cat.id") return render(request, "theme/single.html", args) And here is the forms.py class sendComment(forms.Form): content = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control"})) So I need to pair userid from Comments table to Auth id, and then get the username.
has comment: http://stackoverflow.com/comment/83522864
has comment: http://stackoverflow.com/comment/83522384
has comment: http://stackoverflow.com/comment/83522760
answer count: 1
tagged with: mysql

http://stackoverflow.com/q/48217264
accepted answer: http://stackoverflow.com/a/48217852
tagged with: byte
has title: Python: Converting two sequential 2-byte registers (4 bytes) into IEEE floating-point big endian
has answer: http://stackoverflow.com/a/48217852
linked to: http://stackoverflow.com/q/37093485
tagged with: python
has answer: http://stackoverflow.com/a/48292767
has comment: http://stackoverflow.com/comment/83416550
score: 2
tagged with: hex
type: AnsweredQuestion
answer count: 2
upvote count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/48292767
has body: I am hooking up an instrument to a laptop over TCP/IP. I have been using a python package to talk to it, and have it return numbers. There are two probes hooked up to this instrument, and I believe these are the bytes corresponding to the temperature readings of these two probes. The instrument, by default, is set to Big Endian and these data should be of a 32-bit floating point variety - meaning that the variable (b) in the code chunk represents two numbers. b is representative of the output that I would get from the TCP functions. &gt;&gt;&gt; b = [16746, 42536, 16777, 65230] &gt;&gt;&gt; My goal in this is to convert these into their float values, and automating the process. Currently, I am running b through the (hex) function to retrieve the hexadecimal equivalents of each byte: &gt;&gt;&gt; c =[hex(value) for value in b] &gt;&gt;&gt; &gt;&gt;&gt; c &gt;['0x416a', '0xa628', '0x4189', '0xfece'] &gt;&gt;&gt; ... then I have manually created data_1 and data_2 below to match these hex values, then unpacked them using struct.unpack as I found in this other answer: &gt;&gt;&gt; data_1 = b'\x41\x6a\xa6\x28' &gt;&gt;&gt; import struct &gt;&gt;&gt; struct.unpack('&gt;f', data_1) &gt;(14.665565490722656,) &gt;&gt;&gt; data_2 = b'\x41\x89\xfe\xce' &gt;&gt;&gt; struct.unpack('&gt;f', data_2) &gt;(17.24941635131836,) &gt;&gt;&gt; Some questions: Am I fundamentally missing something? I am a biologist by trade, and usually a R programmer, so Python is relatively new to me. I am primarily looking for a streamlined way to get from the TCP output (b) to the number outputs of struct.unpack. The eventual goal of this project is to constantly be polling the sensors for data, which will be graphed/displayed on screen as well as being saved to a .csv. Thank you!
favorite count: 0
type: Question

http://stackoverflow.com/q/48261062
downvote count: 0
accepted answer: http://stackoverflow.com/a/50039169
has comment: http://stackoverflow.com/comment/83505059
has comment: http://stackoverflow.com/comment/83543710
has comment: http://stackoverflow.com/comment/83505187
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83505217
answer count: 2
upvote count: 2
tagged with: wagtail
has answer: http://stackoverflow.com/a/60443862
possible better answer: http://stackoverflow.com/a/60443862
tagged with: django
has answer: http://stackoverflow.com/a/50039169
tagged with: python
has comment: http://stackoverflow.com/comment/83505733
score: 2
type: AnsweredQuestion
has title: Wagtail installation: Wagtail command not found
has comment: http://stackoverflow.com/comment/83505235
has body: I am trying to install wagtail. As the docs suggest, I installed wagtail using pip: tigran@tigran:~/projects/website$ pip install wagtail Collecting wagtail Using cached wagtail-1.13.1-py2.py3-none-any.whl Collecting html5lib&lt;1,&gt;=0.999 (from wagtail) Using cached html5lib-0.999999999-py2.py3-none-any.whl Collecting Django&lt;1.12,&gt;=1.8.1 (from wagtail) Using cached Django-1.11.9-py2.py3-none-any.whl Collecting djangorestframework&lt;3.7,&gt;=3.1.3 (from wagtail) Using cached djangorestframework-3.6.4-py2.py3-none-any.whl Collecting django-treebeard&lt;5.0,&gt;=3.0 (from wagtail) Collecting Pillow&gt;=2.6.1 (from wagtail) Using cached Pillow-5.0.0-cp27-cp27mu-manylinux1_x86_64.whl Collecting Unidecode&gt;=0.04.14 (from wagtail) Using cached Unidecode-1.0.22-py2.py3-none-any.whl Collecting django-taggit&lt;1.0,&gt;=0.20 (from wagtail) Using cached django_taggit-0.22.2-py2.py3-none-any.whl Collecting django-modelcluster&lt;4.0,&gt;=3.1 (from wagtail) Collecting Willow&lt;1.1,&gt;=1.0 (from wagtail) Using cached Willow-1.0-py2.py3-none-any.whl Collecting beautifulsoup4&gt;=4.5.1 (from wagtail) Using cached beautifulsoup4-4.6.0-py2-none-any.whl Collecting requests&lt;3.0,&gt;=2.11.1 (from wagtail) Using cached requests-2.18.4-py2.py3-none-any.whl Collecting six (from html5lib&lt;1,&gt;=0.999-&gt;wagtail) Using cached six-1.11.0-py2.py3-none-any.whl Collecting webencodings (from html5lib&lt;1,&gt;=0.999-&gt;wagtail) Using cached webencodings-0.5.1-py2.py3-none-any.whl Collecting setuptools&gt;=18.5 (from html5lib&lt;1,&gt;=0.999-&gt;wagtail) Using cached setuptools-38.4.0-py2.py3-none-any.whl Collecting pytz (from Django&lt;1.12,&gt;=1.8.1-&gt;wagtail) Using cached pytz-2017.3-py2.py3-none-any.whl Collecting idna&lt;2.7,&gt;=2.5 (from requests&lt;3.0,&gt;=2.11.1-&gt;wagtail) Using cached idna-2.6-py2.py3-none-any.whl Collecting urllib3&lt;1.23,&gt;=1.21.1 (from requests&lt;3.0,&gt;=2.11.1-&gt;wagtail) Using cached urllib3-1.22-py2.py3-none-any.whl Collecting cert…
has comment: http://stackoverflow.com/comment/83505597

tableau-api
type: Tag
tag name: tableau-api
tags question: http://stackoverflow.com/q/48183127

http://stackoverflow.com/comment/83534314
type: QuestionComment
comment on: http://stackoverflow.com/q/48275013
has text: I've use "py -m pip install [package] and python -m pip install [package] to excuted". The error was same.
score: 0
type: Comment

http://stackoverflow.com/comment/83566779
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48290831
has text: So the data is "rectangular"? (every row has the same number of cells)?

http://stackoverflow.com/q/48215857
has comment: http://stackoverflow.com/comment/83413665
has comment: http://stackoverflow.com/comment/83413697
answer count: 0
has comment: http://stackoverflow.com/comment/83413730
type: UnansweredQuestion
tagged with: arrays
linked to: http://stackoverflow.com/q/3136689
tagged with: string
type: Question
has comment: http://stackoverflow.com/comment/83413676
score: 0
duplicate of: http://stackoverflow.com/q/3136689
has body: I have this variable : terms2 = ['5*x^4', '4*x^3', '2/x^2'] I neew to make some changes when '/' appears and after that terms2 should be: terms2 = ['5*x^4', '4*x^3', '2*x^-2'] I've been shearching for a way to do this for some days, thanks.
has title: How to modify some characters in an array of strings?
has comment: http://stackoverflow.com/comment/83447961
tagged with: python

http://stackoverflow.com/q/48245175
answer count: 1
has comment: http://stackoverflow.com/comment/83473867
has body: Given an array defined below as: a = np.arange(30).reshape((3, 10) col_index = [[1,2,3,5], [3,4,5,7]] row_index = [2,1] Is it possible to index a[row_index, col_index], so I can do something like a[row_index, col_index] =1, so then a becomes [[0,1,2,3,4,5,6,7,8,9], [10,11,12,1,1,1,16,1,18,19], [20,1,1,1,24,1,26,27,28,29]] So to clarify, in row 2, column 1,2,3, and 5 are set to one, and in row 1, column 3,4,5,7 is also set to 1.
favorite count: 0
type: Question
tagged with: numpy
has title: How to index numpy array with an array
has answer: http://stackoverflow.com/a/48245293
upvote count: 2
tagged with: arrays
downvote count: 0
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48245293

http://stackoverflow.com/a/48200970
has body: Generally, the website fetch data from back-end calling or using third party service. But in this case,the original data you scraped is included in native javascript Statement,then import regex module to help filter out or extract the data;finally, leverage json module to parse and fetch the data you want. var tourcode ={ "id": 24588, "title": "تور مشهد 22 دی 96 (از اصفهان)", "slug": "تور-مشهد-22-دی-96-از-اصفهان", .... "packages": { "bundles": { { "308892": { "id": 308892, "hotels": [ { "id": 1298, "bundle_id": 308892, "link": "https://lastsecond.ir/hotels/1298-mehr-reza", "location_id": 410, "location_name": "مشهد", "name": "Mehr Reza hotel", "grade": { "id": 80, "name": "هتل آپارتمان", "icons": [ "fa-building" ], "count": "0", "singleIcon": " " }, "decoratedGrade": " ", "score": 0, "imageUrl": "https://lastsecond.ir/site/images/placeholder/hotel.svg", "reviewsCount": 0, "decoratedScore": " ", "description": "صبحانه", "service_id": 2, "service": "bb", "serviceName": "B.B", "serviceDesc": "با صبحانه", "ordering": "1" } ], "prices": { "1": { "1": "295000" }, "2": { "1": "370000" }, "3": { "1": "295000" }, "4": { "1": "240000" } } } } ... }} } And I found a nice post about how to Extract Data from Native JS statement for your reference. Assuming operated with scrapy shell $ scrapy shell https://lastsecond.ir/tours/24588-%D8%AA%D9%88%D8%B1-%D9%85%D8%B4%D9%87%D8%AF-22-%D8%AF%DB%8C-96-%D8%A7%D8%B2-%D8%A7%D8%B5%D9%81%D9%87%D8%A7%D9%86 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: scrapybot) .... $ import re $ import json $ jsonstr = re.findall("var tourcode = (.+?);\n",response.body.decode('utf-8'),re.S) $ jsonobj = json.loads(jsonstr[0]) # parse json object here
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/83746593
answers question: http://stackoverflow.com/q/48195079
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83752730

http://stackoverflow.com/comment/120349081
type: Comment
has text: `share` is declared twice.
type: AnswerComment
comment on: http://stackoverflow.com/a/48397051
score: 0

http://stackoverflow.com/a/48245562
has comment: http://stackoverflow.com/comment/83484240
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83474123
type: Answer
has comment: http://stackoverflow.com/comment/83474663
upvote count: 3
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48245364
has body: You can save space and time compressing the boolean array into a bitfield using np.packbits and then np.bincount on the rows to compute blocks of 8 scalar products simultaneously. import numpy as np def setup_data(M, N): return {'B': np.random.randint(0, 2, (M, N), dtype=bool), 'A': np.random.random((M,))} def f_vecmat_mult(A, B, decode=np.array(np.unravel_index(np.arange(256), 8*(2,)))): M, N = B.shape out = [(decode * np.bincount(row, A, minlength=256)).sum(axis=1) for row in np.packbits(B, axis=1).T] if N &amp; 7: out[-1] = out[-1][:N &amp; 7] return np.concatenate(out) def f_direct(A, B): return A @ B import types from timeit import timeit for M, N in [(99, 80), (999, 777), (9999, 7777), (30000, 30000)]: data = setup_data(M, N) ref = f_vecmat_mult(**data) print(f'M, N = {M}, {N}') for name, func in list(globals().items()): if not name.startswith('f_') or not isinstance(func, types.FunctionType): continue try: assert np.allclose(ref, func(**data)) print("{:16s}{:16.8f} ms".format(name[2:], timeit( 'f(**data)', globals={'f':func, 'data':data}, number=100)*10)) except: print("{:16s} apparently failed".format(name[2:])) Sample output: M, N = 99, 80 vecmat_mult 0.12248290 ms direct 0.03647798 ms M, N = 999, 777 vecmat_mult 1.67854790 ms direct 5.68286091 ms M, N = 9999, 7777 vecmat_mult 68.74523309 ms direct 571.34140913 ms M, N = 30000, 30000 vecmat_mult 1345.18991556 ms direct apparently failed
has comment: http://stackoverflow.com/comment/83474195
answers question: http://stackoverflow.com/q/48245364

http://stackoverflow.com/comment/83773440
type: Comment
comment on: http://stackoverflow.com/q/48258692
score: 0
has text: @obgnaw "xx is yy" and "yy is xx" is ok. Not the other one
type: QuestionComment

http://stackoverflow.com/comment/83376362
has text: @sKwa: Oops! Typo fixed now.
comment on: http://stackoverflow.com/q/48197549
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83435452
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48226504
has text: I think it is not so nice copy my solution :(

http://stackoverflow.com/comment/83408473
comment on: http://stackoverflow.com/q/48213476
type: Comment
type: QuestionComment
score: 0
has text: possible dup : https://stackoverflow.com/questions/44834/can-someone-explain-all-in-python

http://stackoverflow.com/comment/106763898
comment on: http://stackoverflow.com/a/48197870
score: 0
type: Comment
type: AnswerComment
has text: If I understand you correctly, you are suggesting that `polymorphic_on` will work on a `Column` with a `ForeignKey` parameter only if the types table exists beforehand.

http://stackoverflow.com/q/48214830
favorite count: 0
has answer: http://stackoverflow.com/a/48214844
score: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/19290762
has body: I am trying to modify all of the elements of the list in Python: magicians = ['harry potter', 'scamander', 'snape'] for magician in magicians: magician = 'the Great ' + magician print(magicians) but it returns the original list: ['harry potter', 'scamander', 'snape'] Can you please kindly explain this to me step-by-step? This may be a very stupid question you have ever seen. I'm truly sorry for that.
type: Question
has answer: http://stackoverflow.com/a/48214905
has title: Python: concatenate string variables of a list
answer count: 2
type: UnansweredQuestion
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83642775
type: Comment
comment on: http://stackoverflow.com/q/48317367
type: QuestionComment
score: 0
has text: Most image viewers work in that way. If the images are not too big, there will be little or no lag. If the images are large, it's obviously impractical to pre-load all the images in a directory, because you'll quickly run out of memory (thumb-nail disk-caches are used to get around that problem). I imagine that some image viewers may use a certain amount of runtime caching for recently viewed full-size images - usually there's a config setting for limiting how much memory the program uses.

http://stackoverflow.com/a/48246649
downvote count: 0
upvote count: 1
has body: You are yet another victim of dynamic typing. When you read in data to your num variables, the variables are treated as strings. When Python compares two strings using the &lt; or &gt; operator, it does so lexicographically -- meaning alphabetically. Here's a few examples. 'apple' &lt; 'orange' //true 'apple' &lt; 'adam' //false '6' &lt; '7' //true as expected '80' &lt; '700' //returns false, as 8 &gt; 7 lexiographically Therefore, you want to convert your input using int(), so &lt; comparisons work as expected. Code num1=int("Enter 3 numbers\n") num2=int(input()) num3=int(input()) if(num1 &gt; num2): if(num1 &gt; num3): print("The greatest number is "+ str(num1)) else: print("the greatest number is "+ str(num3)) else: if(num2 &gt; num3): print("The greatest number is " + str(num2)) else: print("The greatest number is " + str(num3))
has comment: http://stackoverflow.com/comment/83476213
has comment: http://stackoverflow.com/comment/83476222
accepted answer of: http://stackoverflow.com/q/48246615
type: Answer
answers question: http://stackoverflow.com/q/48246615
has comment: http://stackoverflow.com/comment/83476171
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48327646
downvote count: 0
upvote count: 1
tagged with: ip-address
favorite count: 0
score: 1
has title: Python ipwhois ASN Registry Error
has body: I am using ipwhois for the first time. Running the basic usage example with a Google IP address works: from ipwhois import IPWhois obj = IPWhois('74.125.225.229') results = obj.lookup_rdap(depth=1) Any other IP address results in this error: ASNRegistryError Traceback (most recent call last) &lt;ipython-input-62-03afc25be9cd&gt; in &lt;module&gt;() ----&gt; 1 results = obj.lookup_rdap(depth=1) ~\_installed\anaconda\envs\geocode\lib\site-packages\ipwhois\ipwhois.py in lookup_rdap(self, inc_raw, retry_count, depth, excluded_entities, bootstrap, rate_limit_timeout, asn_alts, extra_org_map, inc_nir, nir_field_list, asn_methods, get_asn_description) 306 inc_raw=inc_raw, retry_count=retry_count, asn_alts=asn_alts, 307 extra_org_map=extra_org_map, asn_methods=asn_methods, --&gt; 308 get_asn_description=get_asn_description 309 ) 310 ~\_installed\anaconda\envs\geocode\lib\site-packages\ipwhois\asn.py in lookup(self, inc_raw, retry_count, asn_alts, extra_org_map, asn_methods, get_asn_description) 569 if asn_data is None: 570 --&gt; 571 raise ASNRegistryError('ASN lookup failed with no more methods to ' 572 'try.') 573 ASNRegistryError: ASN lookup failed with no more methods to try. I attempted to switch the lookup method to ARIN with bootstrap=True to no avail. How do I remedy this error?
tagged with: python
tagged with: whois
has comment: http://stackoverflow.com/comment/83689496
has comment: http://stackoverflow.com/comment/83640886
type: Question
has comment: http://stackoverflow.com/comment/83641057
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/83689482
type: UnansweredQuestion

http://stackoverflow.com/q/48255952
has answer: http://stackoverflow.com/a/48256233
type: Question
has comment: http://stackoverflow.com/comment/83494930
score: 19
has comment: http://stackoverflow.com/comment/83494899
has title: f-string with float formatting in list-comprehension
upvote count: 20
has comment: http://stackoverflow.com/comment/83494890
tagged with: python
tagged with: list-comprehension
tagged with: python-3.6
has body: The [f'str'] for string formatting was recently introduced in python 3.6. link. I'm trying to compare the .format() and f'{expr} methods. f ' &lt;text&gt; { &lt;expression&gt; &lt;optional !s, !r, or !a&gt; &lt;optional : format specifier&gt; } &lt;text&gt; ... ' Below is a list comprehension that converts Fahrenheit to Celsius. Using the .format() method it prints the results as float to two decimal points and adds the string Celsius: Fahrenheit = [32, 60, 102] F_to_C = ['{:.2f} Celsius'.format((x - 32) * (5/9)) for x in Fahrenheit] print(F_to_C) # output ['0.00 Celsius', '15.56 Celsius', '38.89 Celsius'] I'm trying to replicate the above using the f'{expr} method: print(f'{[((x - 32) * (5/9)) for x in Fahrenheit]}') # This prints the float numbers without formatting # output: [0.0, 15.555555555555557, 38.88888888888889] # need instead: ['0.00 Celsius', '15.56 Celsius', '38.89 Celsius'] Formatting the float in f'str' can be achieved: n = 10 print(f'{n:.2f} Celsius') # prints 10.00 Celsius Trying to implement that into the list comprehension: print(f'{[((x - 32) * (5/9)) for x in Fahrenheit]:.2f}') # This will produce a TypeError: unsupported format string passed to list.__format__ Is it possible to achieve the same output as was done above using the .format() method using f'str'? Thank you.
has comment: http://stackoverflow.com/comment/83494767
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83494997
answer count: 1
tagged with: string
accepted answer: http://stackoverflow.com/a/48256233
downvote count: 1
tagged with: number-formatting
favorite count: 0

http://stackoverflow.com/comment/83472210
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48201451
has text: @Michael-sqlbot I just recreated the subnet and route table config and that fixed my issue. Thanks for the tip on assigning the private subnets to the functions!
type: Comment

http://stackoverflow.com/q/48235441
tagged with: security
tagged with: browser
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
tagged with: flask
answer count: 1
has body: I'm fairly new to Flask, but I like it so far. I am using the method described in the flask.pocoo.org quickstart guide: from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) @app.route('/') def index(): if 'username' in session: return 'Logged in as %s' % escape(session['username']) return 'You are not logged in' Anyways, this works great, but I am concerned with the following. If I login, I can copy the value of the cookie, bring that value to another computer, and insert them into a newly created cookie on that computer and I am logged in. 1) Is this a legit use case, or is this hard for attackers to do? Obviously not copy and paste, but to get access to that cookie value... 2) Do you know of any good ways prevent this? Thanks!
favorite count: 0
has title: Flask use Session value can be copied to another computer and used. Is this ok?
accepted answer: http://stackoverflow.com/a/48237342
type: Question
has answer: http://stackoverflow.com/a/48237342
tagged with: session
tagged with: python

http://stackoverflow.com/comment/83571140
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48292226
type: AnswerComment
has text: `for i in range(len(mylinks)):`

http://stackoverflow.com/comment/83631893
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48322274
type: Comment
has text: So essentially what you're saying is that I need to create new form field class and then render it to the template each time the user wants to add a new field? What if user has to add 15 fields, I'll need to create 15 classes then! I think this method won't be suitable in scenarios where number of fields required to be generated is large. I feel there should be some elegant way to do this which i'm not aware of

http://stackoverflow.com/comment/83536117
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48276017
type: QuestionComment
has text: `KeyError` when accessing `offspring[mut_col][mut_row]`... the keys you calculate with 'int(random.random()*total)` and `mut_col = int(random.random()*2393)` are incorrect.

http://stackoverflow.com/comment/83680536
comment on: http://stackoverflow.com/a/48330011
type: Comment
score: 0
type: AnswerComment
has text: So the problem is an embedded list inside the JSON on the page: `[{'more_resources': None, 'take_action': None, ... 'event': 'TEDGlobal 2005'}]`. The `json` module wants double quotes.

http://stackoverflow.com/q/48194793
tagged with: xlwt
answer count: 1
has body: I have a code given below using which I want to create an excel file.The code is: #!/usr/bin/python import xlwt wb = xlwt.Workbook() ws = wb.add_sheet('A Test Sheet') orf = {1: ('793', 804, 12, 0), 2: ('952', 1020, 69, 0), 3: ('1222', 1227, 6, 0), 4: ('1309', 1338, 30, 0), 5: ('1921', 1977, 57, 0), 6: ('2164', 2253, 90, 0), 7: ('2305', 2337, 33, 0)} ws.write(0, 0, "NO.") ws.write(0, 1, "Direction") ws.write(0, 2, "Frame") ws.write(0, 3, "Start") ws.write(0, 4, "End") ws.write(0, 5, "Codon numbers") ws.write(0, 6, "ORF Sequence") j = 1 k = 2 for i in orf.items(): numorf=i[0] startorf=orf[numorf][0] stoporf=orf[numorf][1] lengthorf=orf[numorf][2] frameorf=orf[numorf][3] ws.write(j, k, numorf) ws.write(j, k, "5 to 3") ws.write(j, k, frameorf) ws.write(j, k, startorf) ws.write(j, k, stoporf) ws.write(j, k, lengthorf) ws.write(j, k, "ATGACA...ATGCGA") j = j+1 k = k+1 wb.save('example.xls') All part of code is working fine but the part within the loop writing dictionary values is not correct and giving following error, for i,j,k in orf.items(): ValueError: need more than 2 values to unpack I tried to solve it but failed to do so. How columns and row numbers can be managed correctly within a loop, so that file can be created with values from dict? To make it clear I want to put the value of numorf below "NO.","5 to 3" below direction, frameorf below "Frame", startorf below "Start", stoporf below "End",lenghtorf below "Codon numbers" and "ATGACA...ATGCGA" below "ORF Sequence".
type: Question
has title: Creating excel file using values from a dict python
has answer: http://stackoverflow.com/a/48195116
accepted answer: http://stackoverflow.com/a/48195116
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 0

iterable-unpacking
type: Tag
tags question: http://stackoverflow.com/q/48185030
tags question: http://stackoverflow.com/q/48292653
tag name: iterable-unpacking

http://stackoverflow.com/comment/83489346
has text: Thanks cᴏʟᴅsᴘᴇᴇᴅ. I've edited the question a bit to explain further on what I'm looking for in comparison to this solution but this is very close.
comment on: http://stackoverflow.com/q/48253241
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48295246
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/83575038
accepted answer: http://stackoverflow.com/a/48295351
has answer: http://stackoverflow.com/a/48295551
favorite count: 0
type: AnsweredQuestion
has title: How to pass None keyword as command line argument
has answer: http://stackoverflow.com/a/48295351
tagged with: python
upvote count: 17
score: 17
has body: I am trying to pass None keyword as a command line parameter to a script as follows, if I explicity mention Category=None it works but the moment I switch to sys.argv[1] it fails, any pointers on how to fix this? category = None --&gt; works #category=sys.argv[1] --&gt; doesn't work so I tried as below which still didn't work if sys.argv[1].strip()==None: category = None else: category=sys.argv[1].strip() Command line passage: script.py None
answer count: 4
has answer: http://stackoverflow.com/a/70811103
has answer: http://stackoverflow.com/a/48295546
possible better answer: http://stackoverflow.com/a/48295546

http://stackoverflow.com/comment/83446564
type: QuestionComment
has text: @guest271314 even when I define index: JSON.stringify() it does not work
comment on: http://stackoverflow.com/q/48232072
score: 0
type: Comment

http://stackoverflow.com/comment/83497125
has text: @ZachSwanson one thing that I can think of is [`read_sql`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html) this function. If you store your data in SQL database, you can filter out data while reading.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48256436
type: AnswerComment

http://stackoverflow.com/comment/83650628
type: Comment
type: AnswerComment
has text: As I se `weights` must sum to 1. How can I calculated `weights` for this collection `{48: ['48','48','48','48','52','52']}` (48,52)?
score: 0
comment on: http://stackoverflow.com/a/48332060

http://stackoverflow.com/a/48310939
has comment: http://stackoverflow.com/comment/85455760
has comment: http://stackoverflow.com/comment/85454629
score: 10
type: Answer
has comment: http://stackoverflow.com/comment/123745945
has comment: http://stackoverflow.com/comment/101765272
upvote count: 13
accepted answer of: http://stackoverflow.com/q/48234032
has comment: http://stackoverflow.com/comment/85482328
has comment: http://stackoverflow.com/comment/106687247
type: AcceptedAnswer
downvote count: 3
answers question: http://stackoverflow.com/q/48234032
has body: As suggested in the comments, using pytest-xdist will be the solution. The plugin is designed for parallel or distributed execution of tests (even a multi-platform execution is possible), but is well suited to serve your request of running each test in a separate process - you can achieve this with the --forked argument. Disclaimer --forked argument will not work on Windows, because Windows doesn't support the fork-exec model and doesn't ship any replacement for fork(). A quick demo Let's define a fixture that will attempt to turn the eager execution on before running each test: from tensorflow.contrib.eager.python import tfe import pytest @pytest.fixture(scope='function', autouse=True) def eager(request): tfe.enable_eager_execution() This fixture will obviously fail all tests but the first one since the eager execution can be turned only once. With some dummy tests: def test_spam(): assert True def test_eggs(): assert True def test_bacon(): assert True Running plain pytest fails as expected: $ pytest -v ============================== test session starts ================================ platform darwin -- Python 3.6.3, pytest-3.3.1, py-1.5.2, pluggy-0.6.0 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python3.6 cachedir: .cache rootdir: /Users/hoefling/projects/private/stackoverflow/so-48234032, inifile: plugins: forked-0.2, mock-1.6.3, hypothesis-3.44.4 collected 3 items test_spam.py::test_spam PASSED [ 33%] test_spam.py::test_eggs ERROR [ 66%] test_spam.py::test_bacon ERROR [100%] ... E ValueError: Do not call tfe.enable_eager_execution more than once in the same process. Note eager-mode methods such as tfe.run() also call tfe.enable_eager_execution. ... Now install pytest-xdist: $ pip install pytest-xdist and rerun the tests: $ pytest -v --forked ============================== test session starts ================================ platform darwin -- Python 3.6.3, pytest-3.3.1, py-1.5.2, pluggy-0.6.0 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python3.6 cac…

http://stackoverflow.com/comment/124372330
has text: It's not clear to me how do you use make_keras_picklable() to pickle my_model. Can you show an example pl.?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48319358
type: Comment

http://stackoverflow.com/comment/83527025
type: Comment
comment on: http://stackoverflow.com/a/48271405
score: 0
type: AnswerComment
has text: the idea was to have a generic solution - whenever a row in the middle of the group is missing, it should be added accordingly.

http://stackoverflow.com/comment/83476038
has text: What are you actually trying to do? Use of `reload()` in normal code is usually not recommended.
comment on: http://stackoverflow.com/q/48246636
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48227940
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48226647
type: Answer
has body: In your detail view's get_context_data method, you can add the list of categories to the context: class DetailView(generic.DetailView): ... def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ... context['categories'] = Category.objects.all() return context Then in your template for the detail view, you can loop through categories. &lt;ul&gt; {% for category in categories %} &lt;li&gt;{{ category.name }}&lt;/li&gt; {% endfor %} &lt;/ul&gt;
accepted answer of: http://stackoverflow.com/q/48226647
score: 0

http://stackoverflow.com/a/48254103
type: Answer
answers question: http://stackoverflow.com/q/48254034
score: 0
has body: for row in filedata: newdata = replace_all(filedata, d) This will leave you with only the last line of the file in newdata. Maybe newdata += instead? Or write the output lines within the loop. But also, why not use csvfile for both files?

http://stackoverflow.com/comment/83369316
score: 0
comment on: http://stackoverflow.com/q/48194230
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48312922
tagged with: flask
tagged with: git
type: Question
tagged with: python
has body: I added a post-receive git hook on the server side so that a flask app runs after the receive. The script works and the app runs on the server. However, from the client side, when pushing, the process gets stuck at even when the flask app is already running on the server. Pushing to root@192.168.XX.XX:~/api/ Here is the post-receive script. #!/bin/sh # Post-receive hook to make the API # run back up again after the changes are made. python3 ../../api_run.py &amp; exit 0
accepted answer: http://stackoverflow.com/a/48418211
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48418211
score: 0
has title: How do I run a Flask App on a remote server with git hooks post-receive?
answer count: 1

http://stackoverflow.com/q/48204445
type: AnsweredQuestion
score: 0
has title: Tensorflow: bag of words text classification: Cannot feed value of shape
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/48205080
answer count: 1
has body: I've nicked this code here: https://sourcedexter.com/tensorflow-text-classification-python/ to try to predict if a given question is either one of two categories. However, I'm getting the following error: Cannot feed value of shape (1, 1666) for Tensor 'TargetsData/Y:0', which has shape '(?, 2)' Relevant code below: # train_x contains the Bag of words and train_y contains the label/ category train_x = list(training[:,0]) train_y = list(training[:,1]) #reset underlying graph data tf.reset_default_graph() #Build neural network net = tflearn.input_data(shape=[None,len(train_x[0])]) #layer? net = tflearn.fully_connected(net,8) #layer? net = tflearn.fully_connected(net,8) #output layer net = tflearn.fully_connected(net, len(train_y[0]),activation='softmax') net = tflearn.regression(net) #define model and set up tensorboard model = tflearn.DNN(net, tensorboard_dir = 'tflearn_logs') #start training (grad descent algo) model.fit(train_x, train_x, n_epoch = 1000, batch_size=1, show_metric = True) model.save('model.tflearn') How do I fix it?
tagged with: text-classification
has answer: http://stackoverflow.com/a/48205080
tagged with: tensorflow

http://stackoverflow.com/comment/83420554
type: QuestionComment
has text: Thank you for that link patrick, i;ll have a read over it now
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48219349

http://stackoverflow.com/a/48794009
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48241016
accepted answer of: http://stackoverflow.com/q/48241016
has body: Turns out this is due to running on Windows Subsystem for Linux. Apparently, the performance of Firestore is sufficiently slow on WSL (I think due to filesystem operations) that the default timeout is too short.

http://stackoverflow.com/comment/83498696
comment on: http://stackoverflow.com/a/48258054
has text: The `urlopen` function (`urllib2.urlopen` in Python 2, and `urllib.request.urlopen` in Python 3) returns a file-like stream that you can use the `read` function on, which allows you to specify a number of bytes. For example, `urllib2.urlopen(my_url).read(512)` will return the first 512 bytes of `my_url`. However, I'm not certain this will *only* download 512 bytes, or if it will try to download the entire file behind-the-scenes and just return the first 512
type: AnswerComment
score: 3
type: Comment

http://stackoverflow.com/comment/83425844
type: QuestionComment
has text: `np.vectorize` doesn't really help performance, it is implemented as a python for-loop, basically.
type: Comment
comment on: http://stackoverflow.com/q/48222142
score: 0

http://stackoverflow.com/comment/83572903
comment on: http://stackoverflow.com/a/48281485
type: Comment
score: 0
has text: i have providede the data above , i hope that will help you
type: AnswerComment

http://stackoverflow.com/comment/83540211
has text: It's completely okay to sort it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48278369
score: 0

modelica
tag name: modelica
type: Tag
tags question: http://stackoverflow.com/q/48202469

http://stackoverflow.com/q/48174172
answer count: 2
has answer: http://stackoverflow.com/a/48174515
has comment: http://stackoverflow.com/comment/83328403
has title: Need help reshaping multidimensional NumPy array
tagged with: tensorflow
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48174443
tagged with: tensor
has body: In TensorFlow, I have a Tensor, h, of shape (?, 14, 14, 512). I reshape by doing tf.reshape(h, [-1, 196, 512]) Which results in a tensor of shape (?, 196, 512). Perfect. I need to do the same with a numpy array. I have a giant multidimensional NumPy array saved to disk. It looks like this: features = numpy.ndarray([3000, 14, 14, 2048], dtype=np.float32) and need it to be of shape: [3000, 196, 2048] How can I do this transformation such that I do not lose information? Would it be numpy.reshape(features, (3000, 196, 2048))? Or numpy.reshape(features, (-1, 196, 2048))? Do both of these methods of reshaping result in the same result or what is the difference?
type: UnansweredQuestion
tagged with: python
score: 0

http://stackoverflow.com/q/48242125
has comment: http://stackoverflow.com/comment/83466893
has comment: http://stackoverflow.com/comment/83466698
downvote count: 0
accepted answer: http://stackoverflow.com/a/48242557
upvote count: 1
tagged with: python
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83467518
type: Question
has comment: http://stackoverflow.com/comment/83466735
has comment: http://stackoverflow.com/comment/83466781
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/83466868
has comment: http://stackoverflow.com/comment/83466911
score: 1
has answer: http://stackoverflow.com/a/48242557
has title: Python (Pandas) how to retrive number value from csv
has comment: http://stackoverflow.com/comment/83466921
type: AnsweredQuestion
has body: I apologise for the nooby question, however after reading the documentation I still can't read double/int data in from my csv program, I think it's a simple syntactic error but could someone help me out? setting up the data frame: data_frame = pandas.DataFrame(data=data, columns=['time', 'low', 'high', 'open', 'close', 'volume']) data_frame.set_index('time', inplace=True) trying to read the data: change = ((data_frame['high'][time[1]]/data_frame['low'][time[0]])-1)*100 print(str(change)) error log: Traceback (most recent call last): File "webcrawl.py", line 99, in &lt;module&gt; processData() File "webcrawl.py", line 94, in processData change = ((data_frame['high'][time[1]]/data_frame['low'][time[0]])-1)*100 TypeError: 'module' object is not subscriptable

http://stackoverflow.com/a/48285705
has body: To avoid recursion you can save the state in a list, I'll explain better. def steps(source, step, dest): q = Queue() q.put((0,1)) while True: source, ste = q.get() if abs(source) &gt; dest: return sys.maxint if source == dest: return step q.put(source+step+1, step+1) q.put(source-step-1, step+1) Doing so you save in the queue the position to check, and every time you check a position which is not the final one you will add the new 2 position at the end of the queue. This method also garantee that the solution found is the shortest. To improve speed even more you cold save a list of number already visited which will stop the research every time you will find the same number again, this will speed up the task a lot
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83555793
answers question: http://stackoverflow.com/q/48285534
has comment: http://stackoverflow.com/comment/83555909
score: 2
type: Answer

django-rest-auth
tag name: django-rest-auth
tags question: http://stackoverflow.com/q/48314694
type: Tag
tags question: http://stackoverflow.com/q/48260248
tags question: http://stackoverflow.com/q/48257161

http://stackoverflow.com/a/48337123
has comment: http://stackoverflow.com/comment/84400925
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: No need of full ros for accessing the data from topic, But you actually need the Basic ROS. Because ROS topics have a ROS msgs type (msgs you are using in the topic must be installed) and to communicate with the topic ros master is required. You can install the basic ROS not the full version. But then you might need to install the different package required for your appllication.
answers question: http://stackoverflow.com/q/48207331

http://stackoverflow.com/comment/83452058
type: AnswerComment
comment on: http://stackoverflow.com/a/48234720
has text: Okay none of these is working. Thanks for the help, I’ll play around a bit and let you know what I find
type: Comment
score: 0

http://stackoverflow.com/comment/83643644
comment on: http://stackoverflow.com/a/48327367
score: 0
type: Comment
has text: Actually the signature is correct because scipy.stats.pearsonr returns a tuple with 2 values, (r, p), see https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.stats.pearsonr.html
type: AnswerComment

http://stackoverflow.com/q/48285951
answer count: 1
downvote count: 0
score: 4
favorite count: 0
tagged with: unit-testing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48328519
tagged with: python-unittest
tagged with: python
accepted answer: http://stackoverflow.com/a/48328519
type: Question
upvote count: 4
tagged with: mocking
has body: I am using Python's mock library along with unittest. I am writing unit tests for a class that uses a function of an external library in one of its methods. Depending on the case, this function returns different values. So let's say I wanna test class A: from external_library import function_foo class A(object): ... In my test class, in order to use the values returned by the function from the external library, I create a patch, and only import class A after defining the patch. However, I need to use this function in all my test methods, and in each method it returns different values. My test class is as follows: class TestA(TestCase): @patch('external_library.function_foo', side_effect=[1, 2, 3]) def test_1(self, *patches): from module import class A obj = A() ... @patch('external_library.function_foo', side_effect=[1, 1, 2, 2, 3, 3]) def test_2(self, *patches): from module import class A obj = A() ... ... I have 10 tests and only 1 (the first one) passes when I run all of them together, for the rest, I get StopIteration error. However, if I run each one of them individually, they all pass. I have tried using with patch('external_library.function_foo', side_effect=[...]) in each method, but the outcome was the same. I also tried creating only once the patch in the setUp method, starting it, reassigning the side_effect within each method, and stopping in tearDown, but it didn't work. Any ideas on what might work in this case? Thanks!
has title: External library mock patch used in all tests doesnt work when tests run together

http://stackoverflow.com/a/72610599
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48181014
has body: You can not connect stream socket multiple times. One of the connect possible errors is EISCONN. The socket is already connected. This goes for stream sockets. man bind also has this: [EINVAL] The socket is already bound to an address, and the protocol does not support binding to a new address; or the socket has been shut down. Again, this goes for stream sockets. From the man connect: Generally, stream sockets may successfully connect() only once; datagram sockets may use connect() multiple times to change their association. I made emphasis on the important line. stream sockets can not be connected multiple times. datagram sockets can be connected multiple times. Generally speaking, BSD sockets have multiple protocols, types, domains avaible. You shall read documentation for your particular case. P.S Get yourself familiar with the readings that were suggested in the comment to your question. That will explain enough to manipulate socket family of functions.

http://stackoverflow.com/q/48303650
tagged with: python-3.x
answer count: 5
has answer: http://stackoverflow.com/a/48303782
has title: What is the best way to get rid of common substring prefix in Python3?
score: 6
tagged with: python
has body: Let's assume we have string and a list of strings: String: str1 = &lt;common-part&gt; List of strings: [&lt;common-part&gt;-&lt;random-text-a&gt;, &lt;common-part&gt;-&lt;random-text-b&gt;] What is the best (in case of readability and code-purity) to get such a list: [&lt;random-text-a&gt;, &lt;random-text-b&gt;]
upvote count: 7
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48303735
has answer: http://stackoverflow.com/a/48304045
accepted answer: http://stackoverflow.com/a/48303793
has answer: http://stackoverflow.com/a/48303793
tagged with: string
tagged with: substring
possible better answer: http://stackoverflow.com/a/48303735
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48303767

at-command
tag name: at-command
type: Tag
tags question: http://stackoverflow.com/q/48237875

http://stackoverflow.com/a/48249337
has body: In the first iteration of the for loop, i=0. i-1 would equal -1. a[-1] finds the LAST item of "a" so therefore 10+35 is 45. To fix, use range(1,len(a)) as shown to ignore the first item: a=[10,15,20] for i in range(1, len(a)): a[i]=b[i-1]+a[i] This then creates another issue - the second value of a is now 25, not 15. So therefore the last output is 45, not 35 as intended. To fix this, create a duplicate of "a" a=[10,15,20] b=[10,15,20] for i in range(1, len(a)): a[i]=b[i-1]+a[i] Therefore if you were to output a, you would get [10,25,35] as desired.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48249248

http://stackoverflow.com/q/48312057
type: AnsweredQuestion
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/53017626
has body: Hello fellow programmers, I would like to change the min_num error message of a formset. My code creates a formset using an inlineformset_factory: formset_clazz = inlineformset_factory(MyParentModel, MyModel, MyModelForm, can_delete=True, min_num=1, validate_min=True) formset = formset_clazz(data=request.POST) print(formset._non_form_errors) if formset.is_valid(): print("yay!") else: print("nay!") return render(request, "mytemplate.html", {'formset':formset}) In the template I render the non_form_errors: {% if formset.non_form_errors %} &lt;ul&gt; {% for error in form.non_form_errors %} &lt;li&gt; {{ error }} &lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endif %} The min_num validation works as intended and shows the error message Please submit 1 or more forms., when a user removes all forms and submits the formset. My question is: How do I change the error message? From [0] I learned, that it is stored in formset._non_form_errors, but without a way to override the too_few_forms [1] (ctrl-F validate_min) code's message. The BaseFormSet class itself uses ngettext to translate the message, but I do not really want to setup internationalization just for this (or is that easy and straight-forward?). Is there a more convenient way to achieve my goal? [0] Django: Displaying formset errors correctly [1] https://docs.djangoproject.com/en/2.0/_modules/django/forms/formsets/#BaseFormSet
linked to: http://stackoverflow.com/q/2173138
score: 8
has title: Django: Change formset error message(s)
upvote count: 8
favorite count: 0
has answer: http://stackoverflow.com/a/79486225
possible better answer: http://stackoverflow.com/a/79486225
type: Question
has comment: http://stackoverflow.com/comment/89238195
has answer: http://stackoverflow.com/a/53017626
tagged with: django
tagged with: python

http://stackoverflow.com/q/48252840
has comment: http://stackoverflow.com/comment/83488275
favorite count: 0
tagged with: benchmarking
type: Question
has comment: http://stackoverflow.com/comment/83491973
has body: I have an application where I have a list of objects, and I need to create a sub list of those objects for which some property is minimum. I naturally started writing for thing in list: type code, and then wondered whether it would be worth getting my head around these map and filter functions I'd read about from time to time, but ignored to now. The task appears to break down into two stages, finding the minimum, and then creating the sub list. Unless I sorted the list, in which case I could slice the result, if I could think of a quick way to find where to slice it. This is my benchmark code import random import time LEN = 1000000 class Thing(): def __init__(self, data): self.data = data def __repr__(self): return 'thing{}'.format(self.data) things = [] for n in range(LEN): things.append(Thing(random.randrange(2,6))) # minimum by looping startminloop = time.time() mindata = 99 for thing in things: if thing.data&lt;mindata: mindata = thing.data stopminloop = time.time() # map for minimum startmap = time.time() mindata = min(map(lambda x: x.data, things)) stopmap = time.time() # create list by looping startlistloop = time.time() outlist = [] for thing in things: if thing.data==mindata: outlist.append(thing) stoplistloop = time.time() # list comprehension startcomp = time.time() outlist = [x for x in things if x.data==mindata] stopcomp = time.time() # list by filter startfilter = time.time() outlist = list(filter(lambda x: x.data==mindata, things)) stopfilter = time.time() # sort for minimum startsort = time.time() things.sort(key=lambda x: x.data) stopsort = time.time() and I got the following results minimum finding loop 0.07794857025146484 sort 0.22138357162475586 map 0.11729907989501953 list creation loop 0.09957003593444824 comp 0.06798076629638672 filt 0.13345861434936523 I was surprised that map and filter were both significantly slower than the naive looping method. While they are both fewer lines of code, they don't look much clearer to my beginner's eye. I'…
answer count: 0
tagged with: python
type: UnansweredQuestion
has title: Python map and filter, am I missing the point, clarity, speed?
linked to: http://stackoverflow.com/q/1247486
tagged with: filter
tagged with: functional-programming
score: 0
upvote count: 1
duplicate of: http://stackoverflow.com/q/1247486
downvote count: 1

http://stackoverflow.com/comment/83553154
comment on: http://stackoverflow.com/q/48284094
score: 0
has text: `list(itertools.permutations(range(1, 5), 2))` gives `[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]` without the annoying sublists and states what you mean without ambiguity. Then drop those first to while loops entirely. The problem is that you are making a superfluous call to `itertools.combinations` that literally does nothing. You could leave that line out and replace the previous line with `lst = [(i, j)]`. The result would be the same. It made your code hard to read because I expected the line to have meaning.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48178904
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/48179671
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/48179671
possible better answer: http://stackoverflow.com/a/48179217
has comment: http://stackoverflow.com/comment/83338317
has answer: http://stackoverflow.com/a/48179217
has title: Condense similar instances in dataframe while adding the features of each
type: Question
has comment: http://stackoverflow.com/comment/83338494
linked to: http://stackoverflow.com/q/39257147
tagged with: python
has body: I am working on a project using Pandas, and am running into trouble when trying to condense similar objects. I have a dataframe with the columns Product ID, Currency, Price, and Book. There are identical products in the Product ID category, such as X11, X23, X25, and so on. There are 3 instances of each, each with one of 3 currencies, with a price, and with one of 3 Books. I want to have a dataframe where each instance is one product, with whatever books they appear in, and the 4 prices of the 4 currencies contained in each instance. This is an example of what the Dataframe looks like now: df = pd.DataFrame({'Product ID' : ['X11' ,'X11', 'X11', 'X23', 'X23', 'X23', 'X25', 'X25'], 'Currency' : ['USD', 'EUR', 'GBP', 'USD', 'EUR', 'GBP', 'EUR', 'GBP'], 'Price' : [100, 90, 90, 200, 180, 180, 90, 90], 'Book' : ['America', 'Canada', 'Mexico', 'America', 'Canada', 'Mexico', 'Canada', 'Mexico']}) df Book Currency Price Product ID 0 America USD 100 X11 1 Canada EUR 90 X11 2 Mexico GBP 90 X11 3 America USD 200 X23 4 Canada EUR 180 X23 5 Mexico GBP 180 X23 6 Canada EUR 90 X25 7 Mexico GBP 90 X25 Ultimately It will be converted to a JSON file that has all of that data in one instance, however before that happens I need to condense the identical products. See below for an example of what the final JSON converted object will look like. What would be the best way of achieving this? I don't fully understand groupby, as some similar questions have suggested, and I haven't seen a question that answers how to do this. The actual conversion itself shouldn't be too hard once I have identical products only occurring in one instance, but with all of the price and book data. Any help is much appreciated.
has comment: http://stackoverflow.com/comment/83337893

http://stackoverflow.com/a/48253573
accepted answer of: http://stackoverflow.com/q/48253441
type: Answer
has comment: http://stackoverflow.com/comment/131893083
answers question: http://stackoverflow.com/q/48253441
has body: This is clearly stated in the sympy manual, here: https://docs.sympy.org/latest/guides/assumptions.html#id28 In particular, the table lists "complex" as an implication of "real" This makes sense from a Mathematical point of view. These "assumptions" are meant to represent attributes of the symbol, in the mathematical sense. So if a number is a real, that means it belongs in the set of all Reals, which is a subset of the Complex plane. Thus, every real is a complex, and sympy adhers to this. You should be fine with Real=True.
has comment: http://stackoverflow.com/comment/83489879
type: AcceptedAnswer
downvote count: 0
score: 8
upvote count: 8

http://stackoverflow.com/q/48236881
has answer: http://stackoverflow.com/a/48236967
tagged with: image-thresholding
tagged with: opencv
score: 3
has title: How to obtain an image's single colour channel without using the split function in OpenCV Python?
tagged with: python
has body: I'd like to highlight a hand for real-time gesture recognition. I observed that the image of a hand gets highlighted differently for different colour channels using the cv2.imsplit function. But this split function is very costly in terms of time. I'm not able to perform the same functionality using Numpy indexing (as given on the official page)
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/48284874
downvote count: 2
upvote count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83456352
tagged with: gesture-recognition

http://stackoverflow.com/q/48186624
has body: I want to calculate the Spearman and/or Pearson Correlation between two columns of a DataFrame, using a rolling window. I have tried df['corr'] = df['col1'].rolling(P).corr(df['col2']) (P is the window size) but i don't seem to be able to define the method. (Adding method='spearman' as argument produces error: File "main.py", line 29, in __init__ _df['corr'] = g['col1'].rolling(P).corr(g['col2'], method = corr_function) File "~\Python36\lib\site-packages\pandas\core\window.py", line 1287, in corr **kwargs) File "~\Python36\lib\site-packages\pandas\core\window.py", line 1054, in corr _get_corr, pairwise=bool(pairwise)) File "~\Python36\lib\site-packages\pandas\core\window.py", line 1866, in _flex_binary_moment return f(X, Y) File "~\Python36\lib\site-packages\pandas\core\window.py", line 1051, in _get_corr return a.cov(b, **kwargs) / (a.std(**kwargs) * b.std(**kwargs)) File "~\Python36\lib\site-packages\pandas\core\window.py", line 1280, in cov ddof=ddof, **kwargs) File "~\Python36\lib\site-packages\pandas\core\window.py", line 1020, in cov _get_cov, pairwise=bool(pairwise)) File "~\Python36\lib\site-packages\pandas\core\window.py", line 1866, in _flex_binary_moment return f(X, Y) File "~\Python36\lib\site-packages\pandas\core\window.py", line 1015, in _get_cov center=self.center).count(**kwargs) TypeError: count() got an unexpected keyword argument 'method' To be fair, i wasn't expecting this to work, since reading the documentation, there is no mention that rolling.corr supports methods... Any suggestions on how to do this, taking into account that the dataframe is quite big (>10M rows)?
accepted answer: http://stackoverflow.com/a/48211159
has answer: http://stackoverflow.com/a/48211159
type: AnsweredQuestion
tagged with: correlation
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
score: 9
type: Question
has title: Pandas Rolling window Spearman correlation
upvote count: 9
tagged with: rolling-computation
tagged with: python

http://stackoverflow.com/comment/83586714
type: Comment
comment on: http://stackoverflow.com/a/48300623
score: 0
type: AnswerComment
has text: Sorry, I was being stupid. It's working now! I forgot to actually go through the register function again haha. You have helped me so much! Thank you!!

http://stackoverflow.com/q/48224794
has answer: http://stackoverflow.com/a/48225238
has body: I'm using python. I've got a text file that has the following format: ########### text lines ########### text lines ########### text lines ########### I want to run an algorithm for each segment found between two "######" lines. How do I reference the text lines between two "######" lines. The number of lines between two "######" lines is not fixed. thanks
tagged with: python
has title: isolate and work with certain lines in text file
has answer: http://stackoverflow.com/a/48224950
has answer: http://stackoverflow.com/a/48226233
accepted answer: http://stackoverflow.com/a/48224975
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48224975
has answer: http://stackoverflow.com/a/48225231
possible better answer: http://stackoverflow.com/a/48224950
type: Question
has comment: http://stackoverflow.com/comment/83431212
answer count: 5

http://stackoverflow.com/comment/83554539
score: 0
type: Comment
type: QuestionComment
has text: Look into groupby. https://pandas.pydata.org/pandas-docs/stable/groupby.html
comment on: http://stackoverflow.com/q/48284385

http://stackoverflow.com/a/48246479
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48246460
upvote count: 5
score: 5
type: Answer
has body: Python allows operator overloading. So you'd best consult the documentation for your particular use case - here its a boolean mask as the comments have pointed out, but python allows you to use any operator to do almost anything you like. For example, you could have a class that uses &gt; to decide if one array is longer than another array if you implemented your own array class. The best thing to do would be to search the documentation for your particular use case and look for operators. Further Clarification Imagine I made a class called train, that just holds a string, and I wanted to use &gt; to stick two trains together. (looks like it would be nice to do that :P) class Train: def __init__(self, cargo): self.cargo = cargo def __call__(self): print("__{0}__".format(self.cargo)) def __gt__(self, another): self.cargo = "{0}__{1}".format(self.cargo, another.cargo) # Make two trains a = Train("check") b = Train("me") a() b() # Join the trains and print again a &gt; b a() b() Which would output __check__ __me__ __check__me__ __me__ Notice that I didn't use this to return true or false, and I didn't even make the operator return anything. It would be important for me to document this in any documentation I provide to tell you what my intended use case for the &gt; symbol is for my class. This is a hugely useful feature that gets used all the time (eg multiplication in the numpy library - python can't natively multiply numpy.arrays).
answers question: http://stackoverflow.com/q/48246460
downvote count: 0

http://stackoverflow.com/a/48250131
has comment: http://stackoverflow.com/comment/83533439
upvote count: 5
type: Answer
has body: You can list and extract the contents of a DMG file with 7zip - the website is here. On macOS, 7zip can be installed with homebrew using: brew install p7zip Then if you have a DMG file, you can list the contents with: 7z l SomeDisk.dmg Sample Output 7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21 p7zip Version 16.02 (locale=utf8,Utf16=on,HugeFiles=on,64 bits,8 CPUs x64) ... ... Modified = 2018-01-14 13:28:17 Date Time Attr Size Compressed Name ------------------- ----- ------------ ------------ ------------------------ 2018-01-14 13:28:16 D.... MyFunkyDMG 2018-01-14 13:28:16 D.... MyFunkyDMG/.HFS+ Private Directory Data 2018-01-14 13:28:17 ..... 524288 524288 MyFunkyDMG/.journal 2018-01-14 13:28:16 ..... 4096 4096 MyFunkyDMG/.journal_info_block 2017-08-27 13:50:45 ..... 255 4096 MyFunkyDMG/client.py 2017-08-27 13:49:22 ..... 356 4096 MyFunkyDMG/server.py 2018-01-14 13:28:16 D.... MyFunkyDMG/[HFS+ Private Data] ------------------- ----- ------------ ------------ ------------------------ 2018-01-14 13:28:17 528995 536576 4 files, 3 folders Then you can extract, say to a new directory called FRED with: 7z x -oFRED SomeDisk.dmg A benefit of using 7zip is that the disk doesn't suddenly flash up on your Desktop as being mounted.
answers question: http://stackoverflow.com/q/48247534
score: 5
downvote count: 0

http://stackoverflow.com/comment/83643421
type: QuestionComment
has text: Do you want to filter Toll objects based on driver's invoice number and with form date less than today?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48327906

http://stackoverflow.com/q/48188716
has title: groupby apply operation of all the other keys
favorite count: 0
has answer: http://stackoverflow.com/a/48188804
type: Question
has answer: http://stackoverflow.com/a/48189203
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48189389
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83383046
has body: Given a pandas dataframe df I can do df.groupby('Age').apply(lambda x: x['ReadingAbility'].mean()) in order to get the average reading ability for each age. Now suppose I want the average reading ability for all the ages except age=k I can do: mu_other_ages = {} for age in df['Age'].unique(): mu_other_ages[age] = df[df['Age'] != age]['ReadingAbility'].mean() This is somehow the opposite of groupby + apply. Is there any shortcut to achieve the same result more efficiently ? See the following example: In [52]: d = pd.DataFrame([[1,10], [2,4],[1, 9], [2,3]], columns=['Age', 'ReadingAbility']) In [53]: In [53]: d Out[53]: Age ReadingAbility 0 1 10 1 2 4 2 1 9 3 2 3 In [54]: d.groupby('Age').apply(lambda x: x['ReadingAbility'].mean()) Out[54]: Age 1 9.5 2 3.5 dtype: float64 In the cases there are only 2 different Age values tahtn the results should just be inverted as: 2=9.5 and 1=3.5 while for more classes the value for Age=k should be : df[df['Age'] != k]['ReadingAbility'].mean() Just to clarify the expected result for this example is: 2=9.5 and 1=3.5
answer count: 3
tagged with: pandas
score: 1
tagged with: group-by
tagged with: python

http://stackoverflow.com/comment/83371418
has text: don't use regexes to parse XML/HTML. use a proper parser like `lxml`
type: QuestionComment
comment on: http://stackoverflow.com/q/48195276
score: 1
type: Comment

http://stackoverflow.com/comment/83566984
type: Comment
comment on: http://stackoverflow.com/a/48283709
score: 0
type: AnswerComment
has text: This is perfect, thank you! Could you ask why you used sp.norm.ppf(x_data) for the regression?

http://stackoverflow.com/comment/83348933
has text: @NullPointer Did not see that there was another change. Fixed.
type: AnswerComment
comment on: http://stackoverflow.com/a/48183967
score: 1
type: Comment

http://stackoverflow.com/a/50110951
type: Answer
accepted answer of: http://stackoverflow.com/q/48256565
answers question: http://stackoverflow.com/q/48256565
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: using TkAgg it works: import matplotlib matplotlib.use('TkAgg') import numpy as np import matplotlib.pyplot as plt my_random = np.random.random(5) plt.plot(my_random) plt.show()
score: 1

sudo
tags question: http://stackoverflow.com/q/48330020
type: Tag
tag name: sudo

http://stackoverflow.com/comment/83562045
type: QuestionComment
score: 0
has text: @Adam if it works, great, but did you try it out before adding the PYTHONPATH line? By commenting out that PATH line, it *should* allow you to use the version of Python already installed on the system, and that *should* mean that pip, and module searching, behave as expected. But I don't know for sure.
type: Comment
comment on: http://stackoverflow.com/q/48236030

http://stackoverflow.com/q/48175870
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83331708
duplicate of: http://stackoverflow.com/q/21423158
has comment: http://stackoverflow.com/comment/83331469
score: 0
has comment: http://stackoverflow.com/comment/83331585
type: Question
tagged with: seaborn
linked to: http://stackoverflow.com/q/21423158
has comment: http://stackoverflow.com/comment/83349302
tagged with: data-visualization
has body: I have a timestamp column which I want to plot against, say, a name column which has several different names. But because my timestamps are within 1 day, my plot looks like this when I use sns.swarmplot(x="name", y='datetime', data=dataset); I know how to change ylim or set_yscale to set the y-axis range from Jan 18 to Jan 19 (since all the values lie in Jan 19) but to scale it more, is there any way to set it over a few hours on the same day? Say, from 12am to 5pm of Jan 19?
has comment: http://stackoverflow.com/comment/83353031
tagged with: matplotlib
answer count: 0
has title: Changing scale of seaborn plots for timestamp data

http://stackoverflow.com/comment/83547255
type: Comment
comment on: http://stackoverflow.com/a/48279403
score: 0
type: AnswerComment
has text: yea i deleted my comment because i made a mistake earlier. got it working now

http://stackoverflow.com/comment/83490167
score: 0
type: Comment
has text: Long story short, it can not be done in plane linear time of `O(n)`
type: AnswerComment
comment on: http://stackoverflow.com/a/48253666

http://stackoverflow.com/a/48270239
answers question: http://stackoverflow.com/q/48270191
has comment: http://stackoverflow.com/comment/83545915
score: 10
type: Answer
has comment: http://stackoverflow.com/comment/83545901
has comment: http://stackoverflow.com/comment/83534124
accepted answer of: http://stackoverflow.com/q/48270191
type: AcceptedAnswer
has body: From the locale module background documentation: Initially, when a program is started, the locale is the C locale, no matter what the user’s preferred locale is. You need to explicitly set the locale using locale.setlocale(); use the empty string to indicate that the user configuration needs to be used: locale.setlocale(locale.LC_TIME, '') This is standard behaviour; the underlying C-level locale system explicitly starts in the C locale regardless of environment variables, as you can't assume that the current program actually wants or needs to honour user settings.
downvote count: 0
upvote count: 10

http://stackoverflow.com/a/48323568
has comment: http://stackoverflow.com/comment/102905053
has comment: http://stackoverflow.com/comment/83633899
has comment: http://stackoverflow.com/comment/83655684
has comment: http://stackoverflow.com/comment/83634777
type: Answer
has comment: http://stackoverflow.com/comment/83634164
has comment: http://stackoverflow.com/comment/83632438
has comment: http://stackoverflow.com/comment/83648033
score: 119
has comment: http://stackoverflow.com/comment/83634635
has comment: http://stackoverflow.com/comment/83642129
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48323493
has body: You have accidentally written a syntactically correct variable annotation. That feature was introduced in Python 3.6 (see PEP 526). Although a variable annotation is parsed as part of an annotated assignment, the assignment statement is optional: annotated_assignment_stmt ::= augtarget ":" expression ["=" expression] Thus, in context["a"]: 2 context["a"] is the annotation target 2 is the annotation itself context["a"] is left uninitialised The PEP states that "the target of the annotation can be any valid single assignment target, at least syntactically (it is up to the type checker what to do with this)", which means that the key doesn't need to exist to be annotated (hence no KeyError). Here's an example from the original PEP: d = {} d['a']: int = 0 # Annotates d['a'] with int. d['b']: int # Annotates d['b'] with int. Normally, the annotation expression should evaluate to a Python type -- after all the main use of annotations is type hinting, but it is not enforced. The annotation can be any valid Python expression, regardless of the type or value of the result. As you can see, at this time type hints are very permissive and rarely useful, unless you have a static type checker such as mypy.
has comment: http://stackoverflow.com/comment/83643632
has comment: http://stackoverflow.com/comment/83662906
has comment: http://stackoverflow.com/comment/83635332
upvote count: 119
answers question: http://stackoverflow.com/q/48323493

http://stackoverflow.com/a/48273543
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48273472
has comment: http://stackoverflow.com/comment/83646943
has comment: http://stackoverflow.com/comment/83531465
type: Answer
has comment: http://stackoverflow.com/comment/83530866
has comment: http://stackoverflow.com/comment/83530790
has comment: http://stackoverflow.com/comment/83530895
has body: This site gets the information displayed via JSON API requests like <a href="https://www.quintoandar.com.br/api/search?q=(and%20vagas:%271%27(and%20area:[20,75](and%20custo:[500,4400]tipo:%27Apartamento%27)))&amp;fq=local:[%27-23.307011585653612,-46.728409802832005%27,%27-23.632637895951785,-46.53820899716794%27]&amp;return=id,foto_capa,aluguel,area,quartos,custo,photos,endereco,regiao_nome&amp;size=12&amp;q.parser=structured&amp;expr.distance=floor(haversin(-23.4698247408027,-46.63330939999997,local.latitude,local.longitude))&amp;expr.rank=relevance_score-(10000*distance)&amp;sort=rank%20desc&amp;start=0" rel="nofollow noreferrer">this one. It is in fact much easier to parse than HTML, e.g.: url = "some url constructed by substituting chunks in the URL quoted above" data = requests.get(url).json() for hit in data["hits"]["hit"]: """ hit is an object like this: {u'fields': {u'aluguel': u'1100', u'area': u'58', u'custo': u'1768', u'endereco': u'Rua Mariquinha Viana', u'foto_capa': u'capa892812990657_7908319390783DSC1351.JPG', u'id': u'892812990', u'photos': [u'892812990-657.7908319390783DSC1351.JPG', u'892812990-262.59010615240265DSC1352.JPG', u'892812990-981.8163710707928DSC1354.JPG', u'892812990-451.7013311422439DSC1355.JPG', u'892812990-173.347171880453DSC1356.JPG'], u'quartos': u'2', u'regiao_nome': u'Santana'}, u'id': u'892812990'} """ Use Developer Tools in your browser (opened by F12) to check for network activity.
score: 0
accepted answer of: http://stackoverflow.com/q/48273472

http://stackoverflow.com/comment/83336587
comment on: http://stackoverflow.com/q/48178002
type: Comment
has text: You need to reduce the indentation of all of the lines after `h = HeadlineRetriever()` as well.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83395472
has text: Have you tried to pass the `create_order()` function a `reverse` object? something like: `from django.urls import reverse` `redirect_url = reverse('administrator:order_waiting_list')`
type: AnswerComment
comment on: http://stackoverflow.com/a/48206846
score: 0
type: Comment

http://stackoverflow.com/comment/83499059
has text: This is perfect... except I want dots, not lines. I'm so lost in this code right now I'm not even sure how to do that. I assumed plt.plot(data.date, data.time, '.') would be sufficient, but that plots dots *and* lines. I'm sure I'll sort through this and understand it better at some point. Thank you again for your very useful help!
score: 0
comment on: http://stackoverflow.com/a/48257654
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48229906
has title: DRF annotate Count on many-to-many through table gives more occurrences than when you use _set.all().count()
answer count: 1
tagged with: django
tagged with: python
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/83460914
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48265133
has body: I have these models: class Topic(BaseModel): name = models.CharField(max_length=60) public_name = models.CharField(max_length=60, blank=True, null=True) class Content(BaseModel): title = models.CharField(max_length=120) series = models.CharField(max_length=120, blank=True, null=True) season = models.CharField(max_length=45, blank=True, null=True) episode = models.CharField(max_length=45, blank=True, null=True) tags = models.ManyToManyField(tags_models.Tag, through='ContentHasTags') topics = models.ManyToManyField(topics_models.Topic, through='ContentHasTopics') class ContentHasTopics(BaseModel): content = models.ForeignKey(Content) topic = models.ForeignKey(topics_models.Topic) order = models.IntegerField(default=99) class Meta: unique_together = ('content', 'topic',) ordering = ('order',) The problem I have is that if I use the next function: @property def get_contents_count(self): return self.contenthastopics_set.all().count() In many cases I have 7 as a result (and is true), but when I use the annotate query like this for Django Rest Framework (in the viewset), it gives me like 28 results, some other topics have 5 contents using the _set.all().count(), but annotate gives me 10 as a result, and so on. queryset = models.Topic.objects.all().annotate( themes_count=Count('themehastopics') ).annotate( contents_count=Count('contenthastopics') ).annotate( tags_count=Count('topichastags') ) How is the right way to annotate the query with the Count correctly added?
has answer: http://stackoverflow.com/a/48265133
type: Question
has comment: http://stackoverflow.com/comment/83450494

http://stackoverflow.com/a/48323639
downvote count: 0
has comment: http://stackoverflow.com/comment/83641920
has comment: http://stackoverflow.com/comment/83658418
has comment: http://stackoverflow.com/comment/83658254
answers question: http://stackoverflow.com/q/48323576
has comment: http://stackoverflow.com/comment/83642199
accepted answer of: http://stackoverflow.com/q/48323576
has body: Here's one approach with views - # https://stackoverflow.com/a/45313353/ @Divakar def view1D(a, b): # a, b are arrays a = np.ascontiguousarray(a) b = np.ascontiguousarray(b) void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[1])) return a.view(void_dt).ravel(), b.view(void_dt).ravel() X1D, Y1D = view1D(X,Y) out = np.in1d(X1D, Y1D).sum() == len(Y1D) Sample run - In [66]: X = np.random.rand(1000,1000) In [67]: Y = X [[3,7,921],:] In [68]: X1D, Y1D = view1D(X,Y) In [69]: np.in1d(X1D, Y1D).sum() == len(Y1D) Out[69]: True In [70]: Y[2] = 1 In [71]: X1D, Y1D = view1D(X,Y) In [72]: np.in1d(X1D, Y1D).sum() == len(Y1D) Out[72]: False Benchmarking and alternatives The proposed way seems pretty fast - In [73]: %timeit np.in1d(X1D, Y1D).sum() == len(Y1D) 10000 loops, best of 3: 39.6 µs per loop We can also do - np.in1d(Y1D, X1D).all(), but I think this would iterate through the elements of X1D for a match in Y1D. Now, in our case, it seems X1D i.e. X is a larger array, so this would be computationally more heavy than using np.in1d(X1D, Y1D) as with the earlier proposed one - In [84]: %timeit np.in1d(Y1D, X1D) 100 loops, best of 3: 5.82 ms per loop In [85]: %timeit np.in1d(X1D, Y1D) 10000 loops, best of 3: 34.1 µs per loop Hence, the alternative solution would be slower - In [79]: %timeit np.in1d(Y1D, X1D).all() 100 loops, best of 3: 5.99 ms per loop
has comment: http://stackoverflow.com/comment/83641779
has comment: http://stackoverflow.com/comment/83658380
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83644614
type: AcceptedAnswer

http://stackoverflow.com/comment/94619375
type: Comment
comment on: http://stackoverflow.com/a/48198192
type: AnswerComment
has text: good to know u find a solution. i know nothing about the specific dev commands u r using. :)
score: 0

http://stackoverflow.com/q/48199784
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48273834
has title: MXNet ML lib C++ segmentation fault on OS X
has body: I have a problem with Apache MXNet machine learning library on OS X. I have been able to run Python version of Lenet, convolutional neural network. I installed these with pip under both Anaconda Python 2.7 and 3.6. conda create -n mxnet27 python=2.7 conda info --envs source activate mxnet27 conda list pip install mxnet==0.12.1 But when I run C++ example files cpp-package/example/lenet.cpp I get the this segfault: Segmentation fault: 11 This is the place in the code where the segfault is thrown: Symbol conv1 = Convolution("conv1", data, conv1_w, conv1_b, Shape(5, 5), 20); I get similar segfault for the other C++ examples. I have built MXNet on OS X 10.13.2 I disabled as many libraries as possible, e.g. OpenCV and CUDA. On Simon Corston-Oliver suggestion I upgraded to MXNet 1.0.0, but that version did not compile with Clang on OS X. Error message: operator_tune.h:150:36: note: add an explicit instantiation declaration to suppress this warning if 'mxnet::op::OperatorTuneByType&lt;float&gt;::tuning_mode_' is explicitly instantiated in another translation unit /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/unordered_map:601:15: error: object of type 'std::__1::pair&lt;int, mxnet::test::perf::TimingInstrument::Info&gt;' cannot be assigned because its copy assignment operator is implicitly deleted
tagged with: mxnet
tagged with: python
tagged with: macos
tagged with: c++
type: Question
has comment: http://stackoverflow.com/comment/83553838
answer count: 2
has answer: http://stackoverflow.com/a/48243321

http://stackoverflow.com/comment/83628876
has text: So, you are looking for something like [`pandas.cumsum()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.cumsum.html)?
score: 0
comment on: http://stackoverflow.com/q/48319706
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83540667
score: 0
comment on: http://stackoverflow.com/q/48263043
has text: I thought there could be an easier method to do this as in QT there is it easily accessible. Thank you for the idea. I started with getting the order of the visible windows and their rectangle (with `GetWindowRect`) so now I have this data. How can I access the `IntersectRect` within Python using the ctypes?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48311177
favorite count: 0
type: Question
tagged with: graph
tagged with: python-3.x
tagged with: dot
has title: Dot file viewer for live updates from python (Through GraphViz)
has body: I'm trying to find a way to visualize a directed graph of nodes in a way such that I can run a script in Python that modifies the graph, and in turn, outputs a new graph. The goal is really to be able to programmatically add and remove edges from the graph in real time. My current implementation is using GraphViz and Python 3.6 on a Windows box, and outputting it into a .dot file. I found a viewer online under a Github project by the name of "gvuv", but it doesn't support Python 3.6. My graph is currently defined by a dictionary of sets, where each key in the dictionary is a node, and each value is a set containing all nodes with a directed edge. If anyone has a different way of viewing this information, please let me know as well. Example graph: graph = { "a" : set("c"), "b" : set("c", "e"), "c" : set("a", "b", "d", "e"), "d" : set("c"), "e" : set("c", "b"), "f" : set() }
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48321922
tagged with: python
tagged with: graphviz
has answer: http://stackoverflow.com/a/48311836
score: 2
upvote count: 2
answer count: 2
downvote count: 0

http://stackoverflow.com/q/48324831
type: UnansweredQuestion
has body: Is there a simple way (or a library available) to read the data in a ".map" file extension document preferably with Python (or in R)? I am working with a modelling tool in python (PCRaster) that writes maps with the .map file extension. Interestingly however, I have not found a python library that can open and study these files. Cheers, A similar question is made here, unfortunately unanswered Here a .txt file is converted to .map, but can't see how to reverse this Here is a list of uses cases from Wikipedia for the .map file format
tagged with: python
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/83635823
score: 2
has answer: http://stackoverflow.com/a/49253329
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/40877629
favorite count: 0
linked to: http://stackoverflow.com/q/24393424
type: Question
has title: How to read or convert a .MAP File Extension document with python?
upvote count: 2

http://stackoverflow.com/a/48174131
score: 7
type: Answer
answers question: http://stackoverflow.com/q/48173746
type: AcceptedAnswer
downvote count: 0
upvote count: 7
accepted answer of: http://stackoverflow.com/q/48173746
has comment: http://stackoverflow.com/comment/83328812
has body: %b is locale dependent. Your system is set to a locale other than English or C, and thus the month names don't match. To see the supported month names in your current locale, run: &gt;&gt;&gt; import calendar &gt;&gt;&gt; print([calendar.month_abbr[i].lower() for i in range(13)]) Set your locale back to C or English before parsing English month names. You only need to do this for the LC_TIME category: import locale locale.setlocale(locale.LC_TIME, 'C') For example, in a spanish locale, your date can't be parsed: &gt;&gt;&gt; import datetime &gt;&gt;&gt; import calendar &gt;&gt;&gt; with calendar.different_locale('es_ES'): ... print([calendar.month_abbr[i].lower() for i in range(13)]) ... datetime.datetime.strptime("Jan 08, 2018 07:04 PM UTC", '%b %d, %Y %I:%M %p %Z') ... ['', 'ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic'] Traceback (most recent call last): File "&lt;stdin&gt;", line 3, in &lt;module&gt; File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/_strptime.py", line 565, in _strptime_datetime tt, fraction = _strptime(data_string, format) File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/_strptime.py", line 362, in _strptime (data_string, format)) ValueError: time data 'Jan 08, 2018 07:04 PM UTC' does not match format '%b %d, %Y %I:%M %p %Z' but in the default C locale parsing succeeds: &gt;&gt;&gt; with calendar.different_locale('C'): ... print([calendar.month_abbr[i].lower() for i in range(13)]) ... datetime.datetime.strptime("Jan 08, 2018 07:04 PM UTC", '%b %d, %Y %I:%M %p %Z') ... ['', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] datetime.datetime(2018, 1, 8, 19, 4) I used the undocumented, internal calendar.different_locale() context manager to temporarily change the LC_TIME locale. It sets the desired locale on entering the context, and on exit it restores the old locale again, using the above locale.setlocale(local…

http://stackoverflow.com/comment/83378475
comment on: http://stackoverflow.com/q/48197173
has text: @DanielPryden: It's pass-by-value if you go by the Java "pass by value but you have to keep in mind that the value you're passing is a reference, not the actual object" terminology, but calling that "pass by value" without any qualification or explanation is more confusing than helpful, and when you add the explanation, the "pass by value" part doesn't really add to the explanation.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83546771
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48281499
type: AnswerComment
has text: OK, so if use my code there is no `NaN`s in last row?

http://stackoverflow.com/comment/83587035
has text: @jdehesa, graph is just a different representation of the data. Of course, our graph is not an arbitrary, but I can't prove that it belongs to one of the special cases https://en.wikipedia.org/wiki/Clique_problem#Special_classes_of_graphs, maybe someone can.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48300032
type: AnswerComment

http://stackoverflow.com/comment/83640201
type: Comment
comment on: http://stackoverflow.com/a/48327277
type: AnswerComment
has text: Can I remove the function and do it without def??
score: 0

http://stackoverflow.com/comment/83477438
type: Comment
type: QuestionComment
has text: This is really basic stuff which most tutorials out there will teach you. You just have to put a for loop inside the body of another for loop. I also recommend creating a list filled with `pygame.Rect`s, because they can be used for the collision detection, and then just loop over this list and pass the rects to `pygame.draw.rect` to draw them.
comment on: http://stackoverflow.com/q/48244479
score: 1

http://stackoverflow.com/comment/83349483
score: 0
type: Comment
has text: OK I understood. Thanks Vivek.
type: QuestionComment
comment on: http://stackoverflow.com/q/48183271

http://stackoverflow.com/a/48257936
has comment: http://stackoverflow.com/comment/83499394
has comment: http://stackoverflow.com/comment/83498381
has comment: http://stackoverflow.com/comment/83498896
score: 12
upvote count: 12
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83499282
accepted answer of: http://stackoverflow.com/q/48257889
has comment: http://stackoverflow.com/comment/83499058
has comment: http://stackoverflow.com/comment/83499236
answers question: http://stackoverflow.com/q/48257889
has comment: http://stackoverflow.com/comment/83500409
has body: I think you can use drop_duplicates. If want check some column(s) and keep first rows if dupe: newDF = df2.drop_duplicates('student_name') print(newDF) student_name test_score 0 Miller 76.0 1 Jacobson 88.0 2 Ali 84.0 3 Milner 67.0 4 Cooze 53.0 5 Jacon 96.0 6 Ryaner 64.0 7 Sone 91.0 8 Sloan 77.0 9 Piger 73.0 10 Riani 52.0 And thank you, @cᴏʟᴅsᴘᴇᴇᴅ for another solution: df2[~df2.student_name.duplicated()] But if want check all columns together for dupes, keep first rows: newDF = df2.drop_duplicates() print(newDF) student_name test_score 0 Miller 76.0 1 Jacobson 88.0 2 Ali 84.0 3 Milner 67.0 4 Cooze 53.0 5 Jacon 96.0 6 Ryaner 64.0 7 Sone 91.0 8 Sloan 77.0 9 Piger 73.0 10 Riani 52.0 11 Ali NaN EDIT by new sample - remove duplicates and sort by both columns: newDF = df2.drop_duplicates().sort_values(['student_name', 'test_score']) print(newDF) student_name test_score 2 Ali 74 1 Miller 75 0 Miller 76 EDIT1: If want replace dupes by first column by NaNs: newDF = df2.drop_duplicates().sort_values(['student_name', 'test_score']) newDF['student_name'] = newDF['student_name'].mask(newDF['student_name'].duplicated()) print(newDF) student_name test_score 2 Ali 74 1 Miller 75 0 NaN 76 EDIT2: More general solution: newDF = df2.sort_values(df2.columns.tolist()) .reset_index(drop=True)‌ ​.apply(lambda x: x.drop_duplicates())
has comment: http://stackoverflow.com/comment/83499216
has comment: http://stackoverflow.com/comment/83499384
type: Answer
has comment: http://stackoverflow.com/comment/83499315

http://stackoverflow.com/comment/83455051
type: AnswerComment
comment on: http://stackoverflow.com/a/48236084
score: 0
type: Comment
has text: The important part in my answer is "your code can't be reproduced" ;). Moreover `len()` will always return an `int` afaik, so the comment in your code is unclear. @M472's answer might be what you are looking for, though.

http://stackoverflow.com/comment/83465154
type: Comment
comment on: http://stackoverflow.com/q/48241274
type: QuestionComment
has text: Just tested according to the comments above. See this link with the results https://repl.it/@vperezher/TriangularWornUpupa
score: 0

http://stackoverflow.com/comment/83376910
type: Comment
comment on: http://stackoverflow.com/a/48197696
type: AnswerComment
score: 0
has text: Yes... this will work within foo, which I said I know, but my question is asking how I can get the execution arguments from foo IN logger

http://stackoverflow.com/a/48291127
upvote count: 13
has body: You can use any to check if any column in the row contains data: for rowdata in reader: # how to check here? if any(x.strip() for x in rowdata): dataSet.append(rowdata)
type: AcceptedAnswer
downvote count: 0
score: 13
has comment: http://stackoverflow.com/comment/106818937
has comment: http://stackoverflow.com/comment/83570100
has comment: http://stackoverflow.com/comment/106827126
answers question: http://stackoverflow.com/q/48291093
has comment: http://stackoverflow.com/comment/106818882
type: Answer
accepted answer of: http://stackoverflow.com/q/48291093

http://stackoverflow.com/comment/83511663
has text: This _might_ work if delta_X is a list and not a numpy array.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48262677
type: Comment

http://stackoverflow.com/comment/83608115
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48311151
has text: any "communication" between client (javascript) and server (pythin) is usually done using AJAX (XMLHttpRequest or fetch on the client side)
type: Comment

http://stackoverflow.com/comment/83496028
comment on: http://stackoverflow.com/q/48256557
type: QuestionComment
has text: Nope, I only know O(log n). I'm not saying O(1) doesn't exist, just that I don't know how to do it..
type: Comment
score: 0

http://stackoverflow.com/comment/83444206
score: 0
comment on: http://stackoverflow.com/a/48230881
type: Comment
has text: How do you figure? Importlib returns the module object then I assign it to a global variable. Exec import is only pointless if you don’t assign local module to global
type: AnswerComment

http://stackoverflow.com/q/48263752
tagged with: heroku
has title: Problems caused by changing the name of my app when deploying to heroku
has answer: http://stackoverflow.com/a/48263877
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48263877
has body: The name of my django app was always workout. Then, when I started to deploy it, I thought it'd be a good idea to change the name to workoutcalendar. So I started a new git repo and put my project files in there (not starting a new django project). The only things I changed were the name of the folder workout (the first one of the django project where settings.py is located) to workoutcalendar as well as changing the DJANGO_SETTINGS_MODULE environment variable. Now, I'm running into problems. It seems that parts of my app are looking for a workout module, which they can't find. Example: 2018-01-15T13:06:40.615612+00:00 app[web.1]: Traceback (most recent call last): 2018-01-15T13:06:40.615613+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 135, in handle 2018-01-15T13:06:40.615614+00:00 app[web.1]: self.handle_request(listener, req, client, addr) 2018-01-15T13:06:40.615615+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 176, in handle_request 2018-01-15T13:06:40.615616+00:00 app[web.1]: respiter = self.wsgi(environ, resp.start_response) 2018-01-15T13:06:40.615617+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 146, in __call__ 2018-01-15T13:06:40.615618+00:00 app[web.1]: response = self.get_response(request) 2018-01-15T13:06:40.615619+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 81, in get_response 2018-01-15T13:06:40.615620+00:00 app[web.1]: response = self._middleware_chain(request) 2018-01-15T13:06:40.615621+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 37, in inner 2018-01-15T13:06:40.615622+00:00 app[web.1]: response = response_for_exception(request, exc) 2018-01-15T13:06:40.615623+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/h…
tagged with: git
type: Question

http://stackoverflow.com/comment/83640599
comment on: http://stackoverflow.com/a/48304642
has text: could be if your internet connection is slow. or if site is working slow. however above code works perfectly find on side. I am able to land to singup page for comment.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83381246
type: QuestionComment
comment on: http://stackoverflow.com/q/48199811
type: Comment
has text: Im not using Unix/Linux system. Working on Windows. When open with Excel second row is empty. But should not be like that, I saw other python data scv file open with Excel and each raw is full filled with data. Something in the code is missing. But can not find what
score: 0

http://stackoverflow.com/a/48269991
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48269790
has body: You forgot : In python, if, elif and else always end with ':' Also when you create a function.

http://stackoverflow.com/comment/83592691
type: Comment
type: QuestionComment
has text: @Amit - thanks for the suggestion I'll give it a try
comment on: http://stackoverflow.com/q/48303200
score: 0

http://stackoverflow.com/q/48329753
has comment: http://stackoverflow.com/comment/83648209
tagged with: web-scraping
tagged with: python
has comment: http://stackoverflow.com/comment/83646173
has comment: http://stackoverflow.com/comment/83646076
has comment: http://stackoverflow.com/comment/83648742
has comment: http://stackoverflow.com/comment/83648295
score: 0
has comment: http://stackoverflow.com/comment/83645522
has comment: http://stackoverflow.com/comment/83645993
has comment: http://stackoverflow.com/comment/83645576
has title: How to avoid Max error retries exceeded in scraping with Python?
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/83645746
has comment: http://stackoverflow.com/comment/83646184
has body: In Python 3 I made a program to scrape the contents of table rows across multiple pages (97893). Each page has a set of tables, so I browse each page and fill a list The page that starts is this: http://www.portaltransparencia.gov.br/PortalComprasDiretasFavorecido.asp?TipoPesquisa=2&amp;Ano=2017&amp;Pagina=1 from bs4 import BeautifulSoup import requests def sopa(link): res = requests.get(link) soup = BeautifulSoup(res.text, "lxml") table = soup.select("table")[1] conjunto = table.findAll("tr") return conjunto planilha = [] for i in range(1,97893): link = "http://www.portaltransparencia.gov.br/PortalComprasDiretasFavorecido.asp?TipoPesquisa=2&amp;Ano=2017&amp;Pagina=" link = link + str(i) conjunto = sopa(link) conta = 0 for linha in conjunto: if conta &gt; 0: documento = linha.find("td", {"class": "firstChild"}, {"style": "white-space: nowrap;"}).text.strip() nome = linha.find("a").text.strip() valor = linha.find("td", {"class": "colunaValor"}).text.strip() dicionario = {"documento": documento, "nome": nome, "valor": valor} planilha.append(dicionario) conta = conta + 1 But on page 458 this error appeared: ConnectionError: HTTPConnectionPool(host='www.portaltransparencia.gov.br', port=80): Max retries exceeded with url: /PortalComprasDiretasFavorecido.asp?TipoPesquisa=2&amp;Ano=2017&amp;Pagina=458 (Caused by NewConnectionError('&lt;urllib3.connection.HTTPConnection object at 0x7feff9ce8f98&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)) I believe I was overthrown because I accessed many pages in sequence. Please, does anyone know how I can avoid this?
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48234422
has comment: http://stackoverflow.com/comment/83451471
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48234512
has comment: http://stackoverflow.com/comment/83451690
has answer: http://stackoverflow.com/a/48234512
has comment: http://stackoverflow.com/comment/83451579
has comment: http://stackoverflow.com/comment/83451514
has body: class Animal: def __init__(self, name, species): self.name = name self.species = species def getName(self): return self.name def getSpecies(self): return self.species def __del__(self): print ("This came from del method") class Dog(Animal): pass def __init__(self, name, isBig): Animal.__init__(self, name, "Dog") self.isBig = isBig I've been playing around with understanding Classes and Child Classes and ran into the following. When instantiating dog = Dog("Bob", True) and try to access the method getName() from the parent, Animal, class I get the following error: Traceback (most recent call last): File "&lt;pyshell#2&gt;", line 1, in &lt;module&gt; dog.getName() AttributeError: Dog instance has no attribute 'getName' What is preventing me from directly accessing methods of the parent class?
favorite count: 0
type: Question
has title: Python 3.6.0 Class Inheritance
answer count: 1
has comment: http://stackoverflow.com/comment/83451522
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83451552
has comment: http://stackoverflow.com/comment/83451506
downvote count: 1
has comment: http://stackoverflow.com/comment/83451838
has comment: http://stackoverflow.com/comment/83451534

http://stackoverflow.com/a/48287544
answers question: http://stackoverflow.com/q/48287289
score: 0
has comment: http://stackoverflow.com/comment/83560396
has comment: http://stackoverflow.com/comment/83560178
type: Answer
has body: runs a function twice: ds.stt(wav.read(directory)[1], wav.read(directory)[0]) Run it once, by unpacking the arguments (in the needed order): ds.stt(*wav.read(directory)[::-1])

http://stackoverflow.com/a/48229822
has body: I would very much recommend using the requests library for doing this kind of things. It's suuuuper flexible and is kind of the de-facto lib for doing requesty stuff. For example (in which I took the liberty of using such lib, and iPython): In [1]: import requests In [2]: r = requests.get("https://api.coinmarketcap.com/v1/ticker/cardano/?convert=USD") In [3]: r.status_code Out[3]: 200 In [4]: r.json() Out[4]: [{'24h_volume_usd': '198429000.0', 'available_supply': '25927070538.0', 'id': 'cardano', 'last_updated': '1515772155', 'market_cap_usd': '20403048889.0', 'max_supply': '45000000000.0', 'name': 'Cardano', 'percent_change_1h': '-3.09', 'percent_change_24h': '5.94', 'percent_change_7d': '-22.7', 'price_btc': '0.00005650', 'price_usd': '0.78694', 'rank': '5', 'symbol': 'ADA', 'total_supply': '31112483745.0'}] In [5]: usd = r.json()[0].get('price_usd') In [6]: usd Out[6]: '0.78694' And if you wanted to print the response as a string, you can use the built-in lib json (for dumping it into a file or whatever): In [8]: import json In [10]: json.dumps(r.text, indent=2) Out[10]: '"[\\n {\\n \\"id\\": \\"cardano\\", \\n \\"name\\": \\"Cardano\\", \\n \\"symbol\\": \\"ADA\\", \\n \\"rank\\": \\"5\\", \\n \\"price_usd\\": \\"0.78694\\", \\n \\"price_btc\\": \\"0.00005650\\", \\n \\"24h_volume_usd\\": \\"198429000.0\\", \\n \\"market_cap_usd\\": \\"20403048889.0\\", \\n \\"available_supply\\": \\"25927070538.0\\", \\n \\"total_supply\\": \\"31112483745.0\\", \\n \\"max_supply\\": \\"45000000000.0\\", \\n \\"percent_change_1h\\": \\"-3.09\\", \\n \\"percent_change_24h\\": \\"5.94\\", \\n \\"percent_change_7d\\": \\"-22.7\\", \\n \\"last_updated\\": \\"1515772155\\"\\n }\\n]"'
type: Answer
score: -1
answers question: http://stackoverflow.com/q/48228783
upvote count: 0
downvote count: 1

http://stackoverflow.com/comment/83552997
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48232794
has text: I normally don't use [conda/miniconda](https://conda.io/miniconda.html) however it is easy to get something up and running quickly: `conda create --channel conda-forge --name test pygrib`. Glad it's working for you now.

http://stackoverflow.com/q/48259782
answer count: 3
has body: I am trying to use Selenium to extract dynamically loaded content. The content is on http://www.afl.com.au/stats I am attempting to navigate to the 'Players' tab, then obtain a list of all the Seasons available. When I do this from the Teams tab, the following code works: from selenium import webdriver from selenium.webdriver.support.ui import Select driver = webdriver.Chrome(executable_path=r'D:\ChromeDriver\chromedriver.exe') driver.get('http://www.afl.com.au/stats') dropdown_menu = Select(driver.find_element_by_xpath('//*[@id="selTeamSeason"]')) for option in dropdown_menu.options: print(option.text) which gives me a list of all the options available in the Seasons tab. However, when I click to the 'Players' tab first, I am unable to get the same list with almost identical code: from selenium import webdriver from selenium.webdriver.support.ui import Select import time driver = webdriver.Chrome(executable_path=r'D:\ChromeDriver\chromedriver.exe') driver.get('http://www.afl.com.au/stats') driver.find_element_by_xpath('//*[@id="stats_tab"]/ul/li[2]').click() time.sleep(3) dropdown_menu = Select(driver.find_element_by_xpath('//*[@id="selTeamSeason"]')) for option in dropdown_menu.options: print(option.text) The click successfully executes, I wait for the content to update, but instead of printing all the years (2001 to 2018), Selenium prints 18 instances of empty strings. I am thoroughly stumped. Any help at all would be appreciated.
tagged with: selenium
has answer: http://stackoverflow.com/a/48260918
type: Question
has answer: http://stackoverflow.com/a/48260805
has title: Selenium Stops Extracting Option Text After Click Command
has answer: http://stackoverflow.com/a/48259975
possible better answer: http://stackoverflow.com/a/48259975
tagged with: python
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48260805

http://stackoverflow.com/comment/83348717
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48184332
has text: 0.20.3. I guess I should update?

http://stackoverflow.com/q/48285212
tagged with: python
has title: The replica master 0 exited with a non-zero status of 1
tagged with: google-cloud-storage
has answer: http://stackoverflow.com/a/48286396
accepted answer: http://stackoverflow.com/a/48286396
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83556394
score: 1
upvote count: 1
answer count: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
has body: My code is perfectly fine on the local machine but when I run it on google cloud storage it throws following exception (previously it worked on google cloud too). Does anyone knows what's the reason? "The replica master 0 exited with a non-zero status of 1. Termination reason: Error. Traceback (most recent call last):\n [...]\n File \"/root/.local/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py\", line 1001, in moving_average_update x, value, momentum, zero_debias=True) File \"/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/moving_averages.py\", line 70, in assign_moving_average update_delta = _zero_debias(variable, value, decay) File \"/usr/local/lib/python2.7/dist packages/tensorflow/python/training/moving_averages.py\", line 180, in _zero_debias \"biased\", initializer=biased_initializer, trainable=False)\n File \"/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/variable_scope.py\", line 988, in get_variable custom_getter=custom_getter)\n File \"/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/variable_scope.py\", line 890, in get_variable\n custom_getter=custom_getter) File \"/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/variable_scope.py\", line 348, in get_variable\n validate_shape=validate_shape)\n File \"/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/variable_scope.py\", line 333, in _true_getter\n caching_device=caching_device, validate_shape=validate_shape) File \"/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/variable_scope.py\", line 639, in _get_single_variable\n name, \"\".join(traceback.format_list(tb))))\nValueError: Variable batch_normalization_1/moving_mean/biased already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at: File \"/root/.local/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py\", line 1001, in moving_average_update x, value, momentum, zero_debias=True) File \"/root/.local/lib/python2.7/…
has comment: http://stackoverflow.com/comment/83556244

http://stackoverflow.com/q/48231164
has answer: http://stackoverflow.com/a/48231226
has body: How would I convert the output of this loop to a string in this format? ABCDEF,BCDEFG,CDEFGH,DEFGHI fileHandle = open( 'urls.txt', 'r' ) raw_URLS = fileHandle.readlines() for items in raw_URLS: print(items[26:32]) fileHandle.close() urls.txt: www.example.com/directory/ABCDEF/pagename www.example.com/directory/BCDEFG/pagename www.example.com/directory/CDEFGH/pagename www.example.com/directory/DEFGHI/pagename
upvote count: 0
has title: Converting for loop output to string
accepted answer: http://stackoverflow.com/a/48231220
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/48231220
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48232578
has answer: http://stackoverflow.com/a/48231326
downvote count: 3
answer count: 4
possible better answer: http://stackoverflow.com/a/48231226
type: Question

http://stackoverflow.com/a/48196235
answers question: http://stackoverflow.com/q/48196188
type: AcceptedAnswer
downvote count: 0
has body: Option 1 groupby orgs = [] for _, g in df.groupby('organisation', as_index=False): orgs.append(g) Or, orgs = [g for _, g in df.groupby('organization', as_index=False)] Now, orgs is a list of dataframes, one for each org. Alternatively, if you want the result as a dict, use - orgs = {i : g for i, g in df.groupby('organization', as_index=False)} Now, to access the dataframe for org1, call orgs['org1']. Option 2 Another option would be filtering using pd.Series.unique - orgs = [] for o in df.organization.unique(): orgs.append(df.query('organization == @o')) Or, orgs = [df.query('organization == @o') for o in df.organization.unique()] Or, orgs = { o : df.query('organization == @o') for o in df.organization.unique()}
score: 3
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/48196188

http://stackoverflow.com/a/48193453
has comment: http://stackoverflow.com/comment/83367724
type: Answer
answers question: http://stackoverflow.com/q/48193344
score: 0
has body: To answer you question, you can access the items in a list like this: ballots=[['1', '2', '3', '0', '0'], ['1', '3', '0', '2', '0'], ...['3', '0', '1', '0', '2']] sub_ballot=ballots[0] #this gets the first sub list, you'll have to iterate through them all vote=sub_ballot[0] #this gets the first vote in the first sub_ballot list, you'll also have to iterate through these I'll leave the rest to you. P.S. This would be way easier using dicts Edit: try this for sub_ballot in ballots: for i,vote in enumerate(sub_ballot,1): #if conditions etc Note that i will be the index of the vote in the sub_ballot list, and it will start at 1 rather than the normal 0.
has comment: http://stackoverflow.com/comment/83368809

http://stackoverflow.com/comment/83394129
score: 0
has text: to be clear, the command to the outlook server did not suceeded. The python command prompt just stuck. I cannot type the next command or do anything except for closing the command prompt and open it again
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48204680

http://stackoverflow.com/q/48287623
downvote count: 0
tagged with: base64
tagged with: python
has answer: http://stackoverflow.com/a/48301914
answer count: 1
type: AnsweredQuestion
favorite count: 0
has title: Python:Conversion of PDF to blob and back to pdf leads to corrupt
has body: I am testing one of the scenarios for my nosql-database setup where I am storing blobs of PDF data. Later, want to use if it can retrieve the original pdf document. Just to test it, I wrote a small test code in Python. import base64 with open('test.pdf', 'rb') as f: blob = base64.b64encode(f.read()) text_file = open('test_blob.txt', "w") text_file.write(blob) text_file.close() with open('test_blob.txt', 'r') as f: blob=f.read().decode('base64') text_file = open('result.pdf', "w") text_file.write(blob) text_file.close() When I checked to see the result.pdf, it was corrupt. What could be the problem?
tagged with: blob
type: Question
upvote count: 2
score: 2
accepted answer: http://stackoverflow.com/a/48301914

http://stackoverflow.com/q/48178450
has body: For example, m is a pandas dataframe: m 5 9 2 5 1 3 Name: label, dtype: int64 I want to have 9*5*3 = 135 similar as row sum, want to do a row multiply. tried dat.rmul, dat.mul, dat.muliply. It seems none of them can do it. thanks!
linked to: http://stackoverflow.com/q/47335608
type: Question
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/47335608
tagged with: python
has comment: http://stackoverflow.com/comment/83337039
score: 0
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/83337048
has comment: http://stackoverflow.com/comment/83337035
tagged with: multiplication
has title: how to get all the element within a pandas column multiplied together?

python-curses
tag name: python-curses
type: Tag
tags question: http://stackoverflow.com/q/48180414

http://stackoverflow.com/q/48219540
has comment: http://stackoverflow.com/comment/83420831
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/83420807
tagged with: binary
accepted answer: http://stackoverflow.com/a/48219602
has comment: http://stackoverflow.com/comment/83420860
answer count: 3
has body: I used this line of code to turn text into binary and I can't seem to find a way to take the binary from this and turn it back to text. Any help would be greatly appreciated. ' '.join(format(ord(x), 'b') for x in contents)
has answer: http://stackoverflow.com/a/48219602
linked to: http://stackoverflow.com/q/7396849
has comment: http://stackoverflow.com/comment/83420868
possible better answer: http://stackoverflow.com/a/48219616
type: AnsweredQuestion
score: 0
has title: converting binary to text python
has answer: http://stackoverflow.com/a/71540478
has answer: http://stackoverflow.com/a/48219616

http://stackoverflow.com/a/48219200
has body: As mentioned in comments, your problem is that you keep replacing ipki in the for loop and only write its final value at the end. re.findall returns a list of zero or more matched strings - since your output file contains the string representation of an empty list ("[]"), it means that the last line of the input file had no match. You could add processing to add found ip4 addresses to a master list, but since re.findall can process large blocks of text, its easier to read the entire file at once and let it do the lifting for you. Once you have the list, you can use set to get rid of duplicates before writing the result file. &gt;&gt;&gt; import re &gt;&gt;&gt; with open('log') as fp: ... ip4addrs = set(re.findall(r'[0-9]+(?:\.[0-9]+){3}', fp.read())) ... &gt;&gt;&gt; with open('output.txt', 'w') as fp: ... fp.write('\n'.join(ip4addrs)) ... 26 &gt;&gt;&gt; print(ip4addrs) {'130.43.58.196', '70.31.28.181'} &gt;&gt;&gt; print(open('output.txt').read()) 130.43.58.196 70.31.28.181
has comment: http://stackoverflow.com/comment/83433873
type: Answer
accepted answer of: http://stackoverflow.com/q/48218930
score: 0
answers question: http://stackoverflow.com/q/48218930
has comment: http://stackoverflow.com/comment/83432319
type: AcceptedAnswer

http://stackoverflow.com/a/48229096
has comment: http://stackoverflow.com/comment/83440516
has comment: http://stackoverflow.com/comment/83440364
type: Answer
answers question: http://stackoverflow.com/q/48228789
has body: The error states that the problem is with ** or pow(), and with the line db=m.ceil(0.65*(((d**3.0)*(T+160))/(i*D*Tb))**0.5). So the problem must lie with either of the ** operators in this statement. It's hard to see how ((d**3.0)*(T+160))/(i*D*Tb)) could yield a string, so the error must lie here: d**3.0; d must be a string Your lambda is lambda:update(dp1,d1), and, earlier you have d1=d.get(). get() will return a string, so you are passing a string as a second argument to update(), which causes your error. Changing d1=d.get() to d1=int(d.get()) or d1=float(d.get()) (with some error-checking for a non-numeric case) should fix it.
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83440718
has comment: http://stackoverflow.com/comment/83440446

http://stackoverflow.com/comment/83636376
has text: I think I get what you mean,I also use: from imutils.object_detection import non_max_suppression
comment on: http://stackoverflow.com/q/48323141
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48300518
tagged with: python-3.x
has title: python import error from setup.py if dependencies are not installed
tagged with: python
tagged with: import
type: Question
has body: In one my python package in setup.py is imported module __about__.py located inside package (where are stored all metadata and want to share it between pakcage and setup). setup.py also installing other dependent third-party library for my package. Also inside package in module __init__.py are imported other modules like (from mypackage.mymodule import MyClass) to keep simple usage (because is easier to write import mypackage and then a = mypackage.MyClass()). The problem is if setup.py importing __about__.py then is also executed __init__.py from package and everything deeper and this generate import error during install, because there is still not installed my dependent library. The structure is: setup.py mypackage/ __init__.py __about__.py mymodule.py I would like to keep same usage and keep structure but solve the import problem during setup if the dependent module was not installed before. probably best way will be to import mypackage.__about__ without executing __init__.py, but how? Or any other advice is welcome. The package is python3 only.
tagged with: setup.py
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48310003
answer count: 1
downvote count: 0
upvote count: 1
score: 1
favorite count: 0

http://stackoverflow.com/comment/83502369
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48240522
has text: Well, I give up. Find a 100*32 is also very hard. (T_T)
score: 0

http://stackoverflow.com/a/48232961
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48232924
downvote count: 0
has body: You can check the file size by using the code from this answer. import os, sys if os.path.getsize("/path/isa_005.mp3") &gt; 5000: sys.exit(0)

http://stackoverflow.com/a/48267374
type: Answer
answers question: http://stackoverflow.com/q/48266531
has body: You are almost right there. As you want to slice the text line by line, instead of looping the text annotations, try to get the direct 'description' from google vision's response as shown below. def parse_image(image_path=None): """ Parse the image using Google Cloud Vision API, Detects "document" features in an image :param image_path: path of the image :return: text content :rtype: str """ client = vision.ImageAnnotatorClient() response = client.text_detection(image=open(image_path, 'rb')) text = response.text_annotations del response # to clean-up the system memory return text[0].description The above function returns a string with the content in the image, with the lines separated by "\n" Now, you can add prefix &amp; suffix as you need to each line. image_content = parse_image(image_path="path\to\image") my_formatted_text = "" for line in image_content.split("\n"): my_formatted_text += " " + line + "\n" my_formatted_text is the text you need.
score: 8
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48266531
upvote count: 8

http://stackoverflow.com/a/48274948
has comment: http://stackoverflow.com/comment/83533877
has comment: http://stackoverflow.com/comment/83533426
type: Answer
has comment: http://stackoverflow.com/comment/83533483
has comment: http://stackoverflow.com/comment/83533538
has comment: http://stackoverflow.com/comment/83533397
answers question: http://stackoverflow.com/q/48274882
has comment: http://stackoverflow.com/comment/83533753
has comment: http://stackoverflow.com/comment/83533972
score: 0
has comment: http://stackoverflow.com/comment/83533775
has comment: http://stackoverflow.com/comment/83533918
has body: The easiest way would be to convert the numbers into string and pass it into set. This will only retain unique digits. &gt;&gt;&gt; len( set(str(num)) ) EDIT : As a function, def unique_digits(num): return len( set(str(num)) ) #driver code : &gt;&gt;&gt; print(unique_digits(123456)) 6 &gt;&gt;&gt; print(unique_digits(112222)) 2
has comment: http://stackoverflow.com/comment/83533766
has comment: http://stackoverflow.com/comment/83533493
has comment: http://stackoverflow.com/comment/83533437
has comment: http://stackoverflow.com/comment/83533610
has comment: http://stackoverflow.com/comment/83533549
has comment: http://stackoverflow.com/comment/83533863
has comment: http://stackoverflow.com/comment/83533814
has comment: http://stackoverflow.com/comment/83533827

http://stackoverflow.com/comment/83544672
type: Comment
type: QuestionComment
score: 0
has text: I need to write the file csv_in (including the comment I added) inside the 'folder_out' with a different name.
comment on: http://stackoverflow.com/q/48280574

http://stackoverflow.com/q/48320804
tagged with: matplotlib
answer count: 1
has title: Jupyter notebook inline plotting breaks, when loading matplotlib rcparams from matplotlibrc file
tagged with: jupyter-notebook
accepted answer: http://stackoverflow.com/a/48322150
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48322150
has comment: http://stackoverflow.com/comment/83632979
downvote count: 0
tagged with: python
has body: I want to write a module with a function to set default style parameters from a matplotlibrc file. A minimal example of the module style.py: import matplotlib as mpl def set_default(): mpl.rc_file('./matplotlibrc') If I want to use the module in a jupyter notebook with inline plotting, the inline plot is not shown, when I call style.set_default() before having plotted anything before. So If I call %matplotlib inline style.set_default() plt.plot() the output is an empty list and no plot is shown. If I call e.g. plt.plot() after enabling inline plotting and before calling the set_default function, the output of both plot calls is shown inline. This even happens, when the matplotlibrc file is empty as it is in my minimal example. Does anyone understand why this happens and has an idea how to solve this problem or another way how to set a default style in a module using a matplotlibrc file? Here are also two images of both cases in a jupyter notebook: inline broken inline working Extra question: Why is the second plot in the second case larger, when the loaded matplotlibrc is empty?
tagged with: plot
has comment: http://stackoverflow.com/comment/83627424
type: AnsweredQuestion
score: 3
upvote count: 3

eval
tag name: eval
type: Tag
tags question: http://stackoverflow.com/q/48209796

http://stackoverflow.com/a/48280859
has comment: http://stackoverflow.com/comment/83561746
answers question: http://stackoverflow.com/q/48280788
has comment: http://stackoverflow.com/comment/83548878
type: Answer
has comment: http://stackoverflow.com/comment/83548707
has comment: http://stackoverflow.com/comment/83556796
score: 0
has body: I suggest that if you want to combine multiple Python scripts, you use them as modules. Script A can import script B as a module and call methods from that module. With the construct if __name__ == "__main__": do_stuff() you can define code that is only executed when the script is called directly, but not when it is imported by another script. This way, you can write Python scripts that act both as modules and standalone.

http://stackoverflow.com/q/48204501
score: 0
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/83390104
has answer: http://stackoverflow.com/a/48204602
has comment: http://stackoverflow.com/comment/83390080
type: Question
has title: startswith returns in Jupyter
answer count: 2
has comment: http://stackoverflow.com/comment/83390421
linked to: http://stackoverflow.com/q/1436703
has body: below startswith query runs fine in my PyCharm environment (Python 2.7): df['starts_with'] = map(lambda x: df.startswith('Wash'), df['CTYNAME']) When running the same in a Jupyter Notebook I am receiving below value in my 'starts_with' column: '&lt;map object at 0x7fbfe6954470&gt;' I understand that it might be a purely Jupyter issue, however, is there a different approach to this query to get around the error in Jupyter? 'starts_with' shall be used for a boolean mask in a next step. Best, P
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48204930
tagged with: pandas

http://stackoverflow.com/q/48310149
tagged with: google-cloud-speech
downvote count: 0
upvote count: 1
tagged with: speech-recognition
favorite count: 0
possible better answer: http://stackoverflow.com/a/48346616
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48346616
score: 1
has title: Google cloud speech to text grammar to narrow results to a number?
tagged with: python
has body: I very simply want to pass is a tiny audio clip (8Khz telephony) containing a single digit number, and get back a single digit number as text, narrowed down to a number. File in > number as text out. Preferably via the python command line API. The problem is, by default, it recognises things like 1,2,3,4,5 as won,too,free,fore,5 ... no good! I believe I want what is called a grammar? Or something like Amazon's number slot types it uses in Alexa? I've looked over the cloud speech docs and can't find it. The only thing I could think of is looping over the alternatives given and see if any match an int rather than a word. And if none do, then what? Thanks.
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48323000
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/48323000

http://stackoverflow.com/a/48272557
score: 0
answers question: http://stackoverflow.com/q/48234398
type: Answer
has body: Set up your Pi as an AWS IoT device.IoT SDK Setup, There are easy to use protocols to manage the bi-directional communication. It will provide you a secure interface between lambda and your Pi, while also providing an easy to use, and consistent, data object.

http://stackoverflow.com/comment/83346436
has text: Yes i was able to covert the BGR to HLS but what i was stuck at how to filt out the pixel that have lightness attribute too low, so that the image will be left with the shade of color white
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48182791

http://stackoverflow.com/a/48339764
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48303370
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48303370
has body: I ran some speed tests using the logistic map with single parameter r as an example. Defining r locally at the start of the function gives the best performance, while setting r either as a class attribute or passing it to the function as an argument (individually or as attribute of an instance of a parameter class) raises computation time by roughly 10%. So I suppose the interpreter recognizes the fact that a locally defined r is a constant when the object is created. (Note that I test with only a single parameter, so the difference may be larger in more complicated models.) In case anyone is curious, here is the code of the test: import matplotlib.pyplot as plt import timeit # Define class class Mod: def __init__(self): self.reset() # self.r = 3.9 # -&gt; uncomment when testing class attribute return def reset(self): self.x = 0.5 def step(self): # -&gt; add r when testing argument # ARGUMENT # self.x = r*self.x*(1-self.x) # +10% computation time # CLASS ATTRIBUTE # self.x = self.r*self.x*(1-self.x) # +10% computation time # LOCAL r = 3.9 self.x = r*self.x*(1-self.x) # Length of test trials = int(1e5) T = int(1e3) # r = 3.9 # -&gt; uncomment when testing class attribute # start timer t0 = timeit.default_timer() for _ in range(trials): x = [] m.reset() for _ in range(T): m.step() # -&gt; add r when testing argument x.append(m.x) # do something with data to avoid interpreter tricks # print computation time print(timeit.default_timer() - t0) plt.plot(x) plt.show()

http://stackoverflow.com/comment/83529072
comment on: http://stackoverflow.com/q/48271573
score: 0
type: QuestionComment
has text: Are you raising a StopIteration in your generator?
type: Comment

http://stackoverflow.com/a/48192893
answers question: http://stackoverflow.com/q/48192785
type: Answer
score: 0
has body: Your code does not work because you are concatenating/summing first element twice example:- lets say listy = [1, 2, 3, 4, 5] &amp; element = listy[0] = 1 Now for first iteration element = element + thingy (1 + 1), since thingy for first iteration also points to listy[0] Just check the type of element of list:- for e.g. if isinstance(string, list[0]) : sum = "" elif isinstance(int, list[0]): sum = 0 else : // raise some error for i in listy: sum += i

http://stackoverflow.com/q/48279399
has title: Handle double quotes inside the field value pandas
has body: I have a row like below in a csv file "1"|"A "Great" Experience"|"T" When I read this using below code pandas.read_csv(file2Name,sep = '|',keep_default_na=False,quoting=csv.QUOTE_ALL) it gives the output as: [1,A Great" Experience",T] I need the output as : [1,A "Great" Experience,T] Tried many ways using using various parameters to it. Can anyone help me. Thanks in advance
has answer: http://stackoverflow.com/a/48279885
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48280139
answer count: 2
tagged with: pandas
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/48305522
has title: Maya Python - How to create shaderOverride?
type: Question
tagged with: maya-api
accepted answer: http://stackoverflow.com/a/48325938
has body: Using python in Maya 2017, I'm able to reproduce the structure of my render_setup (layers, collections and overrides) except for shaderOverride. For a classic override, I use the instance function : maya.app.renderSetup.model.collection.Collection.createOverride() Is there a similar command to create a shader override or do you add some specific attributes? Thanks
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48325938
tagged with: shader
answer count: 1
tagged with: maya

http://stackoverflow.com/q/48284642
downvote count: 2
has answer: http://stackoverflow.com/a/48285061
has answer: http://stackoverflow.com/a/48284779
tagged with: python
has comment: http://stackoverflow.com/comment/83553452
has body: My string is as follow 2 | 848 | Seconds | 660.00 | 900.00 | OK I would like to get the data before the first ' | ' and then between the first ' | ' and the second ' | ' until the last one. I also would like to remove spaces and/or tabs. \|(^\|)*\| I tried this to get rid of ' | ' in between ' | ' but it doesn't work. Any Idea? Thank you
answer count: 4
has comment: http://stackoverflow.com/comment/83553422
type: Question
has comment: http://stackoverflow.com/comment/83553332
score: -2
has comment: http://stackoverflow.com/comment/83555202
has title: How to get string in between N ' | ' and (n+1) ' | ' Occurence in python
favorite count: 0
has answer: http://stackoverflow.com/a/48285706
has comment: http://stackoverflow.com/comment/83553532
has answer: http://stackoverflow.com/a/48285470
accepted answer: http://stackoverflow.com/a/48285061
possible better answer: http://stackoverflow.com/a/48284779
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/comment/83637763
type: Comment
has text: I agree that you can't find comments in the syntax tree. But if you're looking for triple-quoted strings on their own line, you're in luck: those aren't comments, so they should be accessible.
type: QuestionComment
comment on: http://stackoverflow.com/q/48325747
score: 4

http://stackoverflow.com/comment/130743527
comment on: http://stackoverflow.com/a/68939195
has text: This was the most straightforward solution as at the time of writing.
score: 0
type: AnswerComment
type: Comment

imputation
tags question: http://stackoverflow.com/q/48235420
type: Tag
tags question: http://stackoverflow.com/q/48222566
tag name: imputation

http://stackoverflow.com/comment/83526237
comment on: http://stackoverflow.com/q/48219414
type: QuestionComment
has text: One example of such package is `pyautogui` that can't be installed before all the dependencies are installed (in a separate pass), and can't be installed in a headless mode at all. All of that because its `setup.py` imports the `pyautogui` module to read the version, while `pyautogui/__init__.py` imports a ton of code, ranging from dependencies that may not yet be installed, to stuff that checks if there's an X display available, raising an exception if not.
score: 0
type: Comment

http://stackoverflow.com/a/48250933
answers question: http://stackoverflow.com/q/48250436
has comment: http://stackoverflow.com/comment/83487194
score: 0
has body: You cannot pass the literal string name of the variable. Instead, you have to specify the variable position with a ?: import sqlite3 database_list=['easy','mid'] conn_two= sqlite3.connect('videojs.db') c=conn_two.cursor() c.execute("INSERT INTO data VALUES (?, ?)", database_list) conn_two.commit() c.close() conn_two.close()
type: Answer

http://stackoverflow.com/comment/83507770
type: Comment
has text: There's no problem with posting an alternate solution if and when you (or someone else) first answer the actual question, specially when the op did _explicitely_ mention he was aware of the alternative solutions. And I don't care about "making friends" here actually.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48261929

http://stackoverflow.com/a/48285968
has comment: http://stackoverflow.com/comment/83559125
has comment: http://stackoverflow.com/comment/83559191
answers question: http://stackoverflow.com/q/48285915
has comment: http://stackoverflow.com/comment/83557099
has comment: http://stackoverflow.com/comment/83556918
type: Answer
score: 3
upvote count: 3
type: AcceptedAnswer
has body: The closest to the Python code that I can think of is: std::vector&lt;std::vector&lt;int&gt;&gt; ls(10, std::vector&lt;int&gt;(3)); If the sizes are known at compile time, you may also use std::array. std::array&lt;std::array&lt;int, 3&gt;, 10&gt; ls;
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48285915

http://stackoverflow.com/comment/83487731
type: Comment
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/48252649
has text: A huge problem is that it is an undecidable problem to check if two expressions are semantically the sae. Furthermore it is not specified what the "grammar" of the expressions is.

http://stackoverflow.com/q/48191460
type: AnsweredQuestion
downvote count: 0
has title: Send a PDF generated from an API to an external server?
score: 1
tagged with: http://stackoverflow.com/tag/pdf
has body: I have a NodeJS-ExpressJS server (to host a web page) and Django API server. When a specific endpoint in the Django server is called from the ExpressJS server (when a user clicks a button on the web page), a PDF is generated. I want to send this PDF from the Django server to the ExpressJS server and then download it to the user's browser (The user only interfaces with ExpressJS server). In order to do this I encode the PDF as a base64 string in the Django server and return the string in an HTTP response. In the ExpressJS server, I decode the base64 string and then use the res.download() method provided by the ExpressJS framework to download the PDF to the user's browser. This method appears to work, but can it corrupt the PDF file? Is there a way to simply send the PDF file as a binary file and download it to the browser that way (If possible, please provide an example)? Any answers, examples, and suggestions are greatly appreciated. Django API server def process_upload(request): ''' Process request and generate PDF .... ''' with open(pdf, "rb") as pdf_file: encoded_string = base64.b64encode(pdf_file.read()) return HttpResponse(encoded_string) ExpressJS server server.get('/api', function(req, res, next) { request.post({ url: 'http://&lt;api_url&gt;', oauth: oauth, preambleCRLF: true, postambleCRLF: true }, function(error, response, body){ res.writeHead(200, { 'Content-Type': 'application/pdf', 'Content-Disposition': 'attachment; filename="file.pdf"' }); }); const download = Buffer.from(body.toString('utf-8'), 'base64'); res.end(download); });
tagged with: python
has answer: http://stackoverflow.com/a/48193671
type: Question
upvote count: 1
answer count: 1
tagged with: django
accepted answer: http://stackoverflow.com/a/48193671
tagged with: express
favorite count: 0
tagged with: node.js

http://stackoverflow.com/q/48288658
tagged with: py2exe
favorite count: 0
type: Question
tagged with: cx-freeze
tagged with: python-3.x
linked to: http://stackoverflow.com/q/23749530
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53228531
score: 6
tagged with: python
has body: I would like to use cx_freeze to change my hello_world.py into exe file. When I run cxfreeze like this: cxfreeze hello_world.py And I run the exe file, it comes the error: ./hello_world Fatal Python error: Py_Initialize: Unable to get the locale encoding Traceback (most recent call last): File "/home/karl/anaconda3/lib/python3.6/encodings/__init__.py", line 31, in &lt;module&gt; zipimport.ZipImportError: can't decompress data; zlib not available Aborted (core dumped) Does anyone know how to solve this?
upvote count: 6
has answer: http://stackoverflow.com/a/50370494
linked to: http://stackoverflow.com/q/52741673
answer count: 2
has comment: http://stackoverflow.com/comment/84280818
linked to: http://stackoverflow.com/q/43464504
downvote count: 0
has title: zipimport.ZipImportError: can't decompress data; zlib not available

http://stackoverflow.com/comment/83820788
has text: You may want to be more descriptive of what issue you are facing. Errors? Exceptions? What do you expect and what are you getting?
type: Comment
comment on: http://stackoverflow.com/q/48223480
type: QuestionComment
score: 0

http://stackoverflow.com/q/48279801
answer count: 0
has body: My ultimate goal is to get all the posts in a Facebook group along with their entire comment threads. I'm currently using the /group/feed endpoint, but it is not maintained in an orderly fashion. Each post object has two time fields, created_time and updated_time. The first one as the name says is the time when the post was created. The latter however gets updated whenever some comment is added to the post. This is how the current code looks like (pseudo-code): def process_group(group): for post in posts: post_data = parse_data(post) comment_data = get_comments(post_data) save_to_database(post_data) def get_comments(post): return comment_string def main(): while True: for group in groups: process_group(group) if __name__ == "__main__": main() The script runs in an infinite loop because I want to crawl ALL the posts and comments. Once the for group in groups: loop gets finished, the script starts from the first group and continues forward. What I need is a clever way to avoid re-crawling posts and comments that have already been crawled. I tried something with since and until but as per the Graph API documentation, they only apply on the updated_time field. PS: I'm not asking anyone to write code; any helpful suggestions as to how to proceed with the algorithm would be appreciated.
tagged with: facebook-graph-api
has comment: http://stackoverflow.com/comment/83543516
has title: What's a good algorithm to get all the posts and comments in a Facebook group?
type: Question
has comment: http://stackoverflow.com/comment/83543474
score: 0
tagged with: api
type: UnansweredQuestion
tagged with: facebook
tagged with: python
has comment: http://stackoverflow.com/comment/83543284
has comment: http://stackoverflow.com/comment/83543660

http://stackoverflow.com/comment/83657309
type: Comment
comment on: http://stackoverflow.com/a/48254444
type: AnswerComment
has text: Fixed, thanks. Not sure of how, but the thing actually work when I tested it.
score: 0

http://stackoverflow.com/a/48242355
has body: getattr gets the attributes of an object, not the value associated with a key in a mapping. getattr(server, 'login-name', None) is trying to access the attribute server.login-name, not the value server['login-name'] You can instead use the dict.get method server.get('login-name', None)
upvote count: 12
score: 12
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48242217
answers question: http://stackoverflow.com/q/48242217
type: Answer

http://stackoverflow.com/q/48252094
has title: Discord does not embed link when sent by my bot
has comment: http://stackoverflow.com/comment/83488526
tagged with: beautifulsoup
has body: My code works fine and the bot sends the link, but Discord does not recognize it as one and does not embed it. When I copy and paste it myself, it then recognizes it as a link and embed the image. Here is my code: import requests from bs4 import BeautifulSoup if message.content.startswith(".dog"): response = requests.get("https://dog.ceo/api/breeds/image/random") soupRaw = BeautifulSoup(response.text, 'lxml') soupBackend = str(soupRaw).split("message") soup2 = soupBackend[1] soup3 = soup2[3:] soup = soup3[:-20] await bot.send_message(message.channel, soup) Here is an example: https://i.sstatic.net/UuS22.jpg Does anyone know how to make it embed the link when it is sent by my bot? Thanks for the help! Edit: I am not trying to send an embedded message, I am trying to send a link that will BE embedded by Discord, as shown in my example. This is not a duplicate question.
has comment: http://stackoverflow.com/comment/83488491
tagged with: discord.py
has comment: http://stackoverflow.com/comment/83487451
has comment: http://stackoverflow.com/comment/83488601
upvote count: 1
score: 1
linked to: http://stackoverflow.com/q/44862112
tagged with: python
tagged with: discord
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83488624
has answer: http://stackoverflow.com/a/60105452
downvote count: 0
has comment: http://stackoverflow.com/comment/83487238
has comment: http://stackoverflow.com/comment/83492526
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83487035
answer count: 1
linked to: http://stackoverflow.com/q/47515361
has comment: http://stackoverflow.com/comment/83487097

http://stackoverflow.com/q/48264284
has title: How do I test for speed with PyTest / tox?
score: 0
tagged with: tox
upvote count: 1
has body: For testing machine learning algorithms / repositories, I see three things that matter: Does it crash Does it have a minimum test accuracy Is it fast enough While (1) and maybe (2) is standard unit testing, I'm not too sure how to deal with (3). Can I test this with pytest / tox? I found pytest-benchmark, but how would I do this for example for lidtk? In pseudo-code, I want to do the following: def classifier_predict(input_features): # do something smart, but maybe too time-consuming return result def input_generator(): # Generate something random which classifier_predict # can work on - don't measure this time! return input_features class Agents(unittest.TestCase): def test_classifier_predict(): self.assertMaxTime(classifier_predict, input_generator, max_time_in_ms=100)
downvote count: 1
answer count: 1
favorite count: 0
tagged with: testing
tagged with: benchmarking
type: Question
tagged with: python
type: UnansweredQuestion
tagged with: pytest-benchmark
has answer: http://stackoverflow.com/a/48265187

http://stackoverflow.com/comment/83518409
type: Comment
has text: Possible duplicate of [Trouble installing selenium for python](https://stackoverflow.com/questions/45584241/trouble-installing-selenium-for-python)
type: QuestionComment
comment on: http://stackoverflow.com/q/48267633
score: 3

http://stackoverflow.com/q/48255607
score: 0
has answer: http://stackoverflow.com/a/48255642
has body: I want to identify sub-sets of words using a regex pattern using the values() of the following dictionary. creategarbageterms = {'tim_tam' : ['tim_tam','yummy_tim_tam', 'berry_tim_tam'], 'pudding': ['pudding', 'chocolate_pudding', 'biscuits', 'tiramusu'], 'ice_cream': ['ice_cream', 'vanilla_ice_cream']} i.e., given the following strings; **Term -&gt; Output** wow_yummy_tim_tam -&gt; yes melted_tim_tam -&gt;yes berry_tim_tam -&gt; Yes cherry_berry_tim_tam -&gt; yes wow_tam -&gt; No wow_m -&gt; No wow_ti -&gt; No Wow_tim_t -&gt; No My current code/pattern is as follows. creategarbageterms = {'tim_tam' : ['tim_tam','yummy_tim_tam', 'berry_tim_tam'], 'pudding': ['pudding', 'chocolate_pudding', 'biscuits', 'tiramusu'], 'ice_cream': ['ice_cream', 'vanilla_ice_cream']} pattern = re.compile(r'|'.join([r'(\s|\b){}\b'.format(x) for x in creategarbageterms.values()])) if re.findall(pattern, "wow_m".replace("_", " ")): print("yes") else: print("no") However, in my current code the above mentioned No terms also gets accepted. Please let me know where I am making it wrong?
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48255642
has title: Construct regex pattern to identify a sub set of words
tagged with: python
tagged with: regex
type: AnsweredQuestion

http://stackoverflow.com/comment/83495617
comment on: http://stackoverflow.com/a/48245516
score: 0
type: AnswerComment
has text: Thanks! Actually I tried `x.dot(A).dot(y)` initially and got the wrong answer, but I didn't think of `x.dot(A.dot(y))`.
type: Comment

http://stackoverflow.com/a/48325571
answers question: http://stackoverflow.com/q/48325478
has comment: http://stackoverflow.com/comment/83637047
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83636931
has body: EDIT (to account for OP using pandas and ExcelWriter): You need to define your target file with ExcelWriter and then write to it with variable sheet names. Also offering some Python clean-up for your iteration: #breaks up df into systems #exports excel for each system writer = ExcelWriter('U4SysOutput.xlsx') for x in range(1, int(SystemCount)+1): System = minus4[minus4['System'] == "System " + str(x)] System.to_excel(writer, sheet_name='sheet{}'.format(x), index=False) print(System.head())
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48325478

http://stackoverflow.com/q/48245595
type: Question
has comment: http://stackoverflow.com/comment/83473934
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83473967
has title: error: unrecognized arguments while using ArgumentParser
has comment: http://stackoverflow.com/comment/83474019
tagged with: python-2.7
tagged with: list
score: 0
answer count: 0
has body: I am using the following code snippet to take in user arguments parser = argparse.ArgumentParser() parser.add_argument('-k', '--keywords', help='something', type=str) args = parser.parse_args() search_keyword = [str(item) for item in args.keywords.split(',')] When i give the input as -k bears,elephants it works fine but when i give -k polar bears,elephants it gives me error: unrecognized arguments: bears,elephants this is clearly the space character being considered as a separate item. How do i resolve this?
upvote count: 1
has comment: http://stackoverflow.com/comment/83474029
downvote count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83474239

http://stackoverflow.com/comment/83344953
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48181395
has text: i've attached the message.
type: Comment

http://stackoverflow.com/a/48266477
type: Answer
has comment: http://stackoverflow.com/comment/83517734
score: 0
has body: Try to provide key=value arguments into your url_for function. Something like this ">Leave a review here! Also Flask have a great documentation, Flask docs
answers question: http://stackoverflow.com/q/48265877

http://stackoverflow.com/comment/83618194
has text: your solution is extremely good....but the loop is not terminated automatically we need to close it.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48304067
type: Comment

http://stackoverflow.com/comment/83615731
has text: Just give like this in model Question `date_created = models.DateTimeField(auto_now=True, null=True)` and try.
type: QuestionComment
comment on: http://stackoverflow.com/q/48315092
type: Comment
score: 0

http://stackoverflow.com/q/48176794
has title: How to add an email into a path in Django 2.0.1?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83333537
upvote count: 1
has comment: http://stackoverflow.com/comment/83333673
has answer: http://stackoverflow.com/a/48176953
downvote count: 1
linked to: http://stackoverflow.com/q/8022530
has comment: http://stackoverflow.com/comment/83333620
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48176953
answer count: 1
tagged with: django
tagged with: python
has body: I want to add an email into a path in Django. I did this code but I don't know how take the variable called email after username place. path('validate_email/&lt;slug:username&gt;/(?P&lt;email&gt;[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/&lt;slug:token&gt;', views.validate_email, name="validate_email")

http://stackoverflow.com/comment/90391654
comment on: http://stackoverflow.com/q/48178836
score: 0
type: Comment
type: QuestionComment
has text: You say "in example 1, list `b` changed, while in example 2, list `d` is not changed", but your examples show the opposite; list `b` retains its original value (`b` is *not* changed), while list `d` is changing along with list `c` (`d` *is* changed).

http://stackoverflow.com/comment/91287345
comment on: http://stackoverflow.com/a/51940956
score: 0
type: AnswerComment
has text: I ensured it sent out using serial monitor. The issue was that i was inputting ACK instead of 0x06 ... thanks for your reply
type: Comment

http://stackoverflow.com/a/48214646
type: Answer
downvote count: 0
upvote count: 1
score: 1
has body: Networkx has a function to add edges from a list of edges (.add_edges_from()). import networkx as nx import matplotlib.pyplot as plt user = [1,2,4] interactions = [ [2, 7, 9, 4], [7, 1, 5, 7, 8, 3], [9, 5, 3] ] # create the edge list elist = [] for v1,v2 in zip(user,interactions): elist.extend([(v1,v) for v in v2]) # create graph from edge list G = nx.Graph() G.add_edges_from(elist) # plot graph nx.draw(G, with_labels=True) plt.show()
answers question: http://stackoverflow.com/q/48203528

http://stackoverflow.com/q/48324436
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/48324465
has body: I thought this solution would solve my problem but the op here needed to check if the rows of his two data frames contained a difference. I want to do the same but for the columns. The solution was ne = (df1 != df2).any(1) but that does not help with my columns. Yes, I just checked and both of my dataframes have exactly the same shape. If I do df1 == df2 it gives me a new data frame full of trues and falses. Looking at the first hundred rows it looks like most of the columns with a few exceptions are equal. How can you just get one True / False for each column? Here is a toy example: import numpy as np import pandas as pd df1 = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)), columns=['a', 'b', 'c', 'd', 'e']) df2 = df1.copy() df2.at[3,'d'] += 10 Desired output: A True B True C True D False E True
favorite count: 0
type: Question
tagged with: python-3.x
type: AnsweredQuestion
has title: Check for differences between the columns of two pandas data frames side by side
tagged with: python
linked to: http://stackoverflow.com/q/17095101
has answer: http://stackoverflow.com/a/48324465
tagged with: pandas
score: 1

http://stackoverflow.com/q/48176103
upvote count: 1
tagged with: python-3.5
has comment: http://stackoverflow.com/comment/83332237
has answer: http://stackoverflow.com/a/48176298
accepted answer: http://stackoverflow.com/a/48176298
favorite count: 0
has comment: http://stackoverflow.com/comment/83331966
has body: I've looked up other answers regarding the issue but I'm having a hard time implementing the solution in my program (still pretty new to Python). Here's what I have so far: # Purpose: 'guess' randomly selects a number between 0 and 100 (including those # numbers) and calculate the cube of that number. It also prompts the user to # guess the cube root of the cubed number, displaying 'Correct!' if correct, and # asking the user if they would like to try again if incorrect. def guess(): import random rand = random.randint (0, 100) cubed = rand*rand*rand # Forming the input question string = "What is the cube root of" cubed = str(cubed) qmark = "?" question = print(string, cubed + qmark) user = int(input(question)) while (user == rand): print ("\nCorrect!") user = input("\n\tWould you like to try again?").lower() if (user != rand): print ("\tIncorrect!, the cube root of", cubed, "is", rand) And this is supposed to be what the output looks like: guess() What is the cube root of 64000? 56 Incorrect, the cube root of 64000 is 40 Would you like to try again? y What is the cube root of 216? 6 Correct! Would you like to try again? n Goodbye
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83332344
downvote count: 1
tagged with: python
has title: Python 3.5: Guessing the cube root game is returning None as an output
type: Question
has answer: http://stackoverflow.com/a/48176374
possible better answer: http://stackoverflow.com/a/48176374
answer count: 2

vpython
tags question: http://stackoverflow.com/q/48201841
type: Tag
tag name: vpython

http://stackoverflow.com/comment/83527720
comment on: http://stackoverflow.com/a/48271210
score: 0
type: Comment
type: AnswerComment
has text: @COLDSPEED Sorry. I'm actually getting some strange results with this. I want to delete rows with "-" in an effort to clean data. All the columns need to be numeric to perform stats on them and the "-" (census data for Nan) is throwing it all off. When I run the .eq solution it changed one entire column "-" and then randomly changed other column values in another table to "-".

http://stackoverflow.com/comment/84318477
type: AnswerComment
has text: This worked perfectly, what if i want to search for a whole word, like "zipcode".. as i understand it, this function will break down the word and match each character, or am i wrong?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48254658

http://stackoverflow.com/a/48183012
has body: Using your second example - df from to w 0 1 2 0.730297 1 1 4 0.730297 2 0 1 0.670820 3 1 3 0.516398 4 1 5 0.365148 You can argsort the values in the first two columns depending on whether the value is equal to your ID or not. v = df.iloc[:, :-1].values i = np.arange(len(df))[:, None] j = np.argsort(v == 1, axis=1) # replace `1` with your ID v[i, j][:, 0].tolist() [2, 4, 0, 3, 5]
type: Answer
accepted answer of: http://stackoverflow.com/q/48182939
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48182939

http://stackoverflow.com/q/48215909
has comment: http://stackoverflow.com/comment/83413892
tagged with: time-series
type: UnansweredQuestion
tagged with: forecasting
downvote count: 0
tagged with: arima
has body: I a time series data for 1000 customers regarding the number of purchases they made in the last 2 years. I am able to build the time series forecasting model for the entire dataset. But now I want to build the forecasting model for the each of the 1000 customers, what is the best approach to solve this problem. PS: One method I can think of is iterating over each of the 1000 customer and built the separate model for each of them. But in long run its not going to be feasible solution Can someone help me with the better approach sample data: custmore_id,date,count_order 1,2015-06,24 1,2015-07,26 ... 1,2017-08,320 2,2015-06,12 2,2015-07,32 .. 2,2017-08,500
upvote count: 1
tagged with: python
has title: Time Series Analysis for Individual Customers
has comment: http://stackoverflow.com/comment/83417101
tagged with: pandas
has answer: http://stackoverflow.com/a/48223340
has comment: http://stackoverflow.com/comment/83414385
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/83441067
favorite count: 0
type: Question

http://stackoverflow.com/comment/83386618
score: 0
comment on: http://stackoverflow.com/q/48202332
has text: @SachinKukreja Ah, it is not there, only id, ticker and created_at are there. What's the easiest way to add it, just create a new database somehow?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83373530
type: AnswerComment
comment on: http://stackoverflow.com/a/48196176
score: 0
has text: Thank you, I think this function is the best way I could have understood what was happening.
type: Comment

http://stackoverflow.com/a/48233689
accepted answer of: http://stackoverflow.com/q/48233313
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83450171
score: 3
has body: Creating such an array is a bit tedious, but loadmat does it to handle the MATLAB cells and 2d matrix: In [5]: A = np.empty((1,1),object) In [6]: A[0,0] = np.array([[1.23]]) In [7]: A Out[7]: array([[array([[ 1.23]])]], dtype=object) In [8]: A.any() Out[8]: array([[ 1.23]]) In [9]: A.shape Out[9]: (1, 1) squeeze compresses the shape, but does not cross the object boundary In [10]: np.squeeze(A) Out[10]: array(array([[ 1.23]]), dtype=object) but if you have one item in an array (regardless of shape) item() can extract it. Indexing also works, A[0,0] In [11]: np.squeeze(A).item() Out[11]: array([[ 1.23]]) item again to extract the number from that inner array: In [12]: np.squeeze(A).item().item() Out[12]: 1.23 Or we don't even need the squeeze: In [13]: A.item().item() Out[13]: 1.23 loadmat has a squeeze_me parameter. Indexing is just as easy: In [17]: A[0,0] Out[17]: array([[ 1.23]]) In [18]: A[0,0][0,0] Out[18]: 1.23 astype can also work (though it can be picky about the number of dimensions). In [21]: A.astype(float) Out[21]: array([[ 1.23]]) With single item arrays like efficiency isn't much of an issue. All these methods are quick. Things become more complicated when the array has many items, or the items are themselves large. How to access elements of numpy ndarray?
answers question: http://stackoverflow.com/q/48233313
type: Answer

http://stackoverflow.com/q/48241158
has comment: http://stackoverflow.com/comment/83487103
answer count: 1
has title: Correllation (pandas) between integer and boolean?
has answer: http://stackoverflow.com/a/65963284
favorite count: 0
type: Question
tagged with: statistics
has comment: http://stackoverflow.com/comment/83478505
upvote count: 5
has body: I have my data in the form of: price | bool_qual_1 | bool_qual_2 | bool_qual_3 13000 | True | True | True 20000 | False | True | True 15000 | True | True | False 13000 | False | False | False 15000 | True | True | True In other words, my price attribute has 3 boolean qualities. How do I find the correlation between my price and each of my qualities? I am aware of df.corr() which uses pearson correlation but does this value make sense between integer and boolean?
tagged with: python
has comment: http://stackoverflow.com/comment/116638203
tagged with: correlation
score: 5
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/83470882
type: UnansweredQuestion

http://stackoverflow.com/comment/83610200
type: AnswerComment
score: 0
has text: ok, strange. Another idea - could you please try to run this inside virtualenv?
type: Comment
comment on: http://stackoverflow.com/a/48271031

http://stackoverflow.com/a/48236499
has body: itertools.product is what you want here: &gt;&gt;&gt; from itertools import product &gt;&gt;&gt; a = 'a' &gt;&gt;&gt; b = 'b' &gt;&gt;&gt; N = 3 &gt;&gt;&gt; lst = [a, b] &gt;&gt;&gt; [''.join(x) for x in product(lst, repeat = N)] ['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb'] Which can also be written with a triple nested list comprehension: &gt;&gt;&gt; [x + y + z for x in lst for y in lst for z in lst] ['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']
type: Answer
accepted answer of: http://stackoverflow.com/q/48236410
score: 2
answers question: http://stackoverflow.com/q/48236410
type: AcceptedAnswer
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/48293024
tagged with: random
answer count: 2
has body: I'm writing a program for myself that generates a loadout for this game I play. I'm nearly done, I switched from using random.choice to random.sample in order to avoid have repeats in the results but hate the formatting. print("He has", random.choice(kills) + ',', random.choice(kills) + ',', random.choice(kills) + ', and', random.choice(kills)) Outputs: He has Two Handed Choke, Skewer, Skewer, and Pitchfork Stab whereas: print("He has", random.sample(kills, 4)) Outputs: He has ['Knee Snap', 'Jaw Rip', 'Body Slam', 'Choke'] How do I get a sample that outputs like the code for random.choice()? Thanks!
upvote count: 0
tagged with: output
downvote count: 1
favorite count: 0
type: Question
tagged with: format
has title: Formatting output from random module functions
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48293104
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48293104
has answer: http://stackoverflow.com/a/48293128
possible better answer: http://stackoverflow.com/a/48293128

http://stackoverflow.com/q/48279419
has title: What happens when your class does not explicitly define an __init__ method?
has comment: http://stackoverflow.com/comment/83542892
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83542610
type: UnansweredQuestion
has body: How does the quality of my code gets affected if I don't use __init__ method in python? A simple example would be appreciated.
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48279605
linked to: http://stackoverflow.com/q/8609153
has answer: http://stackoverflow.com/a/48279639
tagged with: class
has comment: http://stackoverflow.com/comment/83542430
score: 3
upvote count: 3

http://stackoverflow.com/a/48328884
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: the range function should be used like a regular function Try for i in range(ammountofgames): This should work
answers question: http://stackoverflow.com/q/48328786

http://stackoverflow.com/comment/83747183
type: QuestionComment
has text: Maybe you should tag your question with `python` too. That would draw more attention. Also `django-orm` seems more appropriate than just `orm`.
comment on: http://stackoverflow.com/q/48297178
score: 0
type: Comment

http://stackoverflow.com/comment/83438031
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48227627
score: 0
has text: And if you must have sublists: `list(map(list, product([1,2,3], [4,5,6])))`

http://stackoverflow.com/comment/83557180
type: Comment
comment on: http://stackoverflow.com/q/48286217
type: QuestionComment
score: 0
has text: "object isn't callable" - you're trying to iterate on that. I think you might be looking to use `bucket.objects.all()` which creates an iterable

http://stackoverflow.com/a/48202061
has comment: http://stackoverflow.com/comment/83385151
has comment: http://stackoverflow.com/comment/83385036
has comment: http://stackoverflow.com/comment/83385029
downvote count: 0
has comment: http://stackoverflow.com/comment/83385063
score: 4
has comment: http://stackoverflow.com/comment/83384983
has body: You need to configure the driver to use BMP as a proxy so it can record the network activity. Here is an example.... from browsermobproxy import Server from selenium import webdriver server = Server('/path/to/bmp/bin/browsermob-proxy') #Local path to BMP server.start() proxy = server.create_proxy() #Proxy is used to generate a HAR file containing the connection URLS that the MP3s are loaded from. chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--proxy-server={0}".format(proxy.proxy)) #Configure chrome options driver = webdriver.Chrome(chrome_options=chrome_options) proxy.new_har('filename') Then all the activity will be recorded to that file. In my case, the path for the binary file was C:\Python27\Lib\site-packages\browsermobproxy\browsermob-proxy-2.1.0-beta-3\bin\browsermob-proxy on Windows with Python 2.7
has comment: http://stackoverflow.com/comment/83385159
has comment: http://stackoverflow.com/comment/83385104
answers question: http://stackoverflow.com/q/48201944
type: Answer
upvote count: 4

http://stackoverflow.com/comment/83780519
score: 0
has text: @user2880391 I added an example using setup_logging signal.
comment on: http://stackoverflow.com/a/48370737
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48262752
has body: You can do this with a simple ForeignKey to self to indicate the parent: parent = models.ForeignKey('self', blank=True, null=True, related_name='children') Now you can do a2.parent = a1, and will automatically get access to a1.children.all().
answers question: http://stackoverflow.com/q/48262544
accepted answer of: http://stackoverflow.com/q/48262544
has comment: http://stackoverflow.com/comment/129013439
downvote count: 0
has comment: http://stackoverflow.com/comment/111997752
score: 20
upvote count: 20
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/48298371
has title: Deploy Django 2.0 on Apache 2.2 at ubuntu 12.04
answer count: 1
has comment: http://stackoverflow.com/comment/83581252
downvote count: 1
favorite count: 0
type: Question
tagged with: apache
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/83581523
tagged with: python
accepted answer: http://stackoverflow.com/a/48314844
tagged with: ubuntu
has answer: http://stackoverflow.com/a/48314844
has body: My enviroment: ubuntu 12.04 / python3.6.4 / django 2.0 / apache 2.2.22 I want to deploy newsite on apache I followed django official I want to deploy at www.domainname.com/newsite/ my httpd.conf &lt;Directory /home/usr/project_name/project_name&gt; &lt;Files wsgi.py&gt; Order deny,allow Deny from all &lt;/Files&gt; &lt;/Directory&gt; WSGIDaemonProcess site python-path=/home/usr/site WSGIProcessGroup site WSGIScriptAlias /newsite/ /home/usr/project_mame/project_name/wsgi.py if I add my virtual environment in python-home, I can't pass configtest I browse 127.0.0.1 it shows apache 'It works' page but 127.0.0.1/newsite i just got 403 forbidden log: client denied by server configuration: xxxxxx/xxxxxx/wsgi.py
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/48241916
type: Question
has body: I've used two approaches with the same SKlearn decision tree, one approach using a validation set and the other using K-Fold. I'm however not sure if I'm actually achieving anything by using KFold. Technically the Cross Validation does show a 5% rise in accuracy, but I'm not sure if that's just the pecularity of this particular data skewing the result. For my implementation of KFold I first split the training set into segments using: f = KFold(n_splits=8) f.get_n_splits(data) And then got data-frames from it by using y_train, y_test = y.iloc[train_index], y.iloc[test_index] In a loop, as witnessed in many online tutorials on how to do it. However, here comes the tricky part. The tutorial I saw had a .train() function which I do not think this decision tree classifier does. Instead, I just do this: tree = tree.DecisionTreeClassifier() tree.fit(X_train, y_train) predictions = tree.predict(X_test) The accuracy scores achieved are: Accuracy score: 0.79496591505 Accuracy score: 0.806502359727 Accuracy score: 0.800734137389 ... and so on But I am not sure if I'm actually making my classifier any better by doing this, as the scores go up and down. Isn't this just comparing 9 independent results together? Is the purpose of K-fold not to train the classifier to be better? I've read similar questions and found that K-fold is meant to provide a way to compare between "independent instances" but I wanted to make sure that was the case, not that my code was flawed in some way.
tagged with: python
has answer: http://stackoverflow.com/a/48245531
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48242000
answer count: 2
tagged with: pandas
score: 0
tagged with: validation
has title: Training a decision tree with K-Fold - Is this the correct approach?
upvote count: 1
tagged with: scikit-learn
possible better answer: http://stackoverflow.com/a/48245531
downvote count: 1
accepted answer: http://stackoverflow.com/a/48242000
favorite count: 0

http://stackoverflow.com/comment/83648269
comment on: http://stackoverflow.com/q/48256569
type: Comment
type: QuestionComment
has text: Can you verify that table 'tellytubby' get created successfully? You could use psql CLI to check that 'psql -U username -d mydatabase -c 'SELECT * FROM tellytubby''
score: 0

http://stackoverflow.com/comment/83498867
type: QuestionComment
comment on: http://stackoverflow.com/q/48257308
has text: `happs = win32com.client.Dispatch("PowerPoint.Application")` You cannot access services as you specify,
score: 0
type: Comment

http://stackoverflow.com/q/48240369
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48257300
answer count: 1
has title: Writing function using *args to create a new column in pandas dataframe
type: Question
has body: I'm newbie to pandas and I want to know how to create a new column in dataframe by applying a function using *args on specific columns.. Following is my dataframe: pri pri_loc sec s0 s0_loc s1 s1_loc s2 s2_loc ABC 7 AB,BC,CA AB 7 BC 7 CA 7 PQR 12 PQ,QR PQ NaN QR 12 NaN NaN LMN 21 LM,MN,NM LM NaN MN NaN NM NaN XYZ 5 ZX,YX,YZ ZX 18 YX 25 YZ 34 RST 10 RT,ST RT 50 ST 10 NaN NaN EFG 2 EF EF 2 NaN NaN NaN NaN SRT 8 RK RK 10 NaN NaN NaN NaN MSD 7 SD SD NaN NaN NaN NaN NaN VK 18 NaN NaN NaN NaN NaN NaN NaN I want to create a new column called comp_loc, by passing values of pri_loc,s0_loc,s1_loc,s2_loc columns to function compare_loc which does the following: if (all of s0_loc, s1_loc and s2_loc) == (value of pri_loc) then it should return 'same' if (all of s0_loc,s1_loc,s2_loc) is NULL then it should return 'doubt' if (any one of s0_loc,s1_loc,s2_loc == pri_loc and if any other != pri_loc) then it should return doubt if (all of s0_loc,s1_loc,s2_loc != pri_loc) it should return not same Note that I want to send s0_loc,s1_loc,s2_loc to compare_loc if and only if values in s0,s1,s2 is not null. For Eg.(if s0 is null, s0_loc should not be sent to compare_loc function... Similarly if s1 is null s1_loc should not be sent and if s2 is null s2_loc should not be sent) Following is output dataframe: pri pri_loc sec s0 s0_loc s1 s1_loc s2 s2_loc comp_loc 0 ABC 7 AB,BC,CA AB 7 BC 7 CA 7 same 1 PQR 12 PQ,QR PQ NaN QR 12 NaN NaN doubt 2 LMN 21 LM,MN,NM LM NaN MN NaN NM NaN doubt 3 XYZ 5 ZX,YX,YZ ZX 18 YX 25 YZ 34 not same 4 RST 10 RT,ST RT 50 ST 10 NaN NaN doubt 5 EFG 2 EF EF 2 NaN NaN NaN NaN same 6 SRT 8 RK RK 10 NaN NaN NaN NaN not same 7 MSD 7 SD SD NaN NaN NaN NaN NaN doubt 8 VK 18 NaN NaN NaN NaN NaN NaN NaN NaN Can I get any suggestions on how to achieve this..?? Btw I'm trying to write a function using *args..
has answer: http://stackoverflow.com/a/48257300

http://stackoverflow.com/comment/83442687
has text: @BillMoore Do you only need to use this in ipython? I have a possible solution for you, but it will only work in ipython.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48228215
score: 0

http://stackoverflow.com/q/48187981
answer count: 1
favorite count: 0
has title: Reading depth buffer with PyOpenGL
has comment: http://stackoverflow.com/comment/83442421
has comment: http://stackoverflow.com/comment/83360518
tagged with: pyopengl
has comment: http://stackoverflow.com/comment/83438923
has body: Basically, I'm trying to extract a depth map (by this I mean a matrix with z corresponding to z-coordinates for vertices in GL.glVertex3dv(vertex) call - obviously, interpolated for plane pixels) after rendering a model (script is loading the model from file with path specified as the first command line argument). There are several questions which come to mind: why glReadPixels call returns a numpy array with shape (width, shape), instead of (height, width)? why it returns some trash, not connected to the rendered model? is there an easy way to get z-coordinates on OpenGL legacy code with PyOpenGL framework? is it correct that maximum I can get here is some array with range [0; 1], basically is some fraction between zNear and zFar (and normalized by glReadPixels, for whatever reason)? The code itself: import sys import argparse import pyassimp from pyassimp.postprocess import aiProcess_JoinIdenticalVertices, aiProcess_Triangulate import numpy as np import matplotlib.pyplot as plt from collections import namedtuple from OpenGL import GL, GLUT Mesh = namedtuple('Mesh', ('vertices', 'faces')) def load_mesh(filename): scene = pyassimp.load(filename, processing=aiProcess_JoinIdenticalVertices | aiProcess_Triangulate) mesh = scene.mMeshes[0].contents def get_vector_array(vector): return [vector.x, vector.y, vector.z] def get_face_array(face): return [face.mIndices[i] for i in xrange(face.mNumIndices)] vertices = np.array([get_vector_array(mesh.mVertices[i]) for i in xrange(mesh.mNumVertices)]) faces = np.array([get_face_array(mesh.mFaces[i]) for i in xrange(mesh.mNumFaces)]) pyassimp.release(scene) return Mesh(vertices, faces) def load_ortho(): GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glOrtho(-1, 1, -1, 1, -1, 1) GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() mesh = None width, height = 1920, 1080 def draw_mesh(): global mesh, width, height GL.glClearColor(0, 0, 0, 0) GL.glClearDepth(0.5) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) GL…
type: Question
linked to: http://stackoverflow.com/q/7777913
has answer: http://stackoverflow.com/a/48243123
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: opengl
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48243123

http://stackoverflow.com/a/64093523
answers question: http://stackoverflow.com/q/48203912
type: Answer
has body: You can also use the exec command: program_list = ["script1.py", "script2.py"] for program in program_list: exec(open(program).read()) print("\nFinished: " + program)
score: 0

http://stackoverflow.com/a/48211735
answers question: http://stackoverflow.com/q/48211344
type: Answer
score: 0
has body: Your question is a little unclear. If you mean you want the P values as the Columns and W values as index you can transpose the dataframe: df.T P1 P2 P3 P4 P5 W0 11 7 7 12 8 W1 12 6 11 8 5 W2 10 3 8 13 13
has comment: http://stackoverflow.com/comment/83404798

http://stackoverflow.com/q/48218891
has comment: http://stackoverflow.com/comment/83422862
has answer: http://stackoverflow.com/a/48220342
tagged with: django-models
tagged with: python
score: -1
answer count: 2
has answer: http://stackoverflow.com/a/48218953
upvote count: 0
type: UnansweredQuestion
has body: Does anyone know of a better way to randomly order models instances when showing them? I'm going to have a lot of instances returned and I'm not trying to kill my server with order_by('?')
tagged with: django
downvote count: 1
favorite count: 0
has title: Django randomly ordering model instances
type: Question
has comment: http://stackoverflow.com/comment/83454574

http://stackoverflow.com/q/48317437
downvote count: 0
favorite count: 0
type: Question
has body: I want to use ExternalTaskSensor。 TaskSensor = ExternalTaskSensor( task_id='TaskSensor', external_dag_id='datamart_OTT_CMS_v1', external_task_id="end", allowed_states=None, execution_delta=None, execution_date_fn=None, dag=dag) I write a dag B depend on A. When dag A end (successed) then dag B will run. But when it's running, I found that dag B is poking dag A all the time. why? am I miss something?
upvote count: 2
type: UnansweredQuestion
tagged with: airflow
has answer: http://stackoverflow.com/a/48327049
tagged with: python
score: 2
has title: Airflow ExternalTaskSensor poking another dag all the time
answer count: 1

http://stackoverflow.com/comment/83599413
type: QuestionComment
score: 0
has text: Not sure what you think has gone wrong. Try `print(logouttime[0].total_seconds())`. But this is a timedelta object that represents the time difference between two datetimes, so that possibly represents the total time logged in
type: Comment
comment on: http://stackoverflow.com/q/48306958

inner-join
tags question: http://stackoverflow.com/q/48195601
type: Tag
tag name: inner-join

http://stackoverflow.com/comment/83609444
type: Comment
has text: Why the inverse and not take the derivative?
comment on: http://stackoverflow.com/a/48310418
score: 0
type: AnswerComment

http://stackoverflow.com/q/48256185
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48273383
has comment: http://stackoverflow.com/comment/83496698
downvote count: 1
has title: Python 3.6 pandas import error from 'UserDict.py'
tagged with: python-3.6
favorite count: 0
has comment: http://stackoverflow.com/comment/83496513
has answer: http://stackoverflow.com/a/48256205
has comment: http://stackoverflow.com/comment/83496450
has comment: http://stackoverflow.com/comment/83495281
tagged with: pandas
score: 1
tagged with: python
tagged with: import
has comment: http://stackoverflow.com/comment/83497123
has comment: http://stackoverflow.com/comment/83496668
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/83496390
has body: I'm running Python 3.6.4, and am getting an import error from pandas. I'm installing it with 'pip install pandas' (which installs version 0.22). Installing it seems to go fine, but when I try to import it, an error gets thrown: Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pandas Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python36\lib\site-packages\pandas\__init__.py", line 13, in &lt;module&gt; __import__(dependency) File "C:\Python36\lib\site-packages\pytz\__init__.py", line 32, in &lt;module&gt; from pytz.lazy import LazyDict, LazyList, LazySet File "C:\Python36\lib\site-packages\pytz\lazy.py", line 3, in &lt;module&gt; from UserDict import DictMixin File "C:\Python36\lib\UserDict.py", line 167 raise TypeError, "pop expected at most 2 arguments, got "\ Any help is much appreciated! Thank you!! Edit: Stephen pointed out that the root problem is pytz failing to import. Importing anything form pytz throws the same error. I've found one reference to the same error (http://www.smashcompany.com/technology/weird-that-under-python-3-4-runtime-you-can-import-from-2-7), which suggested an old path variable was the problem. I don't see any outdated python variables in my PATH, however.

http://stackoverflow.com/a/48262221
answers question: http://stackoverflow.com/q/48262125
score: 5
upvote count: 5
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48262125
has body: You also need to tell the new user to use the new manager: class User(AbstractUser): # in your custom user #... objects = CustomUserManager() #... Django does the same thing in the source code As for: There seems to be no documentation telling me where to actually set the CustomUserManager as the actual manager for the User model. Yes, there is actually a nice doc for that too, but explained in a more general way: https://docs.djangoproject.com/en/2.0/topics/db/managers/
type: AcceptedAnswer

http://stackoverflow.com/q/48206900
tagged with: pip
tagged with: python
tagged with: psycopg2
has body: I was trying to install psycopg2 via pip, but ended up with below error. C:\Windows\system32&gt;pip install psycopy2 Collecting psycopy2 Could not find a version that satisfies the requirement psycopy2 (from version s: ) No matching distribution found for psycopy2 C:\Windows\system32&gt;
type: AnsweredQuestion
score: 0
has title: no matching distribution found for psycopy2
answer count: 1
has answer: http://stackoverflow.com/a/48207097
type: Question
accepted answer: http://stackoverflow.com/a/48207097

http://stackoverflow.com/comment/83444283
comment on: http://stackoverflow.com/a/48221140
type: AnswerComment
score: 0
type: Comment
has text: @RoadRunner this example work perfetly, i use `if any('hello' in x for x in lst):` but mayby you know why this is false `search_word = Taxi Stockholm Kostnad för resa 545 kr.pdf`, and list contains `20170906144217_2of3_556944-8102+FAKTURA_luisa@gluehome.com_Taxi Stockholm Kostnad för resa 545 kr.pdf` why it output false?

http://stackoverflow.com/q/48286927
tagged with: visual-foxpro
tagged with: python-requests
favorite count: 0
type: Question
has title: Cannot locate the Microsoft Visual FoxPro support library
type: UnansweredQuestion
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/48388622
tagged with: python
has comment: http://stackoverflow.com/comment/83764908
has comment: http://stackoverflow.com/comment/83756547
has body: I have recently updated the Requests package for Python (I also installed WireShark around the same time, but I'm not sure if that's relevant). Since doing this, whenever I try and execute a Python file from the command line that imports the Requests library, I receive a pop up on screen stating: "Cannot locate the Microsoft Visual FoxPro support library". If I click OK on the prompt, the file executes as normal. I suspect that this is causing problems for my scheduled tasks that import Requests, as they have stopped running to completion since this issue has come about. I used to have a FoxPro database installed on the machine; that's the only time I've ever even heard of Visual FoxPro. Apart from that, I have no idea why this has started showing up. If anybody knows why this might be happening and/or how I can get it to stop, it would be great to hear some suggestions. I'm happy to provide more details if necessary. Thank you. EDIT: I've been able to stop the pop up message from appearing and get my scheduled tasks working by rolling back Requests to an older version. It would still be ideal if anyone could suggest what might be going on with the latest version that would cause the behavior that I described.
downvote count: 0
answer count: 1

http://stackoverflow.com/a/58735049
has body: I faced similar issue when installing firebase_admin library on windows. The solution was to downgrade protobuf library to 3.6.0. pip install protobuf==3.6
score: 2
answers question: http://stackoverflow.com/q/48264536
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/83547390
score: 0
type: AnswerComment
has text: I have absolutely no idea, never seen it before. But I get one last idea - try change `newdf['col2']=df2.columndf2.unique(), newdf['col3']=df3.columndf3.unique()` to `newdf['col2']=list(df2.columndf2.unique()), newdf['col3']=list(df3.columndf3.unique())`.
comment on: http://stackoverflow.com/a/48281499
type: Comment

http://stackoverflow.com/comment/83368291
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48193768
has text: I see you're using a bash-ism `<(...)`, but the error report says `sh: -c: line 0: syntax error near unexpected token '('`. Note that it says `sh`, not `bash`. I'd try to use `/bin/bash` in the `os.system` invocation; maybe you get `sh` substituted for `bash` in the env where you run the Python code.

http://stackoverflow.com/q/48305143
has title: ValueError: setting an array element with a sequence. Desicion Tree
tagged with: pandas
score: 1
tagged with: python
has body: I think Problem is with my variable 'info.venue'. Its actually String values, which i have encoded using labelencoder and hotoneencoder. but its giving me error when i try to implement decision Tree. when I tried with only 2 variables, It worked like a charm. but when i used 'info.venue' using one Hot encoder its giving me following error. Error is "Value Error: Setting an array element with a sequence" info.toss.decision info.toss.winner info.venue field Australia Shere Bangla National Stadium field Australia Adelaide Oval field Australia Melbourne Cricket Ground bat Australia Brabourne Stadium bat Australia Melbourne Cricket Ground bat Australia Sydney Cricket Ground bat Australia Punjab Cricket Association field India Kensington Oval, Bridgetown field India Stadium Australia field India Saurashtra Cricket Association Stadium bat India Kingsmead bat India Melbourne Cricket Ground bat India R Premadasa Stadium Code is as follows: Using LabelEncoder and OneHotEncoder to encode data &gt; from sklearn.preprocessing import LabelEncoder,OneHotEncoder &gt; labelencoder=LabelEncoder() onehotencoder=OneHotEncoder() &gt; df['info.toss.decision'] = &gt; labelencoder.fit_transform(df['info.toss.decision']) &gt; df['info.toss.winner']= &gt; labelencoder.fit_transform(df['info.toss.winner']) &gt; df['info.outcome.winner']= &gt; labelencoder.fit_transform(df['info.outcome.winner']) &gt; df['info.venue']=labelencoder.fit_transform(df['info.venue']) &gt; df['info.venue']=onehotencoder.fit_transform(df'info.venue') select particular columns from the dataframe X = df'info.venue','info.toss.decision','info.toss.winner' Y = df'info.outcome.winner' Splitting the dataset into the Training set and Test set from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.25) Fitting Decision Tree Classification to the Training set from sklearn.tree import DecisionTreeClassifier classifier = DecisionTreeClassifier(cri…
has comment: http://stackoverflow.com/comment/83596196
accepted answer: http://stackoverflow.com/a/48305653
has answer: http://stackoverflow.com/a/48305653
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48305848
has comment: http://stackoverflow.com/comment/83595329
downvote count: 0
has comment: http://stackoverflow.com/comment/83595644
upvote count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/83595767
favorite count: 0
possible better answer: http://stackoverflow.com/a/48305848
type: AnsweredQuestion

http://stackoverflow.com/a/56520511
answers question: http://stackoverflow.com/q/48224680
type: Answer
has body: I tried with Word(nums+'.') but it also accepted none float like 1.1. or 1.1.1 I tried Word(nums) + '.' + Word(nums) but I could not find out why pyparsing didn't catch up the float (it seems like it should work). I ended up using for catching int + float + minus: number = Optional('-') + Word(nums) + Optional('.' + Word(nums)) Not sure it is the best solution but it may help people in the same case as me (I am parsing some custom rules to check their validity).
score: 0

http://stackoverflow.com/comment/120521637
type: Comment
type: AnswerComment
has text: I have been searching for this answer for 3 hours. Thank you very much!
score: 0
comment on: http://stackoverflow.com/a/52919897

http://stackoverflow.com/q/48306295
tagged with: python
tagged with: text-mining
possible better answer: http://stackoverflow.com/a/48306489
has body: I want to know if there is any package to detect and extrac the header and footer or title page from PDF document ? I am new in text mining using python and I want to know for example pdfminer.layout could help to find any text block in pdfs?
favorite count: 0
has title: Is there any way to extract header and footer and title page of a PDF document?
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/83597831
accepted answer: http://stackoverflow.com/a/53419718
tagged with: http://stackoverflow.com/tag/pdf
type: Question
has answer: http://stackoverflow.com/a/48306489
score: 2
answer count: 2
has answer: http://stackoverflow.com/a/53419718
downvote count: 1

http://stackoverflow.com/comment/83526688
type: AnswerComment
has text: No problem. I'd also suggest you to name your relationships in a more meaningful way, for example you can rename "relat" to "lines", so that it's less confusing you can easily spot the plural name, to indicate a list of things.
type: Comment
comment on: http://stackoverflow.com/a/48265668
score: 0

http://stackoverflow.com/comment/83436166
type: AnswerComment
comment on: http://stackoverflow.com/a/48202382
has text: I'm sorry but I tried in various ways and does not seem to work, you can give me an example with the function to monitor inserted in the middle of a code?
type: Comment
score: 0

http://stackoverflow.com/comment/95476584
score: 0
type: AnswerComment
has text: is there an analogue perl solution?
type: Comment
comment on: http://stackoverflow.com/a/48455210

http://stackoverflow.com/comment/83454059
comment on: http://stackoverflow.com/q/48235180
has text: I recommend using a virtual environment: https://virtualenv.pypa.io/en/stable/
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83366671
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48193090
has text: code is corrupt (idenntation) - thats the case in your sources?
type: Comment

http://stackoverflow.com/a/48268412
score: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48266456
downvote count: 0
upvote count: 2
type: Answer
has body: I have modified your code so it will now run. The main issue that I detect is that you don't understand exactly what the code is doing when it is ran. Issues fixed: Removed a pointless while loop and pygame initializations that were done below in the beginning of the program's execution anyway. Unindented the if __name__ == "__main__": branch. This branch is never part of a class. In a class you have methods and variables. That is it. Other than those issues the code is alright but make sure you understand what it does before moving on. I hope this answer helped you and if you have any further questions please feel free to post a comment below! Revised code example: # This just imports all the Pygame modules import pygame class Game(object): def main(self, screen): image = pygame.image.load('player.png') while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: return if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: return screen.fill((200, 200, 200)) screen.blit(image, (320, 240)) pygame.display.flip() if __name__ == '__main__': pygame.init() screen = pygame.display.set_mode((640, 480)) Game().main(screen)
answers question: http://stackoverflow.com/q/48266456

http://stackoverflow.com/comment/83494323
comment on: http://stackoverflow.com/q/48255744
has text: Please provide specific example data as input, show the exact effect of your code on the input, and compare it with desired output. See guidelines for constructing a [Minimal, Complete, and Verifiable Example](https://stackoverflow.com/help/mcve) for assistance.
type: Comment
type: QuestionComment
score: 1

oauth-2.0
type: Tag
tags question: http://stackoverflow.com/q/48272916
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/48228597
tags question: http://stackoverflow.com/q/48264182
tags question: http://stackoverflow.com/q/48291682
tags question: http://stackoverflow.com/q/48255765

http://stackoverflow.com/q/48298306
downvote count: 2
has answer: http://stackoverflow.com/a/48298439
has answer: http://stackoverflow.com/a/48298749
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/48298927
tagged with: python
has body: I wrote the whole code, just in the place of x and y, this has to take input from user: import numpy as np A= np.array([[1,1],[2,4]]) print (A) b = np.array([x,y]) z=np.linalg.solve(A,b) print(z)
answer count: 3
upvote count: 0
has title: How to take user input for matrix in python 3
has comment: http://stackoverflow.com/comment/83581172

relationship
tag name: relationship
type: Tag
tags question: http://stackoverflow.com/q/48262544
tags question: http://stackoverflow.com/q/48330727

http://stackoverflow.com/comment/83575103
has text: Hmm, I convert it to `str`, so it should working nice.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48294752
type: Comment

http://stackoverflow.com/comment/83594061
type: Comment
has text: code: fd = urllib.urlopen("first url") image_file = io.BytesIO(fd.read()) img = Image.open(image_file)
comment on: http://stackoverflow.com/q/48302780
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83375988
comment on: http://stackoverflow.com/q/48195845
score: 0
type: Comment
type: QuestionComment
has text: I compiled it in Numba, just simple compile, and it improved by 5 seconds the script..224.94061994552612 seconds

http://stackoverflow.com/q/48287694
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83582011
accepted answer: http://stackoverflow.com/a/48305805
has title: Integer is required (got type str): using ipyparallel and jupyter
has answer: http://stackoverflow.com/a/48305805
tagged with: python
tagged with: jupyter
tagged with: ipython
score: 2
type: AnsweredQuestion
upvote count: 2
has body: I'm trying to get ipyparallel working. I'm following the Getting Stared guide but the basic functionality isn't working on my machine. I launch a cluster from the command line ipcluster start -n 4 and then I run the script: import ipyparallel as ipp c=ipp.Client() print(c[:].apply_sync(lambda : "Hello, World")) In Python3, it works as expected, but not when run in Python2. I get the error: TypeError: an integer is required (got type str) Also, when I run the snippet in a Jupyter notebook, using both python 2 and 3 kernels, I get the same error. Any ideas why I'm getting this error? Thanks. Edit: The total error in jupyter is: Traceback (most recent call last)~/.local/lib/python3.5/site-packages/ipyparallel/serialize/serialize.py in unpack_apply_message(bufs, g, copy) 185 assert len(bufs) &gt;= 2, "not enough buffers!" 186 pf = buffer_to_bytes_py2(bufs.pop(0)) --&gt; 187 f = uncan(pickle.loads(pf), g) 188 pinfo = buffer_to_bytes_py2(bufs.pop(0)) 189 info = pickle.loads(pinfo) ~/.local/lib/python3.5/site-packages/ipyparallel/serialize/codeutil.py in code_ctor(*args) 22 23 def code_ctor(*args): ---&gt; 24 return types.CodeType(*args) 25 26 def reduce_code(co): TypeError: an integer is required (got type str) I'm using Python3.5.2 and Python2.7.12, with ipyparallel v6.0.2. I've seen somewhere that ipyparallel v6 doesn't required >Python3, though I can't see this in the docs, so I'd be happy to get this working only for Python3.
has comment: http://stackoverflow.com/comment/83560512
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/83589556
type: QuestionComment
score: 0
has text: to itzMEonTV this is error displayed on object.save(). model_rel().objects.get(pk=int(fieldvalue['value']) retrurn object for ForeignKey field.
comment on: http://stackoverflow.com/q/48298713
type: Comment

http://stackoverflow.com/comment/83655337
has text: @user3767047 run forloop over common1 and common2 attributes list and findout corresponding id1 and id2 from file1 and file2 respectively.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48300201
type: Comment

http://stackoverflow.com/q/48312674
has body: i have inputs.csv like below apple 400 banana 401 mango 430 orange 440 banana 401 orange 440 mango 430 apple 400 orange 440 banana 401 i want my output like output.csv apple 400 2 banana 401 3 mango 430 2 orange 440 3 i.e we should count the number of items of that particular type and insert the count as the 3rd column i have tried with the below code with open('new.csv','r') as csvinput: with open('update.csv', 'w') as csvoutput: writer = csv.writer(csvoutput) reader = csv.reader(csvinput) all = [] row = next(reader) row.append("No.of.Rows") all.append(row) cn = Counter(map(itemgetter(0), reader)) for k, v in cn.items(): print("k compared is::",k) for row in reader: print("Executing inner loop") print("row value compared is ::",row[0]) if k == row[0] : print("matched") # here i want to write the count v to the 3rd column in my above code inner for loop is not getting executed. can u please help me further
type: Question
has comment: http://stackoverflow.com/comment/83611259
answer count: 2
has title: Inner for loop is not executed in python
has comment: http://stackoverflow.com/comment/83613926
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48314408
has answer: http://stackoverflow.com/a/48314176
score: 0
tagged with: python-3.x

machine-learning
type: Tag
tags question: http://stackoverflow.com/q/48312094
tags question: http://stackoverflow.com/q/48216574
tags question: http://stackoverflow.com/q/48270395
tags question: http://stackoverflow.com/q/48311807
tags question: http://stackoverflow.com/q/48220660
tags question: http://stackoverflow.com/q/48241606
tags question: http://stackoverflow.com/q/48264656
tags question: http://stackoverflow.com/q/48309322
tags question: http://stackoverflow.com/q/48252006
tags question: http://stackoverflow.com/q/48261013
tags question: http://stackoverflow.com/q/48253348
tags question: http://stackoverflow.com/q/48212629
tags question: http://stackoverflow.com/q/48263163
tags question: http://stackoverflow.com/q/48291032
tags question: http://stackoverflow.com/q/48260568
tags question: http://stackoverflow.com/q/48264676
tags question: http://stackoverflow.com/q/48188865
tags question: http://stackoverflow.com/q/48286504
tags question: http://stackoverflow.com/q/48204717
tags question: http://stackoverflow.com/q/48257144
tags question: http://stackoverflow.com/q/48252312
tags question: http://stackoverflow.com/q/48215159
tags question: http://stackoverflow.com/q/48196282
tags question: http://stackoverflow.com/q/48236507
tags question: http://stackoverflow.com/q/48300974
tags question: http://stackoverflow.com/q/48297322
tags question: http://stackoverflow.com/q/48273748
tags question: http://stackoverflow.com/q/48190843
tags question: http://stackoverflow.com/q/48259511
tags question: http://stackoverflow.com/q/48233400
tags question: http://stackoverflow.com/q/48310058
tags question: http://stackoverflow.com/q/48253906
tags question: http://stackoverflow.com/q/48295661
tags question: http://stackoverflow.com/q/48287931
tags question: http://stackoverflow.com/q/48206320
tags question: http://stackoverflow.com/q/48272152
tags question: http://stackoverflow.com/q/48311021
tags question: http://stackoverflow.com/q/48177832
tags question: http://stackoverflow.com/q/48252481
tags question: http://stackoverflow.com/q/48238113
tags question: http://stackoverflow.com/q/48185719
tags question: http://stackoverflow.com/q/48175587
tags question: http://stackoverflow.com/q/48253024
tag name: machine-learning
tags question: http://stackoverflow.com/q/48264720
tags question: http://stackoverflow.com/q/48222542
tags question: http://stackoverflow.com/q/48290318
tags question: http://stackoverflow.com/q/48191823
tags question: http://stackoverflow.com/q/48213526
tags question: http://stackoverflow.com/q/48231233
tags question: http://stackoverflow.com/q/48330313
tags question: http://stackoverflow.com/q/48179905
tags question: http://stackoverflow.com/q/48242547
tags question: http://stackoverflow.com/q/48245809
tags question: http://stackoverflow.com/q/48262456
tags question: http://stackoverflow.com/q/48223192
tags question: http://stackoverflow.com/q/48301802
tags question: http://stackoverflow.com/q/48243764
tags question: http://stackoverflow.com/q/48256956
tags question: http://stackoverflow.com/q/48241326
tags question: http://stackoverflow.com/q/48265926
tags question: http://stackoverflow.com/q/48322542
tags question: http://stackoverflow.com/q/48309346
tags question: http://stackoverflow.com/q/48312206
tags question: http://stackoverflow.com/q/48216137
tags question: http://stackoverflow.com/q/48253844
tags question: http://stackoverflow.com/q/48249119
tags question: http://stackoverflow.com/q/48235239
tags question: http://stackoverflow.com/q/48324072
tags question: http://stackoverflow.com/q/48288367
tags question: http://stackoverflow.com/q/48320418
tags question: http://stackoverflow.com/q/48211303
tags question: http://stackoverflow.com/q/48196672
tags question: http://stackoverflow.com/q/48232331
tags question: http://stackoverflow.com/q/48211590
tags question: http://stackoverflow.com/q/48287080
tags question: http://stackoverflow.com/q/48256372
tags question: http://stackoverflow.com/q/48239242
tags question: http://stackoverflow.com/q/48323397

http://stackoverflow.com/q/48248333
upvote count: 7
score: 7
has answer: http://stackoverflow.com/a/60044834
favorite count: 0
has answer: http://stackoverflow.com/a/48249005
type: Question
tagged with: django-cors-headers
has title: django-cors-headers not working at all
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90305390
answer count: 2
downvote count: 0
tagged with: django
has body: Well, initially I had forgotten the middleware class but after adding it just worked fine ( It was a week ago ). Now, I am back to my workstation and I find it again not working. The ACCESS_CONTROL_ALLOW_ORIGIN headers are not at all being set. I have tried all that is, placing the middleware at top, before CommonMiddleware but it just doesn't work. This is my setting.py file : DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'account', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', ] # if DEBUG: # INSTALLED_APPS += 'corsheaders', # MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware', ] # else: # MIDDLEWARE = [] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = DEBUG This is the response I am getting : Date: Sun, 14 Jan 2018 09:35:09 GMT Server: WSGIServer/0.1 Python/2.7.14+ X-Frame-Options: SAMEORIGIN Content-Type: text/html; charset=utf-8 Content-Length: 146

http://stackoverflow.com/q/48305785
has title: How do I authenticate the with the Google Storage SDK using a JSON service account key?
has answer: http://stackoverflow.com/a/48305919
type: Question
tagged with: google-cloud-storage
type: AnsweredQuestion
score: 0
has body: I'm having a look at the API reference located at: https://googlecloudplatform.github.io/google-cloud-python/latest/storage/client.html How am I meant to authenticate when using a service account? I don't see how to create the necessary Credentials object.
tagged with: python
accepted answer: http://stackoverflow.com/a/48305919
answer count: 1

http://stackoverflow.com/comment/83337033
score: 1
comment on: http://stackoverflow.com/a/48178398
has text: I am looking for the local maxima, not the absolute maximum. In other words, I would like to know the indices of all the peaks. A peak occurs every time the slope of the tensor changes from positive to negative. See https://i.sstatic.net/5cRng.png for a graphical example.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83467259
score: 0
comment on: http://stackoverflow.com/a/48241290
type: AnswerComment
has text: If you _want_ to carry a patch against Twisted to make your software work, I guess that's your call...
type: Comment

http://stackoverflow.com/a/48175498
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48175334
has comment: http://stackoverflow.com/comment/83330832
has comment: http://stackoverflow.com/comment/83331336
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83333295
has body: You can replace using dictionary d = dict.fromkeys([2,3,4], 7) df['col2'] = df.col2.replace(d) col1 col2 0 1 7 1 2 1 2 3 5 3 4 7 4 2 7 5 4 1 6 1 7 7 3 7 8 5 7 9 3 7 10 2 7 11 2 7 12 1 7 13 5 1
has comment: http://stackoverflow.com/comment/83331026

http://stackoverflow.com/comment/83490582
comment on: http://stackoverflow.com/q/48253996
score: 1
type: Comment
type: QuestionComment
has text: Don't pickle objects for that use. Pickling is meant for exactly the opposite of your use case: Get the data and the behaviour of an object from the time it was pickled. Serialize the data-fields into json or something like that and add tests to make sure that "old" versions get sensible default values when de-serializing.

http://stackoverflow.com/comment/83368019
type: QuestionComment
score: 0
has text: This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting.
type: Comment
comment on: http://stackoverflow.com/q/48193704

http://stackoverflow.com/comment/83336381
type: Comment
type: QuestionComment
score: 0
has text: Yes exactly! I need them to be converted into tuples.
comment on: http://stackoverflow.com/q/48178086

http://stackoverflow.com/q/48222013
has body: So , example i have this dataframe: ColA ColB AD AC BD BC CD CC DD CD how can i convert my df into some dictionary variable like this? mydfDict = {'ColA' : ['AD','BD','CD','DD'] , 'ColB' : ['AC','BC','CC','CD'] }
type: AnsweredQuestion
has title: Convert Pandas Column to Dict with Column Title as Key and Column Values as Values
tagged with: pandas
score: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48222045
upvote count: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48222045
favorite count: 0
type: Question

http://stackoverflow.com/comment/83544943
type: QuestionComment
comment on: http://stackoverflow.com/q/48280197
score: 2
has text: The wording isn't clear. You seem to want to tabulate, for each column, the counts of 1,2 and 3 for that column. It isn't clear what the output is. It would be natural to put it in a 5x3 or 3x5 array, but your wording seems to suggest that you have 15 named variables. In any event -- if you want help on your homework then you should show your efforts.
type: Comment

http://stackoverflow.com/a/48198618
score: 0
has body: You properly needs to use random.SystemRandom(). By default Python generate randoms by system time, if you run your random generation within a short period of time, it will give the same "random" result (To my knowledge, this is a common issue with random generation on OS).
answers question: http://stackoverflow.com/q/48198573
type: Answer

http://stackoverflow.com/comment/83545672
score: 0
type: AnswerComment
has text: i only changed idx0 to a range because of: return np.split(idx0, linv[bins[1:]]). since im not sure what is happening there
type: Comment
comment on: http://stackoverflow.com/a/48279403

http://stackoverflow.com/q/48226225
type: AnsweredQuestion
score: 0
has body: I'm trying to get the value of an IntegerField from a queryset object based on the value of a ForeignKeyField so I can 1 to it like this. all = Comment.objects.filter(video=Video.objects.get(identifier=request.GET['identifier'])).order_by('-uploaded')[:end] for comment in all: comment.indent = Comment.objects.get(id=comment.replyto).indent + 1; However it seems to cause an error saying: TypeError: int() argument must be a string, a bytes-like object or a number, not 'Comment' Why is this? What am I doing wrong? comment model: class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, to_field='username') video = models.ForeignKey(Video, on_delete=models.CASCADE) description = models.TextField(default="none") replyto = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE) uploaded = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) # maybe add ability to update comments... indent = models.IntegerField(default=0) full traceback: Traceback (most recent call last): File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/trie/Desktop/django/vidmiotest/player/views.py", line 69, in obtain_comments comment.indent = Comment.objects.get(id=comment.replyto).indent + 1; File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django…
has comment: http://stackoverflow.com/comment/83434109
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/83434156
has comment: http://stackoverflow.com/comment/83434344
answer count: 1
tagged with: django
has title: why does `Model.objects.get(id=model.ForeignKeyField).IntegerField` not return an integer?
has answer: http://stackoverflow.com/a/48226726
accepted answer: http://stackoverflow.com/a/48226726
has comment: http://stackoverflow.com/comment/83434252

http://stackoverflow.com/comment/83737939
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48302487
has text: @willlplaya Courses and theory can only get you that far, so at least I would go with programming own things. Just remember to also read from time to time :)

http://stackoverflow.com/comment/83607867
type: Comment
has text: Thank you, your generic solution works. Could you also please add an explanation to your answer? Thanks!
comment on: http://stackoverflow.com/a/48310855
score: 0
type: AnswerComment

http://stackoverflow.com/q/48198529
has answer: http://stackoverflow.com/a/48201003
type: AnsweredQuestion
tagged with: tkinter
score: 0
has title: (Radiobutton with JSON) how to check which Radiobutton has been selected
answer count: 1
has body: I would like to sort numbers when I clicked sort numbers Radiobutton. I already achieve this by calling a function when the Radiobutton is clicked. however, i couldn't sort numbers without calling a function. this is my code R1=Radiobutton(root,text="Sort Student Numbers",value=1) R1.pack(anchor=W) R2=Radiobutton(root,text="Sort Student Names",value=2) R2.pack(anchor=W) with open("student.json", "r"") as f: data = json.load(f) for d in data["student"]: if value == 1: data["student"].sort(key = lambda d: d["Numbers"]) elif value == 2: data["student"].sort(key = lambda d: d["Names"]) label_1 = Label(frame , text="Name: %s" %(d["Names"])) label_1.pack() label_2 = Label(frame , text="Student Numbers: %d" %(d["Numbers"])) label_2.pack() if I say for example R1=Radiobutton(root,text="Sort Student Numbers",value=1, command = sorted_numbers(1)) everything works fine but the reason I don't want to use function calling is I would have to create 3 functions to achieve what I want. thanks
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48201003
tagged with: python

http://stackoverflow.com/comment/83434369
has text: If I print(argv) ,it is printing ['file1.py','test.py'] @buhtz
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48198974
type: Comment

http://stackoverflow.com/comment/83605014
comment on: http://stackoverflow.com/q/48307975
has text: @hpaulj For Reading the files there is not much difference in time(does it in a few seconds) but the for loop to convert it into numbers and subtract takes around 5 minutes
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48259680
tagged with: python-2.7
tagged with: list
answer count: 0
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/48303309
type: Question
has title: Sorting and editing a Dictionary in Python
has body: I use the CCL algorithm of Spencer Whitt from Github to remove detected road markings from Noise. First, I run the CCL algorithm over an image so that it recognizes contiguous elements. Now I extended the algorithm so that it ignores elements with a small number of pixels. So I tried to sort and filter the dictionary created by the CCL algorithm. In the additional code, therefore, keys that are not enough are deleted with the corresponding values. Unfortunately, the additional code not only deletes small elements, but also fragments up the "large" contiguous road markings. Why? Image: CCL algorithm: from PIL import Image import PIL from PIL import ImageOps import collections import operator import numpy as np import sys import math, random from itertools import product from ufarray import * Image.MAX_IMAGE_PIXELS = 1000000000 import cv2 def run(img): data = img.load() width, height = img.size # Union find data structure uf = UFarray() # # First pass # # Dictionary of point:label pairs labels = {} for y, x in product(range(height), range(width)): # # Pixel names were chosen as shown: # # ------------- # | a | b | c | # ------------- # | d | e | | # ------------- # | | | | # ------------- # # The current pixel is e # a, b, c, and d are its neighbors of interest # # 255 is white, 0 is black # White pixels part of the background, so they are ignored # If a pixel lies outside the bounds of the image, it default to white # # If the current pixel is white, it's obviously not a component... if data[x, y] == 255: pass # If pixel b is in the image and black: # a, d, and c are its neighbors, so they are all part of the same component # Therefore, there is no reason to check their labels # so simply assign b's label to e elif y &gt; 0 and data[x, y-1] == 0: labels[x, y] = labels[(x, y-1)] # If pixel c is in the image and black: # b is its neighbor, but a and d are not # Therefore, we must check a and d's labels elif x+1 &lt; width and y &gt; 0 and data[x+1, y-1] == 0: c = label…
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
tagged with: ccl
has comment: http://stackoverflow.com/comment/83629343

http://stackoverflow.com/q/48245987
has title: Efficient way to compute the Vandermonde matrix
possible better answer: http://stackoverflow.com/a/48246009
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48246009
has answer: http://stackoverflow.com/a/48274899
has comment: http://stackoverflow.com/comment/83474874
accepted answer: http://stackoverflow.com/a/48274899
tagged with: arrays
tagged with: python
tagged with: linear-algebra
has body: I'm calculating Vandermonde matrix for a fairly large 1D array. The natural and clean way to do this is using np.vander(). However, I found that this is approx. 2.5x slower than a list comprehension based approach. In [43]: x = np.arange(5000) In [44]: N = 4 In [45]: %timeit np.vander(x, N, increasing=True) 155 µs ± 205 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) # one of the listed approaches from the documentation In [46]: %timeit np.flip(np.column_stack([x**(N-1-i) for i in range(N)]), axis=1) 65.3 µs ± 235 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [47]: np.all(np.vander(x, N, increasing=True) == np.flip(np.column_stack([x**(N-1-i) for i in range(N)]), axis=1)) Out[47]: True I'm trying to understand where the bottleneck is and the reason why does the implementation of native np.vander() is ~ 2.5x slower. Efficiency matters for my implementation. So, even faster alternatives are also welcome!
has comment: http://stackoverflow.com/comment/83475043
has comment: http://stackoverflow.com/comment/83764793
upvote count: 12
has comment: http://stackoverflow.com/comment/83475096
type: AnsweredQuestion
score: 12
has comment: http://stackoverflow.com/comment/83475004
tagged with: performance
answer count: 2
downvote count: 0

http://stackoverflow.com/a/48216684
score: 10
type: Answer
has body: The SQL query you're looking for is this: SELECT foo.* FROM foo LEFT JOIN bar ON bar.foo_id = foo.id WHERE bar.foo_id IS NULL; LEFT JOIN, as opposed to INNER JOIN, includes all rows from the 'left' table (i.e. the table specified in FROM tblname), even if they have no associated row in the 'right' table (the table specified in JOIN tblname). This means that rows that have no associated row in the right table will have NULL values instead: foo.id | foo.baz | bar.id | bar.foo_id | bar.zab -------+---------+--------+------------+-------- 1 | 23 | NULL | NULL | NULL 2 | 56 | 7 | 2 | s1 So, filter for those rows that have a NULL in the right table's primary key (which can't be null in any other case, whereas other columns from the right table could be), and you get foo rows that have no associated bar. In SQLAlchemy, that becomes this: q = db.session.query(Foo).join(Bar, isouter=True).filter(Bar.id == None) The isouter=True flag to join is how you do a LEFT JOIN with SQLAlchemy.
accepted answer of: http://stackoverflow.com/q/48216520
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48216520
upvote count: 10

http://stackoverflow.com/a/48310804
has body: Use the Threading module. I just finished a similar project and it worked like a charm. import threading new_thread = threading.Thread( target = <function here>, args = (<function args>), name = <thread name>, ) new_thread.start() Above is the core functionality. Below is a more elaborate example of queuing up a job, adding that job (thread) to a line to wait its turn (with the thread.join() method), and returning a response with the number of jobs (threads) in line for processing. current_jobs = [] for t in threading.enumerate(): if t._Thread__name in (<thread name>, <thread name>): if t.is_alive(): current_jobs.append(t) new_thread = threading.Thread( target = <function here>, args = (<function args here>, current_jobs), name = <thread name here>, ) new_thread.start() # Create message. job_id = uuid.uuid4().hex job_message = "Job Id: " + job_id # Check current job count. job_count = len(current_jobs) if job_count > 0: # extend message if any jobs found. job_message += "\nThere are " + str(job_count) + " ahead of you, so please be patient." return app.make_response(job_message), 200 And pass current_jobs as an argument to your function, with this code executing at the beginning: for j in current_jobs: j.join() Important to note that your function should contain the entire logic of creating your SparkContext, the lazy work on your RDDs/dataframes, and any actual work you want your cluster to do (.collect(), submitting to a db, etc.), as this thread is asynchronous and will have its own scope that would be complicated to transfer back to the main thread.
upvote count: 3
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48302123
score: 3

http://stackoverflow.com/q/48244632
has comment: http://stackoverflow.com/comment/83471945
has comment: http://stackoverflow.com/comment/83472000
has comment: http://stackoverflow.com/comment/83487444
has comment: http://stackoverflow.com/comment/83471914
downvote count: 4
upvote count: 0
score: -4
answer count: 1
has answer: http://stackoverflow.com/a/48244705
has comment: http://stackoverflow.com/comment/83472101
has comment: http://stackoverflow.com/comment/83472096
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83472025
has comment: http://stackoverflow.com/comment/83560903
has body: I have a list of tuples: [('fruit', 'O'), ('is', 'O'), ('the', 'O'), ('subject', 'O'), ('of', 'O'), ('a', 'O'), ('Roald', 'PERSON'), ('Dahl', 'PERSON'), ('children', 'O'), ("'s", 'O'), ('book', 'O'), ('?', 'O')] I want to reduce this list to: [('fruit', 'O'), ('is', 'O'), ('the', 'O'), ('subject', 'O'), ('of', 'O'), ('a', 'O'), ('Roald Dahl', PERSON'), ('children', 'O'), ("'s", 'O'), ('book', 'O'), ('?', 'O')] That is, any consecutive tuples whose second value is not 'O' should have their first value concatenated. This should work for list of any length, and for any number of consecutive tuples to be joined.
type: UnansweredQuestion
has title: Consolidating Elements of a List
tagged with: python

http://stackoverflow.com/q/48273294
has answer: http://stackoverflow.com/a/48278043
answer count: 2
downvote count: 0
tagged with: pandas
has body: I have a dataframe on which I want to apply below logic to get first row of group having analysis of the individual group. def mark_wakeup_source(df): min_id = df['Astart'].idxmin() df.loc[min_id, ["Reason", "Count", "CSwitch", "Used"]] = [df.loc[min_id, "type"], len(df.index), len(df[df['type'] == "Process"]), df["Aduration"].sum()] return df Here is how I am calling the apply function and combining it. df_t1 = df_t[df_t['type'] != 'Unknown'].copy() df_t1['Reason'] = "None" grouped = df_t1.groupby(["CPU", "index"]) df_t1 = grouped.apply(mark_wakeup_source) df_t = df_t1.append(df_t[df_t['type'] == 'Unknown']) There are 29K+ unique group in my current data and it is taking about ~140 sec to process. I have data which is much larger than this one, I need to optimize it, and running out of clue how to do it. My data looks like this, before grouping it: CPU State Start Stop pre_state next_state index Astart \ 0 4 Active 0.015417 0.056283 C1 C1 1 0.015429 1 4 Active 0.015417 0.056283 C1 C1 1 0.015437 18 5 Active 0.015492 0.015499 C1 C1 2 0.015495 14 4 Active 0.015417 0.056283 C1 C1 1 0.019524 20 1 Active 0.019921 0.020071 C3 C3 1 0.019938 Astop Name type Count CSwitch Used Reason Aduration 0 0.015437 System Process 0 0 0 None 0.000008 1 0.032188 wpr.exe Process 0 0 0 None 0.016751 18 0.015498 System Process 0 0 0 None 0.000003 14 0.019727 ntoskrnl.exe DPC 0 0 0 None 0.000203 20 0.020064 System Process 0 0 0 None 0.000126 I have reduced the number of groups as much as possible. Tried Numba but that didn't help at all. Based on many other answers I tried below code, by returning 0 instead of df, which is taking ~180s: def mark_wakeup_source(df, df_parent): df_len = len(df.index) min_id = df['Astart'].idxmin() df_parent.loc[min_id, ["Reason", "Count", "CSwitch", "Used"]] = [df.loc[min_id, "type"], df_len, len(df[df['type'] == "Process"]), df["Aduration"].sum()] return 0 Running out of clues, so looking for some suggestions to do it in optimum way.
has comment: http://stackoverflow.com/comment/83530456
score: 1
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83530809
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48275686
accepted answer: http://stackoverflow.com/a/48275686
has title: How to optimize the apply call on groupby
tagged with: python
tagged with: apply
has comment: http://stackoverflow.com/comment/83534807
possible better answer: http://stackoverflow.com/a/48278043
type: AnsweredQuestion

http://stackoverflow.com/comment/83477011
score: 0
type: Comment
type: AnswerComment
has text: @jezrael Thanks, I just wanted to confirm. I guess it's the same user who has been mass downvoting my answers. They've downvoted 4 of my answers so far. I believe the moderators should be able to handle it from there. They'll record the user's misconduct.
comment on: http://stackoverflow.com/a/48246911

http://stackoverflow.com/q/48236542
has comment: http://stackoverflow.com/comment/83457387
has comment: http://stackoverflow.com/comment/83467072
has comment: http://stackoverflow.com/comment/83455848
has comment: http://stackoverflow.com/comment/83499935
favorite count: 0
has comment: http://stackoverflow.com/comment/83494591
type: Question
has comment: http://stackoverflow.com/comment/83457764
has comment: http://stackoverflow.com/comment/83455714
has comment: http://stackoverflow.com/comment/83455740
has comment: http://stackoverflow.com/comment/83490410
tagged with: python
tagged with: pygame
tagged with: collision-detection
accepted answer: http://stackoverflow.com/a/48448938
has comment: http://stackoverflow.com/comment/83491067
has answer: http://stackoverflow.com/a/48448938
type: AnsweredQuestion
tagged with: python-3.x
score: 2
linked to: http://stackoverflow.com/q/40966994
has title: Getting the side of the collision: Collision detection
upvote count: 2
has body: I am attempting to make a platformer game, in which there are no slopes. I am trying to get collision detection down, but I can't find a way in pygame to get which side collided with the other sprite. Can anyone give me a good way to do this, that isn't too bulky, but would also work well in my situation? Here is my player class: class Player(pg.sprite.Sprite): def __init__(self,game): pg.sprite.Sprite.__init__(self) self.image = pg.Surface((30, 40)) self.game = game self.image.fill(YELLOW) self.rect = self.image.get_rect() self.rect.center = (WIDTH / 2, HEIGHT / 2) self.pos = vec(WIDTH / 2, HEIGHT / 2) self.vel = vec(0, 0) self.acc = vec(0, 0) def jump(self): self.rect.y += 1 hits = pg.sprite.spritecollide(self, self.game.platforms, False) self.rect.y -= 1 if hits: self.vel.y = -15 def update(self): self.acc = vec(0, PLAYER_GRAV) keys = pg.key.get_pressed() if keys[pg.K_LEFT]: self.acc.x = -PLAYER_ACC if keys[pg.K_RIGHT]: self.acc.x = PLAYER_ACC self.acc.x += self.vel.x * PLAYER_FRICTION self.vel += self.acc self.pos += self.vel + 0.5 * self.acc self.rect.midbottom = self.pos Here is my platform class: class Platform(pg.sprite.Sprite): def __init__(self, x, y ,w, h): pg.sprite.Sprite.__init__(self) self.image = pg.Surface((w,h)) self.image.fill(GREEN) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.centerx = x+(w/2) self.centery = y+(h/2) And here is how I currently do collisions (which only works on the top of the platform) hits = pg.sprite.spritecollide(self.player,self.platforms, False) if hits: self.player.pos.y = hits[0].rect.top+1 self.player.vel.y = 0 EDIT: I've added this to my player class and I run it every time the player updates, and it works... almost. def wall_collisions(self): self.rect.centerx = self.pos.x for wall in pg.sprite.spritecollide(self, self.walls, False): if self.vel.x &gt; 0: self.rect.right = wall.rect.left self.vel.x = 0 elif self.vel.x &lt; 0: self.rect.left = wall.rect.right self.vel.x = 0 self.pos.x = self.re…
has comment: http://stackoverflow.com/comment/83467280
answer count: 1
has comment: http://stackoverflow.com/comment/83455819
downvote count: 0

http://stackoverflow.com/comment/83638838
type: AnswerComment
has text: Looks great. However, what versions do you use? I got an error regarding the lambda function (the parenthesis seems to be removed in Python3 with PEP 3113 -- Removal of Tuple Parameter Unpacking). But in Python 2.7 I got the error "'module' object has no attribute 'to_hex'" on line 12 (mcolors.to_hex(c)) .
type: Comment
comment on: http://stackoverflow.com/a/48304132
score: 0

http://stackoverflow.com/comment/83509432
comment on: http://stackoverflow.com/a/48243321
type: AnswerComment
score: 0
has text: Thanks I am trying this. My Clang compiler has gotten very slow after Meltdown and Spectre security patches.
type: Comment

http://stackoverflow.com/comment/83373893
type: Comment
type: AnswerComment
has text: (Depending on the details of the data structure, it might need to be `int(sys.argv[1])` rather than leaving that as a string; OP didn't really provide enough detail to say).
score: 0
comment on: http://stackoverflow.com/a/48196132

http://stackoverflow.com/q/48316773
tagged with: gzip
tagged with: python
type: Question
has title: python: unexpected end of file exception while extracting downloaded file
has comment: http://stackoverflow.com/comment/83622694
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/13137817
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83619407
score: 0
has body: I am trying to download some files from Amazon S3 using python and extract it to the local disk. Here is the code I am using to download the and extract the files. def download(self): filename = BASE_OUTPUT_DIR + "/" + str(self.jobId) + "_" + string.replace(self.jobName, " ", "_") + "_" + str(self.count) try: response = requests.get(self.fileUrl.rstrip(), stream=True, verify=False) if response.status_code == 200: with open(filename + ".gz", 'wb') as out_file: shutil.copyfileobj(response.raw, out_file) del response subprocess.call(["gunzip", "--name", filename]) return filename except Exception as e: self.logger.debug("An exception occurred while downloading file (%s)" % (filename)) self.logger.debug("Trying to delete the file") try: os.system('rm -rf %s' % filename) except Exception as e: self.logger.debug(e) return None Sometimes I got this error gzip: /tmp/files/file_8340.gz: unexpected end of file. I would suspect the files but this issue happens randomly with random files. I guise the download did not complete but I am not sure.

http://stackoverflow.com/q/48251448
tagged with: numpy
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48252024
answer count: 2
has answer: http://stackoverflow.com/a/48252024
tagged with: arrays
linked to: http://stackoverflow.com/q/41190852
possible better answer: http://stackoverflow.com/a/78884624
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83485893
type: Question
has comment: http://stackoverflow.com/comment/83485448
linked to: http://stackoverflow.com/q/30488961
has comment: http://stackoverflow.com/comment/83485363
has comment: http://stackoverflow.com/comment/83485824
has body: I have a 1D numpy numpy array with integers, where I want to replace zeros with the previous non-zero value if and only if the next non-zero value is the same. For example, an array of: in: x = np.array([1,0,1,1,0,0,2,0,3,0,0,0,3,1,0,1]) out: [1,0,1,1,0,0,2,0,3,0,0,0,3,1,0,1] should become out: [1,1,1,1,0,0,2,0,3,3,3,3,3,1,1,1] Is there a vectorized way to do this? I found some way to fill values of zeros here, but not how to do it with exceptions, i.e. to not fill the zeros that are within integers with different value.
upvote count: 5
has title: Filling zeros in numpy array that are between non-zero elements with the same value
tagged with: python
score: 4
tagged with: vectorization
has comment: http://stackoverflow.com/comment/83485319
has answer: http://stackoverflow.com/a/78884624

http://stackoverflow.com/q/48186569
tagged with: lstm
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48188816
upvote count: 2
answer count: 1
downvote count: 0
has body: First I would like to mention I am new to Tensorflow, I am working on OCR project using CTC (Connectionist Temporal Classification) and LSTM (Long Short Term Memory). I have done the training and when i am trying to restore session I found an error that is commonly posted on the internet but different analysis has been provided. Error is :- 2018-01-10 13:42:43.179534: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:893] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2018-01-10 13:42:43.179939: I tensorflow/core/common_runtime/gpu/gpu_device.cc:940] Found device 0 with properties: name: Quadro M4000 major: 5 minor: 2 memoryClockRate (GHz) 0.7725 pciBusID 0000:00:05.0 Total memory: 7.93GiB Free memory: 7.56GiB 2018-01-10 13:42:43.179974: I tensorflow/core/common_runtime/gpu/gpu_device.cc:961] DMA: 0 2018-01-10 13:42:43.179986: I tensorflow/core/common_runtime/gpu/gpu_device.cc:971] 0: Y 2018-01-10 13:42:43.180002: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1030] Creating TensorFlow device (/gpu:0) -&gt; (device: 0, name: Quadro M4000, pci bus id: 0000:00:05.0) 2018-01-10 13:42:43.316563: W tensorflow/core/framework/op_kernel.cc:1158] Invalid argument: Assign requires shapes of both tensors to match. lhs shape= [48] rhs shape= [5,5,1,48] [[Node: save/Assign_1 = Assign[T=DT_FLOAT, _class=["loc:@Variable_1"], use_locking=true, validate_shape=true, _device="/job:localhost/replica:0/task:0/gpu:0"](Variable_1, save/RestoreV2_1/_25)]] 2018-01-10 13:42:43.319682: W tensorflow/core/framework/op_kernel.cc:1158] Invalid argument: Assign requires shapes of both tensors to match. lhs shape= [48] rhs shape= [5,5,1,48] [[Node: save/Assign_1 = Assign[T=DT_FLOAT, _class=["loc:@Variable_1"], use_locking=true, validate_shape=true, _device="/job:localhost/replica:0/task:0/gpu:0"](Variable_1, save/RestoreV2_1/_25)]] 2018-01-10 13:42:43.332996: W tensorflow/core/framework/op_kernel.cc:1158] …
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: tensorflow-serving
tagged with: python
accepted answer: http://stackoverflow.com/a/48188816
has title: InvalidArgumentError in restore: Assign requires shapes of both tensors to match

http://stackoverflow.com/comment/83404841
comment on: http://stackoverflow.com/q/48211816
type: QuestionComment
score: 0
has text: Your explanation is a little confusing. Do you have some code that would illustrate what you want to do?
type: Comment

http://stackoverflow.com/q/48287961
tagged with: python
tagged with: ckeditor
has title: YouTube Plugin in CKEditor Django returns 404
tagged with: youtube
tagged with: django-ckeditor
has answer: http://stackoverflow.com/a/65506983
downvote count: 0
has answer: http://stackoverflow.com/a/64531915
score: 1
upvote count: 1
favorite count: 0
type: Question
answer count: 2
has body: I've been trying to install the YouTube plugin in CKEditor for a project, but I have failed and I couldn't figure out why. I have configured my settings.py in the following manner (stripping it of irrelevant-to-this-issue code: CKEDITOR_CONFIGS = { 'default': { 'toolbar_Collective':[ ['Source', '-', 'Bold', 'Italic'], # ... { 'name': 'links', 'items': ['Link', 'Unlink'] }, { 'name': 'media', 'items': ['ImageButton', 'Youtube'] }, # ... {'name': 'tools', 'items': ['Maximize']}, ], 'toolbar':'Collective', 'width': '100%', 'height': 400, 'tabSpaces': 4, 'extraPlugins': ','.join([ ]), } } Currently I have left the 'extraPlugins' configurations empty, because as soons as I write 'youtube' in there: 'extraPlugins': ','.join([ 'youtube', ]), CKEditor fails, and the following is shown on my terminal: [16/Jan/2018 18:31:16] "GET /post/new/ HTTP/1.1" 200 7239 [16/Jan/2018 18:31:16] "GET /static/ckeditor/ckeditor-init.js HTTP/1.1" 304 0 [16/Jan/2018 18:31:16] "GET /static/css/main.css HTTP/1.1" 304 0 [16/Jan/2018 18:31:16] "GET /static/ckeditor/ckeditor/ckeditor.js HTTP/1.1" 304 0 [16/Jan/2018 18:31:16] "GET /static/js/script.js HTTP/1.1" 304 0 [16/Jan/2018 18:31:16] "GET /static/ckeditor/ckeditor/plugins/youtube/plugin.js?t=H4PG HTTP/1.1" 404 1749 Performing system checks... You can see there are other error codes, even regarding the page css. I don't know why they are there, but they are there regardless of any editing, and the editor functions regardless of them. The real issue is with the YouTube plugin (which is the only plugin I currently plan on having installed). I have also tried configuring my models.py file with the RichTextUploadingField that is mentioned in the docs, and I've done the following: class Post(models.Model): # ... text = RichTextField( config_name='default', extra_plugins=['youtube'], external_plugin_resources=[( 'Youtube', '/static/ckeditor/ckeditor/plugins/youtube/', 'plugin.js', )], ) #... Which has also been fruitless. I have done the same in form…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83569856
tagged with: django

pathlib
tags question: http://stackoverflow.com/q/48190959
tag name: pathlib
tags question: http://stackoverflow.com/q/48181073
type: Tag

http://stackoverflow.com/a/48321626
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83654179
has body: You can achieve the desired outcome if you fill the empty cells in your file with a space character. Alternatively, you can specify fewer options when reading your file and use simple post-processing: import pandas as pd df = pd.read_excel('C:\problem.xlsx', skiprows = [0, 1]) # Replace NaNs with a space character df = df.fillna(' ') df = df.set_index(['Description', 'Segment']) print(df) Output: $ Description Segment Total 1.60528e+08 Brand A 3.67197e+07 Brand A Product 1 Awsome product 107493 Brand A Product 2 Awsome product
answers question: http://stackoverflow.com/q/48313420
has comment: http://stackoverflow.com/comment/83663349
score: 1
accepted answer of: http://stackoverflow.com/q/48313420
type: Answer

http://stackoverflow.com/a/48229161
accepted answer of: http://stackoverflow.com/q/48227108
type: AcceptedAnswer
has body: The rule should be fixed so that it does not raise issues in such cases. I created a ticket to track this issue. As a workaround, you may disable the rule for some given files. See the documentation for ignoring issues on Multiple Criteria, and apply it for python:S100 and for the pattern "**/test/*" (for example).
type: Answer
answers question: http://stackoverflow.com/q/48227108
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83512104
downvote count: 0

http://stackoverflow.com/comment/83468769
has text: @VasilisG. your answer inserts the string into new elements in the list, it's not good. I just want to concatenate the string to the end of the existing elements of the list.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48243018

http://stackoverflow.com/q/48314179
has body: Below is the code I am using to test backtracking algo to solve knight's tour, and it's not able to solve for odd board sizes. I would really appreciate if someone could point out the error in the code. The code works fine for boards of even size, but it fails to find a solution for boards of odd sizes. def get_valid_moves_warnsdorff(moves, x, y, size): valid_moves = [(valid_move, len(get_valid_moves(moves, x + valid_move[0], y + valid_move[1], size))) for valid_move in get_valid_moves(moves, x, y, size)] sorted_moves = sorted(valid_moves, key=lambda w: w[1], reverse=False) return [move[0] for move in sorted_moves]
tagged with: recursive-backtracking
type: Question
accepted answer: http://stackoverflow.com/a/48314463
tagged with: knights-tour
has title: Knight's tour- backtracking (unable to solve for odd board sizes)
has answer: http://stackoverflow.com/a/48314463
tagged with: python
tagged with: backtracking
type: AnsweredQuestion
score: 0
answer count: 1

connexion
tag name: connexion
type: Tag
tags question: http://stackoverflow.com/q/48228111

http://stackoverflow.com/comment/83362166
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48189755
score: 0
has text: Thanks, but I am in another problem. I am using pandas 0.15 and when I edit your code a bit for that, I am getting str_extract() got an unexpected argument 'expand' a = pd.melt(dff1, id_vars=['a','b'], value_vars=['cin','cout'], value_name='c', var_name='in/out') b = pd.melt(dff1, id_vars=['a','b'], value_vars=['din','dout'], value_name='d', var_name='in/out')

http://stackoverflow.com/q/48323148
has answer: http://stackoverflow.com/a/48323233
tagged with: python
accepted answer: http://stackoverflow.com/a/48323233
has title: Python slicing does not change the sliced array's value
has comment: http://stackoverflow.com/comment/83631752
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83631706
has comment: http://stackoverflow.com/comment/83631769
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51908726
possible better answer: http://stackoverflow.com/a/51908726
has body: I am trying to test the slicing feature of Python numpy. For the following code, I would expect the output be [101,100,101,100,101,100]. x = np.array([1,0,1,0,1,0]) y = x y = y + 100 x But it returns [1,0,1,0,1,0]. Why? I thought slicing modifies the original array as well.
favorite count: 0
type: Question
tagged with: numpy
answer count: 2

http://stackoverflow.com/comment/83559626
score: 1
comment on: http://stackoverflow.com/q/48271513
has text: Use tensorboard and visualize your graph. Check if all the layers are connected as expected.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48216075
has answer: http://stackoverflow.com/a/48570128
downvote count: 1
has title: ImportError: No module named filters
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/69096682
answer count: 3
has comment: http://stackoverflow.com/comment/83417229
has comment: http://stackoverflow.com/comment/83414098
linked to: http://stackoverflow.com/q/33686005
tagged with: scikit-image
tagged with: python
has comment: http://stackoverflow.com/comment/83415407
has comment: http://stackoverflow.com/comment/83415145
has comment: http://stackoverflow.com/comment/83414411
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/51628744
has answer: http://stackoverflow.com/a/51628744
accepted answer: http://stackoverflow.com/a/48570128
has comment: http://stackoverflow.com/comment/83414325
has comment: http://stackoverflow.com/comment/83426475
has body: I installed skimage in ubuntu terminal using command: sudo apt-get install python-skimage it installed succesfully but when using it in my code (from skimage.filters import threshold_local). i get an error: Traceback (most recent call last): File "scan.py", line 4, in &lt;module&gt; from skimage.filters import threshold_local ImportError: No module named filters kindly someone help me to correct this!
upvote count: 1

http://stackoverflow.com/comment/83420786
has text: And also I did search for this problem for like 15 minutes and couldn't find an answer.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48219191
type: Comment

http://stackoverflow.com/a/48278318
has body: Yes. Use dict.fromkeys: &gt;&gt;&gt; dict1 = {'key1':0, 'key2':10, 'key3':110} &gt;&gt;&gt; dict.fromkeys(dict1, 0) {'key1': 0, 'key2': 0, 'key3': 0} Be careful, though, if your fill-value is a mutable object, this will mean every value will be the same instance of that mutable object, e.g.: &gt;&gt;&gt; new_dict = dict.fromkeys(dict1, []) &gt;&gt;&gt; new_dict {'key1': [], 'key2': [], 'key3': []} &gt;&gt;&gt; new_dict['key1'].append('foo') &gt;&gt;&gt; new_dict {'key1': ['foo'], 'key2': ['foo'], 'key3': ['foo']}
upvote count: 5
type: Answer
score: 5
answers question: http://stackoverflow.com/q/48278278
has comment: http://stackoverflow.com/comment/83540035
downvote count: 0

http://stackoverflow.com/a/72951961
score: 1
has comment: http://stackoverflow.com/comment/128939216
type: Answer
answers question: http://stackoverflow.com/q/48305869
downvote count: 1
upvote count: 2
has body: I resolved this issue by running below command on my Ubuntu 20.04 machine: sudo apt-get install -y python3.7-lib2to3

http://stackoverflow.com/a/48313090
type: Answer
answers question: http://stackoverflow.com/q/48312983
upvote count: 7
downvote count: 0
has body: The environment variables need to be before your image name. Everything after it is replacing the CMD. Also, it is -e or --env, so your dashes were missing to begin with. You can also just put the python command within the entrypoint file.
score: 7
accepted answer of: http://stackoverflow.com/q/48312983
type: AcceptedAnswer

http://stackoverflow.com/q/48189332
answer count: 0
tagged with: luigi
downvote count: 0
has comment: http://stackoverflow.com/comment/83511578
has comment: http://stackoverflow.com/comment/83468701
has comment: http://stackoverflow.com/comment/83548456
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: python
has title: HTTP error 411 with Luigi central scheduler
has comment: http://stackoverflow.com/comment/83514982
score: 2
has body: As the title says, I am trying to run luigi with a centralized scheduler. I simply run luigid and the scheduler starts. I check localhost:8082/ and I get the page as expected, empty as there are so far no jobs. Then I start my little test program. It is not able to connect to the scheduler, giving the error HTTPError: 411 Client Error: Length Required for url:http://localhost:8082/api/ping I am running Linux 4.4.0-104, Python version 2.7.12 and Luigi version 2.7.1. Here is my little test program that takes an integer n as input. First all files up to that number is written to a file. Then the next task does the same, but for the squared of the numbers import luigi class PrintNumbers(luigi.Task): n = luigi.IntParameter() def requires(self): return [] def output(self): return luigi.LocalTarget("numbers_up_to_{}.txt".format(self.n)) def run(self): with self.output().open('w') as f: for i in range(1, self.n+1): f.write("{}\n".format(i)) class SquareNumbers(luigi.Task): n = luigi.IntParameter() def requires(self): return [PrintNumbers(n=self.n)] def output(self): return luigi.LocalTarget("squares_up_to_{}.txt".format(self.n)) def run(self): with self.input()[0].open() as fin, self.output().open('w') as fout: for line in fin: n = int(line.strip()) out = n*n fout.write("{}:{}\n".format(n,out)) if __name__ == "__main__": luigi.run(['--n', '100000'], main_task_cls=SquaredNumbers) Edit: Added a luigi.cfg file in the work directory: I created a luigi.cfg in my work directory with the following: [core] default-scheduler-host=localhost default-scheduler-port=8082 max-reschedules=2 parallel-scheduling=true rpc-connect-timeout=10.0
tagged with: http-error

http://stackoverflow.com/q/48263038
has title: How to access class object inside the class in flask?
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/83509263
score: 2
upvote count: 3
answer count: 0
has comment: http://stackoverflow.com/comment/83509110
downvote count: 1
has comment: http://stackoverflow.com/comment/83509258
favorite count: 0
has body: I've got flask running in a class from flask import Flask class Server: app = Flask(__name__) def __init__(self, object_with_data): self.object = object_with_data @app.route("/") def hello(self): return self.object.get_data() def run(): self.app.run(host='0.0.0.0') but I get an error saying TypeError: hello() missing 1 required positional argument: 'self'. How do I get access to an instance of the object when running flask within a class? One dirty solution I thought of was using sockets to create a link between my server class and the object_with_data class, but I'm sure someone will know a better way to do this. I read something about event handlers, but I don't fully understand that.
has comment: http://stackoverflow.com/comment/83508935
type: Question
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/a/48306348
type: AcceptedAnswer
has body: These are not a commas separated values, and this is not a list. There is a difference between data and source code. If bob etc. were defined, then running this would generate a list (and the commas would be just part of the formatting when printing the list, not actually part of the list), but as it is, it's just text in an editor. Phrases such as "convert to strings" apply to data, not source code. If you want to manipulate this, then you have to treat it as data. So, for instance, if you were to add quote marks, you can do: list_string = '[54, 25, 1, 3467, 9, 45, 69, 420, 45, 65987, bob, 0, -5, 47.2, john, y]' list_from_string = list_string.replace('[','').replace(']','').split(', ') for index,item in enumerate(list_from_string): try: item_as_int = int(item) item_as_float = float(item) if item_as_int == item_as_float: list_from_string[index] = item_as_int else: list_from_string[index] = item_as_float except: pass
accepted answer of: http://stackoverflow.com/q/48305898
score: -3
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/48305898
downvote count: 3

http://stackoverflow.com/comment/83635861
score: 0
has text: Steinman Thank you so much for a quick answer but when I tried that I get the same error. I will switch back to ClusterIP only. `db<-dbConnect(MySQL(), user = 'root', password ='neurocoreai', + host = "mysql", port=3306) Error in .local(drv, ...) : Failed to connect to database: Error: Can't connect to MySQL server on 'mysql' (107)`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48310711

http://stackoverflow.com/q/48252297
answer count: 2
tagged with: for-loop
tagged with: nested
has answer: http://stackoverflow.com/a/48387084
possible better answer: http://stackoverflow.com/a/48387084
type: Question
has body: Statement of the problem: Given three 1D numpy arrays and three 2D numpy arrays: 1D numpy arrays: V = [ V_a V_b] EL = [EL_a EL_b] E0 = [E0_a E0_b] 2D numpy arrays: T = [[ T_1a T_2a T_3a T_4a ] [ T_1b T_2b T_3b T_4b ]] ET = [[ ET_1a ET_2a ET_3a ET_4a] [ ET_1b ET_2b ET_3b ET_4b]] TS = [[ TS_1a TS_2a TS_3a TS_4a] [ TS_1b TS_2b TS_3b TS_4b]] I would like to create four files: T_1.dat T_2.dat T_3.dat T_4.dat with the following info: T_1.dat | T_2.dat | T_3.dat | T_4.dat ---------------------------------------------------------------------------------------------------------------------------------------- VOLUME: F: | VOLUME: F: | VOLUME: F: | VOLUME: F: | | | V_a F(V_a, T_1) | V_a F(V_a, T_2) | V_a F(V_a, T_3) | V_a F(V_a, T_4) V_b F(V_b, T_1) | V_b F(V_b, T_2) | V_b F(V_b, T_3) | V_b F(V_b, T_4) where F is calculated as: F(V_a, T_1) = EL_a + E0_a + ET_1a - TS_1a F(V_b, T_1) = EL_b + E0_b + ET_1b - TS_1b ... and so on ... My attempt: The following nested loops over all these variables: import numpy as np V = np.array([ 226.331804, 228.817957]) EL = np.array([-3765.00423366, -3765.0072724 ]) E0 = np.array([ 0.07389338, 0.07347015]) T = np.array([[ 10., 30.1, 50.2, 70.3], [ 10., 30.1, 50.2, 70.3]]) ET = np.array([[ 2.86370000e-08, 3.59345110e-05, 2.47740762e-04, 7.11121913e-04], [ 4.16950000e-08, 4.07323670e-05, 2.66315355e-04, 7.47534260e-04]]) TS = np.array([[ 3.14910000e-08, 4.50715970e-05, 3.33253672e-04, 1.00376212e-03], [ 4.60170000e-08, 5.14553150e-05, 3.61155871e-04, 1.06376830e-03]]) rows = ET.shape[0] cols = ET.shape[1] F_all = [] for x, indx_EL, indx_E0 in zip(range(0, rows), range(len(EL)), range(len(E0))): aux = [] for y in range(0, cols): F = EL[indx_EL] + E0[indx_E0] + ET[x,y] + TS[x,y] print F aux.append(F) F_all.append(aux) F_all = np.array(F_all) print ' F_all = ', F_all The result is the following: F_all = [[-3764.93034022 -3764.93025927 -3764.92975929 -3764.9286254 ] [-3764.93380216 -3764.93371006 -3764.93317478 -3764.93199095]] If I manually calculate …
has answer: http://stackoverflow.com/a/48253597
tagged with: multidimensional-array
has comment: http://stackoverflow.com/comment/83697330
accepted answer: http://stackoverflow.com/a/48253597
has title: Nested loops over 2D and 1D numpy arrays saving into files
tagged with: python
tagged with: numpy
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/83361620
type: Comment
type: QuestionComment
has text: When I get rid of the DELETE FROM newegg line and the line, I get this error when I run the code:
score: 0
comment on: http://stackoverflow.com/q/48190135

http://stackoverflow.com/comment/83466890
type: Comment
type: QuestionComment
has text: Thank you Patrick!
comment on: http://stackoverflow.com/q/48242217
score: 0

http://stackoverflow.com/a/48327494
score: 2
has comment: http://stackoverflow.com/comment/83645019
has comment: http://stackoverflow.com/comment/83640836
upvote count: 2
has body: One possibility is to create a seperate shared library to define var and load this before libadd.so. /* resolve.c */ int var = 1; gcc -c -Wall -Werror -fpic resolve.c gcc -shared -o resolve.so resolve.o from ctypes import * sharedlib = CDLL("sharedlib/resolve.so", mode = RTLD_GLOBAL) sharedlib = CDLL("sharedlib/libadd.so", mode = RTLD_GLOBAL)
has comment: http://stackoverflow.com/comment/84092452
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83640878
accepted answer of: http://stackoverflow.com/q/48308845
answers question: http://stackoverflow.com/q/48308845
type: Answer
has comment: http://stackoverflow.com/comment/83645169

http://stackoverflow.com/q/48206439
has comment: http://stackoverflow.com/comment/83437994
has comment: http://stackoverflow.com/comment/83472461
has comment: http://stackoverflow.com/comment/83438070
has comment: http://stackoverflow.com/comment/83394065
has comment: http://stackoverflow.com/comment/83396193
answer count: 0
has comment: http://stackoverflow.com/comment/83410514
score: 1
has comment: http://stackoverflow.com/comment/83394176
tagged with: multithreading
has comment: http://stackoverflow.com/comment/83395817
downvote count: 0
tagged with: amazon-ec2
upvote count: 1
has body: I have a python script that runs a single process with ~150 threads. On Ubuntu Server 16.04 t2.small instance type it runs at around 30% CPUUtilization. Since it has to run constantly at that rate and the baseline performance of t2.small is 20%, I decided to move to t2.medium (whose baseline performance is 40%). However, when I run the script on t2.medium, the script starts consuming around 30% from each of the two computational units (for a total of 60%), hence pushing me above the 40% baseline. From my understanding, a python script running a single process (albeit on multiple threads) doesn't use more than 1 CPU core (in this case it's virtual). And, in any case, if my script is running at 30% cpu usage on t2.small, why doesn't it do just the same on one computational unit on t2.medium, regardless of the availability of a second computational unit? What am I missing here? EDIT: I decided to experiment a little bit and I cloned my instance to create a t2.micro, t2.small, and t2.medium instances of the same image. When I started the same script on each instance, this is my CPUCreditUsage on each: The colors are as follows: Blue: t2.micro Orange: t2.small Green: t2.medium As expected, the t2.medium is consuming twice the amount of credits, so I am really losing any advantage of using medium over small.
has comment: http://stackoverflow.com/comment/83399775
has comment: http://stackoverflow.com/comment/83396579
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83402860
has title: My python script is consuming twice the amount of cpu credits per hour on t2.medium compared to t2.small
has comment: http://stackoverflow.com/comment/83410689
tagged with: python

http://stackoverflow.com/a/48324090
answers question: http://stackoverflow.com/q/48322869
type: Answer
accepted answer of: http://stackoverflow.com/q/48322869
has body: What fixed the issue was reinstalling Django.
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/48211657
type: Question
tagged with: mocking
type: UnansweredQuestion
tagged with: python
has body: Say I have the classes in module.py class A(): INPUTS = {} def __init__(): self.inputs = do_something(self.INPUTS) class B(A): INPUTS = function_with_external_API_call() def something_to_test(): pass # do stuff In my unit tests (using pytest) I want to have an instance of B so that I can test B.something_to_test(). However importing the class B triggers function_with_external_API_call(). This solution works but it seems like a bad solution. with requests_mock.mock() as m: m.get( 'https://url.com', json={'data': [{'id': '1'}]} ) from module import B How do I mock the function call so that I can import the class B and replace INPUTS with a mocked value?
has answer: http://stackoverflow.com/a/48221339
score: 0
tagged with: pytest
answer count: 1
has title: Python: How do I mock a function call that sets a class variable

http://stackoverflow.com/comment/83475300
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48229326
type: Comment
has text: Related: [Printing a long dictionary in the PyCharm console](https://stackoverflow.com/q/21273666/2529619)

http://stackoverflow.com/comment/83637611
comment on: http://stackoverflow.com/q/48324715
has text: I'm voting to close this question as off-topic because this is not a programming question.
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/q/48178619
has answer: http://stackoverflow.com/a/48180372
has title: Data Entry on Hidden Elements with Selenium (Python 2.7) - Elements not visible
type: AnsweredQuestion
has body: I'm writing a script to login to my bank account, using Selenium and Python 2.7. Historically, it worked, however it is now throwing an ElementNotVisibleException exception. This is my code: import time import os import subprocess from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import ui user_id = raw_input('Enter your account number') password = raw_input('Enter your password') driver = webdriver.Chrome() # Optional argument, if not specified will search path. def regular(): site = driver.get('https://www.meridiancu.ca/'); enter_user_id = driver.find_element_by_xpath('//*[@id="memberNo"]').send_keys(user_id) regular() And here is my error message: Traceback (most recent call last): File "C:\Users\Desktop\Programming\Python Files\Monthly\Banking.py", line 50, in &lt;module&gt; regular() File "C:\Users\Desktop\Programming\Python Files\Monthly\Banking.py", line 19, in regular enter_user_id = driver.find_element_by_xpath('//*[@id="memberNo"]').send_keys(user_id) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 349, in send_keys 'value': keys_to_typing(value)}) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 493, in _execute return self._parent.execute(command, params) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 256, in execute self.error_handler.check_response(response) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) ElementNotVisibleException: Message: element not visible** (Session info: chrome=63.0.3239.84) (Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 10.0.16299 x86_64) The exception is being thrown at enter_user_id = driver.find_element_by_xpath('//*[@id="memberNo"]')
tagged with: python
answer count: 4
favorite count: 0
type: Question
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/48180526
accepted answer: http://stackoverflow.com/a/48183384
downvote count: 0
tagged with: selenium
possible better answer: http://stackoverflow.com/a/48179309
has answer: http://stackoverflow.com/a/48183384
has answer: http://stackoverflow.com/a/48179309

http://stackoverflow.com/a/48316452
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83618647
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83618670
answers question: http://stackoverflow.com/q/48316383
accepted answer of: http://stackoverflow.com/q/48316383
type: Answer
has body: I think you need groupby + value_counts and last reshape by unstack: df = df.groupby('rev_id')['label'].value_counts().unstack() Or groupby by both columns and use size: df = df.groupby(['rev_id', 'label']).size().unstack() print (df) label 0.0 1.0 rev_id 37675 6 3
has comment: http://stackoverflow.com/comment/83618686
downvote count: 0

http://stackoverflow.com/comment/83451263
type: Comment
comment on: http://stackoverflow.com/a/48234086
score: 0
has text: failed to process row ['11/01/2018;79830;78590;79845;78555;;'] failed to process row ['10/01/2018;78638;78850;79025;78510;57030;'] failed to process row ['09/01/2018;79242;79750;79925;79100;67500;'] failed to process row ['08/01/2018;79829;79730;79915;79055;57270;'] And it goes
type: AnswerComment

http://stackoverflow.com/a/76756126
score: 0
has body: just add polls.apps in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls.apps' ] now you can add your template at polls/templates/polls/index.html and calling from polls via loader.get_template('polls/index.html') or render(request, 'polls/index.html', {'latest_question_list': latest_question_list, })
type: Answer
answers question: http://stackoverflow.com/q/48230590

http://stackoverflow.com/q/48261882
has title: Can I use libVLC's Python bindings with Python 3.x?
tagged with: python
has body: I want to use libVLC to build a video scheduler for Linux. The PythonBinding wiki for libVLC states that it can be used with Python version greater than 2.5. However, I couldn't find any information explicitly stating that it does or does not work with Python 3.x.
has answer: http://stackoverflow.com/a/48262102
tagged with: vlc
accepted answer: http://stackoverflow.com/a/48262102
type: AnsweredQuestion
score: 0
upvote count: 1
downvote count: 1
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: libvlc
tagged with: linux

http://stackoverflow.com/a/61354658
type: Answer
accepted answer of: http://stackoverflow.com/q/48249291
upvote count: 4
answers question: http://stackoverflow.com/q/48249291
type: AcceptedAnswer
downvote count: 0
has body: You should be able to use pd.read_table(input_file_path) and adjust the args to import your text to a single column, let's call it df['text']. Then try this: df['sents'] = df['text'].apply(lambda x: list(nlp(x).sents)) You'll have a new column with a list of sentence tokens. Good luck!
score: 4

http://stackoverflow.com/comment/83611734
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48312891
has text: Would help if you made a simple dataframe example and posted your desired output for that example dataframe.

http://stackoverflow.com/comment/83587876
has text: I don't understand where the problem is. Except for the line displaying today's date, `DateEntry` gives a result very similar to the one in the picture, the calendar appears when the user clicks on the arrow button.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48298195
score: 0

http://stackoverflow.com/comment/83485293
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48251069
score: 0
has text: What is `print (df['Days'].dtype)` ?

http://stackoverflow.com/comment/83559820
score: 0
has text: Well if I had more details I would give them. However, my code is very trivial, and yet it fails still. I'll see whether standalone mode does the trick, if not, I'll see what else I can provide :) thanks!
comment on: http://stackoverflow.com/q/48287223
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48330128
type: Question
tagged with: jit
has comment: http://stackoverflow.com/comment/84288741
tagged with: numba
tagged with: python
tagged with: optimization
score: 0
answer count: 0
upvote count: 1
type: UnansweredQuestion
has title: numba fails as soon as jitted function is called
tagged with: function
has comment: http://stackoverflow.com/comment/83673236
downvote count: 1
has body: I'm working on a bit of code to 'smooth' a .fits image, and although it works great, it's rather slow (approx. 3 minutes per image). I am trying to optimize the code using numba, but I'm stuck trying to get it to work with the functions I am calling. I believe the issue has to do with the way numba passes variables from one block to another. The function 'smoother' takes a .fits file from the specified folder and feeds it (as an array) into the 'pixcal' function. 'pixcal' turns the image into a stack (i.e. a 1024x32x32 array) and then 'pixcal' feeds this into the 'boxcar' function. 'boxcar' iterates through the image and feeds the stack into 'robust_mean' which does the actual smoothing, and then the smoothed array is returned to the beginning. Here's the pastebin: https://pastebin.com/CwDbN5D3 The code fails as soon as any of the jitted functions are called, before even a single line is executed. Does anyone have a clue what's going wrong here? Here's an error message: Analyzing file 1 of 5: image_contracted_R01_M01_N02.fits begin pixcals and smoothing (may take a while) size of image: (1024, 1024) made stack: (1024, 32, 32) boxcar smoothing Traceback (most recent call last): File "&lt;ipython-input-29-93e136cc4875&gt;", line 1, in &lt;module&gt; runfile('C:/Users', wdir='C:/Users') File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Documents/AAA_Lab_Work/Python/smoothing/good_code/combined code.py", line 197, in &lt;module&gt; smoother() File "C:/Users/Documents/AAA_Lab_Work/Python/smoothing/good_code/combined code.py", line 186, in smoother hdu = fits.PrimaryHDU(pixcal(fits.getdata(filename), width, channels)) #create hdu object to encapsulate data File "C:\ProgramData\Anaconda3\lib\site-packages\numba\dis…
favorite count: 0

http://stackoverflow.com/comment/83497117
has text: Your grammar didn't generate any parses from `trees = list(feature_cfg.parse(nlquery.split()))`. Try the same debugging steps by tearing down the grammar and rebuilding it step by step, you'll find the answer. I believe in you!
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48249488

http://stackoverflow.com/comment/83334571
type: AnswerComment
comment on: http://stackoverflow.com/a/48176806
type: Comment
has text: Don't put error messages in the comments, they are difficult to read. Edit your question and include the full traceback. You haven't shown the `host_view` URL pattern in question.
score: 0

http://stackoverflow.com/a/48271193
score: 6
has body: str.replace() will replace all occurrences of the string you pass in as the first argument. It doesn't matter here that the first argument here is created from a slice, the str.replace() method is not given any information as to where that string came from. Instead, the str.replace() method starts at position 0 and searches forward, it doesn't matter where the substring is found in the input string. So you are really just doing this: string_to_replace = s[9:12] s.replace(string_to_replace, ' ') or even just s.replace('111', ' ') These all have the exact same effect. Your second example only worked because the s[9:12] string value is unique in s; there is only one occurrence to replace, at exactly the right location. Because s[9:12] is the string '111', you asked Python to replace all occurances of that string in s with spaces, and there are two such sequences to replace. You are far better off explicitly slicing the input string: s = s[:9] + ' ' + s[12:] That takes all text before the part you want to replace and all the text after, and puts three spaces in between those two substrings.
accepted answer of: http://stackoverflow.com/q/48271169
upvote count: 6
type: Answer
answers question: http://stackoverflow.com/q/48271169
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/96766067
comment on: http://stackoverflow.com/a/53228531
score: 0
has text: I get the following error `installer: Error - the package path specified was invalid: '/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg'.` on Mojave 10.14
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83475071
type: QuestionComment
comment on: http://stackoverflow.com/q/48246135
score: 0
type: Comment
has text: I don't want to threshold B, I want to threshold A and positions/indexes that are has value less than the threshold has to be made zero in array B.

http://stackoverflow.com/comment/83366626
comment on: http://stackoverflow.com/a/48179671
score: 0
has text: It is likely your row[1] is price column, which contains integer values, hence you are getting this error. You will have to then edit this line: `entry[row[1]+" Price"] = row[2]` with appropriate indices.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83367095
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48188082
has text: Yes, what is print.df.columns?

http://stackoverflow.com/comment/83535310
has text: name `self.y` is missleading - it should name `self.speed` or `self.move`. In `self.y` you could rather keep positon and then you would no need `pos = self.canvas.coords(self.id)`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48273725

http://stackoverflow.com/a/48293183
has comment: http://stackoverflow.com/comment/83599914
has body: This question was recently answered on github and turns out to be a bug stemming from how plotnine interfaces with numpy. You can avoid the problem with: ... + scale_size_manual(values=(3,3,3,3), na_value=-1)
score: 1
accepted answer of: http://stackoverflow.com/q/48290566
type: Answer
answers question: http://stackoverflow.com/q/48290566
downvote count: 0
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48296986
tagged with: python
tagged with: design-patterns
has comment: http://stackoverflow.com/comment/83586894
has title: Designing REST API architecture and implementation
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83587611
upvote count: 3
tagged with: multithreading
answer count: 1
has answer: http://stackoverflow.com/a/48445874
accepted answer: http://stackoverflow.com/a/48445874
has body: Currently I am designing and programming a piece of software that controls a series of devices. The software is planned to have a REST interface through which you would be able to control the software (and the devices) remotely. Now, a very basic abstraction of the architecture could look something like this: As you can note, the system is composed of a master controller, which then handles and monitors different modules that are not dependent on each other. Front End module is an example in the diagram, while others are general abstractions of modules, but they could be anything (Database module, MessageBus module, etc). For the actual REST interface there are both data retrieval, data storage, as well as control commands that are being implemented. My "problem" is that I can't decide on how these "commands" should be propagated down the line. Some cases of possible commands: Command requesting to turn on/off, restart, control a device handled by another module Command requesting to restart/reload the software Command to retrieve data from another module Now I see a few possible ways of the actual logic implementation: All received REST commands are dispatched through a message bus. In this case each request should receive a unique identifier which could be then used to retrieve the status of the request All received REST commands make direct calls to other modules Both of these have pros and cons: The second method of doing everything could very easily fall into spaghetti code and would be hard to debug and expand upon, since there's a lot of multithreading utilization through different modules. But it is possibly the fastest way of handling a command and retrieving data. Especially since the project requires speed and responsiveness. The first method lacks the advantages of the second method, however it would help to keep the code and architecture clean and clear of dependencies from other modules. Furthermore, a Console channel is also planned which could in the…
downvote count: 1
favorite count: 0
type: Question
tagged with: rest
tagged with: restful-architecture

http://stackoverflow.com/a/48203978
answers question: http://stackoverflow.com/q/48203552
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48203552
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/83389083
has body: If you have the data in advance, we can use numpy and/or pandas to first calculate the distance in bulk, and then load the data into a graph. Say for instance we can first construct an n&times;2-matrix with: import numpy as np A = np.array([list(get_coord()) for _ in range(L)]) We then can use scipy to calcuate a 2d matrix of distances, for example: from scipy.spatial.distance import pdist, squareform B = squareform(pdist(A)) If for instance A is: &gt;&gt;&gt; A array([[ 0.16401235, -0.60536247], [ 0.19705099, 1.74907373], [ 1.13078545, 2.03750256], [ 0.52009543, 0.25292921], [-0.8018697 , -1.45384157], [-1.37731085, 0.20679761], [-1.52384856, 0.14468123], [-0.12788698, 0.22348265], [-0.27158565, 0.21804304], [-0.03256846, -2.85381269]]) then B will be: &gt;&gt;&gt; B array([[ 0. , 2.354668 , 2.81414033, 0.92922536, 1.28563016, 1.74220584, 1.84700839, 0.8787431 , 0.93152683, 2.25702734], [ 2.354668 , 0. , 0.97726722, 1.53062279, 3.35507213, 2.20391262, 2.35277933, 1.5598118 , 1.60114811, 4.60861026], [ 2.81414033, 0.97726722, 0. , 1.88617187, 3.99056885, 3.10516145, 3.26034573, 2.20792312, 2.29718907, 5.02775867], [ 0.92922536, 1.53062279, 1.88617187, 0. , 2.15885579, 1.897967 , 2.04680841, 0.64865114, 0.79244935, 3.15551623], [ 1.28563016, 3.35507213, 3.99056885, 2.15885579, 0. , 1.75751388, 1.7540036 , 1.80766956, 1.75396674, 1.59741777], [ 1.74220584, 2.20391262, 3.10516145, 1.897967 , 1.75751388, 0. , 0.1591595 , 1.24953527, 1.10578239, 3.34300278], [ 1.84700839, 2.35277933, 3.26034573, 2.04680841, 1.7540036 , 0.1591595 , 0. , 1.39818396, 1.25440996, 3.34886281], [ 0.8787431 , 1.5598118 , 2.20792312, 0.64865114, 1.80766956, 1.24953527, 1.39818396, 0. , 0.14380159, 3.07877122], [ 0.93152683, 1.60114811, 2.29718907, 0.79244935, 1.75396674, 1.10578239, 1.25440996, 0.14380159, 0. , 3.08114051], [ 2.25702734, 4.60861026, 5.02775867, 3.15551623, 1.59741777, 3.34300278, 3.34886281, 3.07877122, 3.08114051, 0. ]]) And now we can construct a graph based on that matrix: G …
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/83394176
type: Comment
type: QuestionComment
score: 0
has text: Yes, I only upgraded the instance from t2.small to t2.medium and ran the same script.
comment on: http://stackoverflow.com/q/48206439

http://stackoverflow.com/comment/83474032
has text: While creating a text file using app_identity.get_default_gcs_bucket_name(). ```bucket_name = os.environ.get( 'BUCKET_NAME', app_identity.get_default_gcs_bucket_name())``` i didn't get any errors below are the executed lines. ```default: "POST /_ah/gcs/app_default_bucket/sample12.txt HTTP/1.1" 201 - default: "PUT /_ah/gcs/app_default_bucket/sample12.txt?upload_id=encoded_g‌​s_file%3AYXBwX2RlZdA‌​%3D%3D HTTP/1.1" 200``` i couldn't find the sample12.txt in the bucket. This issue is the same if i use the bucket 'bucket-name-12345.appspot.com' @DanCornilescu
comment on: http://stackoverflow.com/q/48240489
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83469735
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48243492
has text: Please provide a [MCVE](https://stackoverflow.com/help/mcve) - your code is "vague". For example `weighting = speed * time` is not a function, and it is completely unclear how the elements of `database` are even relevant and supposed to be used.

virtual-machine
tag name: virtual-machine
tags question: http://stackoverflow.com/q/48264822
type: Tag

http://stackoverflow.com/comment/83518134
comment on: http://stackoverflow.com/q/48267348
has text: @match Can you please elaborate because I didn't anything you just said :)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48250714
type: Answer
answers question: http://stackoverflow.com/q/48235589
score: 0
has body: The question was duplicated on the PsychoPy forum and was answered there: https://discourse.psychopy.org/t/stimuli-on-mac-retina-display-are-in-bottom-left-corner/3739/3

http://stackoverflow.com/comment/83546631
comment on: http://stackoverflow.com/q/48281521
type: Comment
type: QuestionComment
has text: @ezdazuzena This is the code for that: ` @staticmethod def categoryExists(name): try: return Category.objects.get(name=name) is not None except DoesNotExist: return False `
score: 0

http://stackoverflow.com/q/48254520
has body: I'm trying to run a K-Means Clustering algorithm with numpy and python, but keep running into a memory error if I use larger values of K (anything greater than 10 seems to result in the error). I have two numpy arrays of size [42000,784] (the dataset) and [K,784] (the centroids). The memory error occurs when calculating the euclidean distance between each of the centroids and each of the data points. This is the function I have been using: def dist(a,b): a = a[np.newaxis,:,:] b = b[:,np.newaxis,:] dist = np.linalg.norm((a-b), axis=2) return dist Is this a memory leak or do I legitimately not have enough memory (I have 8GB)? How can I fix this?
has answer: http://stackoverflow.com/a/48260902
has comment: http://stackoverflow.com/comment/83491780
answer count: 2
tagged with: k-means
tagged with: memory-leaks
tagged with: python
linked to: http://stackoverflow.com/q/53376686
has comment: http://stackoverflow.com/comment/83492217
has comment: http://stackoverflow.com/comment/83492583
has comment: http://stackoverflow.com/comment/83491781
score: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/72566612
type: AnsweredQuestion
tagged with: ram
downvote count: 0
has answer: http://stackoverflow.com/a/72566612
has comment: http://stackoverflow.com/comment/83492411
favorite count: 0
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48260902
has title: Memory Error Numpy/Python Euclidean Distance
type: Question

http://stackoverflow.com/a/48238449
answers question: http://stackoverflow.com/q/48238432
type: Answer
score: 1
downvote count: 0
upvote count: 1
has body: Using _ for a throw-away variable (one where the code will not use the contents) is self-documenting. Any one who reads the code will immediately see that not using the variable's contents is not an error. (At least, any one who reads the code and is familiar with Python's conventions.)

http://stackoverflow.com/a/48274349
downvote count: 0
upvote count: 1
has body: I guess at some point in your image frame there must be some small components with hue value in the blue range that is why you are getting blue color as false positive. Here is what i would suggest: You can segment the ball in the image and then check hue channel inside of ball spatial region, but this might be not be time efficient. Or else you can find number of all three classes of pixels(Red, green, blue color) present in image frames by using corresponding hue filters that is: Blue color: (95, 0, 0) - (145, 255,255) Green color: (36, 0, 0), (70, 255,255) Red color: [(165, 0, 0) - (180, 255,255)] and [(0, 0, 0) - (15, 255,255)] Maximum of all three classes of pixels will give you true color of ball. I hope that helps.
answers question: http://stackoverflow.com/q/48268272
type: Answer
score: 1

http://stackoverflow.com/comment/133132483
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48327162
type: Comment
has text: It won't work due to artificially queued `None` at the end of the `ThreadPoolExecutor.shutdown()` (see the queue.py for details). The `SimpleQueue()` won't bother about it, but the `Queue` will do and this will deadlock the class upon termination. So it's required to tweak the `shutdown()` method as well and add something like `self._work_queue.get(block=False)`. Probably, this will make the approach too tricky to use.

http://stackoverflow.com/comment/83545287
comment on: http://stackoverflow.com/a/48278392
type: AnswerComment
score: 0
has text: This much only I have written after the code from your answer:- time.sleep(5) select_element.select_by_visible_text("Acura") Also to retrieve data from page, I am supposed to use 'select_element' variable rght? Or some other element
type: Comment

http://stackoverflow.com/a/48290369
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48290283
score: 3
has body: Python for-loops are iterator-based "for-each" loops. The iterating variable is reassigned at the beginning of each iteration. In other words, the following loop: In [15]: nums = 1,2,5,8 In [16]: for num in nums: ...: print(num) ...: 1 2 5 8 Is equivalent to: In [17]: it = iter(nums) ...: while True: ...: try: ...: num = next(it) ...: except StopIteration: ...: break ...: print(num) ...: 1 2 5 8 Similarly, the following loops are equivalent: In [19]: for num in nums: ...: print("num:", num) ...: num += 1 ...: print("num + 1:", num) ...: ...: num: 1 num + 1: 2 num: 2 num + 1: 3 num: 5 num + 1: 6 num: 8 num + 1: 9 In [20]: it = iter(nums) ...: while True: ...: try: ...: num = next(it) ...: except StopIteration: ...: break ...: print("num:", num) ...: num += 1 ...: print("num + 1:", num) ...: num: 1 num + 1: 2 num: 2 num + 1: 3 num: 5 num + 1: 6 num: 8 num + 1: 9 Note, C-style for-loops don't exist in Python, but you can always write a while-loop (c-style for loops are essentially syntactic sugar for while-loops): for(int i = 0; i &lt; n; i++){ // do stuff } Is equivalent to: i = 0 while i &lt; n: # do stuff i += 1 Note, the difference is that in this case, iteration depends on i, anything in # do stuff that modifies i will impact iteration, whereas in the former case, iteration depends on the iterator. Note, if we do modify the iterator, then iteration is impacted: In [25]: it = iter(nums) # give us an iterator ...: for num in it: ...: print(num) ...: junk = next(it) # modifying the iterator by taking next value ...: ...: 1 5
has comment: http://stackoverflow.com/comment/83565988
type: Answer
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83565968
has comment: http://stackoverflow.com/comment/83565984
answers question: http://stackoverflow.com/q/48290283

http://stackoverflow.com/comment/117881974
type: AnswerComment
has text: Is it possible to change "level_0", "level_1", "0"? For example, to "From", "To", "Weight"?
type: Comment
comment on: http://stackoverflow.com/a/48219579
score: 0

http://stackoverflow.com/comment/83659001
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48273451
has text: OK, here it is!
score: 0

http://stackoverflow.com/comment/83415899
score: 0
comment on: http://stackoverflow.com/q/48216921
type: Comment
type: QuestionComment
has text: I think this question is better suited for [Code Review](https://codereview.stackexchange.com/), because there doesn't actually seem to be a question here.

http://stackoverflow.com/a/48176217
has comment: http://stackoverflow.com/comment/83341995
has comment: http://stackoverflow.com/comment/83386224
type: Answer
answers question: http://stackoverflow.com/q/48174005
has body: Compression is good because it saves at-rest storage and transfer bandwidth (both in terms of local disk I/O and network), but it does so at the cost of computing power. These are the metrics that you want to keep in mind when selecting a compression algorithm for your data: depending on the kind of expectation that you have, you can decide to select the appropriate one. But in general, Snappy has been specifically designed to be relatively easy on CPU while providing a fair storage/bandwidth saving, which makes it more than appropriate for many use cases (which is why it's the default). The sensible suggestion is of course to measure and come to a decision based on your observations on your particular setup, but I believe it's fair to say you should not expect a massive relative improvement on resource usage (but probably enough to be of some economic relevance if you are working with a truly massive cluster).
score: 0

http://stackoverflow.com/comment/83646324
has text: And can you post a sample/desired output?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48330147
score: 0

http://stackoverflow.com/comment/83510860
type: AnswerComment
comment on: http://stackoverflow.com/a/48237347
type: Comment
has text: @user32185. I think you are right. I looked through the [github](https://github.com/facebook/prophet/blob/master/python/fbprophet/forecaster.py) source code, and found `df2['yhat'] = df2['trend'] + df2['seasonal']` under the predict method for the Prophet object.
score: 0

http://stackoverflow.com/comment/83465488
has text: What is your project structure? Is the frontend being hosted on the django server or is it being hosted on a node.js server?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48239941
score: 0

http://stackoverflow.com/comment/83633617
type: Comment
type: QuestionComment
has text: Yes, and there you can see that the threshold does not eliminate interference. With the Gabor filter only the road markings are left, no kerbstones or other bright disturbing objects.
comment on: http://stackoverflow.com/q/48322461
score: 0

http://stackoverflow.com/q/48197621
has body: I'm trying to pass variables to query for hive database but I have run into unicodedecoderError as below. Below is my codes. import pyodbc import pandas as pd var1 = 'UCSB' my_connection = pyodbc.connect('DSN=MapR-64-Hive', autocommit=True) my_cursor = my_connection.cursor() my_query = """ select * from polaris_datasets.snmaster where parent_pid rlike ‘%s’ and created_date &gt;= "2017-12-01 00:00:00" """ my_cursor.execute(my_query, var1) and the Error is as below. &gt;&gt;&gt; my_cursor.execute(my_query, var1) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 70: ordinal not in range(128) I'm not sure if this is syntax issue or encoding issue so I need to change somewhere?
tagged with: hive
score: 0
tagged with: sql
has title: UnicodedecoderError;'ascii' codec cant' decode when querying data on hive with python
tagged with: python
tagged with: odbc
has answer: http://stackoverflow.com/a/48197791
type: Question
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/83447871
type: Comment
comment on: http://stackoverflow.com/a/48226927
type: AnswerComment
score: 0
has text: Uh, well the question is a classic X-Y question, asking about the attempted (and not very well reasoned) solution, and not about the problem. First, fit in log-space, second be mindful of the small data set, and third recognize that setting tight bounds on the model (especially at data values) will *prevent* a thorough explanation of parameter space. The question also includes "why doesn't it give the answer from <some other approach>?". I have no idea what that other approach does. Is that sad?

http://stackoverflow.com/q/48274890
has answer: http://stackoverflow.com/a/48275417
tagged with: unicode-literals
has body: Here's a small example: reg = ur"((?P&lt;initial&gt;[+\-])(?P&lt;rest&gt;.+?))$" (In both cases the file has -*- coding: utf-8 -*-) In Python 2: re.match(reg, u"hello").groupdict() # =&gt; {u'initial': u'\ud83d', u'rest': u'\udc4dhello'} # unicode why must you do this Whereas, in Python 3: re.match(reg, "hello").groupdict() # =&gt; {'initial': '', 'rest': 'hello'} The above behaviour is 100% perfect, but switching to Python 3 is currently not an option. What's the best way to replicate 3's results in 2, that works in both narrow and wide Python builds? The appears to be coming to me in the format "\ud83d\udc4d", which is what's making this tricky.
has comment: http://stackoverflow.com/comment/83534842
has comment: http://stackoverflow.com/comment/83699184
has title: Treat an emoji as one character in a regex
downvote count: 0
has comment: http://stackoverflow.com/comment/83534534
linked to: http://stackoverflow.com/q/29109944
score: 11
has answer: http://stackoverflow.com/a/48275291
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48275247
accepted answer: http://stackoverflow.com/a/48357332
linked to: http://stackoverflow.com/q/35404144
tagged with: python-unicode
has answer: http://stackoverflow.com/a/48357332
tagged with: python
possible better answer: http://stackoverflow.com/a/48275291
duplicate of: http://stackoverflow.com/q/26568722
tagged with: regex
has comment: http://stackoverflow.com/comment/83534690
answer count: 4
upvote count: 11
favorite count: 0
has comment: http://stackoverflow.com/comment/83697069
type: Question

http://stackoverflow.com/q/48223231
downvote count: 1
favorite count: 0
tagged with: combinations
type: AnsweredQuestion
score: 0
tagged with: sequence
tagged with: gray-code
has answer: http://stackoverflow.com/a/48223616
accepted answer: http://stackoverflow.com/a/48223616
type: Question
has comment: http://stackoverflow.com/comment/83428102
has body: Below is a vector with all the possible combinations of 2 binary values: [(1,1),(1,0),(0,1),(0,0)] Now, the question is how I can generate a sequence of the same combinations of 2 binary values that each of them has only one component changed compared to previous one in the sequence such as: [(1,0),(1,1),(0,1),(0,0)]
upvote count: 1
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83428148
has title: All combinations of n binary values in an order that just one component changes compared to the prior combination

http://stackoverflow.com/comment/83423017
has text: Thanks for the great answer! That's a lot more than I bargained for, I will have to take some time to read it carefully!
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48220250

http://stackoverflow.com/q/48249589
tagged with: git
favorite count: 0
has body: I'm trying to run this repository from Github, in order to work on it. I downloaded the files but i keep getting the error 'no module named pyttrex' (pyttrex is the name of the repository). I tried to install it using pip (pip install pyttrex) but pip didn't even find the module, after that i tried with pip install git+https://github.com/icoprimers/pyttrex, but i got the error Command "python setup.py egg_info" failed with error code 1, although setuptools is upgraded. I have two versions of python installed: 2.7 and 3.6, i just can't see the error.
type: Question
has comment: http://stackoverflow.com/comment/83481875
has comment: http://stackoverflow.com/comment/83481764
has comment: http://stackoverflow.com/comment/83481745
has comment: http://stackoverflow.com/comment/83482005
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83482521
upvote count: 2
has answer: http://stackoverflow.com/a/48250243
accepted answer: http://stackoverflow.com/a/48250243
score: 1
answer count: 1
has title: Can't install a github repository
has comment: http://stackoverflow.com/comment/83481680
downvote count: 1

http://stackoverflow.com/q/48303173
accepted answer: http://stackoverflow.com/a/48303277
has body: Do I have to explicitly release/unbind a socket so that it can be reused? I'm thinking of using close() but I have seen some options like tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1). Do I have to use it or is close() enough? Is there any way to make sure that port is free for new bind? TorPorts = {} def port_setup(workers): for worker in range(workers): for i in range(2): tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp.bind(('', 0)) port = tcp.getsockname()[1] print("{0} port {1}, tcp {2}".format(i,port,tcp)) if not TorPorts.has_key(worker): TorPorts[worker] = {0:{},1:{}} TorPorts[worker][i] = {"port":port,"tcp":tcp} # do some programing # close ports I s this enough? for thread,ports in TorPorts[0].items(): tcp_port = ports["tcp"] tcp_port.close()
downvote count: 0
answer count: 1
score: 6
favorite count: 0
type: Question
tagged with: sockets
has answer: http://stackoverflow.com/a/48303277
tagged with: python
upvote count: 6
has title: Do I have to "unbind" socket after binding free socket?
type: AnsweredQuestion

http://stackoverflow.com/comment/83605694
score: 0
type: AnswerComment
type: Comment
has text: You're right. It was a coincidence that when I ran the code previously without the Try and Except, that no exceptions were raised. I tried it again and it turned out to be an encoding issue - trying to write an unsupported unicode character into a latin-1 encoded csv file. Thanks to everyone for their help and sorry for the lack of exhaustive testing.
comment on: http://stackoverflow.com/a/48309783

http://stackoverflow.com/a/48313112
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48312773
has comment: http://stackoverflow.com/comment/83612257
answers question: http://stackoverflow.com/q/48312773
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You do not have to rotate the item, but you must rotate the image for it you can use numpy.rot90: i = Image.open("del.png") a = array(i) a = np.rot90(a, -1) img1a = pg.ImageItem(a) v1a.addItem(img1a) v1a.disableAutoRange('xy') v1a.autoRange()

http://stackoverflow.com/comment/83444774
comment on: http://stackoverflow.com/a/48196568
score: 0
type: Comment
has text: Is the client the same as the server? Or are you using different machines?
type: AnswerComment

http://stackoverflow.com/a/48228443
has body: Raster cells have a cell size. So if you have a raster file with x-rows and y-cols, you just need to determine either of the following: min/max coordinate in the X and Y directions lower-left x/y coordinate pair Once you find either of these, simple calculations determine what the center coordinate is based on the index of the 1 in the raster file.
upvote count: 1
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48228018

http://stackoverflow.com/comment/83491735
comment on: http://stackoverflow.com/a/48254369
has text: Hi @Maxim, I am getting the following error: `ValueError: Variable fully_connected_1/kernel does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=None in VarScope?`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83452795
has text: @smart I'm not sure why you have that type error on `write()`. See [here](https://tio.run/##TY0xDsIwEAT7vGIRhRMJpeAVpKCCEgklyhFb4FzkOxP59caBhm52pdldklqejzk7v3BQSJID1HmqqoKt6MhR2zU4pdp06D36oTRQhlhekThC2JNaN0@43wbT/IuPVxRbN9jj3D8JEgNtA@@CGjZjIhUsBZVGuPl3/c21uZ66y840OX8A) the code runs fine (except `\b` is not recognized)
type: AnswerComment
comment on: http://stackoverflow.com/a/48179261
score: 0
type: Comment

apache-spark-2.2
tag name: apache-spark-2.2
type: Tag
tags question: http://stackoverflow.com/q/48262409

http://stackoverflow.com/q/48327695
has title: PyHook for Python 3.6
has answer: http://stackoverflow.com/a/48705679
downvote count: 0
has body: Hello does anyone have succeded in installing pyHook on the last python version C:\Users\T&gt;python --version Python 3.6.4 C:\Users\T&gt;pip install pyHook Collecting pyHook Could not find a version that satisfies the requirement pyHook (from versions: ) No matching distribution found for pyHook C:\Users\T&gt;pip install pyHook-1.5.1-cp36-cp36m-win_amd64.whl pyHook-1.5.1-cp36-cp36m-win_amd64.whl is not a supported wheel on this platform. Everythingi've try so far are not working at all.
score: 1
tagged with: pyhook
answer count: 1
tagged with: python
tagged with: windows-10
favorite count: 0
type: Question
upvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/83335619
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48176885
has text: `DEBUG=False` and has done for a while. However, I have just checked Nginx config and `location /static/ ...` is set but not `location /media/ ...`. Do you think that's the problem?
score: 0

http://stackoverflow.com/q/48199167
score: -1
has body: I created a simple function in PySpark which swaps the key,value pair and return it. def swap(x): swapped = lambda x: (x[1],x[0]) return swapped I have an RDD which gives the count of words in a file: wordsCount = wordsSplit.reduceByKey(lambda a,b: (a+b)) Now, when I call the function to swap key,value pairs, it throws an error: wordsCountSwap = wordsCount.map(swap) wordsCountSwap.collect() Error: Caused by: org.apache.spark.api.python.PythonException: Traceback (most recent call last): File "/home/sumit/spark-2.2.0-bin-hadoop2.7/python/lib/pyspark.zip/pyspark/worker.py", line 177, in main process() File "/home/sumit/spark-2.2.0-bin-hadoop2.7/python/lib/pyspark.zip/pyspark/worker.py", line 172, in process serializer.dump_stream(func(split_index, iterator), outfile) File "/home/sumit/spark-2.2.0-bin-hadoop2.7/python/lib/pyspark.zip/pyspark/serializers.py", line 272, in dump_stream bytes = self.serializer.dumps(vs) File "/home/sumit/spark-2.2.0-bin-hadoop2.7/python/lib/pyspark.zip/pyspark/serializers.py", line 447, in dumps return pickle.dumps(obj, protocol) TypeError: expected string or Unicode object, NoneType found Can anyone help me out? P.S.: I'm able to perform the same task by using a simple lambda expression! swap = lambda x : (x[1],x[0]) wordsCountSwap = wordsCount.map(swap) wordsCountSwap.collect()
tagged with: apache-spark
tagged with: functional-programming
type: AnsweredQuestion
upvote count: 0
possible better answer: http://stackoverflow.com/a/48199208
has answer: http://stackoverflow.com/a/48199208
downvote count: 1
accepted answer: http://stackoverflow.com/a/48199197
favorite count: 0
has answer: http://stackoverflow.com/a/48199197
type: Question
answer count: 2
tagged with: pyspark
tagged with: python
has title: Error While calling a function in PySpark

http://stackoverflow.com/q/48269756
has comment: http://stackoverflow.com/comment/83523174
has title: pip install & UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 9: invalid continuation byte
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48272136
has comment: http://stackoverflow.com/comment/83525325
has answer: http://stackoverflow.com/a/48272136
has answer: http://stackoverflow.com/a/77298157
possible better answer: http://stackoverflow.com/a/49906931
tagged with: python
has answer: http://stackoverflow.com/a/49906931
score: 2
has body: Try install: pip install python-binance Result: Exception: Traceback (most recent call last): File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\compat\__init__.py", line 73, in console_to_str return s.decode(sys.__stdout__.encoding) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 9: invalid continuation byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_set.py", line 634, in _prepare_file abstract_dist.prep_for_dist() File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_set.py", line 129, in prep_for_dist self.req_to_install.run_egg_info() File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_install.py", line 439, in run_egg_info command_desc='python setup.py egg_info') File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\utils\__init__.py", line 676, in call_subprocess line = console_to_str(proc.stdout.readline()) File "c:\users\анна\appdata\local\programs\python\python36\lib\site-packages\pip\compat\__init__.py", line 75, in console_to_str return s.decode('utf_8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 9: invalid continuation byte How to solve?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83525845
answer count: 3
upvote count: 2
downvote count: 0
tagged with: pip

http://stackoverflow.com/comment/83699184
has text: @MariusGedminas Yeah, that's precisely the problem I'm having here - the character consists of a string with two "\u" codepoints.
type: QuestionComment
comment on: http://stackoverflow.com/q/48274890
score: 0
type: Comment

http://stackoverflow.com/comment/83600601
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48290132
has text: @CristiFati yes
score: 0

http://stackoverflow.com/a/48298613
answers question: http://stackoverflow.com/q/48278187
type: Answer
has body: Thank you @match for the right tips. Problem was I was using nargs='+' in the argparse definition #!/usr/bin/env python # -*- coding: utf-8 -*- import os import argparse import sys import glob parser = argparse.ArgumentParser() parser.add_argument('-input', dest='input',help="input one or more files",metavar=None) args = parser.parse_args() def dirlist(path, c = 1): for i in glob.glob(os.path.join(path, "*")): if os.path.isfile(i): filepath, filename = os.path.split(i) print ('----' *c + filename) elif os.path.isdir(i): dirname = os.path.basename(i) print ('----' *c + dirname) c+=1 dirlist(i,c) c-=1 path = os.path.normpath(args.input) print(os.path.basename(path)) dirlist(path) The code works now!
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48278187
score: 0

http://stackoverflow.com/comment/83626973
comment on: http://stackoverflow.com/q/48273451
has text: @Maciek why don't you just write an answer based on your comment?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83336104
comment on: http://stackoverflow.com/q/48177941
score: 0
type: Comment
has text: @MarkRansom well the XY problem is a real thing
type: QuestionComment

http://stackoverflow.com/q/48191071
score: 0
has comment: http://stackoverflow.com/comment/83363376
answer count: 1
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/83362782
type: UnansweredQuestion
tagged with: django-models
tagged with: python
linked to: http://stackoverflow.com/q/7375875
has title: Django models - Able to dynamically calculate the value of a field
has answer: http://stackoverflow.com/a/48191670
has body: Say for example I have a rating which is attached to a product model like so.. class Product(models.Model): ... rating = models.IntegerField(...) I want the product rating to change as new Reviews (that include a star rating of the product) change or updated/deleted. class Review(models.Model): ... related_product = models.ForeignKey(Product, on_delete=models.CASCADE, ...) rating = models.IntegerField(...) Initially, I used a method on the product class to calculate the value of rating by counting the rating value from each review and then dividing by the number of reviews to get an average. class Product(models.Model): ... def rating(self): total_rating = ... reviews_count = ... average = total_rating / reviews_count However, this doesn't allow me to use order_by('rating') when querying the objects and sending back the objects by order of their rating since 'rating' has to be defined in the database (i.e. as a field instead of a method). Is there any way that I can calculate the value for rating which is then stored in the database?

http://stackoverflow.com/comment/83472933
type: Comment
score: 0
has text: Could you write out the code for me?
comment on: http://stackoverflow.com/q/48244479
type: QuestionComment

http://stackoverflow.com/comment/83684477
type: AnswerComment
comment on: http://stackoverflow.com/a/48329220
type: Comment
has text: Just one more thing... How can I align the labels to the left? Just like the picture that I displayed before
score: 0

http://stackoverflow.com/a/48279780
answers question: http://stackoverflow.com/q/48279640
has body: First you connect the original values to its index list. Then you sort it and the original indexes are attched to the new sorted values. Finally unzip them to get both lists. i_xs = [(x, i) for (i, x) in enumerate(xs)] s = sorted(i_xs) sorted_xs, index_lst = unzip(s) Using this def unzip(ls): if isinstance(ls, list): if not ls: return [], [] else: xs, ys = zip(*ls) return list(xs), list(ys) else: raise TypeError Example. In: [34, 23424, 1212, -2324, 34353] Out: [-2324, 34, 1212, 23424, 34353] [3, 0, 2, 1, 4]
upvote count: 2
score: 2
downvote count: 0
type: Answer

http://stackoverflow.com/q/48246400
favorite count: 0
tagged with: beautifulsoup
type: AnsweredQuestion
tagged with: python
score: 4
accepted answer: http://stackoverflow.com/a/48246492
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/48246526
has title: Preserving BeautifulSoup selection order
has answer: http://stackoverflow.com/a/48246492
answer count: 2
has body: If I have a simple document like: hi hello bye try why And I store it in a BeautifulSoup object called doc, calling: > doc.select('p, q') [ hi , bye , why , hello , try ] Is it possible to get these elements in the correct order? I would like to number these tags so that "hi" gets 1, "hello" gets 2 and so on... This is a minimal example, but in practice I will have to select by class, id and tag name.
downvote count: 0
has comment: http://stackoverflow.com/comment/83475667
possible better answer: http://stackoverflow.com/a/48246526

http://stackoverflow.com/comment/83432702
type: QuestionComment
comment on: http://stackoverflow.com/q/48225473
type: Comment
score: 0
has text: These are incomplete code snippets, and you haven't posted the full traceback.

http://stackoverflow.com/q/48193010
type: Question
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/48194681
has comment: http://stackoverflow.com/comment/83371297
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48193437
has body: I am very new to python (three days in) and I have stumbled into a problem I can't solve with google/youtube. I want to scrape the National Governors Association for background data of all US governors and save this into a csv file. I have managed to scrape a list of all governors, but to get more details I need to enter the page of each governor individually and save the data. I have found code suggestions online which utilises a "next" button or the url structure to loop over several sites. This website, however, does not have a next button and the url-links does not follow a loopable structure. So I am stuck. I would appreciate any help I can get very much. I want to extract the info above the main text (Office Dates, School(s) etc in the "address" tag) in each governors page, for example in this one. This is what I have got so far: import bs4 as bs import urllib.request import pandas as pd url = 'https://www.nga.org/cms/FormerGovBios?begincac77e09-db17-41cb-9de0-687b843338d0=10&amp;endcac77e09-db17-41cb-9de0-687b843338d0=9999&amp;pagesizecac77e09-db17-41cb-9de0-687b843338d0=10&amp;militaryService=&amp;higherOfficesServed=&amp;religion=&amp;lastName=&amp;sex=Any&amp;honors=&amp;submit=Search&amp;college=&amp;firstName=&amp;party=&amp;inOffice=Any&amp;biography=&amp;warsServed=&amp;' sauce = urllib.request.urlopen(url).read() soup = bs.BeautifulSoup(sauce, "html.parser") #dl list of all govs dfs = pd.read_html(url, header=0) for df in dfs: df.to_csv('governors.csv') #dl links to each gov table = soup.find('table', 'table table-striped table-striped') links = table.findAll('a') with open ('governors_links.csv', 'w') as r: for link in links: r.write(link['href']) r.write('\n') r.close() #enter each gov page and extract data in the "address" tag(s) #save this in a csv file
tagged with: python
score: -2
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/83367223
linked to: http://stackoverflow.com/q/33895739
upvote count: 0
downvote count: 2
has title: Scrape site with multiple links without "next" button using beautiful soup
tagged with: web-scraping
favorite count: 0

http://stackoverflow.com/comment/83481195
type: Comment
type: QuestionComment
has text: @ChristopherChu Your code works on myside with python2.7 & beautifulsoup4==4.6.0
comment on: http://stackoverflow.com/q/48248653
score: 0

http://stackoverflow.com/comment/83417197
type: QuestionComment
comment on: http://stackoverflow.com/q/48217503
has text: You may use [`\(2\)\s*(\d[\d,.]*)`](https://regex101.com/r/F7PGN0/1) and grab Group 1 value. A more specific pattern can be written as [`\(2\)\s*(\d+(?:,\d+)*\.\d+)`](https://regex101.com/r/F7PGN0/2).
type: Comment
score: 1

http://stackoverflow.com/comment/83574222
score: 0
has text: Can you add data sample?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48294729

http://stackoverflow.com/q/48257449
has comment: http://stackoverflow.com/comment/83516753
has comment: http://stackoverflow.com/comment/83497523
has comment: http://stackoverflow.com/comment/83499165
score: 2
has comment: http://stackoverflow.com/comment/83499061
type: AnsweredQuestion
answer count: 3
has body: I have a data frame as: a b c d...... 1 1 3 3 3 5 4 1 1 4 6 1 0 I want to select number of columns based on value given in column "a". In this case for first row it would only select column b. How can I achieve something like: df.iloc[:,column b:number of columns corresponding to value in column a] My expected output would be: a b c d e 1 1 0 0 1 # 'e' contains value in column b because colmn a = 1 3 3 3 5 335 # 'e' contains values of column b,c,d because colm a 4 1 1 4 1 # = 3 1 0 NAN
tagged with: pandas
has comment: http://stackoverflow.com/comment/83498461
has comment: http://stackoverflow.com/comment/83497588
has comment: http://stackoverflow.com/comment/83499280
has comment: http://stackoverflow.com/comment/83498263
has title: Selecting columns based on value given in other column using pandas in python
has comment: http://stackoverflow.com/comment/83498050
has answer: http://stackoverflow.com/a/48260846
accepted answer: http://stackoverflow.com/a/48260846
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83498245
has answer: http://stackoverflow.com/a/48257507
possible better answer: http://stackoverflow.com/a/48257507
upvote count: 2
has comment: http://stackoverflow.com/comment/83498585
downvote count: 0
has answer: http://stackoverflow.com/a/48257768
has comment: http://stackoverflow.com/comment/83523930
tagged with: python

http://stackoverflow.com/q/48293507
upvote count: 1
has answer: http://stackoverflow.com/a/48293580
downvote count: 1
favorite count: 0
type: Question
has body: I just copied and pasted this code from the documentation page and I used pip to successfully install the package yet I keep running into this error: File "c:\Users\Guppy\Desktop\RACHEAL\RACHEALs Tools\Applications\Weather\weather.py", line 1, in &lt;module&gt; from weather import Weather ImportError: cannot import name 'Weather' Heres the code: from weather import Weather weather = Weather() # Lookup WOEID via http://weather.yahoo.com. lookup = weather.lookup(560743) condition = lookup.condition() print(condition.text()) # Lookup via location name. location = weather.lookup_by_location('dublin') condition = location.condition() print(condition.text()) # Get weather forecasts for the upcoming days. forecasts = location.forecast() for forecast in forecasts: print(forecast.text()) print(forecast.date()) print(forecast.high()) print(forecast.low()) Does anyone know what's wrong or any way to fix this issue?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49353104
has title: ImportError: cannot import name 'Weather'
tagged with: python
has comment: http://stackoverflow.com/comment/83572672
has answer: http://stackoverflow.com/a/48293759
score: 0
tagged with: importerror
answer count: 3

http://stackoverflow.com/q/48296726
has body: I'm having an interactive menu where the user has to edit some numbers if the numbers are floats or not a subset of a given list. The following code is used: grades = np.array([-3,-10.5,0,7,4,8,4,7,10,5]) SevenGradeScale = np.array([-3, 0, 2, 4, 7, 10, 12]) for i in range(np.size(grades)): if grades[i] not in SevenGradeScale: while True: if type(grades[i]) is np.float64: print("{:f} is not a valid grade. The grade must be an integer.".format(grades[i])) elif type(grades[i]) is np.int32: print("{:d} is not within the seven grade scale.".format(grades[i])) else: type("{:f} is not a valid grade.".format(grades[i])) #try: grades[i] = input("Insert new grade: ") And what I'm trying to do is, that the user edits the number that the script sees as invalid. But when trying to type in an integer, I get a float back. Why is that? -10.500000 is not a valid grade. The grade must be an integer. Insert new grade: 10 10.000000 is not a valid grade. The grade must be an integer. Insert new grade:
favorite count: 0
type: Question
upvote count: 2
score: 2
tagged with: python-3.x
answer count: 2
accepted answer: http://stackoverflow.com/a/48296849
has comment: http://stackoverflow.com/comment/83578043
has comment: http://stackoverflow.com/comment/83578250
has answer: http://stackoverflow.com/a/48296848
possible better answer: http://stackoverflow.com/a/48296848
downvote count: 0
tagged with: interactive
type: AnsweredQuestion
has title: Integer input intepreted as a float
has answer: http://stackoverflow.com/a/48296849
has comment: http://stackoverflow.com/comment/83578156
has comment: http://stackoverflow.com/comment/83578080
tagged with: python

http://stackoverflow.com/a/48269746
score: 1
has body: I am not aware of a way that this can be done. However you can just keep a Surface object to render the image and another Rect object to handle all the collision detection business. This is very common. How to do it: Create the Rect object. Create the Surface object. Load in a .png file and blit it onto the Surface that you have just created. Make sure that the x and y values of the Rect object and the Surface object are the same at the end of every frame. I have included some example code to get you started. I commented out the code with loading in the images though. To use your own images: copy the image files into the directory you want. (If in doubt, choose the directory of the script) Get the correct path name and use it in the code below. Now you can use the Rects for collision detection and moving and the image surfaces will always be drawn wherever the Rect is. Note: this approach is commonly done in an object-oriented fashion. I hope that this answer helped you and if you have any further questions please feel free to post a comment below! Example code # create Rects square1 = pygame.Rect(100, 100, 100, 100) square2 = pygame.Rect(100, 300, 100, 100) # create the image surfaces img = pygame.Surface((100, 100)) image_file = pygame.image.load("path/to/image_file") img.blit(image_file, [0, 0]) img2 = pygame.Surface((100,100)) image_file2 = pygame.image.load("path/to/image_file") img.blit(image_file2, [0, 0]) And to blit these Surfaces onto the screen: # draw the image Surfaces screen.blit(img, [square1.x, square1.y]) screen.blit(img2, [square2.x, square2.y])
answers question: http://stackoverflow.com/q/48269074
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/48178411
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83361272
type: Answer
answers question: http://stackoverflow.com/q/48177417
accepted answer of: http://stackoverflow.com/q/48177417
has body: Lets say you have a GroupConcat function like this one: class GroupConcat(models.Aggregate): function = 'GROUP_CONCAT' template = '%(function)s(%(distinct)s%(expressions)s%(ordering)s%(separator)s)' def __init__(self, expression, distinct=False, ordering=None, separator=',', **extra): super(GroupConcat, self).__init__( expression, distinct='DISTINCT ' if distinct else '', ordering=' ORDER BY %s' % ordering if ordering is not None else '', separator=' SEPARATOR "%s"' % separator, output_field=models.CharField(), **extra ) Then you can do: Word.objects.all().annotate( category_names=GroupConcat('categories__name') ).values_list('category_names').distinct() PS. This is a MySQL solution.
score: 1

http://stackoverflow.com/comment/83605200
comment on: http://stackoverflow.com/q/48309591
type: QuestionComment
has text: I think I like the idea of the urls in a file, but then comes the problem of telling Python WHEN to download the files. Maybe the program reads the text file for a signal?
score: 0
type: Comment

http://stackoverflow.com/q/48197987
answer count: 1
has answer: http://stackoverflow.com/a/48199416
favorite count: 0
type: Question
downvote count: 0
tagged with: python
tagged with: html-parsing
accepted answer: http://stackoverflow.com/a/48199416
tagged with: beautifulsoup
type: AnsweredQuestion
score: 3
upvote count: 3
has body: I'm attempting to parse this page using BeatifulSoup4 with Python2.7.5. My code looks like this: url = "https://coinmarketcap.com/currencies/CRYPTO/historical-data/? start=20171124&end=20171130" url.replace('CRYPTO', crypto['id']) response = urllib2.urlopen(url) data = response.read() soup = BeautifulSoup(data, 'html5lib') trs = soup.find(id="historical-data").findAll('tr') where CRYPTO is replaced by 'bitcoin', etc. Looking at the variables in PyCharm, everything looks good EXCEPT for the data in the table . Instead of seeing this: Nov 30, 2017 9906.79 10801.00 9202.05 10233.60 8,310,690,000 165,537,000,000 which is what Google Chrome's Inspect window and curl show me, BeautifulSoup shows me this: Nov 30, 2017 0.009829 0.013792 0.009351 0.013457 152 119,171 Why are the numbers different? I have used urllib2 and requests. I have used response.text and response.read(). I have parsed using lxml and html5lib. I have tried different encoding such iso-8859 and ascii. Nothing works. How do I get the proper numbers to display?
has title: BeautifulSoup is not parsing data properly

http://stackoverflow.com/q/48233400
type: AnsweredQuestion
has title: LSTM Initial state from Dense layer
score: 7
has comment: http://stackoverflow.com/comment/117565634
type: Question
has body: I am using a lstm on time series data. I have features about the time series that are not time dependent. Imagine company stocks for the series and stuff like company location in the non-time series features. This is not the usecase, but it is the same idea. For this example, let's just predict the next value in the time series. So a simple example would be: feature_input = Input(shape=(None, data.training_features.shape[1])) dense_1 = Dense(4, activation='relu')(feature_input) dense_2 = Dense(8, activation='relu')(dense_1) series_input = Input(shape=(None, data.training_series.shape[1])) lstm = LSTM(8)(series_input, initial_state=dense_2) out = Dense(1, activation="sigmoid")(lstm) model = Model(inputs=[feature_input,series_input], outputs=out) model.compile(loss='mean_squared_error', optimizer='adam', metrics=["mape"]) however, I am just not sure on how to specify the initial state on the list correctly. I get ValueError: An initial_state was passed that is not compatible with `cell.state_size`. Received `state_spec`=[&lt;keras.engine.topology.InputSpec object at 0x11691d518&gt;]; However `cell.state_size` is (8, 8) which I can see is caused by the 3d batch dimension. I tried using Flatten, Permutation, and Resize layers but I don't believe that is correct. What am I missing and how can I connect these layers?
downvote count: 0
answer count: 1
tagged with: machine-learning
tagged with: python
upvote count: 7
tagged with: keras
accepted answer: http://stackoverflow.com/a/48237329
favorite count: 0
has answer: http://stackoverflow.com/a/48237329

http://stackoverflow.com/q/48182760
type: Question
answer count: 0
tagged with: clipboard
type: UnansweredQuestion
tagged with: file
downvote count: 0
upvote count: 1
has title: Python3 - Copy File via Filepath to Windows Clipboard (Looking for Solution without PyQT)
tagged with: copy
favorite count: 0
tagged with: windows
score: 1
has body: I'm looking for a function that can take a filepath as input and results in copying the actual file to the Clipboard in Windows. I searched through StackOverflow and found a lot of solutions for copying text but only one for copying a file (via PyQT). Is there another way to achieve this?
tagged with: python

http://stackoverflow.com/q/48236144
score: 1
downvote count: 1
tagged with: tensorflow
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/83455880
answer count: 0
type: UnansweredQuestion
has title: How to split tensorflow's cnn model by column and train it in small batches
has body: I am having a large training model with 59536 column and 200 lines that I want to train using tensorflow's cnn but I am facing the OutOfMemory error. How can I split my model (split it in smaller column) and train it in a small batches? Here is my code # Create the Estimator mnist_classifier = tf.estimator.Estimator( model_fn=cnn_model_fn, model_dir="path/to/model") # Load the data train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": np.array(training_set.data)}, y=np.array(training_set.target), num_epochs=None, batch_size=5, # I added this option but it seems to split my model by lines, I need to split it by column shuffle=True) # Train the model mnist_classifier.train( input_fn=train_input_fn, steps=100, hooks=[logging_hook])
tagged with: python
has comment: http://stackoverflow.com/comment/83548609
has comment: http://stackoverflow.com/comment/83516923
favorite count: 0
has comment: http://stackoverflow.com/comment/83455391
tagged with: tensorflow-estimator
has comment: http://stackoverflow.com/comment/83455995

http://stackoverflow.com/q/48178884
upvote count: 21
has comment: http://stackoverflow.com/comment/83337946
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/48179245
has title: Min-max normalisation of a NumPy array
possible better answer: http://stackoverflow.com/a/48179245
accepted answer: http://stackoverflow.com/a/48178963
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48178960
score: 20
has answer: http://stackoverflow.com/a/55526862
tagged with: arrays
has comment: http://stackoverflow.com/comment/83337862
has comment: http://stackoverflow.com/comment/83337898
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48178963
has body: I have the following numpy array: foo = np.array([[0.0, 10.0], [0.13216, 12.11837], [0.25379, 42.05027], [0.30874, 13.11784]]) which yields: [[ 0. 10. ] [ 0.13216 12.11837] [ 0.25379 42.05027] [ 0.30874 13.11784]] How can I normalize the Y component of this array. So it gives me something like: [[ 0. 0. ] [ 0.13216 0.06 ] [ 0.25379 1 ] [ 0.30874 0.097]]
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83337985

http://stackoverflow.com/comment/83458581
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48236584
has text: To answer the question "what makes you think it failed to completely uninstall?" after an uninstall, the short cuts still exist. Obviously there are some things that aren't getting wiped out.
score: 0

http://stackoverflow.com/comment/83424524
type: QuestionComment
has text: Your question is not clear. What exact output are you looking for? Also, since this is Django, please show the models.
score: 0
comment on: http://stackoverflow.com/q/48221588
type: Comment

http://stackoverflow.com/a/48246047
has comment: http://stackoverflow.com/comment/83474801
has comment: http://stackoverflow.com/comment/83474809
has body: If all you want to do is execute the same command for each user in your text file you can just build the command with a for loop. twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret) with open('test.txt', 'r') as users_file: for user in users_file: twitter.create_friendship(screen_name=user)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48246033

http://stackoverflow.com/comment/139344172
comment on: http://stackoverflow.com/a/48327162
type: Comment
type: AnswerComment
score: 0
has text: In python 3.9+ you will end in a deadlock because thread.py introduced _global_shutdown_lock and is used when you submit a task, if the queue is full your threads will freeze because this _global_shutdown_lock is active and never deactivates.

http://stackoverflow.com/comment/83634093
has text: This fixed it!!! Very big thanks, Will! I learned something that will be very useful throughout my entire project :-)
comment on: http://stackoverflow.com/a/48323625
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48309112
has comment: http://stackoverflow.com/comment/83603900
tagged with: tkinter
tagged with: python-multithreading
linked to: http://stackoverflow.com/q/25430786
tagged with: multithreading
tagged with: tkinter-canvas
has comment: http://stackoverflow.com/comment/83605231
has body: I'm trying to make two balls to move on the screen the position is being updated with thread and the main thread is updating the graphics here is my code: from tkinter import * from threading import * import time width = 500 height = 500 class Ball(Thread): def __init__(self, canvas, x1, y1, x2, y2, color): super().__init__() self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.x_velocity = 9 self.y_velocity = 5 self.canvas = canvas self.id = self.canvas.create_oval(self.x1, self.y1, self.x2, self.y2, fill=color) def update(self): self.canvas.move(self.id, self.x_velocity, self.y_velocity) pos = self.canvas.coords(self.id) if pos[0] &lt;= 0 or pos[2] &gt;= width: self.x_velocity *= -1 if pos[1] &lt;= 0 or pos[3] &gt;= height: self.y_velocity *= -1 def run(self): self.update() def main(): master = Tk() canvas = Canvas(master=master, bg='Grey', width=width, height=height) ball1 = Ball(canvas=canvas, x1=10, y1=10, x2=40, y2=40, color='Black') ball2 = Ball(canvas=canvas, x1=50, y1=50, x2=80, y2=80, color='Red') canvas.pack() ball1.start() ball2.start() while 1: master.update() time.sleep(0.04) if __name__ == '__main__': main() it seems that is not working what is wrong and how to handle it ? the error message is: Exception in thread Thread-2: Traceback (most recent call last): File "/home/muhammad_essam/anaconda3/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/mnt/sda6/CSE/Project/GUI/Learnning/GUI101/main.py", line 30, in run self.update() File "/mnt/sda6/CSE/Project/GUI/Learnning/GUI101/main.py", line 22, in update self.canvas.move(self.id, self.x_velocity, self.y_velocity) File "/home/muhammad_essam/anaconda3/lib/python3.6/tkinter/__init__.py", line 2585, in move self.tk.call((self._w, 'move') + args) _tkinter.TclError: out of stack space (infinite loop?) Exception in thread Thread-1: Traceback (most recent call last): File "/home/muhammad_essam/anaconda3/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/mnt…
has comment: http://stackoverflow.com/comment/83604119
downvote count: 1
has title: python Tkinter multithreading
accepted answer: http://stackoverflow.com/a/48310386
has comment: http://stackoverflow.com/comment/83603871
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/48310386
linked to: http://stackoverflow.com/q/22541693
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/83605508
tagged with: python
has comment: http://stackoverflow.com/comment/83605600
favorite count: 0
type: Question

http://stackoverflow.com/q/48253561
favorite count: 0
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/83489730
has comment: http://stackoverflow.com/comment/83489662
has comment: http://stackoverflow.com/comment/83489667
downvote count: 1
has title: Generating a new list from previous lists with new elements in Python
type: Question
type: UnansweredQuestion
has body: Hi i want to generate from lys1 and lys2 a new list called "lys3" that is the length of 3 that contains the (first value of lys1 * second value of lys2), (second value of lys1 * third value of lys2), (third value of lys1 * fourth value of lys2) using a loop. lys1 = [5,6,2,9] lys2 = [3,8,3,6] lys3 = [i * j for i in lys1 for j in lys2] print(lys3) this is so far the logistics i've been able to figure out,
answer count: 1
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48253596

http://stackoverflow.com/q/48278144
accepted answer: http://stackoverflow.com/a/48280454
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48280454
has title: How to parse a deep nested XML in python
has body: I am new to python, and I have a situation <c> <d>abcd</d> <e> <f>pqrs</f></e></d></c> The algorithm is supposed to be if d has abcd , then find f, if f is present, return a true else return a false with abcd. I would be grateful if there are someone can help me figure how to solve this issue.
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
type: Question
score: -4
has comment: http://stackoverflow.com/comment/83539645
has comment: http://stackoverflow.com/comment/83575987
tagged with: python
has comment: http://stackoverflow.com/comment/83575822
has comment: http://stackoverflow.com/comment/83542157
has comment: http://stackoverflow.com/comment/83553907
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83539817
downvote count: 4

http://stackoverflow.com/a/48243963
has comment: http://stackoverflow.com/comment/83470433
has body: I just find the issue. After an UPDATE you have to send a commit.
type: Answer
answers question: http://stackoverflow.com/q/48243364
score: 0

http://stackoverflow.com/comment/83494597
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48245528
type: AnswerComment
has text: @Gixxerrider replace `devices` with `device` in your template, this should already help.

http://stackoverflow.com/comment/83394901
has text: in administrator's urls it's named 'order_waiting_list' so to access it i have to write administrator:order_waiting_list, but i don't think the url is the problem, the function just doesn't accept the second parameter.
type: Comment
comment on: http://stackoverflow.com/a/48206846
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83326663
has text: Why are you using a list for this, when you would get the correct output by using `random.randint(1, 6)` *directly*, without using those values as indices?
comment on: http://stackoverflow.com/q/48173538
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/48232626
tagged with: python
has body: I want to join 2 DataFrames Zipcode Database (first 10 entries) 0 zip_code City State County Population 0 0 90001 Los Angeles California Los Angeles 54481 1 1 90002 Los Angeles California Los Angeles 44584 2 2 90003 Los Angeles California Los Angeles 58187 3 3 90004 Los Angeles California Los Angeles 67850 4 4 90005 Los Angeles California Los Angeles 43014 5 5 90006 Los Angeles California Los Angeles 62765 6 6 90007 Los Angeles California Los Angeles 45021 7 7 90008 Los Angeles California Los Angeles 30840 8 8 90009 Los Angeles California Los Angeles - 9 9 90010 Los Angeles California Los Angeles 1943 And data (first 10 entries) buyer zip_code 0 SWEENEY,THOMAS R &amp; MICHELLE H NaN 1 DOUGHERTY,HERBERT III &amp; JENNIFER M NaN 2 WEST COAST RLTY SVCS INC NaN 3 LOVE,JULIE M NaN 4 SAHAR,DAVID NaN 5 SILBERSTERN,BRADLEY E TRUST 91199 6 LEE,SUSAN &amp; JIMMY C 92025 7 FRAZZANO REAL ESTATE I NC NaN 8 RUV INVESTMENTS LLC 91730 9 KAOS KAPITAL LLC NaN So the final table should have [buyer, zip_code, City, County]. I'm joining with respect to Zip code. data_2 = data.join(zipcode_database'City', 'County', 'zip_code'.set_index('zip_code'), on='zip_code') But the city and county columns are NaN even for the tuples in data where zipcode is actually present. buyer zip_code City County 10 LANDON AVE TRUST 37736 NaN NaN NaN 11 UMAR,AHMAD NaN NaN NaN 12 3 JPS INC 90717 NaN NaN 13 T &amp; L HOLDINGS INC 95610 NaN NaN 14 CAHP HOLDINGS LLC 90808 NaN NaN 15 REBUILDING TOGETHER LONG BEACH 92344 NaN NaN 16 COLFIN AI-CA 4 LLC NaN NaN NaN 17 GUTIERREZ,HUGO 91381 NaN NaN 18 VALBRIDGE CAP GOLDEN GATE FUND NaN NaN NaN 19 SOLARES,OSCAR 92570 NaN NaN Why is this the case? The zipcode database has all zipcodes from 90001 - 999950. My first thought is the datatype of "zip_code" in both are different: print(zipcode_database['zip_code'].dtype) print(data['zip_code'].dtype) Output: int64 object Thought of typecasting with astype, but this does not work with NaN values. Any thoughts?
has answer: http://stackoverflow.com/a/48232948
score: 0
tagged with: pandas
tagged with: join
answer count: 1
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: pandas join gives NaN values

http://stackoverflow.com/q/48246955
linked to: http://stackoverflow.com/q/16729574
has comment: http://stackoverflow.com/comment/83476611
linked to: http://stackoverflow.com/q/40144769
has comment: http://stackoverflow.com/comment/83476574
has comment: http://stackoverflow.com/comment/83477111
has answer: http://stackoverflow.com/a/48247414
possible better answer: http://stackoverflow.com/a/48247414
has comment: http://stackoverflow.com/comment/83476577
has comment: http://stackoverflow.com/comment/83476595
type: AnsweredQuestion
tagged with: pandas
has title: How to get a value from a cell of a dataframe by position or label?
has answer: http://stackoverflow.com/a/48247245
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48247245
tagged with: python
has comment: http://stackoverflow.com/comment/83476569
has comment: http://stackoverflow.com/comment/83476550
favorite count: 0
has comment: http://stackoverflow.com/comment/83477176
type: Question
score: 2
answer count: 2
upvote count: 2
linked to: http://stackoverflow.com/q/31593201
has body: I read the questions "How to get a value from a cell of a dataframe?" and "How to select the last column of dataframe". I am a bit confused as to what is the accepted method in 2018 for getting a value from the cell of a pandas dataframe, as get_value has been deprecated and the documentation on at is somewhat sparse. I want to select the row by label and the column by position/integer. Is my method below in which I use iloc the accepted approach in 2018? I have this code: import pandas as pd import random import string import csv import io ## Make a table with random column labels and rows in random order. s = '\n'.join(( ## Separate columns by comma. ','.join(( ## Join letters without a separator. ''.join(( ## Randomly choose 3 characters for the labels from ascii_letters. random.choice( string.ascii_letters) for i in range(3))) for j in range(3))), ## Insert a header to distinguish rows with identical index keys x and y. '"Header I, II and III"', ## Randomly shuffle the rows under the first header. '\n'.join(random.sample(('x,0,1', 'y,2,3',), 2)), ## Insert a header to distinguish rows with identical index keys x and y. '"Header IV, V and VI"', ## Randomly shuffle the rows under the second header. '\n'.join(random.sample(('x,4,5', 'y,6,7'), 2)), )) def preprocess(s): header = '' for l in csv.reader(io.StringIO(s)): if len(l) == 1: header = l[0] continue ## Append the header to distinguish identical labels x and y. l[0] = header + '; ' + l[0] yield l print(s, end='\n\n') ## Preprocess the string to avoid duplicate row index keys x and y. df = pd.DataFrame(preprocess(s)) print(df, end='\n\n') ## Set the index to be that of the first column. df = df.set_index(0) ## First select the column by index using iloc ## and then select the relevant row by index label. value = df.iloc[:,-1]['Header I, II and III; x'] print(value) It generates a string s looking like this: YuT,Uva,AsE "Header I, II and III" y,2,3 x,0,1 "Header IV, V and VI" y,6,7 x,4,5 Which is converted to a …
downvote count: 0
linked to: http://stackoverflow.com/q/28757389

http://stackoverflow.com/comment/83387336
type: Comment
type: QuestionComment
score: 0
has text: Use `Popen()` instead of `run()` and see the docs of the `Popen` object: https://docs.python.org/3/library/subprocess.html#popen-objects
comment on: http://stackoverflow.com/q/48203059

http://stackoverflow.com/a/48239354
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48239112
has body: By adding the proper headers and using session we can download and save the file using request module. import requests headers = { "Host": "freemidi.org", "Connection": "keep-alive", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-US,en;q=0.9", } session = requests.Session() #the website sets the cookies first req1 = session.get("https://freemidi.org/getter-13560", headers = headers) #Request again to download req2 = session.get("https://freemidi.org/getter-13560", headers = headers) print(len(req2.text)) # This is the size of the mdi file with open("testFile.mid", "wb") as saveMidi: saveMidi.write(req2.content)
answers question: http://stackoverflow.com/q/48239112
has comment: http://stackoverflow.com/comment/83461597
type: Answer
score: 1

http://stackoverflow.com/comment/98985386
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48197932
type: Comment
has text: @John I can get similar errors by making the sparse matrix so sparse that some columns are empty. Could you check for this in your data set?

http://stackoverflow.com/comment/87821346
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48194261
has text: *"How is dtype inferred?"* as per the current version of the source: https://github.com/pandas-dev/pandas/blob/master/pandas/io/parsers.py ; see also their doc. Unless you have a specific question, noone's going to write an essay answer on ~5+K lines of complex and actively-changing code.
type: Comment

http://stackoverflow.com/comment/83617645
comment on: http://stackoverflow.com/q/48267017
has text: What do you mean by "keep used input" ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48280959
type: AcceptedAnswer
has body: To solve the problem I found an answer. data = read.table("my_binary_file", sep="\t", header=T, row.names=1) d = dist(data, method = "binary") hc = hclust(d, method="complete") write.table(as.matrix(d), file="dist_matrix.txt") Sorry to disturb for nothing.
score: 0
accepted answer of: http://stackoverflow.com/q/48280753
type: Answer
answers question: http://stackoverflow.com/q/48280753

http://stackoverflow.com/comment/83587586
score: 0
comment on: http://stackoverflow.com/q/48285092
type: QuestionComment
has text: @adityathakkar, does not work because my input and output array are different dimensions.
type: Comment

http://stackoverflow.com/comment/83563137
type: Comment
comment on: http://stackoverflow.com/a/48284117
type: AnswerComment
has text: CamelCaseNames is basical programming ettiquette - it has nothing to do with OOP
score: 0

http://stackoverflow.com/q/48274041
has comment: http://stackoverflow.com/comment/83569814
score: 1
has title: Error while migrating flask_admin to 1.5.0
downvote count: 1
favorite count: 0
type: Question
tagged with: flask-admin
answer count: 0
tagged with: python
type: UnansweredQuestion
tagged with: flask
has comment: http://stackoverflow.com/comment/83534761
upvote count: 2
has comment: http://stackoverflow.com/comment/83698469
has body: I am trying to update my dependencies during this process I also update flask_admin from 1.0.8 to 1.5.0. But this change is giving me an issue when I deploy on production. The admin page gives me status code 500. When I look at the stack trace it looks like this: Traceback (most recent call last): File "/srv/venvs/service/trusty/service_venv/local/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/srv/venvs/service/trusty/service_venv/local/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/srv/venvs/service/trusty/service_venv/local/lib/python2.7/site-packages/flask_restful/__init__.py", line 273, in error_router return original_handler(e) File "/srv/venvs/service/trusty/service_venv/local/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/srv/venvs/service/trusty/service_venv/local/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/srv/venvs/service/trusty/service_venv/local/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/srv/venvs/service/trusty/service_venv/local/lib/python2.7/site-packages/lyftflask/__init__.py", line 187, in decorated return f(*args, **kwargs) File "/srv/venvs/service/trusty/service_venv/local/lib/python2.7/site-packages/flask_admin/base.py", line 69, in inner return self._run_view(f, *args, **kwargs) File "/srv/venvs/service/trusty/service_venv/local/lib/python2.7/site-packages/flask_admin/base.py", line 368, in _run_view return fn(self, *args, **kwargs) File "/srv/venvs/service/trusty/service_venv/local/lib/python2.7/site-packages/flask_admin/model/base.py", line 1882, in index_view view_args.search, view_args.filters, page_size=page_size) TypeError: get_list() got an unexpected keyword argum…

http://stackoverflow.com/comment/83636029
comment on: http://stackoverflow.com/q/48318113
type: Comment
type: QuestionComment
has text: So the only two arrays are alpha x and y... The two input arrays are from disk yes? A B and C are just the breakdown of the single long line I've given below ....so they don't actually take up memory? I thought that's what I'm trying to avoid by memmap
score: 0

http://stackoverflow.com/comment/83464116
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48237875
score: 0
has text: Yes, it works and also has no pin either.

http://stackoverflow.com/a/48212916
has comment: http://stackoverflow.com/comment/105426739
answers question: http://stackoverflow.com/q/48210424
has body: The easiest way to talk privately with a user is to send a direct message by using the user ID as channel in chat.postMessage. The message will then appear in the private slackbot channel of that user. Alternatively you can also send messages in your dedicated app channel for a user. See this answer for how it works.
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/105411425
has comment: http://stackoverflow.com/comment/105426982

http://stackoverflow.com/q/48257387
tagged with: http
tagged with: curl
type: Question
tagged with: binary
has comment: http://stackoverflow.com/comment/83499118
type: UnansweredQuestion
tagged with: python
has title: Why is my HTTP POST (binary file) working with Python Requests but not with cURL?
has body: I am trying to send a binary file (.parquet) to a web server via HTTP POST request. The python code below works flawlessly: url = 'http://localhost/update/id' f = open('/home/dev/datafiles/file.parquet', 'rb') files = {'file': f} try: r = requests.post(url, files=files) finally: f.close() However, using cURL, I could not get it to work, resulting in error 400: Bad Request. The cURL command that I am trying is: curl -X POST \ -H 'Content-Type: multipart/form-data' \ --data-binary @/home/dev/datafiles/file.parquet \ http://localhost/update/id I tried with -F instead of -X POST and with -d instead of --data-binary already, but I am getting 400 no matter what. Using curlify to extract the cURL command from the PreparedRequest object in Python, I get: curl -X POST \ -H 'Accept-Encoding: gzip, deflate' \ -H 'Accept: */*' \ -H 'Connection: keep-alive' \ -H 'Content-Length: 85705' \ -H 'Content-Type: multipart/form-data; boundary=c732fde3afb641d2ba5010efc59497bd' \ -H 'User-Agent: python-requests/2.18.4' \ -d '--c732fde3afb641d2ba5010efc59497bd Content-Disposition: form-data; name="file"; filename="file.parquet" [binary_content_goes_here] --c732fde3afb641d2ba5010efc59497bd--' \ http://localhost/update/id But I was not able to get it to work, even when replacing the -d part with -d @/home/dev/datafiles/file.parquet or --data-binary @/home/dev/datafiles/file.parquet. Am I missing something?
duplicate of: http://stackoverflow.com/q/12667797
has comment: http://stackoverflow.com/comment/83503871
score: 0
answer count: 0
linked to: http://stackoverflow.com/q/12667797
has comment: http://stackoverflow.com/comment/83507937
tagged with: python-requests

http://stackoverflow.com/comment/83420966
score: 0
has text: i have a value that changes daily for 60 days in a row, but the change can be an increase or decrease in random range, i figured a loop would make it easier to calculate the change for each day. Although i may have poorly explained my issue. Thanks for the help though, i included a comment to remind myself to check for scalar/ndarray
type: Comment
comment on: http://stackoverflow.com/a/48219164
type: AnswerComment

http://stackoverflow.com/q/48185731
tagged with: python
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/83351600
has comment: http://stackoverflow.com/comment/83354866
favorite count: 0
type: Question
has body: I am creating a django comments app. I have created model Comments class Comments(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add = True) likes = models.IntegerField(default = 0) path = models.CharField(validators=[validate_comma_separated_integer_list], max_length = 100, blank = True, editable = False) depth = models.PositiveSmallIntegerField(default = 0) The way i store path tree is that: First comment will have path [1]. Reply to first comment will have path [1,2] Second comment will have path [3] Second reply to first comment will have path [1,4]. And so on. So something like this should happen. [1] [1,2] [1,4] [3] I display it by fetching using the following line: comment_list = Comments.objects.order_by('-path') The problem is it displays newest comment first like this: [3] [1] [1,4] [1,2] How do i correct it so that it prints oldest comment first?
has title: Python Django threaded comments ordering
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: django

http://stackoverflow.com/q/48202525
possible better answer: http://stackoverflow.com/a/48203354
tagged with: python
has comment: http://stackoverflow.com/comment/83387030
has answer: http://stackoverflow.com/a/48202633
accepted answer: http://stackoverflow.com/a/48202633
has comment: http://stackoverflow.com/comment/83386790
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/83387625
answer count: 2
has answer: http://stackoverflow.com/a/48203354
downvote count: 0
has comment: http://stackoverflow.com/comment/83387343
has body: Code below: def computerCost(x,y,theta): m = len(y) J = np.sum((np.dot(x,theta) - y)**2) /(2*m) return J m = 100 x = np.linspace(-5,10,m) y = np.linspace(1,100,m) x, y = x.reshape(m,1), y.reshape(m,1) theta_0 = np.linspace(-10,10,100) theta_1 = np.linspace(-1,4,100) X,Y = np.meshgrid(theta_0,theta_1) ###### Here I want to initialize a numpy array with generator. J_vals = np.array(computerCost(x,y,np.array([a,b])) for a,b in zip(np.ravel(X), np.ravel(Y)) ) print('out:',J_vals) Running this code in Python 3.5 gives: out:&lt;generator object &lt;genexpr&gt; at 0x0000028ACF28B258&gt; The console prints that J_vals is a generator. Is there some way to change the generator into a np.ndarrray?
favorite count: 0
type: Question
tagged with: numpy
has title: How do I use a generator to initialize a numpy array?
score: 3

http://stackoverflow.com/comment/83337060
score: 0
has text: Not clear about it really. Should I reply x and y, with img1 and img2, respectively? I get errors here.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48178424

http://stackoverflow.com/q/48239221
has comment: http://stackoverflow.com/comment/83470320
has title: Receiving the error "Struct() argument 1 must be string, not unicode" when using Django
tagged with: unicode
type: Question
answer count: 0
type: UnansweredQuestion
has body: I am receiving the error "Struct() argument 1 must be string, not unicode" when running a script in Django but it runs OK in python. I'm trying to translate the hex version of a SID from Active Directory to the string version. The error says argument 1 is unicode but from what I can tell it's not. From what I can tell argument 1 is the sliced value of SID. Any help is appreciated. Here is the code: result = con.search_s(ldap_base, ldap.SCOPE_SUBTREE, criteria, attributes) sid = result[0][1]["objectSid"][0] if sys.version_info.major &lt; 3: revision = ord(sid[0]) else: revision = sid[0] if sys.version_info.major &lt; 3: number_of_sub_ids = ord(sid[1]) else: number_of_sub_ids = sid[1] iav = struct.unpack('&gt;Q', b'\x00\x00' + sid[2:8])[0] sub_ids = [struct.unpack('&lt;I', sid[8 + 4 * i:12 + 4 * i])[0] for i in range(number_of_sub_ids)] sid = 'S-{0}-{1}-{2}'.format(revision, iav, '-'.join([str(sub_id) for sub_id in sub_ids])) Error part 1- Error part 2- Error part 3-
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83506664
score: 0

http://stackoverflow.com/q/48291400
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83568021
has comment: http://stackoverflow.com/comment/83568035
score: 1
has comment: http://stackoverflow.com/comment/83567985
favorite count: 0
has comment: http://stackoverflow.com/comment/83568014
has body: I have this simple problem but for some reason it's giving a headache. I want to add a existing Date column with another column to get a newDate column. For example: I have Date and n columns, and I want to add in NewDate column into my existing df. df: Date n NewDate (New Calculation here: Date + n) 05/31/2017 3 08/31/2017 01/31/2017 4 05/31/2017 12/31/2016 2 02/28/2017 I tried: df['NewDate'] = (pd.to_datetime(df['Date']) + MonthEnd(n)) but I get an error saying "cannot convert the series to class 'int'
type: Question
has comment: http://stackoverflow.com/comment/83568276
has answer: http://stackoverflow.com/a/48291568
tagged with: datetime
upvote count: 1
tagged with: dataframe
tagged with: python
has title: pandas add a value column to datetime
answer count: 1
accepted answer: http://stackoverflow.com/a/48291568

http://stackoverflow.com/a/48327223
score: 0
type: Answer
has body: This line makes use of the python str.format feature to create an xpath expression. It is a little tricky here to separate python string formatting from the xpath expression. li[{}] is part of xpath were {} is the index of the li element you want to query. As you have a loop around this and want the value of the python variable i to be included in the expression. {} will be replaced by format with the value of i. @src is part of xpath and tells something like: "Please give me the value of the src-attribute from the selected img-tag". The final [0] is there because xpath always returns a list and you want the first element. In fact your expression makes sure that there is only one result. If you want this to work with any number of images you might completely drop the range loop and the formatting part and directly make use of xpath: for img in html.xpath('//div[2]/ul/li/img/@src'): print(img) This way you query the HTML for all img tags in the list of the second div container and fetch their src attribute.
answers question: http://stackoverflow.com/q/48326983

http://stackoverflow.com/q/48189768
answer count: 1
downvote count: 1
tagged with: shell
has body: How can I extract info from a multi-column output of a subprocess.call() method execution? I have this command to run: test = subprocess.call('kubectl get ingress -o wide', shell=True) print(test) It returns response as: NAME HOSTS ADDRESS PORTS AGE gateway * 35.202.20.241 80 52m I want to retrieve ADDRESS column value to get the IP address. How can I achieve that scenario?
favorite count: 0
has comment: http://stackoverflow.com/comment/83359707
has title: Extract information from multi column output of subprocess.call()?
type: Question
has answer: http://stackoverflow.com/a/48190977
has comment: http://stackoverflow.com/comment/83360830
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83359676
tagged with: python
has comment: http://stackoverflow.com/comment/83360775
score: 0
tagged with: subprocess
upvote count: 1

http://stackoverflow.com/comment/83368860
type: AnswerComment
comment on: http://stackoverflow.com/a/48193445
type: Comment
has text: @Kodiologist yeah I figured, but I am not quite sure how is this code working.
score: 0

http://stackoverflow.com/a/48262085
answers question: http://stackoverflow.com/q/48261843
score: 2
upvote count: 2
downvote count: 0
has body: People here suggested much cleaner way to solve your problem (a way you are aware of as mentioned in your question). Regarding your question: why it prints as below: [{'India': 'New Delhi', 'Pakistan': 'Islamabad', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu', 'China': 'Beijing', 'Bangladesh': 'Dhaka'}, {'India': 'New Delhi', 'Pakistan': 'Islamabad', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu', 'China': 'Beijing', 'Bangladesh': 'Dhaka'}, {'India': 'New Delhi', 'Pakistan': 'Islamabad', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu', 'China': 'Beijing', 'Bangladesh': 'Dhaka'}, {'India': 'New Delhi', 'Pakistan': 'Islamabad', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu', 'China': 'Beijing', 'Bangladesh': 'Dhaka'}, {'India': 'New Delhi', 'Pakistan': 'Islamabad', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu', 'China': 'Beijing', 'Bangladesh': 'Dhaka'}, {'India': 'New Delhi', 'Pakistan': 'Islamabad', 'Nepal': 'Kathmandu', 'Bhutan': 'Thimphu', 'China': 'Beijing', 'Bangladesh': 'Dhaka'}] The map method applies your function on each element of your lists and collect the return values to a new list. Your function returns the global variable country_capital to which you add elements. Therefore the output of your map (national_info) is a list with n pointers to country_capital. If you'll print country_capital instead of national_info you'll get the output you want.
has comment: http://stackoverflow.com/comment/83506919
type: Answer

http://stackoverflow.com/comment/83588805
comment on: http://stackoverflow.com/q/48298111
type: Comment
type: QuestionComment
score: 0
has text: The problem of finding sets of sequences with a minimum hamming distance (as opposed to a fixed hamming distance) is well-studied but inconclusive. In particular, the maximum size of the set for given minimum distance and sequence length is only known for small and trivial parameter values. I suspect that your version of the problem is not simpler.

http://stackoverflow.com/comment/83636628
score: 0
comment on: http://stackoverflow.com/q/48325414
type: Comment
type: QuestionComment
has text: are there only going to be two dates for each name, spec combination?

http://stackoverflow.com/comment/83337883
has text: It is easy to mess up random number generation by trying to do it yourself. If a PRNG is good, it is random enough already and there's no need to try to make it better. If a PRNG is not good, use one that is good.
comment on: http://stackoverflow.com/q/48178433
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83420088
type: QuestionComment
has text: If you do `b = ...` you will replace the `b` reference. You will not update any other object referenced by the old `b`.
score: 1
comment on: http://stackoverflow.com/q/48219116
type: Comment

http://stackoverflow.com/q/48293400
has comment: http://stackoverflow.com/comment/83571997
type: Question
accepted answer: http://stackoverflow.com/a/48304688
has comment: http://stackoverflow.com/comment/83571988
has answer: http://stackoverflow.com/a/48304688
tagged with: django
has title: Why does Django trigger GET after POST?
tagged with: python
has comment: http://stackoverflow.com/comment/83571853
has body: I have the following view which takes either a URL or an uploaded text file, creates a Word Cloud and finally displays the generated image to the user. def create(request): """ Displays the generated WordCloud from the given URI or uploaded file """ response = HttpResponse(content_type="image/png") # in order to avoid KeyError myfile = request.FILES.get('myfile', None) if request.POST['uri'] == '' and myfile is None: return render(request, 'nube/index.html', { 'error_message': NOTHING_TO_PROCESS }) try: if myfile: cloud = WordCloud(myfile, type="upload") else: cloud = WordCloud(request.POST['uri'], type="internet") except (MissingSchema): return render(request, 'nube/index.html', { 'error_message': URI_COULD_NOT_BE_PROCESSED }) else: # img is a PIL.Image instance img = cloud.get_word_cloud_as_image() img.save(response, 'PNG') return response The image is displayed with no problems; the POST request is processed properly, as can be seen from the log: [16/Jan/2018 22:53:25] "POST /nube/create HTTP/1.1" 200 216961 However, even though the server didn't crash, I noticed an Exception was raised every time immediately after: Internal Server Error: /nube/create Traceback (most recent call last): File "C:\repos\phuyu\venv\lib\site-packages\django\utils\datastructures.py", line 77, in __getitem__ list_ = super().__getitem__(key) KeyError: 'uri' After debugging the code I noticed that my create view was being called once again, but this time as a GET request, and of course, the parameters uri and myfile didn't exist this time, thus raising the exceptions. To make sure, I changed create into a class based view and only defined its post method. As suspected, now I got the following line in the logs after the successful POST: Method Not Allowed (GET): /nube/create [16/Jan/2018 22:44:41] "GET /nube/create HTTP/1.1" 405 0 What would be the correct way to handle this? I'm fairly new to Django.
tagged with: python-imaging-library
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83574135
answer count: 1
has comment: http://stackoverflow.com/comment/83572736
has comment: http://stackoverflow.com/comment/83571840

http://stackoverflow.com/q/48228789
answer count: 1
has body: import tkinter as Tk from tkinter import ttk import math as m win=Tk.Tk() win.title("Propeller Inputs") inputFrame=ttk.LabelFrame(win,text="Input") inputFrame.grid(column=0,row=0) inputlabel=('Water','Lubrication','Power(KW)','Engine speed(rpm)','Gearbox ratio','Shaft strength(N/mm^2)','Bolt strength(N/mm^2)','Number of bolts','PCD of bolts(mm)') for a in range (0,9): ttk.Label(inputFrame,text=inputlabel[a]).grid(column=0, row=a, pady=5) #Adding a Combobox water1=Tk.StringVar() water1=ttk.Combobox(inputFrame, width=20) water1['values']=("Sea", "River") water1.grid(column=1, row=0) water1.current(0) lub1=Tk.StringVar() lub1=ttk.Combobox(inputFrame, width=20) lub1['values']=("Water", "Oil") lub1.grid(column=1, row=1) lub1.current(0) #Adding a Textbox P1=Tk.StringVar() P1=ttk.Entry(inputFrame, width=20) P1.grid(column=1, row=2) en1=Tk.StringVar() en1=ttk.Entry(inputFrame, width=20) en1.grid(column=1, row=3) gb1=Tk.StringVar() gb1=ttk.Entry(inputFrame, width=20) gb1.grid(column=1, row=4) T1=Tk.StringVar() T1=ttk.Entry(inputFrame, width=20) T1.grid(column=1, row=5) Tb1=Tk.StringVar() Tb1=ttk.Entry(inputFrame, width=20) Tb1.grid(column=1, row=6) i1=Tk.StringVar() i1=ttk.Entry(inputFrame, width=20) i1.grid(column=1, row=7) D1=Tk.StringVar() D1=ttk.Entry(inputFrame, width=20) D1.grid(column=1, row=8) def calculate(): P=float(P1.get()) en=float(en1.get()) gb=float(gb1.get()) T=float(T1.get()) # Tb=float(Tb1.get()) # i=float(i1.get()) # D=float(D1.get()) k2=1.10 n=m.ceil(en/gb) if "Water" in (lub1.get()): #print("Water lubricated") k1=1.29 else: #print("Oil lubricated") k1=1.26 #print (k1) #tailshaft dia, intermediate shaft dia if "Sea" in (water1.get()): dp=m.ceil(100*k1*((560*P)/(n*(T+160)))**0.33) d=m.ceil(100*k2*((560*P)/(n*(T+160)))**0.33) else: dp=m.ceil(103.5*k1*((410*P)/(n*(T+160)))**0.33) d=m.ceil(103.5*k2*((410*P)/(n*(T+160)))**0.33) # return (dp,d) update(dp,d) def update(dp,d): T=float(T1.get()) Tb=float(Tb1.get()) i=float(i1.get()) D=float(D1.get()) #bolt dia if …
downvote count: 7
score: -7
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83439549
duplicate of: http://stackoverflow.com/q/73631401
has answer: http://stackoverflow.com/a/48229096
tagged with: python
has title: why i'm getting this error
has comment: http://stackoverflow.com/comment/83439677
has comment: http://stackoverflow.com/comment/83456724
upvote count: 0
linked to: http://stackoverflow.com/q/32171005
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83439614
has comment: http://stackoverflow.com/comment/83440955
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/32171005

http://stackoverflow.com/q/48256007
tagged with: amazon-ec2
tagged with: python
tagged with: boto3
has body: I'd like to run a series of bash commands through boto3 on a newly launched instance. From some research it appears that associating this new instance with SSM is required to achieve this. Are there any clear mistakes or missed steps below? Also are there better approaches to achieve the stated goal? Step 1 - Get clients and resources import boto3 ec2c = boto3.client('ec2') ec2r = boto3.resource('ec2') ssmc = boto3.client('ssm') Step 2 - Create and wait for instance instances = ec2r.create_instances( ImageId = 'ami-####', InstanceType = 't2.micro', MinCount = 1, MaxCount = 1, SecurityGroupIds = ['sg-####']) instance_ids = [i.id for i in instances] instance = instances[0] instance.wait_until_running() Step 3 - Associate instance with IAM profile "RoleName" has the AmazonEC2RoleforSSM policy attached to it res = ec2c.associate_iam_instance_profile( IamInstanceProfile={ 'Arn': 'arn:aws:iam::###:instance-profile/RoleName', 'Name': 'RoleName' }, InstanceId = instance.id ) Step 4 - Check for associations print(ssmc.describe_instance_information()['InstanceInformationList']) &gt; [] (I think this empty list is why the next step is failing) Step 5 - Run commands resp = ssmc.send_command( DocumentName = "AWS-RunShellScript", Parameters = {'commands': [mkdir app]}, InstanceIds = instance_ids ) &gt; botocore.errorfactory.InvalidInstanceId: An error occurred ... &gt; ... (InvalidInstanceId) when calling the SendCommand operation:
has title: AWS - Associate EC2 with SSM to enable ssm.client.send_command
has answer: http://stackoverflow.com/a/48257048
score: 0
answer count: 1
tagged with: aws-ssm
has comment: http://stackoverflow.com/comment/83495277
type: Question
type: UnansweredQuestion
tagged with: cloud

http://stackoverflow.com/q/48181014
score: 0
answer count: 3
has title: Can I use the same socket for multiple connections?
type: Question
has body: I'm trying to make a python function that scans a range of addresses. I started a socket and pass the socket as an argument to the function that connects to it: def scan(socket, address, port): c = socket.connect_ex((address, port)) print(c) then I call scan for each address, each in its own thread. I'm getting Error 114: Operation already in progress.. Do I need to start a new socket for each connection? I'm trying to read about socket reusage, and I found that there exists flags like SO_ADDREUSE or something like that. I tried to insert but it didn't work. I'm trying to think how a socket works. I think the moment I create one, it choses a tcp source port, and then when I create a connection, it sends to a destination port. I think I can't reuse the same socket because the source port would be the same for all destination ports, so the clients would answer to the same port and would cause confusion. So do I need to create a new socket for each connection?
linked to: http://stackoverflow.com/q/14388706
tagged with: network-programming
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/83341919
has answer: http://stackoverflow.com/a/48181015
has answer: http://stackoverflow.com/a/72610599
has answer: http://stackoverflow.com/a/48181075

http://stackoverflow.com/comment/83531756
comment on: http://stackoverflow.com/q/48273945
has text: Thanks Terry, since one the objective is to maximize the performance so i wrote the code like this. i found this is a bit fast then write it more structural after test. anyway i add the readable version for easy reading ^^
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48330454
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48330400
has body: You are using list comprehension, which returns a list, your append line is appending a new list to your list. You are pushing a new value into your list, BUT the value is a list, so it makes a list of lists. It seems that what you are wanting to do, is to append the lists to your list so something like: # linsiz is an array. linsiz += [line[i:i+2] for i in range(0,len(line),1)] Which is the same as doing: [] + [], or Concatenating 2 lists together.

http://stackoverflow.com/q/48287223
tagged with: pyspark
tagged with: python
has comment: http://stackoverflow.com/comment/83559371
has body: A week ago I posted a similar question but it never got answered. I have spent a lot of time debugging the issue I'm having, allow me to briefly introduce the problem: After about 8 - 16 hours (11 hours on average), there is one job that gets stuck and Spark stalls. Screenshots and If I manually (kill) that job, then Spark crashes. The log4j logs don't show any warnings/errors at all. So I added my own logger to find at which step it fails. My code looks like this: DS = KafkaUtils.createDirectStream(ssc, ...) dstream = DS.map(...) dstream.foreachRDD(lambda time, rdd: rdd.foreachPartition(lamda parti: doWork(time, parti) ) ) def doWork(time, parti): for part in parti: mention = part['mention'] # extract string from json words = nltk.wordpunct_tokenize(mention) kw = part['keyword'] #... log.info("I") if len(set(dictKeywords[kw]).intersection([w.lower() for w in words])) &lt;= 0: retobj['keeper']=0 # don't keep it elif detect(editedMention) != 'en': retobj['keeper']=0 # don't keep it cleantxt = ppr.clean(mention) log.info("J") # ... Here is the log file as of when the job got stuck: ... 2018-01-16 16:48:35,797 I 2018-01-16 16:48:35,818 J ... 2018-01-16 16:48:35,853 I ^ this is the end (job got stuck after printing "I") It should print "J", but it doesn't, so one of three functions is causing it to hang/crash/stall: set.Intersect / langdetect.detect / tweet-preprocessor ppr. But it doesn't make sense, why does it fail after so much time? I have "try + except" blocks everywhere in my code, and if there was an exception it would've been logged. I am on local mode (single node). I use "spark-submit" to launch the python script. I have tried making Spark use both Python 3.5.2 and Python 3.6 . I have tried with caching RDDs and without caching. It's not an OOM issue, the GC logs didn't indicate anything unusual. Any ideas? Thanks!!!
has comment: http://stackoverflow.com/comment/83564300
has comment: http://stackoverflow.com/comment/83559614
has comment: http://stackoverflow.com/comment/83559557
score: 0
tagged with: apache-spark
has title: PySpark job hangs forever (during real-time analysis)
has comment: http://stackoverflow.com/comment/83559354
has comment: http://stackoverflow.com/comment/83559820
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83559716
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83559324
has comment: http://stackoverflow.com/comment/83560662
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48309452
tagged with: spark-streaming

http://stackoverflow.com/comment/83639663
score: 0
type: AnswerComment
has text: The only thing that can go wrong with that function is that the link is not a valid url. Check what the error is by printing it in the `except` block.
comment on: http://stackoverflow.com/a/48326781
type: Comment

http://stackoverflow.com/q/48199545
tagged with: ipython
downvote count: 1
favorite count: 0
tagged with: jupyter-notebook
type: Question
has comment: http://stackoverflow.com/comment/83417887
has answer: http://stackoverflow.com/a/48218257
tagged with: python
has title: Jupyter vs IPython: Matplotlib - No module named Tkinter
accepted answer: http://stackoverflow.com/a/48218257
has comment: http://stackoverflow.com/comment/83385693
type: AnsweredQuestion
score: 0
has body: I am using Python 3.5 within a program called OpenQuake. When I execute the following line, I get an import error "No module name 'tkinter'". import matplotlib.pyplot as plt I installed jupyter and executed the same and it works fine. Following is a snapshot. I rechecked using IPython (which I believe comes with jupyter) to get exactly the same original error with the same traceback. Following is the traceback. Traceback (most recent call last): File "&lt;ipython-input-22-964337a9f103&gt;", line 2, in &lt;module&gt; import matplotlib.pyplot as plt File "C:\Program Files\OpenQuake Engine\lib\site-packages\matplotlib\pyplot.py", line 114, in &lt;module&gt; _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "C:\Program Files\OpenQuake Engine\lib\site-packages\matplotlib\backends\__init__.py", line 32, in pylab_setup globals(),locals(),[backend_name],0) File "C:\Program Files\OpenQuake Engine\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 6, in &lt;module&gt; from matplotlib.externals.six.moves import tkinter as Tk File "C:\Program Files\OpenQuake Engine\lib\site-packages\matplotlib\externals\six.py", line 90, in __get__ result = self._resolve() File "C:\Program Files\OpenQuake Engine\lib\site-packages\matplotlib\externals\six.py", line 113, in _resolve return _import_module(self.mod) File "C:\Program Files\OpenQuake Engine\lib\site-packages\matplotlib\externals\six.py", line 80, in _import_module __import__(name) ImportError: No module named 'tkinter' The matplotlib module that is referenced is the same in both the cases. To summarize: The above code snippet gives an import error when using Python and IPython. The code snippet executes successfully in Jupyter. Could someone explain why this is happening?
tagged with: tkinter
linked to: http://stackoverflow.com/q/36327134
tagged with: matplotlib
answer count: 1
has comment: http://stackoverflow.com/comment/83385818
upvote count: 1

http://stackoverflow.com/comment/83506099
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48261569
has text: @C.F what was the problem?
score: 0

http://stackoverflow.com/comment/83761414
has text: Link-only answers are discouraged here. They are prone to link-rot.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48338001
score: 0

http://stackoverflow.com/q/48329730
score: 0
has answer: http://stackoverflow.com/a/48361398
possible better answer: http://stackoverflow.com/a/48330085
answer count: 3
tagged with: http://stackoverflow.com/tag/json
tagged with: beautifulsoup
type: Question
linked to: http://stackoverflow.com/q/21028979
has answer: http://stackoverflow.com/a/48330085
has body: Gah. I've spent a fair amount of time trying to find how to do this both properly and even hackishly, and I am just stumped. I have 2500+ HTML files that I've downloaded from a site, and I need only to extract a limited amount of information from any given page: the title of the talk described by the page (so I can collate this data with a giant CSV we already have), and then the event at which a given talk was given, and the date on which the talk was published. The HTML for these pages is sprawling and filled with &lt;script&gt; elements. I want only the one that is followed by a q. The line that starts this block looks like this: &lt;script&gt;q("talkPage.init", { What follows is quite a bit of data. I need only the three items that look like this: "event":"TEDGlobal 2005", "filmed":1120694400, "published":1158019860, Luckily, "filmed" and "published" only occur once in this large block, but "event" occurs several times. It's always the same, so I don't care which of these any script grabs. My thought was to use BeautifulSoup to find the &lt;script&gt;q element and then pass that onto the json module to parse, but I cannot figure out hot to tell soup to grab the &lt;script&gt; element followed by a q -- classes and ids are easy. Followed by ... not so much. To begin working on the JSON portion, I've created a text file which has only the contents of the &lt;script&gt;q element in it, but I confess that getting the json module to load this is not working terribly well. The code I have for the experiment first loads the text file with the JSON block I'm interested in, and then tries to decode it so I can do other things with it: import json text = open('dawkins_script_element.txt', 'r').read() data = json.loads(text) But clearly the JSON decoder doesn't like what I have, because it throws a ValueError: Expecting value: line 1 column 1 (char 0). Bah! Here's what the first three lines of this script element looks like: &lt;script&gt;q("talkPage.init", { "el": "[data-…
has title: Python find JSON in HTML and get select values
tagged with: python
has answer: http://stackoverflow.com/a/48330011
accepted answer: http://stackoverflow.com/a/48330011
type: AnsweredQuestion

http://stackoverflow.com/comment/83614717
type: QuestionComment
has text: @Pattu: You'll have to be more clear about what you're actually trying to accomplish. Are these properties all simple expressions of `TestUser`'s columns or can they contain arbitrary Python code? Are they front-facing and will they be created/deleted by a (possibly malicious) user? Why can't this user just edit the `models.py` file?
comment on: http://stackoverflow.com/q/48314387
score: 1
type: Comment

http://stackoverflow.com/q/48217991
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48218046
linked to: http://stackoverflow.com/q/3276230
has comment: http://stackoverflow.com/comment/83418245
has answer: http://stackoverflow.com/a/48218108
has answer: http://stackoverflow.com/a/48218366
tagged with: python
tagged with: dictionary
has title: Is it faster to read large amounts of data from multiple .txt files or from a dictionary?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48218108
answer count: 3
score: 1
has body: I am working on a personal project (using Python 3) that will retrieve weather information for any city in the United States. My program prompts the user to enter as many city-state combinations as they wish, and then it retrieves the weather information and creates a weather summary for each city entered. Behind the scenes, I'm essentially taking the State entered by the user, opening a .txt file corresponding to that State, and then getting a weather code that is associated with the city entered, which I then use in a URL request to find weather information for the city. Since I have a .txt file for every state, I have 50 .txt files, each with a large number of city-weather code combinations. Would it be faster to keep my algorithm the way that it currently is, or would it be faster to keep all of this data in a dictionary? This is how I was thinking about storing the data in a dictionary: info = {'Virginia':{'City1':'ID1','City2':'ID2'},'North Carolina':{'City3':'ID3'}} I'd be happy to provide some of my code or elaborate if necessary. Thanks!
downvote count: 0
tagged with: file
upvote count: 1
possible better answer: http://stackoverflow.com/a/48218046
favorite count: 0

http://stackoverflow.com/comment/83487058
score: 0
type: Comment
has text: Help would be appreciated.
type: AnswerComment
comment on: http://stackoverflow.com/a/48248478

http://stackoverflow.com/q/48268390
accepted answer: http://stackoverflow.com/a/48301916
has body: Trying to write part of the python code in Maya to extract the face from object then move it and rotate it. I tried parameters of polyChipOff itself, tried xform and move and rotate functions. Problem is the same. If rotation is after translation face rotates against the previous position not the current one. Am I understand some concepts completely wrong? Code below shows the problem. Simply create a pCube and start the script. From my perspective this code should move face away and then rotate around itself many times. Instead it rotates in a circle with a center in where the face was before move command. from maya import cmds face1 = 'pCube1.f[1]' cmds.select(face1) cmds.polyChipOff(dup=True) cmds.move(2, 2, 0, r=True, os=True, dph=True) cmds.rotate(0,0,10, a=True, os=True, dph=True) for i in range (35): cmds.polyChipOff(dup=True) cmds.rotate(0,0,10, a=True, os=True, dph=True)
tagged with: maya
tagged with: python
has answer: http://stackoverflow.com/a/48301916
type: Question
tagged with: rotation
answer count: 1
has title: Maya 2018, python, move and rotate extracted face
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/120885008
has text: In 2021 this answer is only relevant to Python 2.7.9+
type: AnswerComment
comment on: http://stackoverflow.com/a/48327127
score: 0
type: Comment

http://stackoverflow.com/q/48233783
score: 5
has body: I'm confused on the markdown syntax works to put images in pelican. When I have this, everything works. .. image:: /images/Rugby-Tackle.jpg :alt: About to make the tackle, Yale Alumni Game 2017 But I dug this up on the .rst documentation. The pelican docs have many references to code like this: [![Alt Text]({filename}/images/Rugby-Tackle.jpg)]({filename}/images/Rugby-Tackle.jpg) or this: ![Alt Text]({filename}/images/Rugby-Tackle.jpg) All of which just show up as text when included in the markdown file and don't produce an image. What am I missing here?
answer count: 1
downvote count: 1
upvote count: 6
tagged with: python
tagged with: restructuredtext
favorite count: 0
has title: Syntax to put images in .rst
tagged with: markdown
type: AnsweredQuestion
tagged with: pelican
type: Question
has answer: http://stackoverflow.com/a/48234104
accepted answer: http://stackoverflow.com/a/48234104

http://stackoverflow.com/q/48174601
has title: Using variables in re.findall() regex function
downvote count: 0
type: UnansweredQuestion
answer count: 1
has body: I have a list of regex patterns like k[a-z]p[a-z]+a and a list of words that can fit into these patterns. Now, the problem is that, when I use: re.findall(r'k[a-z]p[a-z]+a', list) Everything works properly, but when I replace the raw expression with a variable like: pattern = "r'" + pattern + "'" and then try: re.findall(pattern, list) or re.findall(str(pattern), list) It no longer works. How could I fix it? Thanks! Spike
has comment: http://stackoverflow.com/comment/83328907
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48174695
has comment: http://stackoverflow.com/comment/83328900
has comment: http://stackoverflow.com/comment/83328962
tagged with: python
tagged with: regex
score: 2
upvote count: 2

http://stackoverflow.com/comment/83602749
has text: Sets require hashable elements. This is what gives `in` fast lookup performance within sets and keys of dicts. A simple solution is to use tuples instead of lists. You can also implement your own `__hash__` method if you'd like.
comment on: http://stackoverflow.com/q/48308498
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48298118
has comment: http://stackoverflow.com/comment/83581651
upvote count: 2
has body: I think assign to column is not necessary, only join and convert by dt.tz_localize, last remove columns by drop: df['datetime'] = pd.to_datetime(df['date'] + " " + df['time']).dt.tz_localize('UTC') df = df.drop(['date','time'], axis=1) print (df) Seq datetime 0 1 2018-01-15 00:00:00+00:00 1 2 2018-01-15 00:01:00+00:00 2 3 2018-01-15 00:02:00+00:00 3 4 2018-01-15 00:03:00+00:00 4 5 2018-01-15 00:04:00+00:00 5 6 2018-01-15 00:05:00+00:00 6 7 2018-01-15 00:06:00+00:00 7 8 2018-01-15 00:07:00+00:00 8 9 2018-01-15 00:08:00+00:00 9 10 2018-01-15 00:09:00+00:00 10 11 2018-01-15 00:10:00+00:00 11 12 2018-01-15 00:11:00+00:00 12 13 2018-01-15 00:12:00+00:00
type: Answer
has comment: http://stackoverflow.com/comment/83581348
score: 2
has comment: http://stackoverflow.com/comment/83581615
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48298076
downvote count: 0
answers question: http://stackoverflow.com/q/48298076
has comment: http://stackoverflow.com/comment/83582238

http://stackoverflow.com/q/48287942
downvote count: 0
tagged with: python
has title: BigQuery Python cannot delete dataset: Dataset is still in use
score: 4
linked to: http://stackoverflow.com/q/48227236
duplicate of: http://stackoverflow.com/q/48227236
has answer: http://stackoverflow.com/a/48288082
has comment: http://stackoverflow.com/comment/83560775
tagged with: google-bigquery
has body: I am writing an integration test using the google-cloud-bigquery python library. My test follows these steps: Create new dataset Create table in dataset Insert rows into table Do some stuff, make sure the stuff makes sense Delete the dataset However, when I try and delete the dataset I get the error google.api_core.exceptions.BadRequest: 400 DELETE {url}: Dataset {dataset} is still in use Looking at the BigQuery UI I see This table has records in the streaming buffer that may not be visible in the preview. Clearly, BigQuery needs to finish doing its thing before I can delete. Is there a sane way of blocking until I am able to delete the dataset?
favorite count: 0
type: Question
upvote count: 4
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/48312878
has body: You can use the loc function.To replace the all the negative values and leverage numpy nan to replace them. sample code look like. import numpy as np df=pd.DataFrame({'a': [1, 2] , 'b': [-3, 4], 'c': [5, -6]}) df.loc[~(df['b'] &gt; 0), 'b']=np.nan
type: Answer
answers question: http://stackoverflow.com/q/48312655
upvote count: 3
downvote count: 0
score: 3

http://stackoverflow.com/a/65061540
upvote count: 1
answers question: http://stackoverflow.com/q/48287989
score: 1
downvote count: 0
has body: Try this: # Setting `Playing ` status await bot.change_presence(activity=discord.Game(name="a game")) # Setting `Streaming ` status await bot.change_presence(activity=discord.Streaming(name="My Stream", url=my_twitch_url)) # Setting `Listening ` status await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="a song")) # Setting `Watching ` status await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="a movie"))
type: Answer

http://stackoverflow.com/comment/83435150
has text: I am sorry. The code is correct
comment on: http://stackoverflow.com/a/48216246
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83477512
has text: The year values were just for examples
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48247401

http://stackoverflow.com/q/48316483
tagged with: pyjnius
possible better answer: http://stackoverflow.com/a/65621230
has body: I am getting this error while trying to use jnius's autoclass to get the android webview inside Kivy app. What could be the fix? Thanks My code looks like this: import kivy from kivy.app import App from kivy.lang import Builder from kivy.utils import platform from kivy.uix.widget import Widget from kivy.clock import Clock from jnius import autoclass #from android.runnable import run_on_ui_thread WebView = autoclass('android.webkit.WebView') WebViewClient = autoclass('android.webkit.WebViewClient') activity = autoclass('org.renpy.android.PythonActivity').mActivity class Wv(Widget): def __init__(self, **kwargs): super(Wv, self).__init__(**kwargs) # Clock.schedule_once(self.create_webview, 0) ` # @run_on_ui_thread # def create_webview(self, *args): # webview = WebView(activity) # webview.getSettings().setJavaScriptEnabled(True) # wvc = WebViewClient(); # webview.setWebViewClient(wvc); # activity.setContentView(webview) # webview.loadUrl('http://www.google.com') class ServiceApp(App): def build(self): return Wv() if __name__ == '__main__': ServiceApp().run
has answer: http://stackoverflow.com/a/65621230
favorite count: 0
type: Question
score: 3
tagged with: android
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/50833860
accepted answer: http://stackoverflow.com/a/50833860
type: AnsweredQuestion
upvote count: 3
answer count: 2
has title: jnius.find_javaclass , jnius.JavaException: Class not found 'android/webkit/WebView'
downvote count: 0

http://stackoverflow.com/q/48297722
upvote count: 1
favorite count: 0
type: Question
has body: How to import the directory contains - ? from gib-bin.Test import print_test print_test() Error: from gib-bin.Test import print_test ^ SyntaxError: invalid syntax
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83580053
linked to: http://stackoverflow.com/q/8350853
score: 1
tagged with: python
has title: How to import the directory contains `-` in Python?
accepted answer: http://stackoverflow.com/a/48297804
duplicate of: http://stackoverflow.com/q/8350853
has answer: http://stackoverflow.com/a/48297804
answer count: 1
downvote count: 0

histogram
tags question: http://stackoverflow.com/q/48281206
tags question: http://stackoverflow.com/q/48179498
type: Tag
tags question: http://stackoverflow.com/q/48273713
tags question: http://stackoverflow.com/q/48232385
tags question: http://stackoverflow.com/q/48227037
tag name: histogram

http://stackoverflow.com/comment/83400630
score: 0
comment on: http://stackoverflow.com/q/48208777
type: Comment
type: QuestionComment
has text: This is not real code. `c.choice_set.getlist` would raise a NameError because `getlist` is a method of a QueryDict - eg `request.POST` - not of a Manager.

http://stackoverflow.com/comment/83529353
comment on: http://stackoverflow.com/q/48272389
has text: @Darkonaut the sorting isn't the problem. It's that the sorting isn't working as expected. The issue cannot be reproduced with 10 values, and it's not as simple as that.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48190027
favorite count: 0
tagged with: jupyter-notebook
type: Question
has title: unable to download nbextensions' javascript and css file
type: UnansweredQuestion
has body: I am trying to install nbextensions to my jupyter notebook. When opening the notebook, I can see the tab for the nbextensions but is is empty. There is a reload button moving but nothing ever shows. I went to command prompt and the following commands were executed successfully: pip install jupyter_contrib_nbextensions pip install https://github.com/ipython-contrib/jupyter_contrib_nbextensions/tarball/master conda install -c conda-forge jupyter_contrib_nbextensions But when I try to execute jupyter contrib nbextension install --user it seems like all extensions validate but when writing them there is a multitude of errors. [I 09:49:34 InstallContribNbextensionsApp] - Validating: ok [I 09:49:34 InstallContribNbextensionsApp] Installing jupyter_contrib_nbextensions items to config in C:\Users\sammy\.jupyter Enabling: jupyter_nbextensions_configurator - Writing config: C:\Users\sammy\.jupyter - Validating... jupyter_nbextensions_configurator ok Enabling notebook nbextension nbextensions_configurator/config_menu/main... Traceback (most recent call last): File "C:\Users\sammy\Anaconda3\Scripts\jupyter-contrib-script.py", line 5, in &lt;module&gt; sys.exit(jupyter_contrib_core.application.main()) File "C:\Users\sammy\Anaconda3\lib\site-packages\jupyter_core\application.py", line 266, in launch_instance return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs) File "C:\Users\sammy\Anaconda3\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance app.start() File "C:\Users\sammy\Anaconda3\lib\site-packages\jupyter_contrib_core\application.py", line 50, in start super(JupyterContribApp, self).start() File "C:\Users\sammy\Anaconda3\lib\site-packages\jupyter_core\application.py", line 255, in start self.subapp.start() File "C:\Users\sammy\Anaconda3\lib\site-packages\jupyter_contrib_nbextensions\application.py", line 226, in start super(ContribNbextensionsApp, self).start() File "C:\Users\sammy\Anaconda3\lib\site-packages\jupyter_core\applicatio…
tagged with: python
tagged with: jupyter-irkernel
tagged with: jupyter-console
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/83360068
score: 1
upvote count: 1
tagged with: jupyter

http://stackoverflow.com/comment/83385091
has text: Actually I was looking for a scalar value in answer of **np.dot**
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48201729

http://stackoverflow.com/q/48277590
downvote count: 1
favorite count: 0
type: Question
tagged with: tkinter
has answer: http://stackoverflow.com/a/48277987
tagged with: python
has comment: http://stackoverflow.com/comment/83545114
accepted answer: http://stackoverflow.com/a/48277987
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83540797
has body: Can I create an if statement whose condition depends on the text of a button? For example: if widget.config(text=2): btn.config(font=font2)
upvote count: 2
has comment: http://stackoverflow.com/comment/83538946
has title: IF statements depending on widget configuration tkinter
score: 1
has comment: http://stackoverflow.com/comment/83544026
has comment: http://stackoverflow.com/comment/83557111
has comment: http://stackoverflow.com/comment/83548325
has comment: http://stackoverflow.com/comment/83553691
answer count: 1
has comment: http://stackoverflow.com/comment/83540808
tagged with: button
has comment: http://stackoverflow.com/comment/83539061

http://stackoverflow.com/q/48310413
has body: I have a help pop up dialog that works fine in Linux and Windows where Python 3.5.x is installed but after a pyinstaller build the rest of the app works fine but that pop up is just an empty form void of all five of its widgets. I can’t see anything wrong with the code I’ve tried to remove widgets one at a time to see if any of them is a problem yet same result works before building and fails after from tkinter import * from tkinter import ttk from tkinterhtml import TkinterHtml as tkhtml class HelpSystem(Toplevel): def __init__(self, parent, dlgTitle='Help', helpfile='help.db', Manuals=None, showtopic=None): Toplevel.__init__(self, parent) self.transient(parent) self.parent = parent self.title(dlgTitle) self.con = sqlite3.connect(helpfile) self.cur = self.con.cursor() self.helpfile = helpfile self.Manuals = Manuals self.showtopic = showtopic self.searchresults = [] self.searchindex = -1 self.search_width = 67 self.tree_height = 19 body = Frame(self) self.initial_focus = self.Dialog_Builder(body) body.pack() self.grab_set() if not self.initial_focus: self.initial_focus = self self.protocol("WM_DELETE_WINDOW", self.exitme) self.initial_focus.focus_set() self.wait_window(self) def Dialog_Builder(self, mybody): self.sbox = Entry(mybody, width=self.search_width, font=('Helvetica', 15)) self.sbuts = Button(mybody, text='Search', command=lambda: self.btnClick('s')) self.sbutn = Button(mybody, text='Next', command=lambda: self.btnClick('n')) ff = self._font_details('Helvetica', 15) self.toc = ttk.Treeview(mybody, show='tree', height=self.tree_height, selectmode=BROWSE) self.toc.bind('<ButtonRelease-1>', self._clicktopic) self.style = ttk.Style() self.style.configure('Treeview', font=("Helvetica", 15)) self.style.configure('Treeview', rowheight=ff[1]) self.toc.column('#0', width=(ff[0] * 20)) self.vwr = tkhtml(mybody, height=ff[1] * self.tree_height) self.sbox.grid(column=0, row=0, columnspan=8, rowspan=1, padx=5, pady=5, sticky=W) self.sbuts.grid(column=8, row=0, columnspa…
has comment: http://stackoverflow.com/comment/83609208
has comment: http://stackoverflow.com/comment/83609189
has comment: http://stackoverflow.com/comment/83610491
has title: tkinter popup dialog works fine running in python 3.5 but not in a pyinstaller build
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83648832
tagged with: pyinstaller
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83647965
has comment: http://stackoverflow.com/comment/83632017
has comment: http://stackoverflow.com/comment/83610564
has comment: http://stackoverflow.com/comment/83644338
tagged with: python
has comment: http://stackoverflow.com/comment/83631892
has comment: http://stackoverflow.com/comment/83644573
has comment: http://stackoverflow.com/comment/83634163
tagged with: tkinter
tagged with: popup
answer count: 0
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83648038
has comment: http://stackoverflow.com/comment/83631560
downvote count: 0

http://stackoverflow.com/comment/132675143
comment on: http://stackoverflow.com/a/48211877
has text: "merge" like a join? That'd be a self-join and could indeed lower the risk of OOM.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48314176
type: Answer
has body: Thanks for the input , i modified the code like below for k, v in cn.items(): print("k compared is::",k) with open('new.csv','r') as csvinput: reader = csv.reader(csvinput) for row in reader: print("Executing inner loop") print("row value compared is ::",row[0]) if k == row[0] : print("matched") row.append(v) all.append(row) break writer.writerows(all) with this code it worked but my worry is csv file will be opened and read for k number of times , so is there any better solution
answers question: http://stackoverflow.com/q/48312674
score: 0
has comment: http://stackoverflow.com/comment/83614041

http://stackoverflow.com/q/48264375
type: AnsweredQuestion
answer count: 3
score: 1
has body: I'd like to capture n times a pattern that repeats itself n times, with n &gt;= 0. I have strings that look like this: a = 'x="2"' b = 'x="2,3", y="hello", z="true"' I'd like to extract 'x' and its value '2,3', 'y' and its value 'hello', etc. Variables are separated by a comma followed by a space; values are inside double quotes. How I can do this with the re library in Python? I tried naively with the following: match = re.search(r'^((?P&lt;variable&gt;[0-9a-zA-Z_-]+)="(?P&lt;value&gt;.*)"(?:,\s)?)*', b) If I print match.groupdict(), it'll output: {'variable': 'x', 'value': '2,3", y="hello", z="true'}
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48265266
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83512306
has comment: http://stackoverflow.com/comment/83512653
has answer: http://stackoverflow.com/a/48265239
accepted answer: http://stackoverflow.com/a/48264823
has title: capturing a repeated group in Python
has answer: http://stackoverflow.com/a/48264823
tagged with: python
tagged with: regex-group
tagged with: regex
possible better answer: http://stackoverflow.com/a/48265239

http://stackoverflow.com/comment/83645542
type: Comment
type: QuestionComment
has text: Yes, the path does exist because it starts creating the folder and writing the part file ('part-0000'). But since the error occurs, it doesn't finish writing and the file becomes empty or blank. How can I check for the writing permission? @pault
score: 0
comment on: http://stackoverflow.com/q/48311797

http://stackoverflow.com/comment/83394867
score: 0
type: AnswerComment
has text: My fault, is `order_waiting_list` named `name='order_waiting_list'` in your `administrator.urls`?
type: Comment
comment on: http://stackoverflow.com/a/48206846

http://stackoverflow.com/a/48282738
has comment: http://stackoverflow.com/comment/83554261
has body: I think you need: pd.Grouper(level='Time',freq='15Min') I believe you can add column Response to groupby, reshape by unstack and plot: a = df_final.groupby([pd.Grouper(level='Time',freq='15Min'), 'Response'])['Response'].count() a.unstack().plot(kind='bar', figsize=(15,10), title="Response Codes")
has comment: http://stackoverflow.com/comment/83554399
has comment: http://stackoverflow.com/comment/83549565
has comment: http://stackoverflow.com/comment/83554224
score: 10
type: Answer
has comment: http://stackoverflow.com/comment/83549536
answers question: http://stackoverflow.com/q/48282691
has comment: http://stackoverflow.com/comment/83549368
has comment: http://stackoverflow.com/comment/83554342
has comment: http://stackoverflow.com/comment/126550158
downvote count: 0
has comment: http://stackoverflow.com/comment/83549257
has comment: http://stackoverflow.com/comment/83554367
has comment: http://stackoverflow.com/comment/83549332
has comment: http://stackoverflow.com/comment/83549208
has comment: http://stackoverflow.com/comment/83549716
upvote count: 10
has comment: http://stackoverflow.com/comment/83549590
has comment: http://stackoverflow.com/comment/83552235
has comment: http://stackoverflow.com/comment/83554159
has comment: http://stackoverflow.com/comment/83553939
has comment: http://stackoverflow.com/comment/83550114
has comment: http://stackoverflow.com/comment/83549425
has comment: http://stackoverflow.com/comment/83554198

http://stackoverflow.com/q/48253850
has comment: http://stackoverflow.com/comment/83490413
has answer: http://stackoverflow.com/a/48254039
score: 2
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/83490393
downvote count: 1
has title: Python - transform string into a table using rsplit for each line
possible better answer: http://stackoverflow.com/a/48254010
linked to: http://stackoverflow.com/q/35730963
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48254056
accepted answer: http://stackoverflow.com/a/48254056
has answer: http://stackoverflow.com/a/48254004
tagged with: regex
has comment: http://stackoverflow.com/comment/83490468
has body: I am new to Python and need some help with a string I have that looks like this: string='Starters\nSalad with Greens 14.00\nSalad Goat Cheese 12.75\nMains\nPizza 12.75\nPasta 12.75\n' and need to transform it into a table that looks more like this: Category Dish Price Starters Salad with Greens 14.00 Starters Salad Goat Cheese 12.75 Mains Pizza 12.75 Mains Pasta 12.75 What would be the best way to achieve this? I was trying to apply string.rsplit(" ",2) but couldn't figure out to make it do it per line. And had no idea how to repeat the headers into a separate column. Any help will be much appreciated. Thanks in advance!
answer count: 4
has answer: http://stackoverflow.com/a/48254010

http://stackoverflow.com/comment/83596555
comment on: http://stackoverflow.com/a/48286070
type: AnswerComment
score: 1
type: Comment
has text: combo_df = pd.DataFrame(data=list(product(df['Column_a_Name'], df['Column_b_Name'])), columns=['Column_a_Name','Column_b_Name'])

multiprocessing
tags question: http://stackoverflow.com/q/48260672
tags question: http://stackoverflow.com/q/48274131
tags question: http://stackoverflow.com/q/48311096
tags question: http://stackoverflow.com/q/48254216
tags question: http://stackoverflow.com/q/48290519
tags question: http://stackoverflow.com/q/48312986
tags question: http://stackoverflow.com/q/48290074
tags question: http://stackoverflow.com/q/48271576
tags question: http://stackoverflow.com/q/48233427
tags question: http://stackoverflow.com/q/48287812
tags question: http://stackoverflow.com/q/48207427
tags question: http://stackoverflow.com/q/48287782
tags question: http://stackoverflow.com/q/48288140
tags question: http://stackoverflow.com/q/48177299
tags question: http://stackoverflow.com/q/48218396
tags question: http://stackoverflow.com/q/48208387
tags question: http://stackoverflow.com/q/48217449
tags question: http://stackoverflow.com/q/48185746
tags question: http://stackoverflow.com/q/48314234
tags question: http://stackoverflow.com/q/48327672
tags question: http://stackoverflow.com/q/48216942
tags question: http://stackoverflow.com/q/48230562
tags question: http://stackoverflow.com/q/48177823
tags question: http://stackoverflow.com/q/48330983
tags question: http://stackoverflow.com/q/48191238
tags question: http://stackoverflow.com/q/48314325
tags question: http://stackoverflow.com/q/48181361
tags question: http://stackoverflow.com/q/48265857
tags question: http://stackoverflow.com/q/48262966
tags question: http://stackoverflow.com/q/48233306
tags question: http://stackoverflow.com/q/48263543
tags question: http://stackoverflow.com/q/48250410
tags question: http://stackoverflow.com/q/48258987
tags question: http://stackoverflow.com/q/48244659
tags question: http://stackoverflow.com/q/48282121
type: Tag
tags question: http://stackoverflow.com/q/48180998
tags question: http://stackoverflow.com/q/48302932
tags question: http://stackoverflow.com/q/48240325
tags question: http://stackoverflow.com/q/48306228
tags question: http://stackoverflow.com/q/48200675
tags question: http://stackoverflow.com/q/48261171
tags question: http://stackoverflow.com/q/48330458
tags question: http://stackoverflow.com/q/48236857
tags question: http://stackoverflow.com/q/48257221
tags question: http://stackoverflow.com/q/48220845
tags question: http://stackoverflow.com/q/48265137
tag name: multiprocessing

http://stackoverflow.com/comment/83557291
score: 0
type: AnswerComment
has text: The example code fixes all issues without directly pointing them out. There is no need to assign b to the function and return it when you can directly return the function.
type: Comment
comment on: http://stackoverflow.com/a/48284787

http://stackoverflow.com/comment/121883048
type: Comment
type: AnswerComment
has text: instead of `if any(f.match(p) for p in patterns` in my testing it was **much faster** to use `if f.suffix.lower() in patterns` and I made patterns a set. I was testing with 8 extensions searching recursively over thousands of files.
comment on: http://stackoverflow.com/a/66905507
score: 0

http://stackoverflow.com/comment/83371309
has text: There are also a couple of typos in your calc, e.g. `df1.['Close']` and `df1['Close].shift(1)`
comment on: http://stackoverflow.com/q/48195007
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83423864
score: 0
has text: It seems you have two very different questions here, making this post to broad really. Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also please [take the SO tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). One question per question please.
comment on: http://stackoverflow.com/q/48221195
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83535586
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48276015
has text: more right ideom is - filtering. Or delete from copy. Or make deferred deletion: keep keys to delete, delete them at the the end as batch

http://stackoverflow.com/q/48191873
answer count: 0
has comment: http://stackoverflow.com/comment/83384635
has comment: http://stackoverflow.com/comment/83393659
tagged with: 3d
type: UnansweredQuestion
tagged with: arrays
downvote count: 0
has body: I have the following problem. I have an an array of 3D coordinates like this: arr = np.array([[21.000,48.000,28.000],[27.000,48.000,31.000],[21.000, 47.000,27.000],[22.000, 21.000, 97.000],[22.000, 20.000, 97.000],[22.000, 20.000, 95.000]]) This is only a small extract of the coordinates, because there a millions. They a all lying in a 3D box. Additionaly I have the miniumum and maxium coordinate of the 3D box the coordinates the are lying in: edgeMaxima = [(0,0,0))(40,59,110)] Now i want to calculate the number of neighbors which each coordinate could have in a specific radius and store it in a second array. So lets assume I take the radius 5 i would have 5^3-1 neighbors for most of my coordinates. The edge coordinates of course would have less neigbors. Is there a good way to calculate the numbers of neighbors?
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83369439
type: Question
has title: Count the numbers of neighbors in an array with 3D coordinates
score: 1
has comment: http://stackoverflow.com/comment/83394572
tagged with: python
has comment: http://stackoverflow.com/comment/83396020
tagged with: scipy
tagged with: numpy
linked to: http://stackoverflow.com/q/48179476
has comment: http://stackoverflow.com/comment/83392173

http://stackoverflow.com/a/48254802
has body: Looks like you want to use pandas. Convert your lists of dictionaries into dataframes: import pandas as pd d1 = pd.DataFrame(first_result) d2 = ... d3 = ... Join them into a new wide dataframe with redundant columns: d = d1.join(d2,rsuffix='b').join(d3,rsuffix='c') # count descr id countb descrb idb countc descrc idc #0 110 foo 109 26 foo 109 72 foo 109 #1 810 bar 114 53 bar 114 42 bar 114 Remove the duplicate columns: d.drop(['idb','idc','descrb','descrc'], axis=1, inplace = True) Convert the result back to the list of dictionaries: list(d.T.to_dict().values()) #[{'countc': '72', 'count': '110', 'descr': 'foo', 'countb': '26', 'id': 109}, # {'countc': '42', 'count': '810', 'descr': 'bar', 'countb': '53', 'id': 114}]
answers question: http://stackoverflow.com/q/48254692
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48254692
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83492521

http://stackoverflow.com/comment/83544771
comment on: http://stackoverflow.com/q/48280605
has text: How come the intersection solution does not work? + please add a code example, it will be easier to help you
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/48202387
downvote count: 0
has comment: http://stackoverflow.com/comment/83397098
tagged with: authentication
has answer: http://stackoverflow.com/a/69319259
upvote count: 1
has comment: http://stackoverflow.com/comment/83385982
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83385820
has comment: http://stackoverflow.com/comment/83385679
has comment: http://stackoverflow.com/comment/83397177
favorite count: 0
has comment: http://stackoverflow.com/comment/83422150
type: Question
has comment: http://stackoverflow.com/comment/83385751
has comment: http://stackoverflow.com/comment/83385853
has comment: http://stackoverflow.com/comment/83394382
has body: I am using python requests library to get the data from adzuna api . if i try r = requests.get("http://api.adzuna.com/v1/api/jobs/gb/search/1?app_id=appID\ &amp;app_key=appKEY&amp;results_per_page=50&amp;\ what=entry%20level&amp;content-type=application/json") print r.text it is fetching me data But if i wrap this inside a fuction def getData (): r = requests.get("http://api.adzuna.com/v1/api/jobs/gb/search/1?app_id=appID\ &amp;app_key=appKey&amp;results_per_page=50&amp;\ what=entry%20level&amp;content-type=application/json") print r.text getData() it is giving me following exception {"display":"Authorisation failed","__CLASS__":"Adzuna::API::Response::Exception","doc":"http://api.adzuna.com/v1/doc","exception":"AUTH_FAIL"} what is the wrong with this function ? See the Image for more info
has comment: http://stackoverflow.com/comment/83386143
has comment: http://stackoverflow.com/comment/83385799
linked to: http://stackoverflow.com/q/7053652
has comment: http://stackoverflow.com/comment/83431005
has comment: http://stackoverflow.com/comment/83385875
has comment: http://stackoverflow.com/comment/83385902
has title: Requests.get failing when using inside function
has answer: http://stackoverflow.com/a/48202770
tagged with: python
accepted answer: http://stackoverflow.com/a/48202770
has comment: http://stackoverflow.com/comment/83393996
has comment: http://stackoverflow.com/comment/83387329
tagged with: get
has comment: http://stackoverflow.com/comment/83397821
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/48202764
has comment: http://stackoverflow.com/comment/83397907
possible better answer: http://stackoverflow.com/a/48202764
has comment: http://stackoverflow.com/comment/83393990
score: 1

http://stackoverflow.com/comment/83661234
type: AnswerComment
comment on: http://stackoverflow.com/a/48318618
score: 0
has text: @JojoBambam - I will leave an edit to my answer, as it's easier to show code markup there.
type: Comment

http://stackoverflow.com/a/48300537
type: AcceptedAnswer
has body: Excellent question! One of Trio's weirdest, most controversial decisions is that it takes the position that the existence of a background task is not an implementation detail, and should be exposed as part of your API. On balance I think this is the right decision, but it's definitely a bit experimental and has some trade-offs. Why does Trio do this? In my experience, other systems make it seem like you can abstract away the presence of a background task or thread, but in reality it leaks in all kinds of ways: they end up breaking control-C handling, or they cause problems when you're trying to exit the program cleanly, or they leak when you try to cancel the main operation, or you have sequencing problems because the function you called completed but the work it promised to do is still going on in the background, or the background task crashes with an unexpected exception and then the exception gets lost and all kinds of weird problems ensue... so while it might make your API feel a little messier in the short term, in the long term everything goes easier if you make this explicit. Also, keep in mind that everyone else writing and using Trio libraries has the same issue, so your API is not going to feel too weird :-). I don't know what you're trying to do exactly. Maybe it's something like a websocket connection, where you want to constantly be reading from the socket to respond to heartbeat ("ping") requests. One pattern would be to do something like: @asynccontextmanager async def open_websocket(url): ws = WebSocket() await ws._connect(url) try: async with trio.open_nursery() as nursery: nursery.start_soon(ws._heartbeat_task) yield ws # Cancel the heartbeat task, since we're about to close the connection nursery.cancel_scope.cancel() finally: await ws.aclose() And then your users can use it like: async with open_websocket("https://...") as ws: await ws.send("hello") ... If you want to get fancier, another option would be to provide one version where your users pa…
score: 54
upvote count: 54
type: Answer
accepted answer of: http://stackoverflow.com/q/48282841
answers question: http://stackoverflow.com/q/48282841
downvote count: 0

http://stackoverflow.com/q/48188881
has comment: http://stackoverflow.com/comment/83358069
has answer: http://stackoverflow.com/a/48191222
tagged with: python
has title: How to obtain the values of a list of objects within a Model in Python?
has comment: http://stackoverflow.com/comment/83358103
type: AnsweredQuestion
score: 0
downvote count: 2
has body: I have two modes, User and Friends, it's a one-to-many relationship I'm trying to get the values like this record = User.query.filter_by(id=7).first() These are the methods and properties that my model has: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', __eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__','__lt__','__mapper__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__table__', '__tablename__', '__weakref__', '_decl_class_registry', '_sa_class_manager', '_sa_instance_state','id', 'rfc', 'name', 'friends'] friends is the array that I want to get their values print('|{}|{}|{}'.format(record.user.rfc, record.user.name, record.friends ) ) |BDS344XX3343|Bob|[&lt;models.Friend object at 0x7f0276752e48&gt;, &lt;models.Friend object at 0x7f0276752eb8&gt; Any idea or suggestion to get the values of friends
answer count: 1
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/83357650
tagged with: sqlalchemy
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83362211
has comment: http://stackoverflow.com/comment/83363081
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/48191222

http://stackoverflow.com/q/48242432
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48242469
score: 3
tagged with: element
linked to: http://stackoverflow.com/q/3428536
has comment: http://stackoverflow.com/comment/83467482
has answer: http://stackoverflow.com/a/48242469
accepted answer: http://stackoverflow.com/a/48242479
tagged with: duplicates
tagged with: python
answer count: 6
has body: Hello I want to know how to subtract 2 lists by duplicate elements, not by value, in python. ListA = [G, A, H, I, J, B] ListB = [A, B, C] ListC = [G, H, I, J] So we subtract the ListB values, if they are found in ListA as duplicates, and the ListC will give back the non-duplicate values in ListA. Mathematically written it would be: ListC = ListA - (ListA ∩ ListB) (I don't want to remove the duplicates in ListA, only the intersection between ListA and ListB, as described in the above formula, so this question is not a duplicate of questions/48242432
has answer: http://stackoverflow.com/a/48242526
has answer: http://stackoverflow.com/a/72702007
has answer: http://stackoverflow.com/a/48242479
has title: Subtract 2 lists by duplicate elements in python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48242499
has answer: http://stackoverflow.com/a/48242504
upvote count: 3
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/comment/83533540
comment on: http://stackoverflow.com/a/48263763
score: 0
has text: @GordThompson: Thanks.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83639153
comment on: http://stackoverflow.com/a/48311477
type: AnswerComment
has text: that seems to be because the set works on the last dimension, and it does not seem to work on 1d tensors. The [None,:] syntax just expands each tensor in one dimension.
score: 0
type: Comment

http://stackoverflow.com/q/48303829
type: Question
accepted answer: http://stackoverflow.com/a/48303900
has answer: http://stackoverflow.com/a/48303900
tagged with: python
tagged with: append
has body: This is the part of my code which works fine; #taking time average average= sum(result.expect[0])/len(t) averagelist=[] averagelist.append([num-Delta, average]) print(averagelist) Giving output; [[-50, 0.99994894092412567]] [[-45, 0.9999371327219414]] [[-40, 0.99992064521708557]] [[-35, 0.99989662709502258]] [[-30, 0.99985966374414359]] [[-25, 0.99979843838324323]] [[-20, 0.99968609192147129]] [[-15, 0.99944283644552467]] [[-10, 0.99874864586107459]] [[-5, 0.99499296595818931]] [[0, 0.50250021597634276]] Now I want to be able to make a new list x= -50,-45,-40 etc and new list y= 0.999..., 0.999..., 0.999... etc Is there a simple way to do this? (I have also tried the extend as oppose to append function, and this gives me the same initial output but with one square bracket not two.)
tagged with: list
type: AnsweredQuestion
score: 0
has title: Loop in python which appends answers to a list, I want to then create new list from this
answer count: 1
tagged with: qutip

http://stackoverflow.com/a/48332364
type: Answer
answers question: http://stackoverflow.com/q/48307842
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83742407
has body: Try to refresh the index pattern. Management > Index Pattern, then there is a refresh button on the top right.

http://stackoverflow.com/comment/83526639
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48271393
type: AnswerComment
has text: For the first option it gives me the error `TypeError: 'NoneType' object is not subscriptable` and for the second it just does not print out anything

http://stackoverflow.com/comment/83336545
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48178028
has text: How is that an answer?
type: AnswerComment

http://stackoverflow.com/comment/83374620
has text: Sure sure. I thought it was something specific to pandas at first, but I now I know.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48196708
type: Comment

http://stackoverflow.com/q/48325294
answer count: 2
has comment: http://stackoverflow.com/comment/83636831
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48326891
has body: let's say I have the following code df1 = ['a'] df2 = ['a'] def some_method(): global df1 global df2 df1 = pd.DataFrame(Some populated dataframe...) df2 = pd.DataFrame(Some populated dataframe...) def test(my_df=df1): print(my_df) In the following scenario, df1 outputs ['a'] when test() is called with no params. df1/df2 will print when they are passed in as params some_method() test() # Prints out ['a'] test(df1) # Works as expected test(df2) # Works as expected Can someone please explain why the default value defined in the test method does not work?
has comment: http://stackoverflow.com/comment/83636282
type: Question
has comment: http://stackoverflow.com/comment/83636041
has comment: http://stackoverflow.com/comment/83636170
has title: Python - Using default values for dataframe in method
has answer: http://stackoverflow.com/a/48326891
tagged with: python
has answer: http://stackoverflow.com/a/48325559
possible better answer: http://stackoverflow.com/a/48325559
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/48292332
has comment: http://stackoverflow.com/comment/83569990
has comment: http://stackoverflow.com/comment/83569968
has comment: http://stackoverflow.com/comment/83570275
score: 2
has comment: http://stackoverflow.com/comment/83598605
has comment: http://stackoverflow.com/comment/83597317
answer count: 0
has comment: http://stackoverflow.com/comment/83573049
upvote count: 2
has body: I'm writing a unittest class to ensure a method tests for a success, and then tests for an Exception. I'm passing a response that should trigger the exception, but in the testing method it does not get raised. Of note, I can manually make the exception raise in the actual method. Test class: class TestAPI(TestCase): def test_send_method(self): with mock.patch('requests.post') as mock_request: mock_response = mock.Mock() mock_response.json.return_value = { "success": "true" } mock_request.return_value = mock_response send_method() // THIS WORKS NICELY # Test that errors from the API are handled correctly. with self.assertRaises(SendException): mock_response.status_code = 500 mock_response.json.return_value = { 'errors': 'An error has occurred.', } send_method() // THIS RAISES NO EXCEPTION As I said, It's odd because I can manually trigger the 500 status code in the actual method and it raises fine. I can even change the initial mock response success to err and it will raise in the actual method. Why would it not raise in the unittest? Method being tested: class SendException(Exception): pass def send_method(): session_headers = { "Content-Type": "application/json", } session_body = { "send": "yes" } session_url = u'{}'.format(URL) session_response = requests.post(session_url, json=session_body, headers=session_headers) try: if(session_response.json().get('errors') is not None): raise SendException( 'Returned error with status {}: {}'.format( session_response.status_code, session_response.json().get('errors') ) ) except ValueError as err: raise SendException( 'Responded with non-json and status code {}. Error: {} - Response Text: {}'.format( session_response.status_code, err, session_response.text ) )
has comment: http://stackoverflow.com/comment/83570073
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/83598117
has comment: http://stackoverflow.com/comment/83570936
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/83601808
has comment: http://stackoverflow.com/comment/83597049
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83576095
has comment: http://stackoverflow.com/comment/83570192
has title: Django unittest with not raising exception as expected with assertRaises()
has comment: http://stackoverflow.com/comment/83607223
has comment: http://stackoverflow.com/comment/83613105
tagged with: django-unittest
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83603745
has comment: http://stackoverflow.com/comment/83573327
has comment: http://stackoverflow.com/comment/83570017
tagged with: python

http://stackoverflow.com/a/48327343
type: AcceptedAnswer
downvote count: 1
answers question: http://stackoverflow.com/q/48327207
accepted answer of: http://stackoverflow.com/q/48327207
type: Answer
has body: you can do like this def nue(li): for i in li[:]: li.remove(i) print(li) li = [1, 2, 3] nue(li) li[:] will clone original li
upvote count: 2
score: 1

http://stackoverflow.com/q/48303580
has body: This My Assignment You are provided with a person’s age and you need to determine which school level the person falls within. If 6 to 11 output ‘primary school’ If 12 to 18 output ‘secondary school’ If neither, then output ‘NA’ This is My code import sys age= int(sys.argv[1]) if age &gt;= 6.0 and age &lt;=11: print ('primary school') if age &gt;=12 and age &lt;=18: print ('secondary school') if age &lt; 6.0 and age &gt;18: print ('NA') This is my error Program Output Program Failed for Input: 5 Expected Output: NA Your Program Output: What am I doing wrong?
tagged with: python
has answer: http://stackoverflow.com/a/48303617
score: 0
has comment: http://stackoverflow.com/comment/83591892
has answer: http://stackoverflow.com/a/48303676
has title: New To Python Having Trouble with boolean logic
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83593143
has comment: http://stackoverflow.com/comment/83591963
has comment: http://stackoverflow.com/comment/83592108
type: UnansweredQuestion

http://stackoverflow.com/a/48228862
answers question: http://stackoverflow.com/q/48228722
has comment: http://stackoverflow.com/comment/83453792
has comment: http://stackoverflow.com/comment/83455017
has comment: http://stackoverflow.com/comment/83452898
has comment: http://stackoverflow.com/comment/83453115
type: Answer
has body: Is there a way to shrink my data so I don't get this OOM error? You can slice your training_set to obtain just a portion of the dataset. Something like: x={"x": np.array(training_set.data)[:(len(training_set)/2)]}, y=np.array(training_set.target)[:(len(training_set)/2)], In this example you are getting the first half of your dataset (you can select up to what point of your dataset you want to load). Edit: Another way you can do this is to obtain a random subset of your training dataset. This you can achieve by masking elements on your dataset array. For example: import numpy as np from random import random as rn #obtain boolean mask to filter out some elements #here you can define your sample % r = 0.5 #say filter half the elements mask = [True if rn() &gt;= r else False for i in range(len(training_set))] #finally, mask out those elements, #the result will have ~r times the original elements reduced_ds = training_set[mask]
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/83455002
downvote count: 0

http://stackoverflow.com/q/48216097
type: Question
has comment: http://stackoverflow.com/comment/83414745
tagged with: metadata
has comment: http://stackoverflow.com/comment/83435162
type: UnansweredQuestion
has title: adding a custom method to Meta class in django
answer count: 1
downvote count: 0
upvote count: 1
tagged with: django
has body: I have an AbstractBase model class that gets inherited by several models in their respective apps. I want the user to be able to set a name that will be used in the verbose_name field in the Meta class. If a user provides a name in one of the fields in the AbstractBase model, then that field will be used as the verbose name this is what I have tried so far class AbstractBase(models.Model): ...... custom_name = models.CharField(blank=True) class Meta(object): abstract = True def update_verbose_name(self, custom_name): if self.project_setting is not None: return verbose_name == self.custom_name when I run this it gives me TypeError: 'class Meta' got invalid attribute(s): update_verbose_name is there another way that I solve this?
favorite count: 0
has answer: http://stackoverflow.com/a/48216437
score: 1
tagged with: django-models
tagged with: python

http://stackoverflow.com/a/48268727
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48268522
accepted answer of: http://stackoverflow.com/q/48268522
upvote count: 2
has body: You can use scikit-image's view_as_windows to create those sliding windows and then we need to permute axes and reshape - from skimage.util.shape import view_as_windows def get_kernels_vectorized(im, k_size): X, Y = im.shape[1] + 1 - k_size, im.shape[0] + 1 - k_size new = view_as_windows(im,(k_size,k_size,1))[...,0].transpose(0,1,3,4,2) return new.reshape(X * Y, k_size ** 2 * 3) Explanation on usage of view_as_windows The idea with view_as_windows is that we feed in the input arg window_shape as a tuple of length same as the number of dimensions in the input array whose sliding windows are needed. Also, the axes along which we don't need to slide are fed as 1s. So, the input value for window_shape here is (k_size, k_size, 1) as the last axis is of color channels, along which we don't need to slide. Sample run for verification - In [186]: np.random.seed(0) ...: im = np.random.randint(0,9,(6,8,3)) In [189]: out1 = get_kernels(im, k_size=3) In [190]: out2 = get_kernels_vectorized(im, k_size=3) In [191]: np.array_equal(out1, out2) Out[191]: True Timings on 3264x2448 image with kernel size = 3 - In [177]: np.random.seed(0) ...: im = np.random.randint(0,9,(3264,2448,3)) In [178]: %timeit get_kernels(im, k_size=3) 1 loop, best of 3: 5.46 s per loop In [179]: %timeit get_kernels_vectorized(im, k_size=3) 1 loop, best of 3: 327 ms per loop 16x+ speedup here.
downvote count: 0
has comment: http://stackoverflow.com/comment/83521032
type: Answer
has comment: http://stackoverflow.com/comment/83521108
score: 2

http://stackoverflow.com/comment/83377185
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48197948
type: QuestionComment
has text: I don't think you can match both criteria at the same time. A regex for the first would be `\b\w+$` (which would slightly over-match if there's punctuation before the word) and the second one could use capture groups `" (\w+) .*$"`

http://stackoverflow.com/q/48194815
has comment: http://stackoverflow.com/comment/83370408
has body: So i have a pandas data frame with a few numeric columns and an id column thats a string in Python id a1 a2 a3 a4 abc 23 33 33 string dbc 2 3 3 string abc 3 4 100 string i want to add all the numeric columns for the same id string. id a1 a2 a3 a4 abc 26 37 133 string dbc 2 3 3 string Is there an elegant way if doing it in pandas or do i have to make a unique list of objects in the first column and loop through them and add them?
type: Question
has comment: http://stackoverflow.com/comment/83370372
answer count: 0
has comment: http://stackoverflow.com/comment/83370381
type: UnansweredQuestion
has title: How to add multiple rows on dataframe based on a column of distinct values? pandas/python
linked to: http://stackoverflow.com/q/39922986
score: 0
tagged with: pandas
duplicate of: http://stackoverflow.com/q/39922986
tagged with: python

http://stackoverflow.com/q/48313003
has comment: http://stackoverflow.com/comment/83611874
favorite count: 0
answer count: 1
has title: NameError: name 'textSuface' is not defined
downvote count: 0
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48313015
type: Question
has answer: http://stackoverflow.com/a/48313015
type: AnsweredQuestion
has body: After the player rect has collided with the window width I am now getting an error suggesting that textSurface has not been defined even though it has been defined under def message_display(text): The help would be greatly appreciated. Here is my source code: https://pythonprogramming.net/displaying-text-pygame-screen/?completed=/adding-boundaries-pygame-video-game/ And here is the source video: https://www.youtube.com/watch?v=dX57H9qecCU&amp;index=5&amp;list=PLQVvvaa0QuDdLkP8MrOXLe_rKuf6r80KO Contrasting here is my code: # This just imports all the Pygame modules import pygame import time pygame.init() display_width = 800 display_height = 600 # This initates your colors black = (0,0,0) # You have 256 color options so you only use 255 because one of those is 0 white = (255,255,255) red = (255,0,0) plyrImg_width = 30 gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption('Bit Racer') clock = pygame.time.Clock() plyrImg = pygame.image.load('Sprite-01 double size.png') def player(x,y): gameDisplay.blit(plyrImg,(x,y)) def text_objects(text, font): textSurface = font.render(text, True, black) return textSuface, textSurface.get_rect() def message_display(text): largeText = pygame.font.Font('freesansbold.ttf',115) TextSurf, TextRect = text_objects(text, largeText) TextRect.center = ((display_width/2),(display_height/2)) gameDisplay.blit(TextSurf, TextRect) pygame.display.update() time.sleep(2) game_loop() def killed(): message_display('You Died') def game_loop(): x = (display_width * 0.45) y = (display_height * 0.8) x_change = 0 gameExit = False while not gameExit: # This handles any and all events in the game for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() print(event) if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 if event.key == pygame.K_RIGHT: x_change = 5 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0 x…
tagged with: python
tagged with: pygame

http://stackoverflow.com/comment/83535419
has text: I didn't write it down with speed in mind. But if we do, you'll want to use `pd.factorize(df.lid.values)` in `pir`
comment on: http://stackoverflow.com/a/48275799
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83359560
has text: The last query has 2 separate EXISTS subquery expressions, so you do get what it asks for, but you'd need to include both predicates in a single EXISTS expression, which Flask-Restless would not seem to support at the moment, at least on a glance.
comment on: http://stackoverflow.com/q/48187843
type: QuestionComment
score: 1
type: Comment

http://stackoverflow.com/a/48191338
has comment: http://stackoverflow.com/comment/83365611
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83363239
has comment: http://stackoverflow.com/comment/83364741
has comment: http://stackoverflow.com/comment/83390785
has comment: http://stackoverflow.com/comment/83363881
has comment: http://stackoverflow.com/comment/83365490
accepted answer of: http://stackoverflow.com/q/48191060
has comment: http://stackoverflow.com/comment/83364241
has comment: http://stackoverflow.com/comment/83363961
has comment: http://stackoverflow.com/comment/83368685
has comment: http://stackoverflow.com/comment/83365072
answers question: http://stackoverflow.com/q/48191060
has comment: http://stackoverflow.com/comment/83368360
type: Answer
has comment: http://stackoverflow.com/comment/83363715
has body: We can extend this solution to your 3D case, by leveraging np.lib.stride_tricks.as_strided based sliding-windowed views for efficient patch extraction, like so - from skimage.util.shape import view_as_windows def get_patches(data, locations, size): # Get 2D sliding windows for each element off data w = view_as_windows(data, (1,1,size,size)) # Use fancy/advanced indexing to select the required ones return w[np.arange(len(locations)), :, locations[:,0], locations[:,1]][:,:,0,0] We need those 1,1 as the window parameters to view_as_windows, because it expects the window to have the same number of elements as the number of dims of the input data. We are sliding along the last two axes of data, hence keeping the first two as 1s, basically doing no sliding along the first two axes of data. Sample runs for one-channel and more than channel data - In [78]: n, c, h, w = 3, 1, 4, 4 # number of channels = 1 ...: data = np.arange(n * c * h * w).reshape(n, c, h, w) ...: ...: size = 2 ...: locations = np.array([ ...: [0, 1], ...: [1, 1], ...: [0, 2] ...: ]) ...: ...: crops = np.stack([d[:, y:y+size, x:x+size] ...: for d, (y,x) in zip(data, locations)]) In [79]: print np.allclose(get_patches(data, locations, size), crops) True In [80]: n, c, h, w = 3, 5, 4, 4 # number of channels = 5 ...: data = np.arange(n * c * h * w).reshape(n, c, h, w) ...: ...: size = 2 ...: locations = np.array([ ...: [0, 1], ...: [1, 1], ...: [0, 2] ...: ]) ...: ...: crops = np.stack([d[:, y:y+size, x:x+size] ...: for d, (y,x) in zip(data, locations)]) In [81]: print np.allclose(get_patches(data, locations, size), crops) True Benchmarking Other approaches - # Original soln def stack(data, locations, size): crops = np.stack([d[:, y:y+size, x:x+size] for d, (y,x) in zip(data, locations)]) return crops # scholi's soln def allocate_assign(data, locations, size): n, c, h, w = data.shape crops = np.zeros((n,c,size,size)) for i, (y,x) in enumerate(locations): crops[i,0,:,:] = data[i,0,y:y+size,x:x+size] return cro…
has comment: http://stackoverflow.com/comment/83365254
has comment: http://stackoverflow.com/comment/83368947
has comment: http://stackoverflow.com/comment/83363781

http://stackoverflow.com/comment/83473451
score: 5
comment on: http://stackoverflow.com/q/48245292
has text: Please, provide an example that I can copy and paste into my terminal. Not this.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83408495
score: 0
has text: Are you certain the working directory is `/usr/local/bin/ProcessManager`? `with open("FBatch", "r") as f:` will try to open a file in the current working directory.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48212964

http://stackoverflow.com/q/48305158
tagged with: openpyxl
has title: How to set up the Graphical Properties of Chart Area using openpyxl
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83658432
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: charts
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49581915
linked to: http://stackoverflow.com/q/43329669
tagged with: python
has body: I would like to change the background color of Chart_area as well as remove all borders. Regarding the background color, I have tried the solution suggested: How to set Background Color of Plot Area of Chart using openpyxl but this solution doesn't work for any charts i.e. BarChart, AreaChart, LineChart, ScatterChart, RadarChart etc... I tried two openpyxl versions: 2.4.7, 2.4.9. without success. # setup the chart chart = LineChart() # test to remove border line ***************************************************** chart.graphical_properties = GraphicalProperties(ln=LineProperties(noFill=True)) chart.height = 9 chart.width = 13.4 props = GraphicalProperties(solidFill="f2f2f2") # setup and append the first series list_names = ['Fund', 'Market', 'Benchmark'] data = Reference(ws2, min_col=2, min_row=1, max_col=n + 1, max_row=p + 1) chart.x_axis.number_format = 'mmm yy' chart.x_axis.majorTimeUnit = "months" chart.add_data(data, titles_from_data=True) dates = Reference(ws2, min_col=1, min_row=2, max_col=1, max_row=1 + p) chart.set_categories(dates) # Style the lines chart.series[0].graphicalProperties.line.solidFill = "7E3F00" chart.series[1].graphicalProperties.line.solidFill = "45788C" chart.series[2].graphicalProperties.line.solidFill = "8BADD9" chart.plot_area.graphicalProperties = props # test to change background color ***************************************************** chart.graphical_properties = props ws1.add_chart(chart, "B14") I also tried to remove the borders of chart_area. I found this post: openpyxl - Ability to remove border from charts?. But I don't understand how do I handle to modify the library. I am a bit surprised that there is no simpler way. Many thanks in advance for your help.
has comment: http://stackoverflow.com/comment/83624398
linked to: http://stackoverflow.com/q/36988384
score: 2
upvote count: 2

http://stackoverflow.com/q/48235621
tagged with: jupyter
favorite count: 0
type: Question
has title: Jupyter Notebook: Change Data Rate Limit Inside Active Notebook
has comment: http://stackoverflow.com/comment/116235380
type: UnansweredQuestion
upvote count: 6
tagged with: python
has body: I have a jupyter notebook where an executed cell gives the following error: IOPub data rate exceeded... I understand this is an option: jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10 However, I would really prefer to just to set this along with my import statements and other notebook settings instead of tweaking configuration files or command line when starting notebooks. Is there an easy way to do this?
tagged with: ipython
downvote count: 0
has comment: http://stackoverflow.com/comment/116218449
has answer: http://stackoverflow.com/a/48239389
answer count: 1
score: 6

http://stackoverflow.com/comment/83560854
type: QuestionComment
comment on: http://stackoverflow.com/q/48287841
has text: Also, you mean `del dict1[key]` rather than `del dict[key]`.
score: 0
type: Comment

http://stackoverflow.com/comment/83586345
comment on: http://stackoverflow.com/q/48300891
type: QuestionComment
score: 0
has text: As @Dark mentioned...it depends !
type: Comment

http://stackoverflow.com/comment/83531706
type: QuestionComment
has text: Post your *actual* code. You need both Ball and Paddle classes. Methods must be indented.
comment on: http://stackoverflow.com/q/48273725
score: 0
type: Comment

http://stackoverflow.com/q/48175098
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/55771024
tagged with: python
tagged with: computer-vision
score: 4
tagged with: google-cloud-vision
answer count: 1
has body: I am new to python and cloud vision.I need to label ~20k images.My code although does the work, needs lots of time to process.Is there a way I can be more efficient?Any help will be really appreciated filename=[] description=[] score=[] for root, dirs, filenames in os.walk(indir): for f in filenames: if f.endswith('.jpg'): file_name=indir+'/'+f with io.open(file_name, 'rb') as image_file: content = image_file.read() image = types.Image(content=content) response = client.label_detection(image=image) labels = response.label_annotations for label in labels: filename.append(f) description.append(label.description) score.append(label.score) import pandas as pd vision_op = pd.DataFrame( {'filename': filename, 'description': description, 'score': score })
has comment: http://stackoverflow.com/comment/89682229
favorite count: 0
type: Question
upvote count: 4
has title: Google cloud vision batch process of large number of images using python

http://stackoverflow.com/comment/83362780
type: Comment
type: QuestionComment
has text: Show your code and the errors you got.
comment on: http://stackoverflow.com/q/48191218
score: 0

dictionary
tags question: http://stackoverflow.com/q/48243425
tags question: http://stackoverflow.com/q/48271646
tags question: http://stackoverflow.com/q/48218862
tags question: http://stackoverflow.com/q/48240820
tags question: http://stackoverflow.com/q/48305646
tags question: http://stackoverflow.com/q/48299199
tags question: http://stackoverflow.com/q/48253241
tags question: http://stackoverflow.com/q/48276015
tags question: http://stackoverflow.com/q/48198646
tags question: http://stackoverflow.com/q/48183810
tags question: http://stackoverflow.com/q/48197173
tags question: http://stackoverflow.com/q/48229422
tags question: http://stackoverflow.com/q/48215945
tags question: http://stackoverflow.com/q/48226273
tags question: http://stackoverflow.com/q/48274024
tags question: http://stackoverflow.com/q/48308059
tags question: http://stackoverflow.com/q/48242797
tags question: http://stackoverflow.com/q/48206785
tags question: http://stackoverflow.com/q/48294099
tags question: http://stackoverflow.com/q/48202334
tags question: http://stackoverflow.com/q/48252941
tags question: http://stackoverflow.com/q/48263875
tags question: http://stackoverflow.com/q/48302618
tags question: http://stackoverflow.com/q/48259680
tags question: http://stackoverflow.com/q/48273802
tags question: http://stackoverflow.com/q/48217991
tags question: http://stackoverflow.com/q/48210056
tags question: http://stackoverflow.com/q/48215649
tags question: http://stackoverflow.com/q/48205371
tags question: http://stackoverflow.com/q/48295547
tags question: http://stackoverflow.com/q/48203795
tags question: http://stackoverflow.com/q/48224019
tags question: http://stackoverflow.com/q/48235431
tags question: http://stackoverflow.com/q/48284976
tags question: http://stackoverflow.com/q/48173695
tags question: http://stackoverflow.com/q/48218271
tags question: http://stackoverflow.com/q/48235331
tags question: http://stackoverflow.com/q/48198413
tags question: http://stackoverflow.com/q/48246092
tags question: http://stackoverflow.com/q/48234473
tags question: http://stackoverflow.com/q/48182073
tags question: http://stackoverflow.com/q/48287289
tags question: http://stackoverflow.com/q/48181511
tags question: http://stackoverflow.com/q/48208044
tags question: http://stackoverflow.com/q/48209017
tags question: http://stackoverflow.com/q/48265827
tags question: http://stackoverflow.com/q/48205375
tags question: http://stackoverflow.com/q/48208343
tags question: http://stackoverflow.com/q/48276016
tags question: http://stackoverflow.com/q/48218864
tags question: http://stackoverflow.com/q/48281341
tags question: http://stackoverflow.com/q/48264692
tags question: http://stackoverflow.com/q/48289874
tags question: http://stackoverflow.com/q/48309747
tags question: http://stackoverflow.com/q/48329959
tags question: http://stackoverflow.com/q/48205315
tags question: http://stackoverflow.com/q/48240139
tags question: http://stackoverflow.com/q/48193502
tags question: http://stackoverflow.com/q/48329257
tags question: http://stackoverflow.com/q/48221317
tags question: http://stackoverflow.com/q/48242541
tags question: http://stackoverflow.com/q/48245882
tags question: http://stackoverflow.com/q/48197549
tags question: http://stackoverflow.com/q/48253582
tags question: http://stackoverflow.com/q/48325433
tags question: http://stackoverflow.com/q/48252914
type: Tag
tags question: http://stackoverflow.com/q/48201152
tags question: http://stackoverflow.com/q/48252855
tags question: http://stackoverflow.com/q/48205032
tags question: http://stackoverflow.com/q/48256911
tags question: http://stackoverflow.com/q/48242272
tags question: http://stackoverflow.com/q/48201530
tags question: http://stackoverflow.com/q/48189750
tags question: http://stackoverflow.com/q/48193440
tags question: http://stackoverflow.com/q/48194793
tags question: http://stackoverflow.com/q/48290057
tags question: http://stackoverflow.com/q/48254918
tags question: http://stackoverflow.com/q/48243569
tags question: http://stackoverflow.com/q/48280793

http://stackoverflow.com/comment/83901196
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48280537
score: 0
has text: :) I see. I thought I needed to convert the pivot table to data frame first before I could use the code from last line. I didn't realize pivot table was already a data frame. I tried the code on my table and it worked perfectly! Was exactly what i was trying to do without having to calculate totals outside the table since I already had them in the table. So, then do I understand correctly that I can use df.iloc[x, y] to locate any value in the table? And can I reference the values by by row/column names instead of indexes?

http://stackoverflow.com/comment/83346899
score: 1
type: QuestionComment
type: Comment
has text: What exactly is `rw`? Is it a dataframe? Please give the *minimum* code so that someone could run it and produce your same error.
comment on: http://stackoverflow.com/q/48183174

http://stackoverflow.com/a/50280264
answers question: http://stackoverflow.com/q/48230706
has body: Hmm my config looks different. Just remove this file and it will default to making a token $ cat ~/.jupyter/jupyter_notebook_config.json { "NotebookApp": { "password": "sha1:d0a89f391169:9ca771c3518f845438693b938b39703ce1104eaf" }
downvote count: 0
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48230706
score: 34
upvote count: 34

http://stackoverflow.com/a/49880788
score: 7
downvote count: 0
upvote count: 7
has body: The problem is that importing a module acquires a lock (which lock depends on your python version), see the docs for imp.lock_held. Locks are shared over multiprocessing so your deadlock occurs because your main process, while it is importing your module, loads and waits for a subprocess which attempts to import your module, but can't acquire the lock to import it because it is currently being imported by your main process. In step form: Main process acquires lock to import myfile.py Main process starts importing myfile.py (it has to import myfile.py because that is where your job() function is defined, which is why it didn't deadlock for print()). Main process starts and blocks on subprocess. Subprocess tries to acquire lock to import myfile.py => Deadlock.
type: Answer
answers question: http://stackoverflow.com/q/48218897

http://stackoverflow.com/q/48231910
tagged with: python
has body: I was hoping some heavy Jupyter and bokeh users might have a workaround for this. So I have a bunch of bokeh plots in my Jupyter notebook and I want to export the notebook to pdf. In the Jupyter Notebook file menu there is an option to download a notebook as a pdf. Also--and my preferred route--is to use nbconvert. The problem is that the bokeh plots are not exported into the final pdf file. Bokeh does not export its plots to a format that is caught by Latex to compile the pdf. In constrast, a package like matplotlib will generate png files for each plot, and then those plots are linked in the latex to generate the pdf. Right now when I export the notebook, all of the text comes out in the pdf but none of the plots come through. The plots come in if I export to an html file--but of course the plots spill off the page if I try and print the document. Has anyone found a decent workaround for this? The users I work with still want to be able to print out documents and mark them up.
type: AnsweredQuestion
tagged with: bokeh
has title: Jupyter and Bokeh: workaround for exporting bokeh plots when exporting Jupyter notebook to pdf
tagged with: jupyter-notebook
favorite count: 0
type: Question
upvote count: 2
score: 2
tagged with: nbconvert
has answer: http://stackoverflow.com/a/48235975
accepted answer: http://stackoverflow.com/a/48235975
downvote count: 0
answer count: 1

http://stackoverflow.com/q/48202410
score: 0
has answer: http://stackoverflow.com/a/48203724
accepted answer: http://stackoverflow.com/a/48203724
answer count: 1
has comment: http://stackoverflow.com/comment/83387757
has comment: http://stackoverflow.com/comment/83386577
tagged with: scikit-learn
has title: Confusion in sklearn Logistic Regression
has comment: http://stackoverflow.com/comment/83387298
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/83388620
has body: I was reading the documentation for Logistic Regression and ran into a confusion. In particular, I'm am confused between the usage of fit_intercept and intercept_scaling fit_intercept : bool, default: True Specifies if a constant (a.k.a. bias or intercept) should be added to the decision function. intercept_scaling : float, default 1. Useful only when the solver liblinear is used and self.fit_intercept is set to True. In this case, x becomes [x, self.intercept_scaling], i.e. a "synthetic" feature with constant value equal to intercept_scaling is appended to the instance vector. 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. From what I understand intercept acts as a dummy feature for the dataset as it is added to output each time a prediction is made. In the paragraph under intercept_scaling, it is mentioned that- a "synthetic" feature with constant value equal to intercept_scaling is appended to the instance vector But aren't these two the same thing? That's my primary question and confusion. Lastly, the documentation mentions that this is useful only when I am using liblinear as the solver. If these two indeed are the same and I keep fit_intercept as True, what happens then?
has comment: http://stackoverflow.com/comment/83387721
type: AnsweredQuestion

http://stackoverflow.com/comment/83600260
type: Comment
has text: @kingforever: put the code to color every button wherever you want. Call that code inside `onDrag`. It's as simple as that.
comment on: http://stackoverflow.com/a/48304414
type: AnswerComment
score: 0

http://stackoverflow.com/q/48183771
has comment: http://stackoverflow.com/comment/83348321
has body: With respect to this question and this answer , I've some more queries with some detailed information. So here I'm updating my question Now data is like this; [OrderedDict([('caseId', 20), ('userId', 1), ('userName', 'user1'), ('emailStatus', 21), ('emailBody' , 'body')]), OrderedDict([('caseId', 20), ('userId', 1), ('userName', 'user1'), ('emailStatus', 20), ('emailBody' , 'body')]), OrderedDict([('caseId', 18), ('userId', 4), ('userName', 'user4'), ('emailStatus', 21), ('emailBody' , 'body')]), OrderedDict([('caseId', 19), ('userId', 3), ('userName', 'user3'), ('emailStatus', 21), ('emailBody' , 'body')]), OrderedDict([('caseId', 18), ('userId', 1), ('userName', 'user1'), ('emailStatus', 20), ('emailBody' , 'body')]), OrderedDict([('caseId', 20), ('userId', 3), ('userName', 'user3'), ('emailStatus', 21), ('emailBody' , 'body')]), OrderedDict([('caseId', 18), ('userId', 4), ('userName', 'user4'), ('emailStatus', 20), ('emailBody' , 'body')]), OrderedDict([('caseId', 19), ('userId', 1), ('userName', 'user1'), ('emailStatus', 20), ('emailBody' , 'body')])] I want to get a list of nested lists, something like this; [{ "caseId": "20", "users": [ { "userId": "1", "userName" : "user1", "emailStatus": [ { "emailStatus" : "20", "emailBody" : "body" }, { "emailStatus" : "21", "emailBody" : "body" } ] }, { "userId": "3", "userName" : "user3", "emailStatus": [ { "emailStatus" : "21", "emailBody" : "body" } ] } ] }, { "caseId": "19", "users": [ { "userId": "1", "userName" : "user1", "emailStatus": [ { "emailStatus" : "20", "emailBody" : "body" } ] }, { "userId": "3", "userName" : "user3", "emailStatus": [ { "emailStatus" : "21", "emailBody" : "body" } ] } ] }, { "caseId": "18", "users": [ { "userId": "1", "userName" : "user1", "emailStatus": [ { "emailStatus" : "20", "emailBody" : "body" } ] }, { "userId": "4", "emailStatus": [ { "emailStatus" : "20", "emailBody" : "body" }, { "emailStatus" : "21", "emailBody" : "body" } ] } ] } ] presenting a nested list like this; I tried do…
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/83347280
linked to: http://stackoverflow.com/q/48166852
has title: Convert list of ordered dict to nested lists with multiple values
score: 1
accepted answer: http://stackoverflow.com/a/48183967
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48183967
favorite count: 0
type: Question

http://stackoverflow.com/comment/83595434
comment on: http://stackoverflow.com/q/48303858
has text: @MrName Oops, sorry about that. It throws `RuntimeError: super(): no arguments`. I've added the traceback to the question.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83640191
type: Comment
comment on: http://stackoverflow.com/q/48327085
type: QuestionComment
has text: I think the numpy version may be it. I have been updating packages since I posted this question, and the error has gone away.
score: 0

http://stackoverflow.com/comment/83503765
type: QuestionComment
comment on: http://stackoverflow.com/q/48260418
has text: The size of `values` should either be equal to size of `uniqueMonth`(when both are one dimensional) or the size of `values` needs to be k times the size of 1d `uniqueMonth`, with each column representating a set dataset
score: 1
type: Comment

http://stackoverflow.com/q/48239842
has comment: http://stackoverflow.com/comment/83476117
duplicate of: http://stackoverflow.com/q/8505375
answer count: 1
tagged with: selenium
has body: I use selenium to parse a html, but have trouble getting only the parent text. The html snippet looks like: Who Mario I get the element with div.find_element_by_xpath('p/span[contains(text/(), "Who")]../').text.strip() But this returns all text ("Who Mario") inside the p tag. How can i only retrieve the parent text (Mario) without .replace(), etc?
linked to: http://stackoverflow.com/q/45303767
type: Question
has title: selenium - get parent text using selenium
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83462690
tagged with: xpath
linked to: http://stackoverflow.com/q/8505375
has answer: http://stackoverflow.com/a/48239907
type: UnansweredQuestion

http://stackoverflow.com/q/48233179
tagged with: python
has answer: http://stackoverflow.com/a/48239144
linked to: http://stackoverflow.com/q/17245123
linked to: http://stackoverflow.com/q/46724680
has title: Convert adjective to adverb
has comment: http://stackoverflow.com/comment/83497187
upvote count: 5
linked to: http://stackoverflow.com/q/14489309
has body: Does anyone know how to convert an english adjective to its respective adverb? Python would be ideal, but really any programmatic approach would be great. I've tried pattern.en, nltk wordnet, and spacy to no avail. Converting adverbs to their root adjective form is no problem. I'm using the SO solution here. What I want is to go the other way. From adjective to adverb. Here is nltk wordnet code that kind of converts words between different word forms, but fails for adjective &lt;--> adverb conversions. Specifically, I'd like a function getAdverb like this: getAdverb('quick') &gt;&gt;&gt; quickly getAdverb('noteable') &gt;&gt;&gt; notably getAdverb('happy') &gt;&gt;&gt; happily Any code, resources, or suggestions would be greatly appreciated!
tagged with: wordnet
tagged with: nlp
favorite count: 0
type: Question
score: 5
tagged with: spacy
tagged with: nltk
type: UnansweredQuestion
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/83631510
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48322679
has text: If this is a problem on Ubuntu, the proper way is a program called `alternatives`, which is a soft-link manager that keeps track of versioning options of a set of softwares. I use it all the time in `source activate XX` scripts. Not sure if there is similar tool for Windows.
score: 0

http://stackoverflow.com/comment/83462591
has text: This lacks detail and I have no idea how that would make it detectable. I may be close to a solution and will update when and if it works.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48232527

http://stackoverflow.com/comment/83368608
comment on: http://stackoverflow.com/a/48193445
type: AnswerComment
has text: @iam.Carrot Try sorting `A` first. I've made the edit above.
score: 0
type: Comment

http://stackoverflow.com/comment/83518769
type: Comment
comment on: http://stackoverflow.com/q/48267100
score: 0
type: QuestionComment
has text: The database class is imported to 'Loading_UI' and then instantiated there. It's an object that contains information from the csv files. The actual code is not relevant here, since I only want to pass the object on to the main class. It may as well be e.g. a variable that is passed on.

http://stackoverflow.com/q/48297768
has body: I am django newbie and working on a math based project. I need to save texts involving mathematical symbols like integral, sigma, product etc. At the same time, I also need to emphasize or bold some texts (and do all kinds of rich text editing) and include figures that explains a mathematical concept. At present, I am just saving all the fields in a CharField (with dummy texts and without including any mathematical symbol) and have no idea how to include such a field. If you have any idea/hint or you have worked on similar projects, please help.
tagged with: python
has answer: http://stackoverflow.com/a/48329350
has comment: http://stackoverflow.com/comment/83680683
has comment: http://stackoverflow.com/comment/88791646
upvote count: 2
has comment: http://stackoverflow.com/comment/83627575
has comment: http://stackoverflow.com/comment/88792359
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/116054
tagged with: django
favorite count: 0
type: Question
has title: Django How to Integrate a Maths Editor
has comment: http://stackoverflow.com/comment/88791850
type: UnansweredQuestion
score: 1
tagged with: math

http://stackoverflow.com/q/48245453
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48245964
tagged with: django-views
answer count: 3
has body: I'm trying to get all attributes of a single object. I keep getting a "Devices matching query does not exist." I just cannot figure out my issue. Models.py `class Devices(models.Model): category_id = models.ForeignKey(Category, on_delete=models.CASCADE) device_description = models.CharField(max_length=100) device_status = models.CharField(max_length=50) device_date = models.DateTimeField() device_user = models.CharField(max_length=50)` Views.py def view_status(request, pk=None): device = Devices.objects.get(pk=pk) return render(request, 'homesite/device_status.html', device) urls.py url(r'^viewstatus/$', views.view_status, name='ViewStatus'), here is the url I use to call http://localhost:8000/homesite/viewstatus/?pk=1 device_satus.html {% extends "base.html" %} {% block head %} Device Status {% endblock%} {% block body %} Device Status Detail {{ devices.device_description }} {{ devices.device_status }} {% endblock %} There are 4 records in my able so I know there is a match for PK=1.
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48245528
upvote count: 2
has answer: http://stackoverflow.com/a/48245528
has answer: http://stackoverflow.com/a/48245964
has answer: http://stackoverflow.com/a/48246146
tagged with: django
tagged with: python
has title: Django objects.get matching query does not exist
score: 2

http://stackoverflow.com/a/48327074
answers question: http://stackoverflow.com/q/48326983
has comment: http://stackoverflow.com/comment/83639716
type: Answer
score: 0
has body: {} is a placeholder, and becomes the value of i because of the .format() call. &gt;&gt;&gt; print 'My name is {}'.format('Steve') My name is Steve [0] means "the first item in this list", i.e. html.xpath(...) returns more than one value, and we only want the first one. &gt;&gt;&gt; mylist = [ 'Apples', 'Oranges', 'Bananas' ] &gt;&gt;&gt; print mylist[0] Apples
has comment: http://stackoverflow.com/comment/83639872

http://stackoverflow.com/comment/83650810
type: QuestionComment
comment on: http://stackoverflow.com/q/48329849
score: 0
has text: But for Random Forest classifier , python 2.7 gives me an error (similar to the error I posted) .. However , I tried to use python 3.5 , it did not give me an error , it worked well without changing anything in the param_grid!
type: Comment

http://stackoverflow.com/a/48205063
type: Answer
answers question: http://stackoverflow.com/q/48204924
downvote count: 0
has body: Yeah you can remove duplicate data by pandas simple function. df.drop_duplicates() You can refer documentation here. For removing particular column redundant data you can pass column name as a parameter "subset". It will remove whole row for duplicate data.
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48204924
score: 1

http://stackoverflow.com/comment/83570695
type: QuestionComment
has text: ＠ekhumoro I am in ubuntu16.04
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48279901

http://stackoverflow.com/a/48346103
score: 0
accepted answer of: http://stackoverflow.com/q/48306462
type: AcceptedAnswer
has body: So, this is by no means a perfect solution (and gets terrible performance on my machine) but here you go: from tkinter import * text = [['A','B','C','D'],['E','F','G','H'],['I','J','K','L'],['M', 'N', 'O', 'P'],['Q','R','S','T'],['U','V','W','X'],['Y','Z','1','2'],['3','4','5','6']] root = Tk() for c, i in enumerate(text): Grid.rowconfigure(root, c, weight=1) for a, b in enumerate(i): Label(root, text=b, font=('', 10)).grid(row=c, column=a) Grid.columnconfigure(root, a, weight=1) class Resize: def __init__(self, root): self.root = root self.root.update() self.startsize = (root.winfo_width(),root.winfo_height()) self.root.bind("&lt;Configure&gt;", self.on_resize) def on_resize(self, event): for i in self.root.winfo_children(): i.config(font=('', int(10*((((self.root.winfo_width() * root.winfo_height()) - (self.startsize[0] * self.startsize[1]))/(self.startsize[0] * self.startsize[1]))+1)))) Resize(root) root.mainloop() To answer your queries: Centering the label's text inside each grid cell Widgets default to the centre of the grid "cell", what I'm assuming you mean is having them evenly spread out over the window. This is accomplished using the commands: Grid.rowconfigure(root, c, weight=1) and Grid.columnconfigure(root, a, weight=1) Here, we are giving every grid column and row an equal weight of 1. Meaning that every column will share any extra x-axis space that the window gains and every row will share any extra y-axis space that the window gains. Which means that every "cell" shares space with the other children of the window equally, so they're spread out evenly. Automatically resizing the label's text size to fill the entire cell In order to achieve this, we need to calculate the size increase of the window compared to its original size. So we use this long equation: ((((self.root.winfo_width() * root.winfo_height()) - (self.startsize[0] * self.startsize[1]))/(self.startsize[0] * self.startsize[1]))+1) To make this more readable it's the same as the below: (((…
answers question: http://stackoverflow.com/q/48306462
type: Answer

http://stackoverflow.com/comment/83566083
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48288763
has text: Better read [40 things programmers believe about names](https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/) (spoiler: all are false).
score: 0

http://stackoverflow.com/q/48292070
has answer: http://stackoverflow.com/a/50230998
linked to: http://stackoverflow.com/q/12661253
favorite count: 0
type: Question
has body: I am just wondering if it's possible to bulk save queries in django. for example, usually I would have to loop through each object for obj in queryset: if condition: obj.field = True obj.save() EDIT: I know the above case can be handled with the update method. However, the sample above is saving all the fields with the same value. What if there are different conditions? for obj in queryset: if condition: obj.field = True obj.save() else: obj.field = False obj.save() The above might not be the best sample I can think of at the moment but something similar I would say. would there be a faster way to do this? Thanks in advance for any advices
upvote count: 2
has title: Best way to bulk update query with dynamic values conditionally in Django
possible better answer: http://stackoverflow.com/a/50230998
has comment: http://stackoverflow.com/comment/83570106
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83569621
accepted answer: http://stackoverflow.com/a/48292216
has answer: http://stackoverflow.com/a/77044803
score: 2
has answer: http://stackoverflow.com/a/48292216
type: AnsweredQuestion
tagged with: django-queryset
answer count: 3
tagged with: save
downvote count: 0

http://stackoverflow.com/comment/83565199
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48289110
has text: @VanessaS. Oh, are you using python 2?
type: Comment

http://stackoverflow.com/comment/83447799
type: Comment
has text: Yes, I myself got it working. Thank you! I used PhantomJS because i wanted it to work in the background.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48232588

build
tag name: build
type: Tag
tags question: http://stackoverflow.com/q/48288839
tags question: http://stackoverflow.com/q/48189689

http://stackoverflow.com/q/48214760
tagged with: python
tagged with: plot
accepted answer: http://stackoverflow.com/a/48214976
has comment: http://stackoverflow.com/comment/83412965
has comment: http://stackoverflow.com/comment/83411849
has answer: http://stackoverflow.com/a/48214976
tagged with: pandas
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83415019
has comment: http://stackoverflow.com/comment/83415403
has comment: http://stackoverflow.com/comment/83411700
answer count: 1
has title: Groupby Pandas dataframe and plot
type: Question
has body: I have a Pandas dataframe and wish to plot from a specific column by group. The goal is to have a separate graph for each org (like the image below). Example plot What is the most efficient way to accomplish this? Source excerpt: date time1 time2 time3 org 2017-11-16 02:14:20 36.46 20.42 16.04 abc 2017-11-21 08:39:15 40.12 10.18 29.94 abc 2017-11-06 08:21:08 33.00 0.00 33.00 bcd 2017-10-30 14:29:03 47.50 10.33 37.17 bcd 2017-11-09 07:51:48 31.92 1.92 30.00 efg 2017-11-07 08:53:05 33.00 1.04 31.96 efg Attempted Code: # load data df = pd.read_csv('Dataset.csv') # identify unique values in org col org_group = sorted(df['org'].unique()) # set date as index for plot df = df.set_index('date') df.head() for i in range(len(org_group)): # select specific org value from df df_group = df[df.org == org_group[i]] # display plot df_plot = df_group.resample('W').agg('median').plot(title="Median Times for "+org_group[i]) plt.show() # iterate i = i+1
has comment: http://stackoverflow.com/comment/83415081

http://stackoverflow.com/a/48256695
has body: Have your regex start with \A and end with \Z. This will make sure that the match begins at the start of the input string, and also make sure that the match ends at the end of the input string. So for the example you gave, it would look like: pattern = re.compile(r'\A\d+\Z')
upvote count: 2
answers question: http://stackoverflow.com/q/48256678
type: Answer
accepted answer of: http://stackoverflow.com/q/48256678
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48183104
has comment: http://stackoverflow.com/comment/83346764
tagged with: python
tagged with: ubuntu
tagged with: gtk
tagged with: python-2.7
answer count: 2
has title: ImportError: No module named gtk
downvote count: 0
has comment: http://stackoverflow.com/comment/83346177
has comment: http://stackoverflow.com/comment/83345748
has answer: http://stackoverflow.com/a/77126457
has comment: http://stackoverflow.com/comment/83366016
has comment: http://stackoverflow.com/comment/83345892
favorite count: 0
type: Question
score: 5
has body: I have a PC running Ubuntu 17.10. I want to runn a python script that uses gtk. HoweverI get the following error: Traceback (most recent call last): File "/usr/local/bin/selectvm.py", line 3, in &lt;module&gt; import gtk ImportError: No module named gtk I have tried already many things like: sudo apt install python-gtk2 sudo apt install python-gtk2-dev but none of them works. APT says they are already installed.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/55014839
upvote count: 5

http://stackoverflow.com/comment/83559191
has text: @user929304, It works because both `std::vector` and `std::array` use contiguous data. In theory, it's undefined behavior.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48285968

http://stackoverflow.com/q/48315369
has comment: http://stackoverflow.com/comment/83616409
has answer: http://stackoverflow.com/a/48396909
has answer: http://stackoverflow.com/a/48315596
has comment: http://stackoverflow.com/comment/83616292
answer count: 4
type: Question
has comment: http://stackoverflow.com/comment/83616322
upvote count: 0
has body: #TASK ONE # LISTS # import sys import time cows = [] val = [] num4 = 0 literd = [] test1 = [] val1 = [] day = [] end = [] num2 = [] days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] daya = ["1234567"] # COW ID VALIDATION # h = int(input("How many cows do you have? ")) for x in range(h): Id = int(input("Enter the 3 digit code of your cows: ")) if len(str(Id)) != 3: print("Sorry, the code ID can only be 3 digit numbers!") sys.exit() elif Id in cows: print("The cow ID is already in!") sys.exit() else: cows.append(Id) ################### # NUMBER OF COW LITERS # print(" ") dayz = list(days) cowz = list(cows) print(" ") print("In reality a cow can get milked 25 liters a day, beware!") for day in days: print("Day: ", dayz[0]) cowz = list(cows) dayz.pop(0) for cow in cows: print("Cow: ", cow) test1.append(float(input("How many liters did you milk the cow at AM? "))) test1.append(float(input("How many liters did you milk the cow at PM? "))) val = list(test1) ######################## #ROUNDING NUMBERS AND ADDING THE LITTERS OF COW MILKED# val = [ round(elem, 1) for elem in test1 ] kek = list() total = sum(map(len, daya)) * h for x in range(total): num1 = val[0] + val[1] num2.append(num1) kek.append(num1) for x in range(2): val.pop(0) num3 = list(num2) ######################################################## # PRINTS OUT THE RESULTS # print(" ") print("A table will print out in just a second showing the results.") cowz = list(cows) print(" ") for day in days: print("Day: ", day) for cow in cows: print("Cow: ", cow, end = " ") print("liters: ", num2[0]) num2.pop(0) ######################################################## cow1 = list() #TASK TWO # PRINTING OUT THE TOTAL LITERS OF MILK THIS WEEK# weekly = list() num5 = len(num3) for x in range(num5): num4 += num3[0] num3.pop(0) print("Total liters of milk this week", num4) ################################################# # ADDING ALL THE LITERS FOR EACH COW # for day in days: cowz = list(cows…
score: -7
downvote count: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/83616217
type: AnsweredQuestion
has title: My index in my code doesn't work
has answer: http://stackoverflow.com/a/48372579
accepted answer: http://stackoverflow.com/a/48396909
has answer: http://stackoverflow.com/a/48315854
possible better answer: http://stackoverflow.com/a/48315596
has comment: http://stackoverflow.com/comment/83617181
tagged with: python

http://stackoverflow.com/q/48244160
linked to: http://stackoverflow.com/q/8282553
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/678236
tagged with: python
has body: I got lost when trying to get a list of files but without their extension. I am getting the a list of files in this specific directory using: files = os.listdir("C:/Users/sp500/") All files are with ".csv" extension which I would like to remove (I need the list of tickers only). Using strip as suggested here and here (I am getting this error: TypeError: expected str, bytes or os.PathLike object, not list) doesn't help nor other remove function etc. I will appreciate your help very much!
score: 0
duplicate of: http://stackoverflow.com/q/678236
answer count: 0
has title: How to create a list of files without their extensions in python 3
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83470950
has comment: http://stackoverflow.com/comment/83470841

http://stackoverflow.com/q/48265877
type: AnsweredQuestion
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48266482
possible better answer: http://stackoverflow.com/a/48266477
has body: I'm building a Netflix like website for my Devops course. I made a Python list of dictionaries (Mockfilms) to define my films, and want to populate a database (Ratings) with reviews in preparation for sending data in the format :filmid: :userid: :rating: to a recommendation engine. My index page is a list of film images with a link to a review form under each one. I want each review form to appear on a different url (/review/ID where ID is saved in mockfilms as oid). In order to do this I want to access mockfilms.oid, then pass it to the view function to make the url for the form. Once the form is complete I then want to add this ID to the Ratings database. Here is what I have so far: Index: {% extends "base.html" %} {% block content %} Hello, {{ current_user.username }}! Welcome to our extensive video library: {% for film in mockfilms %} {% set ID = film.oid %} ">Leave a review here! {% endfor %} {% endblock %} Route: @app.route('/review/<ID>', methods = ['GET', 'POST']) @login_required def review(ID): form = ReviewForm() if form.validate_on_submit(): review = Ratings(User_id = current_user.id, Score_given = form.score.data, Film_id = ID) db.session.add(review) db.session.commit() flash('Thanks for your review') return redirect(url_for('index')) return render_template('review.html', title='Review Page', form=form) The following error is what I get when I run it: File "/home/jc/Desktop/Lokal/DevopsAssig/microblog/Kilfinnan/lib/python3.5/site-packages/werkzeug/routing.py", line 1768, in build raise BuildError(endpoint, values, method, self) werkzeug.routing.BuildError: Could not build url for endpoint 'review'. Did you forget to specify values ['ID']? From this I assume that the issue is with the ID variable within this template. My searchings and learnings led me to believe that {% set %} in the index template would let me declare the ID variable and then use it in the dynamic.
tagged with: flask
tagged with: jinja2
favorite count: 0
has answer: http://stackoverflow.com/a/48266477
type: Question
tagged with: werkzeug
has comment: http://stackoverflow.com/comment/83537645
linked to: http://stackoverflow.com/q/7478366
tagged with: python
accepted answer: http://stackoverflow.com/a/48266482
has title: How to access variables within html template url_for

http://stackoverflow.com/comment/83571838
type: QuestionComment
has text: so since i my pc has Python 3, this shouldn't be an issue? also would it affect attempts to decrypt the info?
comment on: http://stackoverflow.com/q/48293161
score: 0
type: Comment

http://stackoverflow.com/comment/83336386
type: Comment
has text: @DavidZ The question asks how do you import some function of a class and have its use available in another file. The question I linked with the accepted answer points to that it's not possible to link attributes of a class, being the methods. Can you please explain what's different; I'm not sure if I get your difference?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48178011

http://stackoverflow.com/comment/83565360
score: 1
comment on: http://stackoverflow.com/q/48272061
type: QuestionComment
type: Comment
has text: Make sure you have the appropriate VS Redistributable installed - see the Instant Client download page for which one to use for each Instant Client version.

http://stackoverflow.com/comment/127145087
comment on: http://stackoverflow.com/a/71953241
score: 1
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

http://stackoverflow.com/comment/92257298
type: Comment
has text: Hi, Have you read the documentation of `tf.estimator.train_and_evaluate`? All indeces should start from zero. So the chief obviously has `"index":0` and the workers also start with index 0. However, keep in mind that the chief is also a worker. So if you have one chief, and two workers you got three workers in total. This is especially important for your input pipeline. If you use https://www.tensorflow.org/api_docs/python/tf/data/Dataset#shard then you have to increase all worker indeces (not the chief index) by 1. Otherwise, the chief worker and the first normal worker use the same data.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48205733

http://stackoverflow.com/comment/83628420
type: AnswerComment
comment on: http://stackoverflow.com/a/48321412
score: 0
type: Comment
has text: I did set `self.component` using `=` earlier and the component instance stored should be the same as the one in the event. As shown in the code snippets, calling `id` on both objects returns the same value isn't that what `is` does as well?

http://stackoverflow.com/q/48279081
tagged with: opencv
has title: Moment of image into center of blank image (Python, OpenCV)
type: Question
has body: This is my problem. I try to copy this image (20x20): into a new one created by code (28x28 blank canvas) with precise position. What I am trying to do is to set the violet point of source image centered into a new (canvas) image. This is my code to do it: import cv2 import numpy as np import os # Read images : src image will be cloned into dst im = cv2.imread(os.path.expanduser('~\\Desktop\\cube.png')) obj = cv2.imread(os.path.expanduser('~\\Desktop\\testCV.png')) # Create an all white mask mask = 255 * np.ones(obj.shape, obj.dtype) # The location of the center of the src in the dst center = (int(10), int(13)) # Seamlessly clone src into dst and put the results in output normal_clone = cv2.seamlessClone(obj, im, mask, center, cv2.NORMAL_CLONE) # Write results cv2.imwrite(os.path.expanduser('~\\Desktop\\fin.png'), normal_clone) and this is the output : How do you see is not perfect there is some white in the right part and cause me some problems, i know the problem is the "mask", i try to modify it, but when i change 1 thing the code doesn't work. Do you know other ways to do the same think or maybe i only need to modify this. Desired output should be like this example , centered according the reequest. Thanks
linked to: http://stackoverflow.com/q/48280828
tagged with: python
has comment: http://stackoverflow.com/comment/83542941
possible better answer: http://stackoverflow.com/a/48281657
has comment: http://stackoverflow.com/comment/83543254
has answer: http://stackoverflow.com/a/48281657
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48702838
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48702838
score: 1
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/83625658
comment on: http://stackoverflow.com/q/48265555
type: Comment
type: QuestionComment
score: 0
has text: do you know the difference between combine_first, fillna and update ?

http://stackoverflow.com/a/48290569
has body: While you can use the admin panel for all users, I don't recommend it. Security is tight, but not very flexible. Also, dedicated pages developed for your user functions can be better suited for the job from both the design and functionality standpoints. Take the time to develop quality pages for your users. You won't regret it.
has comment: http://stackoverflow.com/comment/83567281
downvote count: 0
score: 5
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/48289834
has comment: http://stackoverflow.com/comment/83567358

http://stackoverflow.com/a/48280450
has body: Here is the more or less canonical argsort solution: import numpy as np def f_argsort(A): idx = np.argsort(A) As = A[idx] ne_ = np.r_[True, As[:-1] != As[1:], True] bnds = np.flatnonzero(ne_) valid = np.diff(bnds) != 1 return [idx[bnds[i]:bnds[i+1]] for i in np.flatnonzero(valid)] n = 30000 A = np.random.randint(0, 1000, n) groups = f_argsort(A) for grp in groups: print(len(grp), set(A[grp]), end=' ') print()
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/48279206
downvote count: 0
has comment: http://stackoverflow.com/comment/83568473
has comment: http://stackoverflow.com/comment/83568624

http://stackoverflow.com/q/48198974
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83422354
tagged with: sys
has body: I am getting an error where it says: no such file or directory exists` The file is in the same directory where I keep my code is. Here is my code: from sys import argv script, filename=argv txt=open(filename) print(f"So the name of the file is {filename}.") print(txt.read()) Output:on cmd E:\python codes\ python file1.py test.txt Traceback (most recent call last): File"file1.py", line 4, in &lt;modeule&gt; txt=open(filename) FileNotFoundError:: [Erno 2]No such file or directory: 'test.txt'
upvote count: 1
has comment: http://stackoverflow.com/comment/83423715
downvote count: 1
has comment: http://stackoverflow.com/comment/83421767
has comment: http://stackoverflow.com/comment/83382403
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83401559
score: 0
has comment: http://stackoverflow.com/comment/83458887
has title: How to open a files specified by sys.argv in Python3?
has comment: http://stackoverflow.com/comment/83458969
has comment: http://stackoverflow.com/comment/83379816
tagged with: python
has comment: http://stackoverflow.com/comment/83379778
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/83434369
has comment: http://stackoverflow.com/comment/83434282

http://stackoverflow.com/comment/83351986
has text: Unrelated note: if you have an array with multiple dimensions and you just want to index the first or the last, you can use an ellipsis for better readability for the non-index axes; e.g. `sics[1::3,:,:]=sicm[0][1:,:,:]` could be `sics[1:3, ...] = sicm[0][1:, ...]`
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48185749
type: QuestionComment

http://stackoverflow.com/comment/83455116
has text: You may want to see this: https://stackoverflow.com/questions/40050438/how-to-move-multiple-turtles-at-the-same-time-in-python
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48236081

http://stackoverflow.com/a/48185266
has body: I find another solution to your problem and it works! I used directly matplotlib library instead of using plot attribute of the data frame : here is the code : import pandas as pd import matplotlib.pyplot as plt %matplotlib inline # for jupyter notebook pers1 = ["Jesús","lord",2] pers2 = ["Mateo","apostel",1] pers3 = ["Lucas","apostel",1] dfnames = pd.DataFrame([pers1,pers2, pers3], columns=["name","type","importance"]) fig, ax = plt.subplots() bars = ax.bar(dfnames.name, dfnames.importance) colors = {'apostel':'blue','lord':'green'} for index, bar in enumerate(bars) : color = colors.get(dfnames.loc[index]['type'],'b') # get the color key in your df bar.set_facecolor(color[0]) plt.show() And here is the results :
type: Answer
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48184332
score: 2

http://stackoverflow.com/comment/83530257
type: Comment
comment on: http://stackoverflow.com/q/48273222
type: QuestionComment
has text: would that not accept "ab", "bc", "Ab", "aB", "bC", and "Bc" as well as the wanted single letters? @StephenRauch
score: 0

http://stackoverflow.com/comment/83534122
has text: I don't get that, I get the exact same error as before.
score: 0
comment on: http://stackoverflow.com/a/48275291
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83369647
type: QuestionComment
comment on: http://stackoverflow.com/q/48194362
has text: f-strings might make your string building more readable: https://www.python.org/dev/peps/pep-0498/
score: 0
type: Comment

http://stackoverflow.com/comment/83600478
type: QuestionComment
comment on: http://stackoverflow.com/q/48307531
score: 1
has text: Please read why a [**`screenshot of HTML or code or error is a bad idea`**](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors). Consider updating the Question with formatted text based HTML and code trials.
type: Comment

http://stackoverflow.com/q/48206383
upvote count: 2
type: UnansweredQuestion
tagged with: flask-admin
downvote count: 0
has answer: http://stackoverflow.com/a/48406069
has title: Flask-admin overriding multiple choices for number of items in view
linked to: http://stackoverflow.com/q/32106940
has comment: http://stackoverflow.com/comment/83394011
has comment: http://stackoverflow.com/comment/83799586
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/83744865
answer count: 1
tagged with: python
type: Question
has body: I would like to override the 'items' drop-down list in standard Views by setting more option values (instead of: 20,50,100), when 'can_set_page_size' is set to True. I thought it would have been an easy task, but I cannot find any way to change the basic behavior. Could you please point me in the right direction?
has comment: http://stackoverflow.com/comment/83394068
has comment: http://stackoverflow.com/comment/83743876

http://stackoverflow.com/comment/83530156
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ: yeah.. though there are only 10 possible values it can take..
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48273112

http://stackoverflow.com/q/48286968
type: Question
score: 3
has comment: http://stackoverflow.com/comment/83559192
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83558964
has body: I've created an Estimator and exported it to a SavedModel file using the Estimator's export_savedmodel() function. For reproducibility reasons, I would like to be able to re-create the Estimator, load the variables in the SavedModel file then call evaluate() and get the same results. I thought the way to do this is to create my SessionRunHook to do the loading and pass it to the hooks parameter in evaluate(), like so: class myhook(tf.train.SessionRunHook): def begin(self): tf.saved_model.loader.load(tf.get_default_session(), ['serve'], '../best_model/1516075471/') load_best_model_hook = myhook() res2 = da_model.evaluate(test_input_fn, hooks=[load_best_model_hook]) But this gives the following error: File "/home/user7891/Code/scratch.py", line 106, in begin tf.saved_model.loader.load(tf.get_default_session(), ['serve'], '../best_model/1516075471/') File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/saved_model/loader_impl.py", line 198, in load with sess.graph.as_default(): AttributeError: 'NoneType' object has no attribute 'graph' It looks like a session was not created when begin() was called. I can't override after_create_session because the graph can't be modified at this point.
tagged with: python
answer count: 0
upvote count: 3
downvote count: 0
has title: How to get the default Session for an Estimator in TensorFlow?
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/83507902
type: Comment
comment on: http://stackoverflow.com/q/48257116
type: QuestionComment
has text: @Sang-ilAhn, now you can [upvote](https://meta.stackexchange.com/questions/173399/how-to-upvote-on-stack-overflow) too ;-)
score: 1

http://stackoverflow.com/comment/83756597
score: 0
type: AnswerComment
has text: @MarcinMożejko But shouldn't the higher loss be reflected within the first few epochs of training with my new reg term? The higher loss only showed up after loading my saved model. I basically trained for a few epochs with new regularization term, and during this time the loss was very low. Due to time constraints, I had to stop training and saved the model. I then loaded the model, and the loss suddenly became very high. It's almost as if the effects of the new regularization term didn't come into effect until I saved and loaded my model. Thanks!
type: Comment
comment on: http://stackoverflow.com/a/48330834

http://stackoverflow.com/comment/83451177
type: Comment
has text: Wow, simple and straightforward. Thank you!
type: AnswerComment
comment on: http://stackoverflow.com/a/48234223
score: 0

http://stackoverflow.com/comment/83498967
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48253635
score: 0
has text: Thank you for your time and insight. You made my day! @Brad Martsberger

http://stackoverflow.com/a/48231170
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48230301
type: Answer
accepted answer of: http://stackoverflow.com/q/48230301
has body: You are trying to get all files that have .xls in them, and you're trying the glob pattern: /*.xls/* This will find directories (note the trailing /) that end in .xls, not files. You need: glob.glob(path + "/*.xls*") but that would not be precise, as this would match any file having just the string .xls in them e.g. foo.xlsbar. The problem is that the standard shell globbing (even leveraging [], ? would not do here) is not so flexible as Regex as needed here, you can wrap the glob in some Regex check afterwards: import glob import re req = re.compile(r'\.xls[xm]?$') all_files = list(filter(lambda x: req.search(x), glob.iglob(path + '/*.xls*')))
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/83459615
type: QuestionComment
comment on: http://stackoverflow.com/q/48235445
has text: Just to be clear, "Your username" is your actual username as you see it in your browser (capitalisation is important), right? I don't get it, your code works fine for me!
type: Comment
score: 0

http://stackoverflow.com/q/48183050
tagged with: gnupg
favorite count: 0
type: Question
tagged with: pgp
has comment: http://stackoverflow.com/comment/83345656
type: UnansweredQuestion
downvote count: 0
tagged with: python
has body: How do I renew a key's expiration date using the library gnupg in python? I've listed the key details and they're expired as of now. The only method I've seen so for in renewing these keys is via pgp itself, which I do not have access to at the moment. Here is my reference
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/83345903
has title: How to renew a key expiration date in python gnupg?
upvote count: 1

http://stackoverflow.com/q/48280931
accepted answer: http://stackoverflow.com/a/48280971
answer count: 1
has title: NoReverseMatch 1 pattern(s) tried: ['(?P<id>\\d+)/(?P<slug>[-\\w]+)/$']
type: Question
has answer: http://stackoverflow.com/a/48280971
has body: I'm new in Django, using version 2.0. Started building a 'shop' application according to the 'Django by Example' book. But the book uses django version 1.8. The problem is, when I browse http://127.0.0.1:8000/ this error appears: "NoReverseMatch at/ Reverse for 'product_detail' with arguments '(None, 'alpina')' not found. 1 pattern(s) tried: ['(?P\d+)/(?P[-\w]+)/$']". 'alpina' is the product's name which I added from admin site. Here is urls.py of my app: from django.conf.urls import url from . import views app_name='shop' urlpatterns = [ url(r'^$', views.product_list, name='product_list'), url(r'^(?P&lt;category_slug&gt;[-\w]+)/$', views.product_list, name='product_list_by_category'), url(r'^(?P&lt;id&gt;\d+)/(?P&lt;slug&gt;[-\w]+)/$', views.product_detail, name='product_detail'), ] Here is the models.py of my app: from django.urls import reverse from django.db import models class Category(models.Model): name = models.CharField( max_length=200, db_index=True ) slug = models.SlugField( max_length=200, db_index=True, unique=True ) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse( 'shop:product_list_by_category', args=[self.slug] ) class Product(models.Model): category = models.ForeignKey( Category, related_name='products', on_delete=models.CASCADE ) name = models.CharField( max_length=200, db_index=True ) slug = models.SlugField( max_length=200, db_index=True ) image = models.ImageField( upload_to='products/%Y/%m/%d', blank=True ) description = models.TextField( blank=True ) price = models.DecimalField( max_digits=10, decimal_places=2 ) stock = models.PositiveIntegerField() available = models.BooleanField( default=True ) created = models.DateTimeField( auto_now_add=True ) updated = models.DateTimeField( auto_now=True ) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __init__(self, *args, **kwargs): super().__init__( *args…
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/48265569
has comment: http://stackoverflow.com/comment/83521916
type: Question
upvote count: 2
answer count: 0
has comment: http://stackoverflow.com/comment/83539212
tagged with: python
type: UnansweredQuestion
tagged with: gdi+
has comment: http://stackoverflow.com/comment/83514715
has comment: http://stackoverflow.com/comment/83514209
tagged with: image
has comment: http://stackoverflow.com/comment/83514287
tagged with: c++
has comment: http://stackoverflow.com/comment/83514627
has comment: http://stackoverflow.com/comment/83537374
has body: I am trying to use BitBlt() function to copy the bitmap data. When I use the python win32ui/win32gui API the average time it takes is coming around 30 ms, while the same API when I call using C++, the average time comes around 10-15 ms. So I am wondering, what could be the reason for the this behavior? Thanks EDIT : Here is the snippet : python : hdesktop = win32gui.GetDesktopWindow() # create a device context desktop_dc = win32gui.GetWindowDC(hdesktop) img_dc = win32ui.CreateDCFromHandle(desktop_dc) # create a memory based device context mem_dc = img_dc.CreateCompatibleDC() # create a bitmap object screenshot = win32ui.CreateBitmap() screenshot.CreateCompatibleBitmap(img_dc, width, height) oldbmp = mem_dc.SelectObject(screenshot) # copy the screen into our memory device context mem_dc.BitBlt((destUpLeftX, destUpLeftY), (width, height), img_dc, (srcUpLeftX, srcUpLeftY),win32con.SRCCOPY) mem_dc.SelectObject(oldbmp) win32gui.DeleteObject(screenshot.GetHandle()) img_dc.DeleteDC() win32gui.ReleaseDC(hdesktop, desktop_dc) mem_dc.DeleteDC() C++ : HDC hwindowDC=GetDC(GetDesktopWindow()); HDC hwindowCompatibleDC=CreateCompatibleDC(hwindowDC); // create a bitmap HBITMAP hbwindow = CreateCompatibleBitmap( hwindowDC, width, height); LOG(LOG_DBG, "before SelectObject"); // SAVE OLD BITMAP HGDIOBJ hOldBmp = SelectObject(hwindowCompatibleDC, hbwindow); //copy from hwindowCompatibleDC to hbwindow BitBlt(hwindowCompatibleDC, destUpLeftX, destUpLeftY, width, height, hwindowDC, srcUpLeftX, srcUpLeftY, SRCCOPY); SelectObject(hwindowCompatibleDC, hOldBmp); DeleteDC(hwindowCompatibleDC); DeleteObject(hbwindow); // RELEASE WINDOW DC ReleaseDC(GetDesktopWindow(), hwindowDC);
has title: why BitBlt() is slower in python compared to C++?
has comment: http://stackoverflow.com/comment/83514180
score: 2
has comment: http://stackoverflow.com/comment/83514953
downvote count: 0
tagged with: win32gui
favorite count: 0
has comment: http://stackoverflow.com/comment/83605964

http://stackoverflow.com/comment/83609126
has text: What do you mean? What kind of data should I provide?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48311228
score: 0

http://stackoverflow.com/comment/83514823
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48218015
type: AnswerComment
has text: @NFB: see things added (below the example output)

http://stackoverflow.com/q/48320087
tagged with: geocoding
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48320231
has title: Google Maps Geocoding API is not returning coordinates from the complete list of addresses
tagged with: google-maps
type: UnansweredQuestion
has body: Its working fine on single address or few addresses but I am trying to read addresses from a CSV which contains 200 addresses but the program is returning only few coordinates. It also giving error index out of range when I run it without handling exception. import requests import json import csv apiKey = "" with open('address.csv') as csvDataFile: try: csvReader = csv.reader(csvDataFile) for row in csvReader: # print(row) r = requests.get("https://maps.googleapis.com/maps/api/geocode/json?address=" + str(row) + "&amp;key=" + apiKey) d = json.loads(r.content) print(d['results'][0]['geometry']['location']) except: `enter code here`pass
upvote count: 1
tagged with: python
downvote count: 1
tagged with: google-maps-api-3
score: 0
answer count: 1

http://stackoverflow.com/q/48190381
has answer: http://stackoverflow.com/a/48328263
downvote count: 0
has title: Control tick-labels from multi-level FactorRange
score: 7
tagged with: python
tagged with: bokeh
type: Question
has body: I've got a three-level bokeh.models.FactorRange which I use to draw tick labels on a vbar-plot. The problem is that there are dozens of factors in total and the lowest-level labels get very cramped. I can use plot.xaxis.formatter = bokeh.models.PrintfTickFormatter(format='') to suppress drawing of the lowest-level labels, but this seems like an ugly hack. Also, I need to have the second-level tick labels to be rotated, yet plot.xaxis.major_label_orientation = ... only ever affects the lowest-level ticks (just like plot.xaxis.formatter does). How to control each level of bokeh.models.FactorRange individually?
answer count: 2
type: UnansweredQuestion
upvote count: 7
has answer: http://stackoverflow.com/a/63606667
favorite count: 0

http://stackoverflow.com/q/48286609
tagged with: http://stackoverflow.com/tag/json
linked to: http://stackoverflow.com/q/2464959
has answer: http://stackoverflow.com/a/48286896
accepted answer: http://stackoverflow.com/a/48286896
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83558522
answer count: 2
tagged with: rest
score: -2
has body: I'm about 2 days into Python (2.7 I think) and I'm trying to make the API response here a lot more readable, at the moment it's hard to decipher the English response. import json, requests response = requests.get("http://data.dublinked.ie/cgi- bin/rtpi/realtimebusinformation?stopid=1341&amp;routeid=49&amp;format=json") data = response.json() print data The response is this, and it's very ugly :( I would like to A) format it so it's more readable, maybe in a list or key:value pair? B) How do pick only certain information from the response? numberofresults: 2 timestamp: 16/01/2018 17:04:15 errormessage: results: [{u'origin': u'Tallaght', u'direction': u'Inbound', u'destinationlocalized': u'Sr\xe1id an Phiarsaigh', u'monitored': u'true', u'departureduetime': u'6', u'route': u'49', u'additionalinformation': u'', u'destination': u'Pearse St', u'scheduleddeparturedatetime': u'16/01/2018 17:09:00', u'scheduledarrivaldatetime': u'16/01/2018 17:09:00', u'sourcetimestamp': u'16/01/2018 17:01:53', u'operator': u'bac', u'departuredatetime': u'16/01/2018 17:10:56', u'arrivaldatetime': u'16/01/2018 17:10:56', u'lowfloorstatus': u'no', u'originlocalized': u'Tamhlacht', u'duetime': u'6'}, {u'origin': u'Tallaght', u'direction': u'Inbound', u'destinationlocalized': u'Sr\xe1id an Phiarsaigh', u'monitored': u'true', u'departureduetime': u'37', u'route': u'49', u'additionalinformation': u'', u'destination': u'Pearse St', u'scheduleddeparturedatetime': u'16/01/2018 17:42:00', u'scheduledarrivaldatetime': u'16/01/2018 17:42:00', u'sourcetimestamp': u'16/01/2018 16:43:44', u'operator': u'bac', u'departuredatetime': u'16/01/2018 17:42:13', u'arrivaldatetime': u'16/01/2018 17:42:13', u'lowfloorstatus': u'no', u'originlocalized': u'Tamhlacht', u'duetime': u'37'}] errorcode: 0 stopid: 1341 [Finished in 0.7s] I'm most probably doubling up on a question/answer but I can't seem to find it! Sorry. Also, the "u" is something I don't understand either. Thank you all in advance x
downvote count: 2
has comment: http://stackoverflow.com/comment/83557886
has title: Python API response - How to format/choose layout of reponse
tagged with: python
has comment: http://stackoverflow.com/comment/83558358
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48287028
possible better answer: http://stackoverflow.com/a/48287028
tagged with: python-2.7
upvote count: 0
has comment: http://stackoverflow.com/comment/83558013

http://stackoverflow.com/comment/83332407
comment on: http://stackoverflow.com/a/48173974
type: Comment
score: 0
type: AnswerComment
has text: Thanks @9000 -- I'm going to play with this solution too - always can use more practice with dictionaries....

http://stackoverflow.com/q/48271353
has comment: http://stackoverflow.com/comment/83527076
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has body: How can I get a response back and in this format in json using python? # Request curl -H "Authorization: Bearer &lt;personal_access_token&gt;" \https://app.asana.com/api/1.0/projects/1331
tagged with: curl
possible better answer: http://stackoverflow.com/a/48271424
type: AnsweredQuestion
score: 0
has title: How to get format curl request and format to json using python?
answer count: 2
accepted answer: http://stackoverflow.com/a/48271435
upvote count: 1
tagged with: request
downvote count: 1
has answer: http://stackoverflow.com/a/48271435
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48271424

http://stackoverflow.com/comment/83617806
comment on: http://stackoverflow.com/q/48316200
has text: What's the exception? Add some explanation to your code please.
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48282691
score: 7
possible better answer: http://stackoverflow.com/a/48282738
favorite count: 0
has answer: http://stackoverflow.com/a/48282738
type: Question
tagged with: python-3.x
has body: I have a pandas dataframe with the following form: Response Time 2018-01-14 00:00:00 201 2018-01-14 00:00:00 400 2018-01-14 00:00:00 200 2018-01-14 00:00:00 400 2018-01-14 00:00:00 200 Time is the index column. I wanted to get graphs for the responses grouped over time (15 min intervals) so I wrote the following: for ind, itm in enumerate(df_final['Response'].unique()): ax=df_final[df_final['Response'] == itm].groupby(pd.Grouper(key='Time',freq='15Min')).count().plot(kind='bar', figsize=(15,10), title="Response Codes") ax.legend(["Response: {}".format(itm)]) This worked with the depreciated TimeGrouper where the second line in the above code was: ax=df_final[df_final['Response'] == item].groupby(pd.TimeGrouper(freq='15Min')).count().plot(kind='bar', figsize=(15,10), title="Response Codes") but when I run the Grouper code I get the error: KeyError: 'The grouper name Time is not found' I also changed the key to be df_final.index.name but that also resulted in KeyError: 'The grouper name Time is not found' The index was of type index but I changed it to DatetimeIndex: type(df_final.index) pandas.core.indexes.datetimes.DatetimeIndex After I changed the index type and ran : ax=df_final[df_final['Response'] == itm].groupby(pd.Grouper(key=df_final.index, freq='15Min')).count().plot(kind='bar', figsize=(15,10), title="Response Codes") I got: TypeError: unhashable type: 'DatetimeIndex' I'm obviously missing something. What am I doing wrong here? Just to show what the index is df_final.index gave the result: DatetimeIndex(['2018-01-14 00:00:00', '2018-01-14 00:00:00', '2018-01-14 00:00:00', '2018-01-14 00:00:00', '2018-01-14 00:00:00', '2018-01-14 00:00:00', '2018-01-14 00:00:00', '2018-01-14 00:00:00', '2018-01-14 00:00:00', '2018-01-14 00:00:00', ... '2018-01-15 00:00:00', '2018-01-15 00:00:00', '2018-01-15 00:00:00', '2018-01-15 00:00:00', '2018-01-15 00:00:00', '2018-01-15 00:00:00', '2018-01-15 00:00:00', '2018-01-15 00:00:00', '2018-01-15 00:00:00', '2018-01-15 00:00:00…
has title: pandas grouper issue with key that is an index
has answer: http://stackoverflow.com/a/48298396
accepted answer: http://stackoverflow.com/a/48298396
tagged with: python
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: pandas
upvote count: 7

http://stackoverflow.com/comment/83521734
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48267845
has text: And what part of your code doesn't work?
score: 0

gbk
tags question: http://stackoverflow.com/q/48257946
type: Tag
tag name: gbk

http://stackoverflow.com/q/48194546
linked to: http://stackoverflow.com/q/37924377
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83370184
favorite count: 0
has comment: http://stackoverflow.com/comment/83369965
tagged with: moving-average
has body: I have a Series of data, each reflects a value that was taken every 7 days. I'd like to calculate the exponential moving average of that Series using a half-life of 3 days. What value should I use for the halflife attribute in the ewm function call? s = pd.Series([232848661129,327042265468,235595837210,220903949498,287582315011]) s.ewm(halflife=7/3,min_periods=0,adjust=True,ignore_na=False).mean() What halflife value would be correct here? Is halflife=7/3 correct? I'm not sure how to make this work.
downvote count: 0
tagged with: pandas
score: 1
tagged with: python
has title: What value to use for halflife in pandas ewm function? (Python)
has comment: http://stackoverflow.com/comment/83370230
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/83372048

http://stackoverflow.com/a/57814205
has body: Try A.flatten()[0] This will flatten the array into a single dimension and extract the first item from it. In your case, the first item is the only item.
upvote count: 2
answers question: http://stackoverflow.com/q/48233313
downvote count: 0
score: 2
type: Answer

http://stackoverflow.com/q/48266705
has comment: http://stackoverflow.com/comment/83516479
score: 0
has comment: http://stackoverflow.com/comment/83516443
has comment: http://stackoverflow.com/comment/83518923
has body: I need to launch a program within a python script that has an argument. Code is: from datetime import date, timedelta import os yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y') os.system('"E:/Bootdrv/AlohaTs/Bin/grind.exe /yesterday"') Any help?
type: Question
has comment: http://stackoverflow.com/comment/83516545
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48266809
has title: Launching external program Python with parameter
answer count: 1
has comment: http://stackoverflow.com/comment/83516574
tagged with: python
has comment: http://stackoverflow.com/comment/83516447

http://stackoverflow.com/q/48259500
upvote count: 1
has comment: http://stackoverflow.com/comment/83502837
has comment: http://stackoverflow.com/comment/83501840
tagged with: string
has title: Efficiently finding the longest matching prefix string
has answer: http://stackoverflow.com/a/48259961
accepted answer: http://stackoverflow.com/a/48259961
favorite count: 0
type: Question
has body: My current implementation is this: def find_longest_matching_option(option, options): options = sorted(options, key=len) longest_matching_option = None for valid_option in options: # Don't want to treat "oreo" as matching "o", # match only if it's "o reo" if re.match(ur"^{}\s+".format(valid_option), option.strip()): longest_matching_option = valid_option return longest_matching_option Some examples of what I'm trying to do: "foo bar baz something", ["foo", "foo bar", "foo bar baz"] # -&gt; "foo bar baz" "foo bar bazsomething", (same as above) # -&gt; "foo bar" "hello world", ["hello", "something_else"] # -&gt; "hello" "a b", ["a", "a b"] # -&gt; "a b" # Doesn't work in current impl. Mostly, I'm looking for efficiency here. The current implementation works, but I've been told it's O(m^2 * n), which is pretty bad. Thanks in advance!
tagged with: longest-substring
has comment: http://stackoverflow.com/comment/83502780
answer count: 2
has comment: http://stackoverflow.com/comment/83502180
has comment: http://stackoverflow.com/comment/83501704
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83502038
has comment: http://stackoverflow.com/comment/83501889
has comment: http://stackoverflow.com/comment/83501750
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83501974
has comment: http://stackoverflow.com/comment/83501778
score: 1
has answer: http://stackoverflow.com/a/48259859
possible better answer: http://stackoverflow.com/a/48259859
has comment: http://stackoverflow.com/comment/83502692
has comment: http://stackoverflow.com/comment/83502259

http://stackoverflow.com/comment/83413835
score: 2
type: AnswerComment
has text: Be careful with `str = ['R142389', 'hello', 'J123456']`. Your overwriting a built-in name which can cause [strange errors](https://stackoverflow.com/questions/45740182/im-getting-typeerror-list-object-is-not-callable-how-do-i-fix-this-error) and the like. It'd would be best to use a name such as `strs` instead. Anyway's, nice answer. +1
comment on: http://stackoverflow.com/a/48215949
type: Comment

camera-matrix
tags question: http://stackoverflow.com/q/48240239
tag name: camera-matrix
type: Tag

http://stackoverflow.com/a/48285181
has body: The error message is telling you that your editor is incompatible with the .NET version you are using. You may wish to update your path to include both the .NET 3.5 and 4.0 versions.
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/48285154
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48285154

http://stackoverflow.com/comment/83559057
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/48287127
type: Comment
has text: You want to use *string formatting*, otherwise, you are appending a *tuple* of objects.

http://stackoverflow.com/comment/115053127
type: Comment
type: AnswerComment
has text: In case the `frames` are not the same , what are you doing?
comment on: http://stackoverflow.com/a/48186874
score: 0

http://stackoverflow.com/comment/83658835
comment on: http://stackoverflow.com/a/48328169
type: AnswerComment
has text: You should explain explain your answer. Once you've done that I'll remove my comment & up-vote.
score: 0
type: Comment

http://stackoverflow.com/q/48275385
has body: I am newbie in Django. My task is design a backend where there will be login system (using the default user table provide by django). There are two other tables, one is the image table which has the imgvalue column which contains the key from redis database. The other table (imgacl), is to provide the access control to users for viewing the particular images which a required user has access. The redis database is actually storing the images with key-value pair, and that key is stored in the imgvalue column. Here are my codes: models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Image(models.Model): imgvalue = models.Charfield(max_length =250) class Imageacl(models.Model): id = models.ForeignKey(Image,on_delete =models.CASCADE) userlist= models.Textfield(null=True) The userlist contains the list of user which can see a particular image. A separate python program for storing 50 images in Redis db. Suppose there are 5 users, the user1 can view 10 images, users2 can view 15 images... import redis from PIL import Image rd = redis.StrictRedis() for x in range(1,51): img = open("{}.jpg".format(x),"rb").read() rd.set("key{}".format(x),img) I have two questions: 1) How I wll integrate redis with django &amp; 2) How I will provide the access control to users??
type: UnansweredQuestion
answer count: 1
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51000031
favorite count: 0
score: 2
has title: Integrating redis with django
downvote count: 0
linked to: http://stackoverflow.com/q/2080653
type: Question
upvote count: 2
tagged with: redis

http://stackoverflow.com/comment/83593685
comment on: http://stackoverflow.com/a/48274806
score: 0
type: AnswerComment
has text: I suggest using [the API explorer, ml.projects.predict endpoint](https://developers.google.com/apis-explorer/#search/machine%20learning/ml/v1/ml.projects.predict), to see eventual changes in performance when _striping the code_ away from the job, leaving pure HTTP requests-responses. Please reply with the results
type: Comment

http://stackoverflow.com/a/48230651
has body: I would recommend using Cython instead of SWIG. It is specifically designed for writing Python native code extensions, with mappings for C/C++ external code being quite easy to write. For the above example, a Cython definition file (.pxd) can be written: cdef extern from "Foo.h": cppclass Model: pass void foo(vector[string], Model*, vector[vector[double]]) void foo(vector[vector[FS]], Model*, vector[vector[vector[double]]], Model*) Cython implementation code can then cimport from the .pxd file and use the C++ functions directly. See documentation for more C++ interfacing examples and extension types for implementation code examples.
score: 0
has comment: http://stackoverflow.com/comment/83626356
answers question: http://stackoverflow.com/q/48230430
has comment: http://stackoverflow.com/comment/83522254
type: Answer

http://stackoverflow.com/q/48272540
has comment: http://stackoverflow.com/comment/83530122
has answer: http://stackoverflow.com/a/48273177
type: UnansweredQuestion
score: 10
tagged with: python
has title: Pandas TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64Index'
has body: I've got some order data that I want to analyse. Currently of interest is: How often has which SKU been bought in which month? Here a small example: import datetime import pandas as pd import numpy as np d = {'sku': ['RT-17']} df_skus = pd.DataFrame(data=d) print(df_skus) d = {'date': ['2017/02/17', '2017/03/17', '2017/04/17', '2017/04/18', '2017/05/02'], 'item_sku': ['HT25', 'RT-17', 'HH30', 'RT-17', 'RT-19']} df_orders = pd.DataFrame(data=d) print(df_orders) for i in df_orders.index: print("\n toll") df_orders.loc[i,'date']=pd.to_datetime(df_orders.loc[i, 'date']) df_orders = df_orders[df_orders["item_sku"].isin(df_skus["sku"])] monthly_sales = df_orders.groupby(["item_sku", pd.Grouper(key="date",freq="M")]).size() monthly_sales = monthly_sales.unstack(0) print(monthly_sales) That works fine, but if I use my real order data (from CSV) I get after some minutes: TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64Index' That problem comes from the line: monthly_sales = df_orders.groupby(["item_sku", pd.Grouper(key="date",freq="M")]).size() Is it possible to skip over the error? I tried a try except block: try: monthly_sales = df_orders.groupby(["item_sku", pd.Grouper(key="date",freq="M")]).size() monthly_sales = monthly_sales.unstack(0) except: print "\n Here seems to be one issue" Then I get for the print(monthly_sales) Empty DataFrame Columns: [txn_id, date, item_sku, quantity] Index: [] So something in my data empties or brakes the grouping it seems like? How can I 'clean' my data? Or I'd be even fine with loosing the data of a sale here and there if I can just 'skip' over the error, is this possible?
tagged with: pandas
downvote count: 0
tagged with: validation
upvote count: 10
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83530059
type: Question
has comment: http://stackoverflow.com/comment/83528976

http://stackoverflow.com/a/48300601
upvote count: 6
has comment: http://stackoverflow.com/comment/83585631
has body: It seems like you want to preserve order. In that case you can keep a set that keeps track of what lists have been added. Here is an example: mylist = [['xxx', 879], ['yyy', 315], ['xxx', 879], ['zzz', 171], ['yyy', 315]] # set that keeps track of what elements have been added seen = set() no_dups = [] for lst in mylist: # convert to hashable type current = tuple(lst) # If element not in seen, add it to both if current not in seen: no_dups.append(lst) seen.add(current) print(no_dups) Which Outputs: [['xxx', 879], ['yyy', 315], ['zzz', 171]] Note: Since lists are not hashable, you can add tuples instead to the seen set.
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/48300501
type: Answer

http://stackoverflow.com/comment/83501524
has text: @JohnSmith I think its due to the fact that `xaxis` and `yaxis` are not present for `table` object of plotly, so by default it gets applied to the `bar` chart!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48237465

http://stackoverflow.com/q/48314127
score: 0
answer count: 1
has title: Method of Gradient Descent in Python
tagged with: optimization
has answer: http://stackoverflow.com/a/48314267
type: Question
tagged with: gradient-descent
has body: So I'm running a simple algorithm for gradient descent in python, trying to find the minimums of functions. My code is reasonably straightforward, I feel it is intuitive. I've tried with the simple example of a second order polynomial. def s(x): return x**2 def t(x): return 2*x def steepd(a, alpha, epsilon): b = a - alpha*t(a) while abs(t(a)) &gt; epsilon: if t(b) ==0: return b else: a = b b = a - alpha*t(a) return b print(steepd(2,0.1,0.001)) x = np.arange(-10,10,0.01) plt.plot(x,s(x)) plt.show() I'm not getting anywhere near close to the minimum however, even by varying both alpha and epsilon significantly. Can someone point out what the issue is? Cheers.
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/48218794
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/83419607
has comment: http://stackoverflow.com/comment/83419529
has title: Replace greedy elements with the appropriate
has answer: http://stackoverflow.com/a/48218816
accepted answer: http://stackoverflow.com/a/48218816
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48219114
downvote count: 0
upvote count: 1
score: 1
possible better answer: http://stackoverflow.com/a/48219114
favorite count: 0
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/267399
has body: I have such a following list: import re l = ['Part I, Where I’M Coming From', 'Part Ii, Life Principles', 'Part Iii, Work Principles'] I want a result, l = ['Part I, Where I’M Coming From', 'Part II, Life Principles', 'Part III, Work Principles'] I tried: In [19]: [re.sub(r'(?&lt;=I)i+', 'I+', s) for s in l] Out[19]: ['Part I, Where I’M Coming From', 'Part II+, Life Principles', 'Part II+, Work Principles'] It output 'Part II+, Work Principles' not 'Part III, Work Principles' How to accomplish such a task?

http://stackoverflow.com/q/48272976
has comment: http://stackoverflow.com/comment/83529868
has comment: http://stackoverflow.com/comment/83530049
type: AnsweredQuestion
score: 0
has body: My password checker is working however it resolves only when the user input is the same as the entire .txt file. How can I put multiple passwords in the .txt file and have my program work if any of them match the input? I would like to be able to be able to add the password 123456 so that my second if statement will work. #simple program to check passwords against a txt file database passwordfile = open('secretpasswordfile.txt') secretpassword = passwordfile.read() print('Enter your password.') typedpassword = input() if typedpassword == secretpassword: print('Access granted.') if typedpassword == '123456': print('This password is not secure.') else: print('Access denied.') the secretpasswordfile.txt only has genericpassword written in it.
answer count: 1
has comment: http://stackoverflow.com/comment/83530027
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83529859
has title: python 3 password checker will only read the exact txt file content
accepted answer: http://stackoverflow.com/a/48273034
type: Question
has answer: http://stackoverflow.com/a/48273034
tagged with: python
has comment: http://stackoverflow.com/comment/83529891

http://stackoverflow.com/q/48190249
has body: I am trying to interface Python and Fortran. I am stuck at the most trivial example (from here mpi4py and f2py). The example defines the following Fortran subroutine: ! file: helloworld.f90 subroutine sayhello(comm) use mpi implicit none integer :: comm, rank, size, ierr call MPI_Comm_size(comm, size, ierr) call MPI_Comm_rank(comm, rank, ierr) print *, 'Hello, World! I am process ',rank,' of ',size,'.' end subroutine sayhello The subroutine above is processed with f2py, through this command (Linux CLI): $ f2py -c --fcompiler=gnu95 --f90exec=mpif90 --include-paths /usr/local/include/ -L/usr/local/lib/lib -lmpi helloworld.f90 -m helloworld The command ends successfully, and the object helloworld.so is created. I created the following python driver script (file driver_helloworld.py) #!/usr/bin/env python #-------------- # Loaded Modules #-------------- from mpi4py import MPI import helloworld #------------------------------------ # Set the MPI communicator #------------------------------------- fcomm = MPI.COMM_WORLD.py2f() #----------------------------------------- # Calling the Fortran subroutine #----------------------------------------- helloworld.sayhello(fcomm) Running script above in serial works fine, namely: $ python driver_helloworld.py the output is the expected: Hello, World! I am process 0 of 1 . However, when I attempt to run through mpiexec, namely: $ mpiexec -n 2 python driver_helloworld.py I obtain the following error: [linux-box] [[INVALID],INVALID] ORTE_ERROR_LOG: Not found in file ess_env_module.c at line 367 [linux-box] [[INVALID],INVALID] ORTE_ERROR_LOG: Not found in file ess_env_module.c at line 367 [linux-box] tcp_peer_recv_connect_ack: invalid header type: 259457024 [linux-box] tcp_peer_recv_connect_ack: invalid header type: 259457024 I am using: Open MPI 1.10.2 GNU Fortran (Debian 4.9.2-10) 4.9.2 Python 2.7.9 Does someone know what/where the problem is?
tagged with: python
tagged with: mpi4py
has comment: http://stackoverflow.com/comment/83994085
tagged with: f2py
answer count: 0
tagged with: fortran
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
has title: Error when Python calls Fortran with MPI: `[[INVALID],INVALID] ORTE_ERROR_LOG: Not found in file ess_env_module.c`
tagged with: mpi
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84003991
has comment: http://stackoverflow.com/comment/83993954

http://stackoverflow.com/comment/83367074
comment on: http://stackoverflow.com/a/48184840
score: 0
has text: @FlorentB. I'm agree with your concern. But can you suggest some alternatives to get rid from these kind of situation.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48230843
has answer: http://stackoverflow.com/a/48256850
downvote count: 0
upvote count: 1
tagged with: django
type: AnsweredQuestion
score: 1
answer count: 1
tagged with: orm
has body: The model is something like this: class Application(models.Model): application_id = models.IntegerField() version_id = models.IntegerField() # some other attributes where application_id and version_id together determine an Application entry, in that one application may have several versions, and an entry with the largest version_id is the application's current version. And the goal is to find the current versions of all applications. The SQL (in MySQL) is something like: SELECT * FROM application AS app WHERE version_id = (SELECT max(version_id) FROM application WHERE application_id = app.application_id); How to achieve this? Please note that the object here is to filter the QuerySet, rather than only fetching the largest version_id, which would be as simple as using a GROUP BY, or in django a values() followed by an annotate(). I'm interested in the other attributes of the current version as well.
tagged with: python
tagged with: mysql
tagged with: web
accepted answer: http://stackoverflow.com/a/48256850
favorite count: 0
type: Question
has title: How to filter a QuerySet to max members of each group in django?

http://stackoverflow.com/q/48217119
has title: keras - get probability per each class
has body: I'm trying to get the probability per each class out of the keras model. Please find sample keras model below: width = 80 height = 80 model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=( width, height, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(32, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors model.add(Dense(64)) model.add(Activation('relu')) #model.add(Dropout(0.5)) model.add(Dense(2)) model.add(Activation('softmax')) model.compile(loss='sparse_categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) However, after the model is trained, and I load an image to be predicted via: img = image.load_img('Test2.jpg', target_size=(80, 80)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) images = np.vstack([x]) classes = model.predict_proba(images, batch_size=1) print(classes) [[ 0. 1.]] I still get the classes labels, rather than probabilities. Any hints what am I doing wrong? EDIT This is how the model is trained: train_datagen = ImageDataGenerator( rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') # this is the augmentation configuration we will use for testing: # only rescaling test_datagen = ImageDataGenerator( rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') train_generator = train_datagen.flow_from_directory( '.\\train', # this is the target directory target_size=(width, height), # all images will be resized to 150x150 batch_size=batch_size, class_mode='binary', shuffle=True) # since we use binary_crossentropy loss, we need binary labels # this is a similar generator, for validation data v…
linked to: http://stackoverflow.com/q/37312421
tagged with: python
has answer: http://stackoverflow.com/a/48223921
accepted answer: http://stackoverflow.com/a/48223921
type: AnsweredQuestion
tagged with: deep-learning
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83416692
has comment: http://stackoverflow.com/comment/83428752
answer count: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/83424782
favorite count: 0
type: Question

http://stackoverflow.com/q/48289191
tagged with: python-3.x
type: AnsweredQuestion
tagged with: python
tagged with: python-decorators
possible better answer: http://stackoverflow.com/a/74981391
upvote count: 2
score: 2
answer count: 2
has comment: http://stackoverflow.com/comment/83590617
has body: I have a number of classes for which I wish to run a decorator function on. As I am aware decorators only run when the class/function/whatever they label is loaded into the code. e.g. def decorator(cls): print("Decorator executed") return cls @decorator class Example: pass Example() How can I trigger the decorator function on all the classes a decorator labels at startup of the django application without having to load each class separately? (or without having knowledge of the classes for which a decorator labels)
has title: How to execute a decorator function at startup in a Django/Python Application?
downvote count: 0
has answer: http://stackoverflow.com/a/48379866
tagged with: django
accepted answer: http://stackoverflow.com/a/48379866
favorite count: 0
has answer: http://stackoverflow.com/a/74981391
type: Question

http://stackoverflow.com/q/48277120
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83539280
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/csv
has body: How would I check a CSV with unknown amount of rows and columns whether it has some certain headers? Let's say I have a CSV file called Testy.py and it has M columns with M headers. But I can only validify this CSV file if it has the headers: ID in the first column and Name in the second column. Meaning if the file does not fulfill the requirements, I will set the uploaded file to 0. I have the following code, and I tried to use the if statement under the Cols definition but it doesn't work. #Loading a file filename = input("Please enter .csv filename: ") path = os.listdir(os.getcwd()) #*If the file is in the path, the code will run* if filename in path[:len(path)]: print("\nData has been loaded!\n") loadcsv = pd.read_csv(filename, header = None, names = cols) cols = ['StudentID', 'Name'] if (loadcsv.iloc[0] != cols).all(): print("The uploaded file is not valid") break else: print("\nFile has not been found.") #File upload gets reset if not found in listdir. loadcsv = np.array([])
downvote count: 0
has comment: http://stackoverflow.com/comment/83537910
tagged with: python
has comment: http://stackoverflow.com/comment/83538130
type: AnsweredQuestion
score: 1
upvote count: 1
answer count: 1
tagged with: file-upload
has answer: http://stackoverflow.com/a/48277548
accepted answer: http://stackoverflow.com/a/48277548
has title: How to check if an uploaded N x M csv file has certain headers?

http://stackoverflow.com/comment/83647485
comment on: http://stackoverflow.com/q/48330480
type: Comment
type: QuestionComment
score: 0
has text: The code you posted will return a trivial dict, the value of every key is `[]`, not to mention the indentation error. If you just want to replace [1] in second file by every host name in the first file, you can simply skip all rows containing '['.

http://stackoverflow.com/q/48208839
has comment: http://stackoverflow.com/comment/83398972
has title: Why do I need to pass the class instance or object to a function definition inside a class?
tagged with: class
answer count: 0
duplicate of: http://stackoverflow.com/q/114214
has comment: http://stackoverflow.com/comment/83398937
downvote count: 0
has body: Say I have a class: class myM(): def __init__(self): print("original") I then instantiate this class a=myM() From which I can call a.__init__() However, if I use the class itself to call __init__, myM.__init__() results in an error. These 2 options work however: myM.__init__(myM) and myM.__init__(a) where a=myM(). Question: Why do I have to pass myM or a as an argument to __init__, for myM.__init__ to work? Why dont I need to do that if I call a.__init__() instead?
has comment: http://stackoverflow.com/comment/83399044
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83398565
has comment: http://stackoverflow.com/comment/83402816
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83399072
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83402649
has comment: http://stackoverflow.com/comment/83399128

http://stackoverflow.com/comment/83408971
has text: `os.getcwd()` returns `/` but my file `gobatch.py` isn't here... I don't understand.
type: QuestionComment
comment on: http://stackoverflow.com/q/48212964
score: 0
type: Comment

http://stackoverflow.com/q/48240470
tagged with: curl
tagged with: bitbucket
type: AnsweredQuestion
score: 0
tagged with: http-error
has comment: http://stackoverflow.com/comment/83465997
linked to: http://stackoverflow.com/q/48218119
answer count: 1
has comment: http://stackoverflow.com/comment/83464859
has comment: http://stackoverflow.com/comment/83465295
tagged with: urllib
has comment: http://stackoverflow.com/comment/83465511
type: Question
has title: bad request error 400
accepted answer: http://stackoverflow.com/a/48245057
linked to: http://stackoverflow.com/q/48161651
has answer: http://stackoverflow.com/a/48245057
linked to: http://stackoverflow.com/q/48047296
has comment: http://stackoverflow.com/comment/83472313
tagged with: python
has comment: http://stackoverflow.com/comment/83467867
has body: I want to replicate the below with Client config. Curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" http://localhost:7990/rest/api/1.0/projects https://developer.atlassian.com/server/bitbucket/how-tos/example-basic-authentication/ This is to download a file for updating exe in a private repo. I'm getting 400 errors on a regular basis with bitbucket. What I had: client = Client(ClientConfig(), headers={'basic_auth':'U:P' }, refresh=True) I want to include this header header = {'Content-Type': 'application/json'} So something like: client = Client(ClientConfig(), headers={'basic_auth': 'brofewfefwefewef:EKAXsWkdt5H6yJEmtexN'}, header = {'Content-Type': 'application/json'}, refresh=True) Should fix? At least according to.... "Some http client software expects to receive an authentication challenge before it will send an authorization header and this may mean that it may not behave as expected. In this case you may need to configure it to supply the authorization header as described above rather than relying on its default mechanism." and... https://stackoverflow.com/questions/8840303/urllib2-http-error-400-bad-request For me though, I always get error even with this change 400 https://pastebin.com/V9ibxTRX (full code here or short version below) Optional errors message (it's not pretty but I did reduce it): ~~~~~ACCESSING PAGE AND FOUND!~~~ DEBUG:pyupdater.client.downloader:Url for request: https://api.bitbucket.org/2.0/repositories/Username/repository/downloads/keys.gz DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.bitbucket.org send: b'GET /2.0/repositories/Username/repository/downloads/keys.gz HTTP/1.1\r\nHost: api.bitbucket.org\r\nAccept-Encoding: identity\r\nauthorization: Basic ywafdwafawffwawffawafwfwaawfawfg==\r\n\r\n' reply: 'HTTP/1.1 302 Found\r\n' ~~~~~~RETRYING REDIRECTION PRESENT (IS THIS THE CAUSE OF ISSUES)??~~ DEBUG:urllib3.connectionpool:https://api.bitbucket.org:443 "GET /2.0/repositories/U…
has comment: http://stackoverflow.com/comment/83466997
linked to: http://stackoverflow.com/q/8840303

http://stackoverflow.com/comment/83576927
has text: Are you sure you are using tuple? Isn't it list tupleDocuments = []
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48296181
score: 0

http://stackoverflow.com/comment/83643548
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48328736
has text: I am getting "SyntaxError: multiple statements found while compiling a single statement". Also I really appreciate your help getting this far.
type: AnswerComment

http://stackoverflow.com/a/48304067
has comment: http://stackoverflow.com/comment/83596363
type: AcceptedAnswer
downvote count: 0
has body: The information you're looking for (username, rating) is located in 'div.review-container' tags. About the tags that have no rating, you can just ignore them. for k in soup.find_all('div',{"class":"review-container"}): rating = k.find('span', class_='rating-other-user-rating') if rating: rating = ''.join(i.text for i in rating.find_all('span')[-2:]) name = k.find('span', class_='display-name-link').text print name, rating The information that shows when you press the Load More button is loaded via XHR requests. You'll find the all data you need in order to preform the request in a 'div.load-more-data' tag. load_more = soup.find('div', class_='load-more-data') url = 'http://www.imdb.com{}?paginationKey={}'.format( load_more['data-ajaxurl'], load_more['data-key'] ) r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') Just repeat the above process untill you have all the info. import requests from bs4 import BeautifulSoup url = "http://www.imdb.com/title/tt2866360/reviews?ref_=tt_ov_rt" ajax_url = url.split('?')[0] + "/_ajax?paginationKey={}" reviews = [] while True: r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') for k in soup.find_all('div',{"class":"review-container"}): rating = k.find('span', class_='rating-other-user-rating') if rating: rating = ''.join(i.text for i in rating.find_all('span')[-2:]) name = k.find('span', class_='display-name-link').text reviews.append([name, rating]) print name, rating load_more = soup.find('div', class_='load-more-data') if not load_more: break url = ajax_url.format(load_more['data-key'])
answers question: http://stackoverflow.com/q/48303583
has comment: http://stackoverflow.com/comment/83596450
has comment: http://stackoverflow.com/comment/83621981
has comment: http://stackoverflow.com/comment/83618629
has comment: http://stackoverflow.com/comment/83618194
type: Answer
has comment: http://stackoverflow.com/comment/83618271
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48303583

http://stackoverflow.com/comment/83340656
type: Comment
has text: Did you fix your template, e.g. change the `{{user.category_id}}`...?
type: AnswerComment
comment on: http://stackoverflow.com/a/48176061
score: 0

numba
tags question: http://stackoverflow.com/q/48215914
type: Tag
tags question: http://stackoverflow.com/q/48243370
tags question: http://stackoverflow.com/q/48285430
tag name: numba
tags question: http://stackoverflow.com/q/48330128

http://stackoverflow.com/a/48188953
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83357924
has body: A sounder way to implement this would be a classmethod. That allows you to dynamically access the attributes of the class that the method is called on: class Treasure(Card): @classmethod def pile_setup(cls, player_count): return (floor(player_count/cls.normal_full_table) + 1) * cls.pile_player_rate You could implement this method on Card, and without overriding it, it would access the attributes of Treasure when called on Treasure.
score: 4
accepted answer of: http://stackoverflow.com/q/48188845
upvote count: 4
answers question: http://stackoverflow.com/q/48188845

inheritance
tags question: http://stackoverflow.com/q/48312870
tags question: http://stackoverflow.com/q/48211945
tags question: http://stackoverflow.com/q/48231573
tag name: inheritance
tags question: http://stackoverflow.com/q/48324176
tags question: http://stackoverflow.com/q/48265480
tags question: http://stackoverflow.com/q/48280605
tags question: http://stackoverflow.com/q/48177952
tags question: http://stackoverflow.com/q/48297186
tags question: http://stackoverflow.com/q/48188845
tags question: http://stackoverflow.com/q/48241910
type: Tag
tags question: http://stackoverflow.com/q/48252357
tags question: http://stackoverflow.com/q/48210662

http://stackoverflow.com/comment/83500815
comment on: http://stackoverflow.com/a/48217352
score: 0
type: Comment
has text: I tried the second method you suggested and it works fine. Thanks a lot :D
type: AnswerComment

http://stackoverflow.com/a/48261506
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/83506846
accepted answer of: http://stackoverflow.com/q/48260848
has comment: http://stackoverflow.com/comment/83506951
has comment: http://stackoverflow.com/comment/83507362
type: Answer
has comment: http://stackoverflow.com/comment/83507260
upvote count: 6
has comment: http://stackoverflow.com/comment/83506984
has body: In [26]: chk_set = set(df.MACHINE.unique()) In [27]: df[df.groupby('UNIT')['MACHINE'] .transform(lambda x: x.is_monotonic_increasing &amp; chk_set.issubset(set(x)))] Out[27]: UNIT MACHINE 5 b222 001 6 b222 002 7 b222 002 8 b222 003 UPDATE: assuming you have the following DF: In [90]: df Out[90]: UNIT MACHINE 1 a100 001 2 a100 002 3 a100 003 4 a100 001 5 b222 001 6 b222 002 7 b222 002 8 b222 003 9 c1 001 10 c1 003 11 c2 078 12 c2 079 13 c2 080 14 c3 078 16 c3 080 and an array of concatenated groups to check against: In [91]: chk_groups = np.array(['001002003','078079080']) Solution: In [92]: df[df.groupby('UNIT')['MACHINE'] .transform(lambda x: x.is_monotonic_increasing &amp; np.in1d(x.unique().sum(),chk_groups))] Out[92]: UNIT MACHINE 5 b222 001 6 b222 002 7 b222 002 8 b222 003 11 c2 078 12 c2 079 13 c2 080
has comment: http://stackoverflow.com/comment/83507642
answers question: http://stackoverflow.com/q/48260848
type: AcceptedAnswer

http://stackoverflow.com/q/48299320
tagged with: python
tagged with: excel
has comment: http://stackoverflow.com/comment/83586169
has comment: http://stackoverflow.com/comment/83587800
has comment: http://stackoverflow.com/comment/83586195
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83584102
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/83588328
linked to: http://stackoverflow.com/q/5552555
type: Question
has title: python 3.6 pandas - transfer csv data to excel in loop
has comment: http://stackoverflow.com/comment/83586190
has comment: http://stackoverflow.com/comment/83586177
type: UnansweredQuestion
has body: This is the code that I wrote. I don't understand why I get an error message. import CSV import openpyxl import xlsxwriter from pandas.io.excel import ExcelWriter import pandas def create_excell_from_csv(): arr = ['users', 'account'] dest_filename = r'transformed.xlsx' wb = xlsxwriter.Workbook(dest_filename) with ExcelWriter(dest_filename) as ew: for arr1 in arr: wb.add_worksheet('sh_' + arr1) pandas.read_csv(arr1 + '.csv').to_excel(ew, index=FALSE, sheet_name='sh_sh_users' , encoding='utf-8' ) wb.add_worksheet('Sheet').hide() create_excell_from_csv()

http://stackoverflow.com/comment/83380179
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48199383
type: QuestionComment
has text: if you leave out the `usecols` argument, do you get a `C` column in the resulting data frame?

http://stackoverflow.com/a/48245136
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48244999
has body: API Gateway can't interact directly with Python running in EC2. API Gateway has HTTPS endpoints. You will need to either have Python react to HTTPS requests directly or use the AWS Python SDK Here's some general reading on Python and APIs https://realpython.com/blog/python/api-integration-in-python/ Here's AWS boto3 SDK https://aws.amazon.com/sdk-for-python/ I would check these out and when you feel like you're getting close ask another question and provide details on your code Good luck!

http://stackoverflow.com/q/48247027
has comment: http://stackoverflow.com/comment/83477008
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/8848285
type: Question
has answer: http://stackoverflow.com/a/48247138
has body: How could I turn my python program to a windows application? As python is a scripting language how we make its programs for desktop applications
type: UnansweredQuestion
tagged with: package
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/83476701
has title: What is the easy way to package my python program as desktop application?
score: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83476980

debugging
tags question: http://stackoverflow.com/q/48255267
tag name: debugging
tags question: http://stackoverflow.com/q/48312903
tags question: http://stackoverflow.com/q/48184668
tags question: http://stackoverflow.com/q/48254504
type: Tag
tags question: http://stackoverflow.com/q/48197324
tags question: http://stackoverflow.com/q/48261561

http://stackoverflow.com/a/48327363
answers question: http://stackoverflow.com/q/48327293
type: Answer
has body: How about having a custom function and using map def conInt(x): try: return int(x) except ValueError: return x my_list = ['a', '1', '2'] a, b, c = map(conInt, my_list) print a,b,c Result: a 1 2
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83490723
type: AnswerComment
has text: This is not the best answer, as you should change the code if you include a dessert. @Diman answer is more general. imho
comment on: http://stackoverflow.com/a/48254004
score: 0
type: Comment

http://stackoverflow.com/a/48308858
score: 1
has comment: http://stackoverflow.com/comment/83605085
has comment: http://stackoverflow.com/comment/83604429
downvote count: 0
has comment: http://stackoverflow.com/comment/83605024
has comment: http://stackoverflow.com/comment/83604749
has comment: http://stackoverflow.com/comment/83603271
has comment: http://stackoverflow.com/comment/83604191
answers question: http://stackoverflow.com/q/48308560
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83603566
has body: Repeating series kindof hurt dicts, so use only lists: Added repeating series to the data.... import csv t = """ID Name Series Value 250 A 3 20 250 A 3 40 250 A 3 60 251 B 4 16 251 B 4 18 251 B 4 24 251 B 4 42 250 A 3 140 250 A 3 160""" results = list() tempList = list() lastKey = None reader = csv.DictReader(t.splitlines(), skipinitialspace=True, delimiter=' ' ) for row in reader: actKey = row["Series"] actVal = row["Value"] if not lastKey or lastKey != actKey: # new series starts here lastKey = actKey if tempList: # avoids result starting with [] results.append(tempList) tempList = [actVal] # this value goes into the new list continue tempList.append(actVal) # same key as last one, simply add value if tempList: results.append(tempList) # if not empty, add last ones to result print(results) Output: [['20', '40', '60'], ['16', '18', '24', '42'], ['140', '160']]
has comment: http://stackoverflow.com/comment/83604239

plaintext
tag name: plaintext
tags question: http://stackoverflow.com/q/48308012
type: Tag

mod-wsgi
tags question: http://stackoverflow.com/q/48202568
type: Tag
tags question: http://stackoverflow.com/q/48317792
tags question: http://stackoverflow.com/q/48261494
tag name: mod-wsgi
tags question: http://stackoverflow.com/q/48194777
tags question: http://stackoverflow.com/q/48308571
tags question: http://stackoverflow.com/q/48232042
tags question: http://stackoverflow.com/q/48218236

http://stackoverflow.com/comment/83438762
comment on: http://stackoverflow.com/q/48227999
type: QuestionComment
score: 0
has text: What should happen if `n=4`? Here there are not enough unique cases in `Col4`.
type: Comment

http://stackoverflow.com/a/48281299
type: Answer
score: 3
answers question: http://stackoverflow.com/q/48281034
upvote count: 3
downvote count: 0
has body: Just brake it into two lines and leave input() without a prompt: delay_print("\nGET UP? Y/N: ") GetUp = input() That way, your print will behave the way you want it and the input will read the user input unobstructed. Do not complicate your life when you don't have to ;) If you insist on doing it in a single line you have to modify the definition of delay_print by adding a return '' statement. That way, instead of the default None it will return and empty string instead. Note however, that GetUp=input(delay_print("\nGET UP? Y/N: ")) is not a very clean coding style. In my opinion that is.

http://stackoverflow.com/a/48323625
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48323523
has body: you can make a flag variable that indicates if you have already seen the line you want to write for s in Probe_Paths: with open (s) as Probe: seen = [0, 0] if "Core0: CPU utilization" in fileLine and not seen[0]: worksheet.write(row, col, int(re.sub('[^0-9]', '', fileLine))) seen[0] = 1 elif "Core1: CPU utilization" in fileLine and not seen[1]: worksheet.write(row +1, col, int(re.sub('[^0-9]', '', fileLine))) seen[1] = 1 col +=1 # have both, can stop looking in the file # will not increment col for skipped lines if all(seen): break
type: Answer
type: AcceptedAnswer
score: 2
has comment: http://stackoverflow.com/comment/83634093
accepted answer of: http://stackoverflow.com/q/48323523

http://stackoverflow.com/a/48313338
upvote count: 8
score: 8
has comment: http://stackoverflow.com/comment/83612498
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/109237899
accepted answer of: http://stackoverflow.com/q/48313301
has comment: http://stackoverflow.com/comment/83612609
answers question: http://stackoverflow.com/q/48313301
has body: list.sort uses only &lt; comparisons. This is documented. Binary operators like &lt; will try the left-hand operand's method first unless the right-hand operand's class is a subclass of the left-hand operand's class. The other operand's method will only be considered if the first method is missing or returns NotImplemented. The left-hand operand's method for &lt; is __lt__, and the right-hand operand's method is __gt__. This is also documented. Since all your list elements have the same class and __lt__ always succeeds, only the __lt__ methods end up getting called.

pyinstaller
tags question: http://stackoverflow.com/q/48179088
tags question: http://stackoverflow.com/q/48196885
tags question: http://stackoverflow.com/q/48219294
tags question: http://stackoverflow.com/q/48284853
tags question: http://stackoverflow.com/q/48310413
type: Tag
tags question: http://stackoverflow.com/q/48315785
tags question: http://stackoverflow.com/q/48248013
tags question: http://stackoverflow.com/q/48265137
tags question: http://stackoverflow.com/q/48279091
tags question: http://stackoverflow.com/q/48180551
tag name: pyinstaller
tags question: http://stackoverflow.com/q/48176087
tags question: http://stackoverflow.com/q/48204222
tags question: http://stackoverflow.com/q/48278418
tags question: http://stackoverflow.com/q/48267331

http://stackoverflow.com/comment/88580969
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48267058
has text: What version of numpy were you using? What is x in 1.14.x?

http://stackoverflow.com/comment/83494721
comment on: http://stackoverflow.com/a/48255956
has text: Most probably `not in range(10,20)` is not what you think it is.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83387458
type: QuestionComment
has text: @Rawing Trying to find a greedy solution.
comment on: http://stackoverflow.com/q/48203126
score: 0
type: Comment

http://stackoverflow.com/a/48301493
upvote count: 1
answers question: http://stackoverflow.com/q/48301323
type: Answer
has comment: http://stackoverflow.com/comment/83588489
has comment: http://stackoverflow.com/comment/83587861
has comment: http://stackoverflow.com/comment/83587775
score: 1
has body: How about using proper methods etc. instead of a mere field in the class? class First: def list(self): return [] def get_final_list(self): return self.list class Second(First): def list(self): return super().list() + ['one'] class Third(Second): def list(self): return super().list() + ['two'] Then you can: Third().list() # returns ['one', 'two']
downvote count: 0

http://stackoverflow.com/comment/83683952
comment on: http://stackoverflow.com/q/48330101
has text: The expected result is correct, however, the 'value>5' looks like have syntax error
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48301542
accepted answer: http://stackoverflow.com/a/48302002
tagged with: branch
favorite count: 0
type: Question
tagged with: git-branch
has comment: http://stackoverflow.com/comment/83587982
has body: Is there a Python way to run git log command to fetch details of repository without cloning it? I want to run commands on bitbucket server to find all activities of a repository.
has title: Python way to run git log command to fetch details of repository without cloning it
answer count: 1
has answer: http://stackoverflow.com/a/48302002
tagged with: python
tagged with: git
has comment: http://stackoverflow.com/comment/83587822
tagged with: bitbucket
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/83501704
score: 0
comment on: http://stackoverflow.com/q/48259500
type: QuestionComment
has text: If you're looking for efficiency, regex should be thrown! You should look at a solution with `str.startswith`.
type: Comment

http://stackoverflow.com/q/48191062
score: 0
accepted answer: http://stackoverflow.com/a/48196206
has body: I have the following button event handler: def select_source_folder(self, event): with wx.DirDialog(self.panel,message="Choose Source Directory" style=wx.DD_DEFAULT_STYLE): if wx.DirDialog.ShowModal() == wx.ID_CANCEL: pass I was reading on this page about wx.FileDialog and in the example it uses the with statement. I'm aware I'm using wx.DirDialog but is it possible to use the with statement with wx.DirDialog? I get the following error when I try my code: TypeError: DirDialog.ShowModal(): first argument of unbound method must have type 'DirDialog' From this page, it seems I would have t close and clean it up manually.
tagged with: modal-dialog
answer count: 1
tagged with: wxpython
type: Question
tagged with: python-3.x
has title: Possible to use with statement with wx.DirDialog()
has answer: http://stackoverflow.com/a/48196206
tagged with: python
linked to: http://stackoverflow.com/q/19790010
type: AnsweredQuestion

http://stackoverflow.com/comment/83479509
comment on: http://stackoverflow.com/a/48248460
score: 0
type: Comment
type: AnswerComment
has text: @vinodbhandary, do you expect us to type your data set manually from those pictures in order to try to help you? ;-)

http://stackoverflow.com/q/48207377
answer count: 1
has body: I wrote the following script that allows me to set the amount of sensors and the amount of bulk inserts for them. Each bulk insert gets a different epoch time. Each sensor insert gets a different value + different tag (temp) value. Kairos version: root@ip-172-16-0-147:~# echo "version" | nc -w 30 localhost 4242 KairosDB 1.2.0-0.3beta.20171211170411 Scylla (Backend Storage) version: [centos@ip-172-16-0-128 ~]$ scylla --version 2.0.2-0.20171201.07b039f The problem: Only the 1st bulk is inserted into Kairos, the other bulks are just ignored and I can't figure out why. Any ideas as to why, or how to correct the script are appreciated. The script: import socket import time import random s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("[Kairos_IP]", 4242)) start_time = time.time() lowerRange = 1 upperRange = 5 sensor_amount = 10 sensors = [] for x in range(lowerRange, upperRange): str="" curr_epoch = time.time() #curr_epoch = int(time.time() * 1000) time.sleep(1) for y in range(1,sensor_amount): statement = "put SENSOR_%d %d %d temp=%d\n" %(y,curr_epoch,random.randint(1,500),random.randint(1,500)) sensors.append(statement) str+=(sensors[y-1]) print statement s.send(str) print curr_epoch print("--- %s seconds ---" % (time.time() - start_time)) Example of output: put SENSOR_1 1515672684 240 temp=500 put SENSOR_2 1515672684 279 temp=403 put SENSOR_3 1515672684 380 temp=376 put SENSOR_4 1515672684 59 temp=38 put SENSOR_5 1515672684 405 temp=46 put SENSOR_6 1515672684 61 temp=255 put SENSOR_7 1515672684 19 temp=21 put SENSOR_8 1515672684 246 temp=80 put SENSOR_9 1515672684 289 temp=233 1515672684.72 put SENSOR_1 1515672685 58 temp=12 put SENSOR_2 1515672685 245 temp=199 put SENSOR_3 1515672685 492 temp=220 put SENSOR_4 1515672685 185 temp=432 put SENSOR_5 1515672685 235 temp=416 put SENSOR_6 1515672685 218 temp=297 put SENSOR_7 1515672685 378 temp=3 put SENSOR_8 1515672685 317 temp=397 put SENSOR_9 1515672685 103 temp=229 1515672685.72 put SENSOR_1 1515672686 …
has answer: http://stackoverflow.com/a/48210386
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/48210386
tagged with: python
tagged with: kairosdb
has title: Python script to inject bulks into KairosDB - only 1st bulk inserted, the rest ignored
type: AnsweredQuestion

http://stackoverflow.com/a/48229094
has body: It isn't pretty but it is a solution that covers your above stipulations, I believe. We can split the DataFrames using split_array form numpy. See this post for more details on it. import numpy as np df = pd.DataFrame({'D': 'a a a b b b c c c c c c'.split(' '), 'A': range(12)}) n = 3 # here we count the nth position of the the 'D' categorical df = df.assign(ranked=lambda df: df.groupby('D').transform(lambda x: x.rank())) # we now filter into two dfs: one df with evenly distributed columns Ds # and one with all the left overs where ranked &gt; n df1 = df.loc[lambda x: x.ranked&lt;=n, :].sort_values('ranked') df2 = df.loc[lambda x: x.ranked&gt;n, :].sort_values('ranked') # split them as mentioned before df1_list = np.array_split(df1, n) df2_list = np.array_split(df2, n) #zip the lists of them back together and join df1 and df2 chunks list_of_chunked_dfs = [pd.concat(df).drop('ranked', axis=1) for df in zip(df1_list, df2_list)]
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48227999

http://stackoverflow.com/a/48265187
answers question: http://stackoverflow.com/q/48264284
downvote count: 0
upvote count: 1
score: 1
has body: Handcraft-solution Here is the pseudo-code of a rather hand-crafted solution: def classifier_predict(input_features): # do something smart, but maybe too time-consuming return result def input_generator(): # Generate something random which classifier_predict # can work on - don't measure this time! return input_features class Agents(unittest.TestCase): def test_classifier_predict(): nb_tests = 1000 total_time = 0.0 for _ in range(nb_tests): input_ = input_generator() t0 = time.time() classifier_predict(input_) t1 = time.time() total_time += t1 - t0 self.assertLessEqual(total_time / nb_tests, 100) Drawbacks No nice graphs (like pytest-benchmark seems to generate) In general, hard limits might be difficult due to different hardware and also due to different external work load
type: Answer

http://stackoverflow.com/comment/83641940
type: AnswerComment
has text: Thanks for the info! I didn't realize that it bound it to the variables definition at the time of creation. I was kinda assuming it did your if clause under the hood :(
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48326891

http://stackoverflow.com/a/48236620
type: Answer
has body: def removeDuplicates(arr, n): if n == 0 or n == 1: return n temp = list(range(n)) j = 0; for i in range(0, n-1): if arr[i] != arr[i+1]: temp[j] = arr[i] j += 1 temp[j] = arr[n-1] j += 1 for i in range(0, j): arr[i] = temp[i] return j To call: lst = [1,1,2] removeDuplicates(lst, len(lst))
answers question: http://stackoverflow.com/q/48236576
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/72285925
type: Answer
has body: In my case I made a typo mistake. I wrote field instead of fields
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48282599

http://stackoverflow.com/comment/83658418
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48323639
has text: thanks! I have added a minimal input validation to check for nans. Nice and fast solution anyway
type: Comment

http://stackoverflow.com/q/48325521
has comment: http://stackoverflow.com/comment/83640597
has comment: http://stackoverflow.com/comment/83640795
has comment: http://stackoverflow.com/comment/83639121
has title: Not able to click on drop down option in a ajax webpage using selenium python
has answer: http://stackoverflow.com/a/48327806
answer count: 4
has comment: http://stackoverflow.com/comment/83640630
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83640056
has comment: http://stackoverflow.com/comment/83637599
tagged with: onclick
upvote count: 1
has body: I am able to click on the drop down heading but not able to click on the options. Also I am not able to identify the 'id' or xpath for options which is visible after clicking the dropdown option. Find the HTML below: <div role="menu" aria-label="1" class="font89" style="padding-left: 0px; cursor: pointer; position: absolute; left: 0px; color: rgb(126, 126, 126); width: 43px; height: 20px; line-height: 20px; background: transparent;" onclick="plw.menu.click(this,351,0,"1",true);" onmouseenter="plw.menu.over(event,this,351,0,"1");this.style.color="rgb(174,174,174)";this.style.backgroundColor="rgb(255,255,255)"" onmouseleave="plw.menu.out(351);this.style.background="transparent";this.style.color="rgb(126,126,126)";"> New Below is my selenium code: new_create = WebDriverWait(driver, 40).until( EC.presence_of_all_elements_located((By.XPATH, '/html/body/div[2]/div[2]/div[5]/div/div/div/div'))) driver.find_element_by_id("object260310").click() #its working fine till here driver.find_element_by_xpath(".//*[contains(@onclick, '231')]").click() #This line doesnt seems to work. And here is a screenshot of the site.
has answer: http://stackoverflow.com/a/48353961
tagged with: selenium
has comment: http://stackoverflow.com/comment/83636727
downvote count: 1
has comment: http://stackoverflow.com/comment/83640310
favorite count: 0
type: Question
tagged with: ajax
has answer: http://stackoverflow.com/a/48325645
possible better answer: http://stackoverflow.com/a/48325645
has comment: http://stackoverflow.com/comment/83638693
has comment: http://stackoverflow.com/comment/83640180
has answer: http://stackoverflow.com/a/48329285
has comment: http://stackoverflow.com/comment/83639209
accepted answer: http://stackoverflow.com/a/48353961
tagged with: python

http://stackoverflow.com/comment/83381299
type: AnswerComment
comment on: http://stackoverflow.com/a/48183359
has text: Don't change the xpath, use the one I have provided. The xpath should work, I have executed the program on my machine and it worked.Why did you tweak the Xpath?
type: Comment
score: 0

http://stackoverflow.com/comment/83548280
type: Comment
has text: no, apply_async() has the same effect if called within a task as without- it sends a message to the task queue to schedule a job on the next available worker. It WOULD mean that you can't use results of 'a' to track completion of 'c', if you were relying on the celery results api you would have to pass back the task id of the spawned tasks. (however, I have also never used the results api, instead relying on logging and the signals generated by the tasks in the data stores)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48272645

amazon-vpc
type: Tag
tag name: amazon-vpc
tags question: http://stackoverflow.com/q/48286457

http://stackoverflow.com/q/48220279
downvote count: 0
has title: Why do tuples in a list comprehension need parentheses?
duplicate of: http://stackoverflow.com/q/60986850
has answer: http://stackoverflow.com/a/48220412
has answer: http://stackoverflow.com/a/61013005
tagged with: tuples
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48220412
accepted answer: http://stackoverflow.com/a/48220426
tagged with: python
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/48220426
favorite count: 0
tagged with: python-3.x
tagged with: python-2.7
linked to: http://stackoverflow.com/q/60986850
upvote count: 8
score: 8
has body: It is well known that tuples are not defined by parentheses, but commas. Quote from documentation: A tuple consists of a number of values separated by commas Therefore: myVar1 = 'a', 'b', 'c' type(myVar1) # Result: &lt;type 'tuple'&gt; Another striking example is this: myVar2 = ('a') type(myVar2) # Result: &lt;type 'str'&gt; myVar3 = ('a',) type(myVar3) # Result: &lt;type 'tuple'&gt; Even the single-element tuple needs a comma, and parentheses are always used just to avoid confusion. My question is: Why can't we omit parentheses of arrays in a list comprehension? For example: myList1 = ['a', 'b'] myList2 = ['c', 'd'] print([(v1,v2) for v1 in myList1 for v2 in myList2]) # Works, result: [('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')] print([v1,v2 for v1 in myList1 for v2 in myList2]) # Does not work, result: SyntaxError: invalid syntax Isn't the second list comprehension just syntactic sugar for the following loop, which does work? myTuples = [] for v1 in myList1: for v2 in myList2: myTuple = v1,v2 myTuples.append(myTuple) print myTuples # Result: [('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')]
answer count: 3

http://stackoverflow.com/a/48213424
accepted answer of: http://stackoverflow.com/q/48210900
has comment: http://stackoverflow.com/comment/83410152
has body: The key is to pass the right arguments to the method. Let's have a closer look at the error you're getting in the first place: TypeError: unbound method do_something() must be called with OtherPerson #instance as first argument (got nothing instead) When you look at OtherPerson.do_something, it's clear that it's expecting an instance as its first parameter. So now p.do_something refers to OtherPerson.do_something, it needs that first parameter. Therefore, a correct call, in the current state, would be: p.do_something(p) Of course, this is not really nice, since you have to specify the instance twice. That's because the method is now unbound: it does not know of the instance on which it is called, ie it does not know self. The solution I'm proposing consists in making p.do_something refer to a function that calls OtherPerson.fo_something with p as first argument. Let's have two classes, Foo and Bar, defined as follow: class Foo: def __init__(self, x): self.x = x def speak(self): print("Foo says:", self.x) class Bar: def __init__(self, x): self.x = x def speak(self): print("Bar says:", self.x) Suppose you have a foo instance from the Foo class. Now, you want to dynamically override its speak method, so that it calls Bar's instead. You can simply reassign foo.speak to a function that calls Bar.speak. &gt;&gt;&gt; foo = Foo(2) &gt;&gt;&gt; foo.speak() Foo says: 2 &gt;&gt;&gt; foo.speak = lambda: Bar.speak(foo) &gt;&gt;&gt; foo.speak() Bar says: 2 You can make it even more generic. For the sake of example, let's write a function that takes an instance, a method name, and a target class, and overrides the instance's matching method with the target class': def override(instance, method_name, target_class): class_method = getattribute(target_class, method_name) def new_method(*args, **kwargs): return class_method(instance, *args, **kwargs) setattribute(instance, method_name, new_method) You can observe the same expected behaviour: &gt;&gt;&gt; foo = Foo(2) &gt;&gt;&gt; over…
answers question: http://stackoverflow.com/q/48210900
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83416590
has comment: http://stackoverflow.com/comment/83411244
has comment: http://stackoverflow.com/comment/83442468
type: Answer

http://stackoverflow.com/a/48204797
has body: According to the documentation you can set the permission on directory with: os.makedirs(folder, mode=0o777) Beware that mode is not string but octal
has comment: http://stackoverflow.com/comment/83401487
answers question: http://stackoverflow.com/q/48202897
type: Answer
score: 0

http://stackoverflow.com/a/48244922
upvote count: 2
has body: This looks like a numpy array to me. Option 1 You can leverage np.cumsum to come up with an efficient solution. &gt;&gt;&gt; (x.cumsum(axis=0) &gt; 0).astype(int) array([[0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], [1, 0, 1, 1], [1, 0, 1, 1], [1, 0, 1, 1], [1, 0, 1, 1]]) Where x is your input. Option 2 np.maximum.accumulate by @DSM - &gt;&gt;&gt; np.maximum.accumulate(x) array([[0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], [1, 0, 1, 1], [1, 0, 1, 1], [1, 0, 1, 1], [1, 0, 1, 1]], dtype=int32) If your arrays can contain values larger than 1, add a clip call at the end. np.maximum.accumulate(x).clip(None, 1)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83472560
downvote count: 0
has comment: http://stackoverflow.com/comment/83472468
answers question: http://stackoverflow.com/q/48244794
type: Answer
accepted answer of: http://stackoverflow.com/q/48244794
has comment: http://stackoverflow.com/comment/83472567
score: 2

http://stackoverflow.com/comment/83400759
type: AnswerComment
comment on: http://stackoverflow.com/a/48209068
has text: Now I understand, thx! (By the way: there has to be a minus between the first and second term: `Tₙ(x) = 2xTₙ₋₁(x) - Tₙ₋₂(x)` in the last line `return 2 * x * T(n-1) - T(n-2)` instead of the plus, like you mentioned correctly in your text above ;)
type: Comment
score: 0

http://stackoverflow.com/a/48251097
downvote count: 0
has body: df.groupby(pd.cut(df['Age'], bins=[0, 35, np.inf]))['Days'].mean() Out: Age (0.0, 35.0] 4.000000 (35.0, inf] 4.666667 Name: Days, dtype: float64
has comment: http://stackoverflow.com/comment/83485189
has comment: http://stackoverflow.com/comment/83485385
answers question: http://stackoverflow.com/q/48251058
type: Answer
has comment: http://stackoverflow.com/comment/83485716
score: 2
has comment: http://stackoverflow.com/comment/83485213
has comment: http://stackoverflow.com/comment/83484656
has comment: http://stackoverflow.com/comment/83485153
upvote count: 2

http://stackoverflow.com/comment/83574051
type: QuestionComment
has text: You should provide a [Minimum, Complete and Verifiable Example](https://stackoverflow.com/help/mcve). This way it is easier for people to be able to help you. I would guess you have a problem with your coordinate system. You could try creating your image of the desired size and then moving it to the specified position, [e.g.](https://stackoverflow.com/a/48292064/7675174)
type: Comment
comment on: http://stackoverflow.com/q/48292594
score: 1

http://stackoverflow.com/comment/83612877
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48313205
has text: @umutto there are roughly 25k training examples and am using a validation split of .25. I have used dropout in some of the more complex models that I have created but purposefully left it out here in the name of simplicity. I am going to play with the random forest approach now and will update with any new information.

http://stackoverflow.com/q/48313837
has body: I am trying to extend a class that contains member variables that are objects. Is it possible to create/modify the member variable that is itself an object? See my example below...hopefully that will clarify things: class C1(object): def __init__(self): self.x1 = 100 self.y1 = 100 self.z1 = 100 class C2(object): def __init__(self): self.v2 = 200 self.obj = C1() class C3(C2): def __init__(self): super(C3, self).__init__() # Here I'm adding a member variable a1 self.a1 = "A1" # Want to do something like below, # but this results in an error self.obj.x3 = 200 c = C3() In my real case, I am doing an import of what is effectively class C1 and C2. I need some way to customize/extend the member variable obj in C2.
has comment: http://stackoverflow.com/comment/83613802
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83613866
has comment: http://stackoverflow.com/comment/83614149
tagged with: python
has title: How do I customize an extended python class containing an object?
tagged with: python-2.7
score: 0
answer count: 0
type: Question

http://stackoverflow.com/comment/135335398
comment on: http://stackoverflow.com/a/48317553
has text: @tomasantunes I've updated them. Thanks for pointing out.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83487428
score: 0
comment on: http://stackoverflow.com/a/48251641
type: Comment
type: AnswerComment
has text: Go team! Congrats. And stay away from Excel, especially their stats and regression modules are abysmal.

http://stackoverflow.com/a/48260074
has comment: http://stackoverflow.com/comment/83507048
has comment: http://stackoverflow.com/comment/83510222
has comment: http://stackoverflow.com/comment/83503562
type: Answer
has body: Depending on how varied the junk is you could use regex to clean up the content. import re dirty = "Samsung SM-G930F Fekete - BLACK" regex = "^.+-([A-Z]{1}[0-9]{3}).+$" m = re.search(regex, dirty) print(m.group(1)) Something like that would give you your "G930".
has comment: http://stackoverflow.com/comment/83503218
has comment: http://stackoverflow.com/comment/83503732
score: 0
answers question: http://stackoverflow.com/q/48259883
has comment: http://stackoverflow.com/comment/83504650
has comment: http://stackoverflow.com/comment/83507411
has comment: http://stackoverflow.com/comment/83507997
has comment: http://stackoverflow.com/comment/83503980
has comment: http://stackoverflow.com/comment/83507632
has comment: http://stackoverflow.com/comment/83504147

http://stackoverflow.com/comment/83334000
type: AnswerComment
comment on: http://stackoverflow.com/a/48175011
has text: Which URL do you get the 404 for?
type: Comment
score: 0

http://stackoverflow.com/q/48209453
favorite count: 0
type: Question
answer count: 2
tagged with: lazy-loading
possible better answer: http://stackoverflow.com/a/48209926
has answer: http://stackoverflow.com/a/48209926
tagged with: python
accepted answer: http://stackoverflow.com/a/48209618
tagged with: lazy-evaluation
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48209618
linked to: http://stackoverflow.com/q/610883
score: 1
downvote count: 0
has body: Python beginner here. I currently have some code that looks like a=some_file_reading_function('filea') b=some_file_reading_function('fileb') # ... if some_condition(a): do_complicated_stuff(b) else: # nothing that involves b What itches me is that the load of 'fileb' may not be necessary, and it has some performance penalty. Ideally, I would load it only if b is actually required later on. OTOH, b might be used multiple times, so if it is used once, it should load the file once for all. I do not know how to achieve that. In the above pseudocode, one could trivially bring the loading of 'fileb' inside the conditional loop, but in reality there are more than two files and the conditional branching is quite complex. Also the code is still under heavy development and the conditional branching may change. I looked a bit at either iterators or defining a class, but (probably due to my inexperience) could not make either work. The key problem I met was to load the file zero times if unneeded, and only once if needed. I found nothing on searching, because "how to load a file by chunks" pollutes the results for "file lazy loading" and similar queries. If needed: Python 3.5 on Win7, and some_file_reading_function returns 1D- numpy.ndarray 's.
upvote count: 1
has title: Python define variable as "load file at first use"

http://stackoverflow.com/q/48251056
type: Question
tagged with: if-statement
has body: I am new to Python programming. I want to display a number based on the input code. The below code shows four irrespective of the entered code. from Tkinter import* from math import* root = Tk() root.title('Barcode Reader') #title of code text1 = StringVar() #initiate text1 text1.set('0') #initiate text1 entry=Entry(root) #entry widget entry.pack() def check(): if entry.get() == 0011: # entered code print(entry.get()) text1.set('2') # corresponding value for 0011 elif entry.get() == 0100: text1.set('3') # corresponding value for 0100 else: text1.set('4') button=Button(root, text='check', command=check) #button definition button.pack() label=Label(root, textvariable=text1) #label to display result label.pack() mainloop()
has comment: http://stackoverflow.com/comment/83565455
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83484672
tagged with: tkinter
has answer: http://stackoverflow.com/a/48251138
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83577530
has title: Difficulty in getting value out of if -else loop in python-tkinter

http://stackoverflow.com/a/48308431
has body: Firstly I think you have a concept problem: check whether the given input is a valid Hostname or valid IP or none of them either You can check if the IP is valid using the RFCs for IPv4 and IPv6 but you can never discard a hostname because xyz can be reachable within you LAN and not from the internet. Also I don't know python very well but it seems that your code is generating an exception that must be caught with a try-catch block.
type: Answer
answers question: http://stackoverflow.com/q/48308202
score: 0

http://stackoverflow.com/comment/83575374
comment on: http://stackoverflow.com/q/48295381
score: 1
type: Comment
has text: `[item for item in L if item[1] in ["one", "two"]]`
type: QuestionComment

http://stackoverflow.com/q/48278038
score: 0
tagged with: ansible
has body: I'm trying to 12-factor my django settings by passing environment variables from ansible. My problem is that I don't know how to pass the variables host1 and host2 from an ansible yaml file, so that MYSETTING is a python list, not a string. I'm trying to get: MYSETTING = ['host1', 'host2'] # this should be a list, not a string I have tried various options in ansible, but they both seem to result in MYSETTING being a string: # settings.py MYSETTING = os.environ.get(ANSIBLE_VALUE, []) # ansible vars file ANSIBLE_VALUE: "['host1', 'host2']" or # settings.py MYSETTING = [os.environ.get(ANSIBLE_VALUE, None)] # ansible vars file ANSIBLE_VALUE: "'host1', 'host2'" but neither option seems to work. I'm sure there is something simple, but I can't figure it out.
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48278396
tagged with: django
tagged with: python
has title: build python list from ansible list of values
accepted answer: http://stackoverflow.com/a/48278357
possible better answer: http://stackoverflow.com/a/48278396
has answer: http://stackoverflow.com/a/48278357
type: AnsweredQuestion

http://stackoverflow.com/comment/83596970
type: Comment
has text: Do you need a sparse matrix result? Dense array construction is nearly always faster, but does hit memory limits sooner.
type: QuestionComment
comment on: http://stackoverflow.com/q/48303879
score: 1

http://stackoverflow.com/comment/83631071
score: 0
type: QuestionComment
has text: I edited the post.
comment on: http://stackoverflow.com/q/48322722
type: Comment

http://stackoverflow.com/comment/83402324
comment on: http://stackoverflow.com/a/48209997
type: AnswerComment
has text: Note, this is valid in python2. In python3, the type of all inputs is a string and you need to explicitly construct the number.
type: Comment
score: 0

http://stackoverflow.com/q/48200837
has title: pandas rolling mean didn't work for my time data series
answer count: 1
has comment: http://stackoverflow.com/comment/83382842
tagged with: python
has comment: http://stackoverflow.com/comment/83382969
has comment: http://stackoverflow.com/comment/83382801
type: Question
has comment: http://stackoverflow.com/comment/83383353
linked to: http://stackoverflow.com/q/40060842
has comment: http://stackoverflow.com/comment/83383343
has comment: http://stackoverflow.com/comment/83383321
accepted answer: http://stackoverflow.com/a/48206157
type: AnsweredQuestion
tagged with: moving-average
score: 0
has answer: http://stackoverflow.com/a/48206157
has body: I'm writing a moving average function on time series: def datedat_moving_mean(datedat,window): #window is the average length datedatF = pandas.DataFrame(datedat) return (datedatF.rolling(window).mean()).values The code above is copied from Moving Average- Pandas The I apply this function to this time series: datedat1 = numpy.array( [ pandas.date_range(start=datetime.datetime(2015, 1, 30),periods=17), numpy.random.rand(17)]).T However, datedat_moving_mean(datedat1,4) just return the original datedat1. It moving averaged nothing! What's wrong?
has comment: http://stackoverflow.com/comment/83382958
tagged with: pandas

http://stackoverflow.com/comment/83514824
comment on: http://stackoverflow.com/q/48265821
has text: Are you saying you have some asynchronous signal that is going on and off and you have to catch it when it is on? The only reliable way to read it would be to use interrupts and/or DMA/FIFO.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48308743
has comment: http://stackoverflow.com/comment/83603053
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/83603077
upvote count: 0
accepted answer: http://stackoverflow.com/a/48309142
has answer: http://stackoverflow.com/a/48309142
has comment: http://stackoverflow.com/comment/83602996
downvote count: 1
has title: performing just one iteration of a function using python
type: Question
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/83603146
has body: I have a function, but for testing purposes, I would like to run it just once and not have it iterate through the whole dataset. My code looks as follows: def issue_ago(date): today = datetime.today() if type(date) == str: date = datetime.strptime(date, '%Y-%m-%d %H:%M:%S.%f') print date epoch = datetime(1970, 1, 1) diff = today - date date = diff.days /365.25 return date else: return date I am then running this across a column in my dataset to convert a date using the below code. The column in my dataset is a series: data['Issue_Ago'] = data['issue_created_on'].apply(issue_ago) I was considering using a ˋbreakˋ clause but that it seems requires use of a ˋforˋ loop. What would be recommendations on the best way to do this?
has answer: http://stackoverflow.com/a/48309208
has comment: http://stackoverflow.com/comment/83603581
tagged with: break
tagged with: python
has comment: http://stackoverflow.com/comment/83603365
has comment: http://stackoverflow.com/comment/83602995
possible better answer: http://stackoverflow.com/a/48309208
type: AnsweredQuestion

http://stackoverflow.com/a/48257232
accepted answer of: http://stackoverflow.com/q/48257080
type: Answer
answers question: http://stackoverflow.com/q/48257080
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: To identify the Email address and Password fields the Locator Strategy which you have used looks brittle. You have to adopt a Locator Strategy which uniquely identifies the Email address and Password field through any of the following code blocks : css_selector : username = driver.find_element_by_css_selector("input.form-control.input-sm.snl-widgets-input-text.snl-selectable.action[name=username]") password = driver.find_element_by_css_selector("input.form-control.input-sm.snl-widgets-input-text.snl-selectable.action[name=password]") username.send_keys('user') password.send_keys('pass') xpath : username = driver.find_element_by_xpath("//input[@class='form-control input-sm snl-widgets-input-text snl-selectable action' and @name='username']") password = driver.find_element_by_xpath("//input[@class='form-control input-sm snl-widgets-input-text snl-selectable action' and @name='password']") username.send_keys('user') password.send_keys('pass')

http://stackoverflow.com/q/48298389
tagged with: python
has body: In python, I am trying to cast a Tensorflow placehoder of type tf.float32 to tf.string. The converse is possible through tf.to_float(), however there is no to_string... Trying: resample_multiplier_ = tf.placeholder(tf.float32, [], name='resample_multiplier') name_ = tf.placeholder(tf.string) resample_multiplier_str_ = tf.cast(resample_multiplier_,tf.string) + name_ gives me (when I try to run the session): UnimplementedError: Cast float to string is not supported How could I convert a Tensorflow placehoder of type tf.float32?
score: 2
upvote count: 2
type: AnsweredQuestion
has title: Python Tensorflow: cast placeholder to string
downvote count: 0
tagged with: casting
has answer: http://stackoverflow.com/a/48299000
answer count: 1
accepted answer: http://stackoverflow.com/a/48299000
tagged with: string
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/a/48184545
type: Answer
has body: That's quite simple: match = re.search(r"_((\d+)_(\d+))_", your_string) print(match.group(1)) # print time_date &gt;&gt; 0800_20180101 print(match.group(2)) # print time &gt;&gt; 0800 print(match.group(3)) # print date &gt;&gt; 20180101 Note that for such tasks the group operator () inside the regexp is really helpful, it allows you to access certain substrings of a bigger pattern without having to match each one individually (which can sometimes be much more ambiguous than matching a larger one). The order in which you then access the groups is from 1-n_specified, where group 0 is the whole matched pattern. Groups themselves are assigned from left to right, as defined in your pattern. On a side note, if you have control over it, use unix timestamps so you only have one number defining both date and time universally.
has comment: http://stackoverflow.com/comment/83349042
upvote count: 5
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/48184487

http://stackoverflow.com/a/48235478
has comment: http://stackoverflow.com/comment/83465104
type: Answer
has comment: http://stackoverflow.com/comment/83489130
has comment: http://stackoverflow.com/comment/83488608
has comment: http://stackoverflow.com/comment/83460944
has body: You should using axis=1 rather than 0 . from sklearn.preprocessing import Imputer mean_imputer_y = Imputer(strategy="mean", axis=1,missing_values=np.nan) mean_imputer_y.fit_transform(df.Val) array([[13495. , 16500. , 16500. , 13950. , 17450. , 15250. , 17710. , 18920. , 23875. , 18117.5, 16430. , 16925. , 20970. , 21105. , 24565. ]])
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48235420
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48235420

http://stackoverflow.com/a/48265938
has comment: http://stackoverflow.com/comment/83515057
answers question: http://stackoverflow.com/q/48265827
has body: Dictionaries (like all built-in containers) are represented with their contents shown as representations, essentially using the repr() function on each. For strings, those are meant to be as helpful as possible in that they are shown as string literals that can simply be copied and pasted to recreate their value. That means they also show unprintable characters or characters with special meaning as escape sequences. Your newline characters are just such characters. In other words, you can't do what you want just by inserting \n characters in the string values. Instead, you need to do your own formatting if you really want to show your dictionary that way. Just print out the keys and values yourself: def represent_dict(d): print('{', end='') # no newline first = True for key, value in d.items(): # newline at the start, not end, with commas print('{}\n{!r}: {!r}'.format('' if first else ',', key, value), end='') first = False print('}') # closing with a brace and a newline Remove the \n addition in your reading code; it can be simplified to just produce the dictionary directly with a dictionary comprehension: def read_dictionary(): with open("text.tsv") as tsvfile: tsvreader = csv.reader(tsvfile, delimiter = "\t") return {row[0]: row[1:] for row in tsvreader} represent_dict(read_dictionary()) You generally should keep presentation and data structure separate. Those newlines in the keys can easily cause issues elsewhere, and they are only there for the presentation output. Demo of the output: &gt;&gt;&gt; dictionary = {"string1":["a","b","c"], "string2":["d","e","f"], ... "string3":["g","h","i"], "string4":["j","k","l"]} &gt;&gt;&gt; represent_dict(dictionary) { 'string1': ['a', 'b', 'c'], 'string2': ['d', 'e', 'f'], 'string3': ['g', 'h', 'i'], 'string4': ['j', 'k', 'l']}
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48265827
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/83454486
has text: Interesting question... are your values (e.g., `1, 2, 3, 4`) an index, or values in the df? Specifically, are you trying to replace some values, or replace parts of the index?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48235513

http://stackoverflow.com/q/48263875
has answer: http://stackoverflow.com/a/48265525
accepted answer: http://stackoverflow.com/a/48263967
has body: I have a dictionary that consists of numbers and their value dict = {1:5, 2:5, 3:5} I have an array with some numbers arr = [1,2] What I want to do is: iterate through the dict and the array where the dictionary value is equal to the number in the array, set the dictionary value to zero any value in the dictionary for which there isn't a value in the array matching it, add 1 so in the above example, I should end up with arr = [1,2] dict = {1:0, 2:0, 3:6} The bit I am getting stuck on is creating a variable from the array value and accessing that particular number in the dictionary - using dict[i] for example
tagged with: loops
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
score: 0
has answer: http://stackoverflow.com/a/48264057
possible better answer: http://stackoverflow.com/a/48263950
has answer: http://stackoverflow.com/a/48263950
tagged with: python
tagged with: dictionary
answer count: 4
has answer: http://stackoverflow.com/a/48263967
has comment: http://stackoverflow.com/comment/83510730
type: AnsweredQuestion
has title: python iterate through an array and access the same value in a dictionary
tagged with: arrays

http://stackoverflow.com/comment/83458083
type: QuestionComment
comment on: http://stackoverflow.com/q/48233950
score: 0
type: Comment
has text: I am not a professional. I will be happy if you can provide a link where I can know more about it. @Sean Francis N. Ballais 9

http://stackoverflow.com/a/48201483
has comment: http://stackoverflow.com/comment/83386378
has comment: http://stackoverflow.com/comment/83386226
type: Answer
score: 4
answers question: http://stackoverflow.com/q/48201454
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48201454
has comment: http://stackoverflow.com/comment/83385099
has body: Option 1 You can do it like this, using str.contains - df.loc[df.Name.str.contains(r'\w[nk]\w'), 'Name'].tolist() ['Mike', 'Anna', 'Luke'] Details First, the regex - \w # any alpha-numeric char [nk] # character class; letters "n" and "k" \w # any alpha-numeric char This ensures that, if the word begins or ends with "n" or "k" (without containing them in the middle of the word), it is not picked up ("n" or "k" have to have something on either side). A similar regex, to match any surrounding character (besides alphanumeric characters) would be - r'.[nk].' Or, if you want a regex that matches a string with "n" or "k" in the middle and anything but "n" and "k" at the ends, use - r'^[^nk].*[nk].*[^nk]$' Output of the str.contains call - df.Name.str.contains(r'\w[nk]\w') 0 True 1 False 2 False 3 True 4 True 5 False 6 False Name: Name, dtype: bool Output of the slicing operation with loc - df.loc[df.Name.str.contains(r'\w[nk]\w'), 'Name'] 0 Mike 3 Anna 4 Luke Name: Name, dtype: object Now, calling pd.Series.tolist gives you your list of names. Option 2 Another option using str.findall - df.Name.str.findall(r'^.*\w[nk]\w.*$').str[0].dropna().tolist() ['Mike', 'Anna', 'Luke'] Which works similar to the first, with some differences. Details First, the output of the findall call - a list of matches. The regex pattern is the same as above, but modified slightly to capture the entire string if the pattern in the middle is found. df.Name.str.findall(r'^.*\w[nk]\w.*$') 0 [Mike] 1 [] 2 [] 3 [Anna] 4 [Luke] 5 [] 6 [] Name: Name, dtype: object Get the first element from each list. Empty lists return NaNs, which are subsequently dropped - df.Name.str.findall(r'.*\w[nk]\w.*').str[0].dropna() 0 Mike 3 Anna 4 Luke Name: Name, dtype: object From there, convert to list with pd.Series.tolist.
has comment: http://stackoverflow.com/comment/83386102
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83386311
downvote count: 0

http://stackoverflow.com/comment/83529620
has text: tnx mate, cheerz!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48272798

http://stackoverflow.com/q/48192836
has answer: http://stackoverflow.com/a/48193256
tagged with: pandas
score: 3
upvote count: 3
tagged with: matplotlib
has body: I am trying to make a line plot in which every one of the elements from the index appears as an xtick. import pandas as pd ind = ['16-12', '17-01', '17-02', '17-03', '17-04', '17-05','17-06', '17-07', '17-08', '17-09', '17-10', '17-11'] data = [1,3,5,2,3,6,4,7,8,5,3,8] df = pd.DataFrame(data,index=ind) df.plot(kind='line',x_compat=True) however the resultant plot skips every second element of the index like so: My code to call the plot includes the (x_compat=True) parameter which the documentation for pandas suggests should stop the auto tick configuratioin but it seems to have no effect.
answer count: 1
has title: Pandas line plot suppresses half of the xticks, how to stop it?
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: plot

http://stackoverflow.com/comment/83488960
comment on: http://stackoverflow.com/q/48253225
type: Comment
type: QuestionComment
has text: The current code can't throw this error as you aren't passing anything to `util.msg_with_time`.
score: 3

http://stackoverflow.com/comment/83526754
has text: how is this question different from your previous question about this same problem?
type: QuestionComment
comment on: http://stackoverflow.com/q/48271438
type: Comment
score: 0

amazon-web-services
tags question: http://stackoverflow.com/q/48175271
tags question: http://stackoverflow.com/q/48209088
tags question: http://stackoverflow.com/q/48244999
tags question: http://stackoverflow.com/q/48310756
tags question: http://stackoverflow.com/q/48330428
tags question: http://stackoverflow.com/q/48204861
tags question: http://stackoverflow.com/q/48214088
tags question: http://stackoverflow.com/q/48187021
tags question: http://stackoverflow.com/q/48287018
tags question: http://stackoverflow.com/q/48250426
tags question: http://stackoverflow.com/q/48308584
tags question: http://stackoverflow.com/q/48201451
tags question: http://stackoverflow.com/q/48262698
tags question: http://stackoverflow.com/q/48244172
tags question: http://stackoverflow.com/q/48325992
tags question: http://stackoverflow.com/q/48246117
tags question: http://stackoverflow.com/q/48232314
tags question: http://stackoverflow.com/q/48266106
tags question: http://stackoverflow.com/q/48286457
tags question: http://stackoverflow.com/q/48233200
tags question: http://stackoverflow.com/q/48286141
tags question: http://stackoverflow.com/q/48319496
tags question: http://stackoverflow.com/q/48194886
tags question: http://stackoverflow.com/q/48177244
tags question: http://stackoverflow.com/q/48217312
tags question: http://stackoverflow.com/q/48314268
tags question: http://stackoverflow.com/q/48325011
tags question: http://stackoverflow.com/q/48317680
tags question: http://stackoverflow.com/q/48286217
tags question: http://stackoverflow.com/q/48177836
tags question: http://stackoverflow.com/q/48290879
type: Tag
tags question: http://stackoverflow.com/q/48272415
tags question: http://stackoverflow.com/q/48177408
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/48298295
tags question: http://stackoverflow.com/q/48216379
tags question: http://stackoverflow.com/q/48241838
tags question: http://stackoverflow.com/q/48307919
tags question: http://stackoverflow.com/q/48317116
tags question: http://stackoverflow.com/q/48234398
tags question: http://stackoverflow.com/q/48250068
tags question: http://stackoverflow.com/q/48201101
tags question: http://stackoverflow.com/q/48295375
tags question: http://stackoverflow.com/q/48264656
tags question: http://stackoverflow.com/q/48207257
tags question: http://stackoverflow.com/q/48218263
tags question: http://stackoverflow.com/q/48323239
tags question: http://stackoverflow.com/q/48221591

http://stackoverflow.com/comment/83442489
has text: Replace `import m` with `__import__(m)`. Don't forget to return the loaded module and assign it in your base namespace.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48228215
score: 0

http://stackoverflow.com/comment/83482361
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48249710
type: Comment
has text: @JohnKugelman yes I know, that was the entire point of the answer, because this is a requirement of the question if we read the question's title literally. If you meant to point out that this means the second loop should also be a `while` loop instead of a `for` loop, that's correct, I missed that and just edited to fix that

http://stackoverflow.com/a/48204058
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/48203741
has comment: http://stackoverflow.com/comment/83389958
type: Answer
has comment: http://stackoverflow.com/comment/83390639
accepted answer of: http://stackoverflow.com/q/48203741
has body: In your __neg__ method, you are modifying your Matrix class in-place instead of returning a new one, you can print your variables in this order to see what's happening : print I2, '\n' print -I2, '\n' print I2 It will output : 1 0 0 1 -1 0 0 -1 -1 0 0 -1 You can solve it by creating a new Matrix object in your __neg__ method, and returning it, instead of modifying the one you already have, and returning it.

http://stackoverflow.com/comment/83550282
comment on: http://stackoverflow.com/q/48283125
type: QuestionComment
score: 3
has text: I'm very lazy. Could you supply the actual data arrays to make your chart?
type: Comment

http://stackoverflow.com/comment/83605356
has text: Possible duplicate of [How can I reconnect to the browser opened by webdriver with selenium?](https://stackoverflow.com/questions/47861813/how-can-i-reconnect-to-the-browser-opened-by-webdriver-with-selenium)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48309776
score: 0

http://stackoverflow.com/q/48253844
downvote count: 1
favorite count: 0
has body: I am trying to solve the Titanic problem on Kaggle (https://www.kaggle.com/c/titanic) . I am trying to encode the column "Sex" categorically using the LabelEncoder and OneHotEncoder classes of sklearn.preprocessing library. Here is my code: # Importing data analysis libraries import pandas as pd import numpy as np import random as rnd # Importing data visualization libraries import seaborn as sns import matplotlib.pyplot as plt # Importing Machine Learning Libraries from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC, LinearSVC from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB from sklearn.linear_model import Perceptron from sklearn.linear_model import SGDClassifier from sklearn.tree import DecisionTreeClassifier # Getting the datasets train = pd.read_csv('./input/train.csv') test = pd.read_csv('./input/test.csv') combine = [train, test] # Feature visualizations g = sns.FacetGrid(train, col='Survived') g.map(plt.hist, 'Age', bins=20) grid = sns.FacetGrid(train, col='Survived', row='Pclass', size=2.2, aspect=1.6) grid.map(plt.hist, 'Age', alpha=.5, bins=20) grid.add_legend() g = sns.FacetGrid(train, col='Survived') g.map(plt.hist, 'Parch', bins=20) g = sns.FacetGrid(train, col='Survived') g.map(plt.hist, 'SibSp', bins=20) g = sns.FacetGrid(train, col='Survived') g.map(plt.hist, 'Fare', bins=20) g = sns.FacetGrid(train, col='Survived') g.map(plt.hist, 'Sex', bins=20) # taking care of missing values train.fillna(train.median(), inplace = True) # Categorising Embarked and Sex features # train['Embarked'] = train['Embarked'].map( {'S': 0, 'C': 1, 'Q': 2} ) # train['Sex'] = train['Sex'].map( {'male': 0, 'female': 1} ) # Data preprocessing X_train = train.iloc[:, [0, 2, 4, 5, 6, 7, 9]].values y_train = train.iloc[:, [1]].values X_test = test.iloc[:, [1, 3, 4, 5, 6, 8]].values from sklearn.preprocessing import Imputer, LabelEncoder, OneHotEncoder, Stan…
has title: ValueError in categorising String data
type: AnsweredQuestion
tagged with: data-analysis
has comment: http://stackoverflow.com/comment/83502758
tagged with: python
score: -1
type: Question
has comment: http://stackoverflow.com/comment/83490331
accepted answer: http://stackoverflow.com/a/48253991
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48253991
upvote count: 0
answer count: 1
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/83502631
tagged with: scikit-learn

http://stackoverflow.com/a/48377976
score: 0
accepted answer of: http://stackoverflow.com/q/48286838
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48286838
has body: Like I pointed out in my question I do not want the async stuff to bloat up my testcases. The only simple working solution I could find so far is to use multiprocessing. I understand that process.terminate() is not the "optimal way" to end the asyncio loop but at least it works reliably. # -*- coding: utf-8 -*- import time from multiprocessing import Process import pytest from my_server import server @pytest.fixture def fake_server(): p = Process(target=server.run, args=()) p.start() yield p.terminate() def test_add2(fake_server): time.sleep(30) assert m.add(1, 2) == 3
type: Answer

http://stackoverflow.com/q/48260014
has answer: http://stackoverflow.com/a/48269082
has body: I would like to replace part of my plot where the function dips down to '-1' with a dashed line carrying on from the previous point (see plots below). Here's some code I've written, along with its output: import numpy as np import matplotlib.pyplot as plt y = [5,6,8,3,5,7,3,6,-1,3,8,5] plt.plot(np.linspace(1,12,12),y,'r-o') plt.show() for i in range(1,len(y)): if y[i]!=-1: plt.plot(np.linspace(i-1,i,2),y[i-1:i+1],'r-o') else: y[i]=y[i-1] plt.plot(np.linspace(i-1,i,2),y[i-1:i+1],'r--o') plt.ylim(-1,9) plt.show() Here's the original plot Modified plot: The code I've written works (it produces the desired output), but it's inefficient and takes a long time when I actually run it on my (much larger) dataset. Is there a smarter way to go about doing this?
favorite count: 0
type: Question
upvote count: 4
tagged with: numpy
tagged with: python
has comment: http://stackoverflow.com/comment/83504369
score: 4
accepted answer: http://stackoverflow.com/a/48260915
tagged with: plot
linked to: http://stackoverflow.com/q/45176584
has answer: http://stackoverflow.com/a/48279676
has answer: http://stackoverflow.com/a/48260915
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/83503607
has title: Replacing part of a plot with a dotted line
tagged with: matplotlib
downvote count: 0
possible better answer: http://stackoverflow.com/a/48269082

http://stackoverflow.com/q/48184778
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/83349513
tagged with: recursion
has title: Python Recursion in pascal's triangle
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83349559
has comment: http://stackoverflow.com/comment/83349606
upvote count: 1
has comment: http://stackoverflow.com/comment/83349752
has comment: http://stackoverflow.com/comment/83349874
has comment: http://stackoverflow.com/comment/83349633
favorite count: 0
linked to: http://stackoverflow.com/q/24093387
type: Question
has comment: http://stackoverflow.com/comment/83349777
has body: can someone explain this code to me in detail? im trying to grasp how recursion is working here especially how previous_lines is building up as a list. I'm getting confused to the point where n==2, I wonder why it doesn't show out of array error for previous_lines[i+1] where previous_lines does not even have 2 elements when n==2 is used. I surmise that previous_lines is only [1] at n==2 def pascal(n): if n == 1: return [1] else: line = [1] previous_line = pascal(n-1) for i in range(len(previous_line)-1): line.append(previous_line[i] + previous_line[i+1]) line += [1] return line print(pascal(6))
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/24093387
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83349428

http://stackoverflow.com/a/48187502
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48186115
downvote count: 0
type: Answer
score: 4
answers question: http://stackoverflow.com/q/48186115
has body: Well, this is relatively memory-inefficient as it converts individual bits to strings, but it seems to work: import itertools def convertbits(data, From, To): bits_orig = itertools.chain.from_iterable(bin(n)[2:].zfill(From) for n in data) chunks = iter(lambda: ''.join(itertools.islice(bits_orig, To)), '') return [int(n, 2) for n in chunks] print(convertbits(b'hello', 8, 5)) print([13, 1, 18, 22, 24, 27, 3, 15]) Once you got a stream of bits of the numbers (bits_orig), it's then simple to slice this stream into chunks of equal length (chunks) (this version doesn't do padding but it's fairly simple to implement) and convert the strings of ones and zeros back to numbers. If you're working with 8-bit numbers exclusively, here's an algorithm that's 8.5(!) times faster than the one above: from collections import deque def convert8bits(data, To): number = int.from_bytes(data, 'big') ret = deque() th = (1 &lt;&lt; To) - 1 while number: ret.appendleft(number &amp; th) number &gt;&gt;= To return ret
type: AcceptedAnswer

http://stackoverflow.com/comment/83346811
type: Comment
has text: Please read [How to ask](https://stackoverflow.com/help/how-to-ask). Don't post urls to pictures. Include the pictures themselfs in the posting. Please use correct interpunction and upper case letters. Please reformulate what you really want. What is your goal. It is unclear.
type: QuestionComment
comment on: http://stackoverflow.com/q/48183073
score: 0

http://stackoverflow.com/comment/83643549
has text: No, I didn't see that it was not indented when I was writing the question.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48328882

http://stackoverflow.com/comment/83429324
has text: Can you test with `commands.getoutput('netsh advfirewall show allprofiles state').split()`
type: QuestionComment
comment on: http://stackoverflow.com/q/48223813
score: 0
type: Comment

http://stackoverflow.com/q/48313828
tagged with: dataframe
tagged with: python
tagged with: filter
tagged with: pandas
has comment: http://stackoverflow.com/comment/83616373
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48313921
answer count: 1
accepted answer: http://stackoverflow.com/a/48313921
type: Question
has body: I have 2 dataframe that are filtered df_pass = total_avg[total_avg&gt;3] produces the following dataframe AAPL GOOGL GOOG MSFT 1 3.401017 NaN NaN 3.255119 2 NaN NaN NaN NaN 3 4.16666 NaN NaN 3.264101 4 3.049794 4.331 NaN NaN I have another filter on another DF but the layout of the DF is identical to the first on. So this code produces the follow DF results df_min_pass = total_min[total_min&gt;-10] AAPL GOOGL GOOG MSFT 1 NaN NaN -2.099 NaN 2 NaN NaN -6.08 NaN 3 NaN -8.319 -1.86 -7.3 4 NaN -7.304 -6.92 NaN Keep in mind this is just a sample of the DFs. They have many more columns. I want to get a resulting dataframe that combines the do. So if it passed both condition it would give show a result in another DF otherwise show NaN if it did not meet bother conditions. I have tried a number of combinations such as df_combo_all = (df_pass[df_pass &gt;3]) &amp; (df_min_pass[df_min_pass &gt;-10]) df_combo_all = df_combo_all[(df_pass[df_pass &gt;3]) &amp; (df_min_pass[df_min_pass &gt;-10])] Individually the filters work but I keep getting this error TypeError: ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''. There seems to be multi mask questions and others on bitwise errors but I cant seem to find one that works for me. Can anyone please help
has title: filter dataframe with different masks

http://stackoverflow.com/q/48190355
answer count: 2
has body: I am using Pexpect to run a command remotely on a server and saving the output in a file. However, it does not save the whole output as it's truncated due to --More-- . Is there a way to avoid --More--, so that the whole output is saved in the output file? I have tried using child.setwinsize(1000,1000) but it didn't solve the issue. Current code: import pexpect import time child = pexpect.spawn('ssh username@ip_address') time.sleep(1) child.sendline('password') time.sleep(1) child.logfile = open("output.txt", "w") child.sendline('command') child.expect(pexpect.EOF) print child.before, child.after child.close
downvote count: 0
upvote count: 1
favorite count: 0
has title: Python Pexpect full output is not saved (How to deal with the "--More--" prompt?)
type: Question
tagged with: pexpect
accepted answer: http://stackoverflow.com/a/48198192
score: 1
possible better answer: http://stackoverflow.com/a/53881747
has answer: http://stackoverflow.com/a/48198192
tagged with: stdout
tagged with: python
has comment: http://stackoverflow.com/comment/83364399
has answer: http://stackoverflow.com/a/53881747
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/a/48299173
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48298991
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48298991
type: Answer
has body: From the documentation of pd.merge, it's an intersection, so an AND as you described: how : {‘left’, ‘right’, ‘outer’, ‘inner’}, default ‘inner’ left: use only keys from left frame, similar to a SQL left outer join; preserve key order right: use only keys from right frame, similar to a SQL right outer join; preserve key order outer: use union of keys from both frames, similar to a SQL full outer join; sort keys lexicographically inner: use intersection of keys from both frames, similar to a SQL inner join; preserve the order of the left keys
downvote count: 0

http://stackoverflow.com/q/48176774
has title: Django: path doesn't find the right primary key in url path
tagged with: django-generic-views
answer count: 1
has body: I'm using django2 and I get an error when I access this url: http://127.0.0.1:8000/hotes/12/access/7/update I get an error 404 "None access object was found" To make a long story short: I want to update an object linked to another. To do so, I have to send through the link, both primary keys (12 and 7 in the url). Also, I use the generic view "UpdateView" given by Django. This is the path concerned in my project.urls: urlpatterns = [ path('hotes/<int:pk>/access/<int:access_pk>/update/',views.AccessUpdateView.as_view(), name='access_update'), path('hotes/add',views.host_add, name='host_add'), path('hotes/<int:pk>/', include([ path('edit',views.HostUpdateView.as_view(), name='host_update'), path('delete',views.host_delete, name='host_delete'), ])), path('hotes/<int:pk>/add/', include([ path('access',views.access_add, name='access_add'), path('oncall',views.onCall_add, name='onCall_add'), path('network',views.network_add, name='network_add'), ])), path('hotes/<int:pk>/',views.host_view, name='host_view'), path('hotes/',views.hosts_view, name='hosts_view'), path('', views.home, name='home'), path('admin/', admin.site.urls), ] I want the second primary key to be used in my view "AccessUpdateView". This is a part of my models.py: class Host(models.Model): name = models.CharField(max_length=30, unique=True) usage = models.CharField(max_length=30, blank=True) function = models.CharField(max_length=30, blank=True) production = models.NullBooleanField(blank=True, null=True) place = models.CharField(max_length=30, blank=True) type = models.CharField(max_length=30, blank=True) processor = models.DecimalField(max_digits=3, decimal_places=2, null=True, blank=True) storage = models.CharField(max_length=10, blank=True) memory = models.CharField(max_length=10, blank=True) dns_inner = models.CharField(max_length=50, blank=True) dns_extern = models.CharField(max_length=50, blank=True) os = models.ForeignKey(Os, null=True, related_name='hosts', on_delete=models.SET_NULL, blank=True) cl…
tagged with: django
accepted answer: http://stackoverflow.com/a/48176806
type: Question
type: AnsweredQuestion
score: 0
tagged with: django-views
tagged with: python
has answer: http://stackoverflow.com/a/48176806
tagged with: django-forms

http://stackoverflow.com/a/48313258
has body: You could use pandas.Series.str.get_dummies. This will alllow you to split the column directly with a delimiter. df = pd.concat([df.ID, df.Values.str.get_dummies(sep=",")], axis=1) ID 1 2 3 4 0 1 1 1 0 0 1 2 0 0 1 1 df.Values.str.get_dummies(sep=",") will generate 1 2 3 4 0 1 1 0 0 1 0 0 1 1 Then, we do a pd.concat to glue to df together.
has comment: http://stackoverflow.com/comment/83612694
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48312529

http://stackoverflow.com/a/48248446
score: 2
has body: I'm assuming you don't want to load the entire JSON for performance reasons. If that's the case, perhaps ijson is what you need. I used it to search huge JSON files (>8gb) and it works well. However, you will have to implement the search code yourself.
type: Answer
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48237809

http://stackoverflow.com/comment/83349633
type: QuestionComment
comment on: http://stackoverflow.com/q/48184778
score: 0
has text: Hello, please take a time to go through the welcome tour to know your way around here , read how to create a [mcve] example and also check [ask] so you increase your chances to get feedback and useful answers.
type: Comment

http://stackoverflow.com/comment/83579016
type: QuestionComment
has text: sklearn's DBSCAN is, unfortunately, memory intensive. If you choose a too large threshold, it needs O(n²) memory. Usual implementations of DBSCAN should only use O(n) memory. However, with 300 dimensional vectors, choosing the epsilon parameter for DBSCAN *will* be difficult with any implementation. Maybe that is where your problem is, because I find ELKI to be easy to use (make sure to add an index for large data, it does not do this automatically!)
comment on: http://stackoverflow.com/q/48281026
score: 1
type: Comment

http://stackoverflow.com/comment/83478555
has text: sorry,my bad the binary tree you made is for the example which I gave but could you explain what 1 1 1 1 1 1 1 - below your B Tree diagram depicts?
type: Comment
comment on: http://stackoverflow.com/a/48245775
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83394861
has text: i will take care of it from next time.. thanks for advice @andy G
comment on: http://stackoverflow.com/a/48206957
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48180416
has body: I don't do python but if it were me, I would remove all the try/catches and replace them with find_elements_* and check for empty list. For example replace specific_element = result.find_element_by_xpath(""".//*[@class="specific"]/div""").text with elements = result.find_elements_by_xpath(".//*[@class='specific']/div") if elements specific_element = elements[0] This basically just makes sure that any element is found before accessing it and you can avoid all the try/catches. I'm of the opinion that exceptions should be exceptional... rare. They shouldn't be expected or used as flow control, etc.
type: Answer
answers question: http://stackoverflow.com/q/48179010
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/84514298
type: Comment
comment on: http://stackoverflow.com/a/48701634
type: AnswerComment
has text: Looking at the BasicDecoder code, it does look like the projection layer is applied at every decode step: https://github.com/tensorflow/tensorflow/blob/c959ec71e8a06a9a4a20fc3fce0511f4316d337d/tensorflow/contrib/seq2seq/python/ops/basic_decoder.py#L140
score: 0

http://stackoverflow.com/comment/83943923
comment on: http://stackoverflow.com/q/48237226
score: 0
type: Comment
type: QuestionComment
has text: @python_fan did you have a chance to check my answer?

http://stackoverflow.com/q/48225118
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: Bokeh table with dictionary of dictionaries
tagged with: python
tagged with: bokeh
score: 4
has answer: http://stackoverflow.com/a/48259124
upvote count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48259124
has body: I am trying to draw a table using bokeh to represent a dictionary of dictionaries, but I can't figure out how to do it. Here is my simple code: from bokeh.models import ColumnDataSource from bokeh.models.widgets import DataTable, DateFormatter, TableColumn def testTable(): data = {'position1': {'x': 0, 'y': 0, 'z': 0}, 'position2': {'x': 1.1, 'y': 2.3, 'z': 3}, 'position3': {'x': 2.9, 'y': 4.3, 'z': 3.1}} source = ColumnDataSource(data) columns = [ TableColumn(field="x", title="x"), TableColumn(field="y", title="y"), TableColumn(field="z", title="z"), ] data_table = DataTable(source=source, columns=columns, width=400, height=280) plot = column(widgetbox(data_table)) show(plot) When I run this code I get the error: ValueError: expected an element of ColumnData(String, Seq(Any)), got {'position2': {'y': 2.3, 'x': 1.1, 'z': 3}, 'position3': {'y': 4.3, 'x': 2.9, 'z': 3.1}, 'position1': {'y': 0, 'x': 0, 'z': 0}} What I would like to do is to create a table like this: x y z position1 0 0 0 position2 1.1 2.3 3 position3 2.9 4.3 3.1 What is the right way to do it? EDIT: I was able to obtain something by refactoring the input data in a different way: from bokeh.models import ColumnDataSource from bokeh.models.widgets import DataTable, DateFormatter, TableColumn from bokeh.layouts import widgetbox, column from bokeh.io import output_file, show def testTable(): data = {'InitPosition': ['position1', 'position2', 'position3'], 'x': [0,0,0], 'y': [1.1, 2.3, 3], 'z': [2.9, 4.3, 3.1]} source = ColumnDataSource(data) columns = [ TableColumn(field="InitPosition", title="Init Position"), TableColumn(field="x", title="x"), TableColumn(field="y", title="y"), TableColumn(field="z", title="z") ] data_table = DataTable(source=source, columns=columns, width=400, height=280) plot = column(widgetbox(data_table)) show(plot) if __name__ == '__main__': testTable() However the drawn table looks like this: So the new question is: how to get rid of the first automatically drawn table?

http://stackoverflow.com/comment/83482489
comment on: http://stackoverflow.com/a/48249819
score: 0
type: Comment
type: AnswerComment
has text: It was returning just the first URL. I changed it as follows: `num_options = len(driver.find_elements_by_class_name("w-dyn-item")) for i in range(num_options): tag = driver.find_elements_by_class_name("w-dyn-item")[i] tag.find_element_by_tag_name("a").click() print driver.current_url`. Now it returns around 6 URLs and then it says `IndexError: list index out of range`.

http://stackoverflow.com/comment/83456678
type: QuestionComment
score: 0
has text: This question could help you, too: https://stackoverflow.com/q/47895765/4865723 If you provide an full example I could help you more.
comment on: http://stackoverflow.com/q/48232844
type: Comment

http://stackoverflow.com/q/48265319
score: 0
has comment: http://stackoverflow.com/comment/83513873
has title: Redirecting HTTP requests to device without static/public IP
has body: I'm using a service that sends me some data from user over webhooks. If there is any user interaction on this service, it hits my URL with HTTP request, with the data in POST/GET, and then expects text/json response to show back to the user. The response has to be in few seconds, otherwise the HTTP request times out and the service has no way of finding out what should be the response to the user. The problem here is that now I'm not processing these data on my server with public IP, but I need to do it on my RPi, which keeps moving, which meains it has different IP every few hours, and mostly not public. I'm sure I will still need to use the server with public IP to redirect these requests to my RPi, and I have few ideas, but I don't know what is reliable or if it even would work. Let the API talk to my server and save the data. Then have the RPi constantly asking my server if there are any new data. Propably the dumbest idea - not ideal to use over metered connection, propably longer reply, and it will be harder to return the RPi's reply in the HTTP request made from API. Having (Python) script running on my server, that will a) serve as socket server and RPi will connect to this socket, and b) have running SimpleHTTPRequestHandler to process requests from API and send them to the socket, the reply with RPi's reply. Propably easy way to keep connection between my server and RPi, allowing me to pass data in both directions. Open SSH tunnel between the RPi and my server. This way, I could process the requests from service directly on my RPi. But how reliable is this solution? (Keeping it alive, opening the tunnel automatically, etc, propably question for superuser forum) I'm thinking of going with choice 3 if it will be possible, but first I'd like to hear what you guys think. Is this a good and reliable idea? Or are there any better ways I don't know about? Or did anybody already faced this problem? To sum it up: Something sends HTTP request to public IP. I need to…
tagged with: ssh-tunnel
type: Question
has comment: http://stackoverflow.com/comment/83513682
has comment: http://stackoverflow.com/comment/83513801
answer count: 0
type: UnansweredQuestion
tagged with: sockets
tagged with: http-redirect
tagged with: python

http://stackoverflow.com/comment/113336695
type: AnswerComment
type: Comment
has text: For completeness I will add that once you are in the Thonny System Shell you can run either "pip" or "pip3" to install the module you need. For example: "pip3 install requests" OR "pip install requests" to install the HTTP requests module.
comment on: http://stackoverflow.com/a/48338893
score: 0

http://stackoverflow.com/comment/83478631
type: Comment
comment on: http://stackoverflow.com/a/48244750
score: 0
type: AnswerComment
has text: Indeed but I don't know why I have to add `%matplotlib notebook` in the cell, it isn't working when I am using `%matplotlib notebook`at the top of my notebook

http://stackoverflow.com/a/48197696
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83377012
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83377127
downvote count: 1
has comment: http://stackoverflow.com/comment/83377172
has comment: http://stackoverflow.com/comment/83376910
accepted answer of: http://stackoverflow.com/q/48197527
type: Answer
has body: import the sys module and check sys.argv[]: import sys if len(sys.argv) &gt; 1: # sys.argv[0] == the script name so we start from index 1 for arg in sys.argv: print arg and from the command line: ~$ python my_script.py some_arg some_other_arg which outputs: ~$ my_script.py ~$ some_arg ~$ some_other_arg
answers question: http://stackoverflow.com/q/48197527

http://stackoverflow.com/comment/83614101
type: AnswerComment
has text: it shows a error: local variable 'correct_captcha' referenced before assignment
comment on: http://stackoverflow.com/a/48314183
score: 0
type: Comment

http://stackoverflow.com/comment/83441574
score: 0
comment on: http://stackoverflow.com/q/48229422
type: QuestionComment
has text: Thank you about that. It worked
type: Comment

http://stackoverflow.com/a/48218851
answers question: http://stackoverflow.com/q/48218717
type: Answer
accepted answer of: http://stackoverflow.com/q/48218717
score: 0
has body: You need to move the assignment of d2, and all the variables it depends on that could change, inside the loop. Otherwise, you're just repeatedly using the same value of d2, so of course you get the same time difference. import datetime import time date_time = datetime.datetime.now() redsent_time = '00:00:00.00' f = '%H:%M:%S.%f' tred = redsent_time d1 = datetime.datetime.strptime(tred, f) def exec_code(): counter = 0 while True: tred2 = date_time.time() tred3 = str(tred2) #converts tred2 into a sting value instead of a command d2 = datetime.datetime.strptime(tred3, f) if ((d2-d1).total_seconds()) &gt;= 1: counter += 1 print((d2-d1).total_seconds()) print counter time.sleep(10) exec_code()
type: AcceptedAnswer

http://stackoverflow.com/comment/83530115
comment on: http://stackoverflow.com/q/48273112
type: Comment
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ all columns in dataframe are categorical
type: QuestionComment

http://stackoverflow.com/a/48207834
type: AcceptedAnswer
downvote count: 0
score: 13
has comment: http://stackoverflow.com/comment/107852092
has comment: http://stackoverflow.com/comment/118472268
has comment: http://stackoverflow.com/comment/132717752
answers question: http://stackoverflow.com/q/48207774
type: Answer
accepted answer of: http://stackoverflow.com/q/48207774
has body: IIUC: In [93]: df = pd.DataFrame(np.random.randint(10,size=(9, 3))) In [94]: df Out[94]: 0 1 2 0 7 4 5 1 9 9 3 2 1 7 6 3 0 9 2 4 2 3 7 5 6 7 1 6 1 0 1 7 8 4 7 8 0 0 9 In [95]: df.rolling(window=3).apply(lambda x: x[0]-x[-1]) Out[95]: 0 1 2 0 NaN NaN NaN 1 NaN NaN NaN 2 6.0 -3.0 -1.0 3 9.0 0.0 1.0 4 -1.0 4.0 -1.0 5 -6.0 2.0 1.0 6 1.0 3.0 6.0 7 -2.0 3.0 -6.0 8 1.0 0.0 -8.0
upvote count: 13

http://stackoverflow.com/q/48259702
has answer: http://stackoverflow.com/a/48260009
answer count: 5
type: UnansweredQuestion
tagged with: python
has body: a=('A','1022', '1023', '1024', '1025', '1026', '1027', '1028', '1029', '1030', '1030') b=('B', '-1.0', '1', '-2.443', '-1.456', '4.00', '3.00', '-2.343', '2.112', '3.00', '') I want to exclude first element Ave B from a and b and calculate the averages of the values in a and b tuple. I was trying to write a code like this: def avarage(value): sum=0 value=list(value) first=value[0] value.pop(0) for i in value: sum+=i avrg=sum / (len(value)) return avrg print(avarage(a)) print(avarage(b)) I got a few mistakes like this and this: TypeError: unsupported operand type(s) for +=: 'int' and 'str' How can I resolve this error or how can I find the average?
has comment: http://stackoverflow.com/comment/83502072
score: 0
has title: calculating the average of elements in a tuple python
upvote count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/48259837
has answer: http://stackoverflow.com/a/48261811
has comment: http://stackoverflow.com/comment/83502075
has answer: http://stackoverflow.com/a/48260128
has answer: http://stackoverflow.com/a/48259869
favorite count: 0
type: Question

http://stackoverflow.com/comment/83607650
has text: `child = Child(Parent, 'child'` is definitely a working option and resolves all the issue, but smells really bad. Just imagine there's 10 different `Child` (or its descendants) properties in the Parent descendant - in each of them you'll have to put those 2 properties. Other than that - `Child` can have several other arguments in the `__init__`. I was looking for a solution without the 2 extra arguments. Sorry for not being clear enough in the question, will add this right now.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48310670

http://stackoverflow.com/q/48285154
type: Question
tagged with: unity-game-engine
tagged with: c#
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/52485975
accepted answer: http://stackoverflow.com/a/48285181
tagged with: visual-studio
has answer: http://stackoverflow.com/a/48285181
type: AnsweredQuestion
has title: IronPython (for .NET 4.x) integration with Unity
has body: I am trying to integrate a python script with my Unity application using Visual Studio 2017. I have followed all the steps given in the various online tutorials, and this is my code: image Also, when I go to the Unity inspector, this is the error seen when I select the dll (saved in Assets/Editor/plugins/resources directory): image2 I have installed the latest version of IronPython which states that it is compatible with .NET 4.x as well as 3.5. Could someone please suggest a fix for this, or some other alternative to use for Python integration?
tagged with: python
tagged with: ironpython
has answer: http://stackoverflow.com/a/52485975

http://stackoverflow.com/comment/83371614
comment on: http://stackoverflow.com/a/48195266
type: Comment
score: 0
type: AnswerComment
has text: Are you using a `Sequential` model? What is your keras version? What layer you put after this one?

http://stackoverflow.com/comment/83615553
type: Comment
has text: This is not helping because I need to apply grouping on level_id and name. If I move .values() after annotate(), the grouping doesn't take place
type: AnswerComment
comment on: http://stackoverflow.com/a/48302116
score: 0

http://stackoverflow.com/a/48199208
answers question: http://stackoverflow.com/q/48199167
type: Answer
has body: PS: I'm able to perform the same task using simple lambda expression! And that is a perfectly valid way to do what you want. rdd.map(lambda x : (x[1], x[0])).collect() The def approach is simply replacing lambda with def, and adding a return, not adding another function in between. def swap(x): return x[1], x[0] rdd.map(swap).collect() To see it more visually, take the Scala approach rdd.map(_ =&gt; swap(_)) Becomes rdd.map(swap) Where the map argument (a single RDD record) is passed implicitly to the function, which only accepts one parameter
upvote count: 2
downvote count: 0
score: 2

http://stackoverflow.com/comment/83328111
comment on: http://stackoverflow.com/a/48174257
type: AnswerComment
has text: Oh....i understand now.It wasn't my intention to create a set in the map function.I just wanted to apply the map with a custom predicate for the data and get the unique's after.
score: 0
type: Comment

http://stackoverflow.com/comment/83353057
comment on: http://stackoverflow.com/q/48185575
score: 0
type: Comment
type: QuestionComment
has text: Yes............

http://stackoverflow.com/comment/83379816
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48198974
type: QuestionComment
has text: Cannot reproduce...

http://stackoverflow.com/comment/83398545
score: 0
comment on: http://stackoverflow.com/q/48208507
type: Comment
type: QuestionComment
has text: Up to you :) There are implications to choosing serialization/deserialization over deepcopy, and its hard to say if your use case will be affected by those. THAT is why it is faster- it is not doing a lot of the stuff deepcopy is doing. Further, in the event that you really don't need the stuff deepcopy is doing, the most performant thing is almost certainly to write a simple method to copy exactly what you do need, since that will wind up doing less than msgpack or json.loads(json.dumps(x)) would do.

http://stackoverflow.com/comment/118159261
has text: FWIW, I think the `if b.get(k, not a[k]) == a[k]` is ingenious.
comment on: http://stackoverflow.com/a/48246160
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/87821367
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48194261
type: QuestionComment
has text: *"Is there a way to check the type before actually creating the dataframe in read_csv pandas method?"* I think you mean you want to access the type inference engine, specifically get the list of columns and inferred dtypes, rather than the output dataframe? If so that's a duplicate of @roganjosh's [Can I access dtype inference of read_csv() when creating a DataFrame from a nested list?](https://stackoverflow.com/questions/45753777/can-i-access-dtype-inference-of-read-csv-when-creating-a-dataframe-from-a-nest), please close this

http://stackoverflow.com/a/48228907
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83566073
answers question: http://stackoverflow.com/q/48228475
downvote count: 0
has body: You need to change the 0 to a 1 in the self.menubar.entryconfig line. The first parameter 1 has to be the index of the item you want to change, starting from 1.
has comment: http://stackoverflow.com/comment/83568184
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/48228475

http://stackoverflow.com/q/48217706
has title: Split Variable by Text In Between Numbers In Python
has answer: http://stackoverflow.com/a/48219702
has comment: http://stackoverflow.com/comment/83417693
has comment: http://stackoverflow.com/comment/83420648
has body: I have a text file that looks like this: 1 a more or less orderly pile or heap: a precariously balanced stack of books; a neat stack of papers. 2 a large, usually conical, circular, or rectangular pile of hay, straw, or the like. 3 Often, stacks. a set of shelves for books or other materials ranged compactly one above the other, as in a library. It's messy to say the least. I want to grab the text between each number and store it to a variable. Between numbers 1 and 2 i would have var1, and between 2 and 3 have var2 store the text. Here's where it gets tricky, Sometimes the numbers go up to 24, sometimes they only go to 1. I am quite inexperienced with parsing in python and I have no idea what to write to make this work. How would I parse this data? TIA
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48219713
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/83418883
has answer: http://stackoverflow.com/a/48219713
tagged with: python
has comment: http://stackoverflow.com/comment/83420720
has comment: http://stackoverflow.com/comment/83417903
tagged with: parsing
type: Question
has comment: http://stackoverflow.com/comment/83417625
accepted answer: http://stackoverflow.com/a/48219702
answer count: 2
has comment: http://stackoverflow.com/comment/83420642

http://stackoverflow.com/q/48214382
answer count: 2
has answer: http://stackoverflow.com/a/66109466
has title: Q: Python stops working at end of script in Batch
has answer: http://stackoverflow.com/a/48215066
upvote count: 1
has body: I'm running a series of python scripts from the Command window via a batch file. Previously, it's worked without issue. However now, without a change in code, every time it gets to the end of a script I get a "Python.exe has stopped working" error. The scripts have actually completed processing, but I need to close the error window for the batch to proceed. I've tried adding sys.exit to ends of the scripts but that makes no difference. The first script has no issue but every script after has this issue. How do I stop this error from happening? Batch File C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script1 C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script2 C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script3 C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script4a C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script4b C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script4c C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script4d C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script5 C:\Path\to\Python\ArcGIS64bitversion C:\Path\to\Script6 the python scripts do, all, actually complete. Scripts 2-5 all use multiprocessing, however script 6 does not use multiprocessing and still experiences the error. General Script Structure import statements global variables get data statements Def Code: try: code sys.exit except: print error in text file Def multiprocessing: pool = multiprocessing.pool(32) pool.map(Code, listofData) if main statement try: code multiprocessing() sys.exit except: print error to text file Script 2 (the first script to error) import arcpy, fnmatch, os, shutil, sys, traceback import multiprocessing from time import strftime #=========================================================================================== ras_dir = r'C:\Path\to\Input' working_dir = r'C:\Path\to\Output' output_dir = os.path.join(working_dir, 'Results') if not os.path.isdir(output_dir): os.mkdir(output_dir) #==========================================================…
has comment: http://stackoverflow.com/comment/83415559
favorite count: 0
has comment: http://stackoverflow.com/comment/83410557
type: Question
has comment: http://stackoverflow.com/comment/83410566
has comment: http://stackoverflow.com/comment/83410698
has comment: http://stackoverflow.com/comment/83411288
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83446878
tagged with: python
score: -1
tagged with: python-2.7
tagged with: batch-file
downvote count: 2

http://stackoverflow.com/comment/83550607
type: QuestionComment
comment on: http://stackoverflow.com/q/48279206
score: 0
type: Comment
has text: in set space, `a&~b` is implemented as `a-b`. Similarly, with `csr` matrices you could do `A.multiply(A - B)`

http://stackoverflow.com/comment/83582080
type: Comment
type: QuestionComment
has text: I think you can use keras build in [reshape](https://keras.io/layers/core/#reshape) layer.
comment on: http://stackoverflow.com/q/48285092
score: 0

http://stackoverflow.com/q/48312773
type: AnsweredQuestion
score: 0
tagged with: pyqt
has answer: http://stackoverflow.com/a/48313112
answer count: 1
tagged with: image-processing
has title: Widget is appearing next to image?
type: Question
accepted answer: http://stackoverflow.com/a/48313112
has body: I am attempting to put pyqtgraph ROI widgets (information here) on top of a .PNG image. When I import the image into the program, it comes out rotated and flipped the wrong way. I assume this is a bug. To attempt to fix it, I have rotated the image BUT when I do so, my ROI widget goes off of the image. How do I fix this? Without image rotation: i = Image.open("del.png") a = array(i) #converting to numpy array img1a = pg.ImageItem(a) v1a.addItem(img1a) Once I add img1a.rotate(90) to the code above, the ROI widget goes off the screen. How do I position the image the correct way and have my ROI widget appear normally on top of the image? The entire code is found below (edited from this example found here.) import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import numpy as np from numpy import array from PIL import Image ## create GUI app = QtGui.QApplication([]) w = pg.GraphicsWindow(size=(1000,800), border=True) w.setWindowTitle('pyqtgraph example: ROI Examples') text = """text""" w1 = w.addLayout(row=0, col=0) label1 = w1.addLabel(text, row=0, col=0) v1a = w1.addViewBox(row=1, col=0, lockAspect=True) #img1a = pg.ImageItem(arr) i = Image.open("del.png") a = array(i) img1a = pg.ImageItem(a) v1a.addItem(img1a) img1a.rotate(90) v1a.disableAutoRange('xy') v1a.autoRange() rois = [] rois.append(pg.EllipseROI([150, 150], [1, 1], pen=(4,9))) rois.append(pg.EllipseROI([0, 0], [300, 300], pen=(4,9))) for roi in rois: v1a.addItem(roi) ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
tagged with: python
tagged with: pyqtgraph
tagged with: roi

http://stackoverflow.com/comment/83424379
has text: Not in any way any other dict couldn't do.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48221400

http://stackoverflow.com/q/48185531
tagged with: database
tagged with: django
tagged with: python
has body: I use python and django. I want to remove duplicate data by field ‘agent__id’ and 'account', and count the field 'agent__id' by the same data . My code is follow: list(AgentPayLog.objects.values('agent__id', 'account'). distinct().values('agent__id').annotate(agent_count=Count(F('agent'))). values('agent__id', 'agent_count')) the data is following: account_id agent_id 30001 1 30001 2 30001 2 the code print is following: agent_id agent_count 1 1 2 2 I want the data is following: agent_id agent_count 1 1 2 1
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48199880
accepted answer: http://stackoverflow.com/a/48199880
answer count: 1
downvote count: 0
has title: How to remove duplicate data and calculate number by the same data’s field
favorite count: 0
type: Question

http://stackoverflow.com/comment/83488065
comment on: http://stackoverflow.com/a/48252639
type: Comment
has text: I just tried it but when I do I get a lengthy KeyError: -1 Error message (Not sure if it helps posting the entire long error message, can do if helpful). I checked and my id is int64 & col_name is float64, could this be a problem?
score: 0
type: AnswerComment

cx-freeze
tags question: http://stackoverflow.com/q/48189689
tag name: cx-freeze
tags question: http://stackoverflow.com/q/48299396
type: Tag
tags question: http://stackoverflow.com/q/48177683
tags question: http://stackoverflow.com/q/48265137
tags question: http://stackoverflow.com/q/48178962
tags question: http://stackoverflow.com/q/48288658

http://stackoverflow.com/comment/83649000
type: AnswerComment
has text: No problem. Happy too :D
comment on: http://stackoverflow.com/a/48298354
type: Comment
score: 0

http://stackoverflow.com/comment/83563692
type: AnswerComment
has text: Thanks for the answer. But this seems not working for some simple cases such as: `© 2004 Shie Mannor and Nahum Shimkin.`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48289327

http://stackoverflow.com/comment/83609844
has text: On windows you can run `ipconfig` in the command prompt and it should be under `IPv4 Address`, On linux you can run `ifconfig` and it would either be under `eth0` or `wlan0` then `inet xxx.xxx.xxx.xxx`
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48311952

http://stackoverflow.com/comment/83548325
has text: @JamesAnderson I don't think you've asked good questions on your earlier posts but I think the above question is well asked. It may be lacking research but it is well asked nonetheless. But I also think [Goyo's comment](https://stackoverflow.com/questions/48277590/if-statements-depending-on-widget-configuration-tkinter#comment83538946_48277590) helps better understanding the question. I think if you believe the community here is toxic perhaps try to get more feedback on the questions you had asked earlier by discussing them on [meta](https://meta.stackoverflow.com/questions/ask).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48277590

http://stackoverflow.com/comment/83415213
type: Comment
comment on: http://stackoverflow.com/q/48216573
type: QuestionComment
has text: But suppose that segment contains ` ... `? What then?
score: 0

http://stackoverflow.com/comment/83510689
score: 0
has text: Any parallel process still has a non-parallel part. The only explanation here is: memory bottleneck. If you were using a real code, you'd hit disk IO bottleneck, network bottleneck ... Here, even in this simple example, your processes still have to access the memory (to write `sum`, to write the loop counter). So the more processes are running, the higher the bottleneck is. But on my machine, with 40 processes, it's globally 5 times faster (I don't have a lot of CPUs), so don't worry about that, it's still worth using the multiprocessing module.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48263543

http://stackoverflow.com/q/48278482
has answer: http://stackoverflow.com/a/48278504
tagged with: loops
possible better answer: http://stackoverflow.com/a/48278571
has title: Speed up python list search (Nested for loops)
has answer: http://stackoverflow.com/a/48278571
type: Question
linked to: http://stackoverflow.com/q/513882
tagged with: python
has comment: http://stackoverflow.com/comment/83540279
has body: I'm currently working on moving some excel worksheets over to python automation, and have come across a speed issue. I have a list of lists containing around 10.000 lists each with 20 or so columns. I also have a list of account numbers (100.000 numbers) I wish to iterate over my list of lists and then pick out values from the list, if the account number in the lists matches one in the account list. By running this code, i am able to get my desired result, however it is painfully slow. calc = 0 for row in listOfLists: if row[1] in Accounts: calc += row[8] Any ideas on how to optimize for speed?
has comment: http://stackoverflow.com/comment/83540258
tagged with: optimization
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/48278504
has comment: http://stackoverflow.com/comment/83540287
answer count: 2

http://stackoverflow.com/comment/83531516
score: 0
type: AnswerComment
has text: Thank you for your fast response! When i tried that the same import errors came up as before: ImportError: No module named 'requests.exceptions
type: Comment
comment on: http://stackoverflow.com/a/48273980

http://stackoverflow.com/q/48308240
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/38943403
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48308307
tagged with: multidimensional-array
score: 6
tagged with: python
answer count: 6
has body: I have a 2D numpy array with 'n' unique values. I want to produce a binary matrix, where all values are replaced with 'zero' and a value which I specify is assigned as 'one'. For example, I have an array as follows and I want all instances of 35 to be assigned 'one': array([[12, 35, 12, 26], [35, 35, 12, 26]]) I am trying to get the following output: array([[0, 1, 0, 0], [1, 1, 0, 0]]) what is the most efficient way to do it in Python?
possible better answer: http://stackoverflow.com/a/48309550
upvote count: 6
has title: How to replace all values in a numpy array with zero except one specific value?
has comment: http://stackoverflow.com/comment/83602048
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48308307
has answer: http://stackoverflow.com/a/48308492
tagged with: matrix
downvote count: 0
has answer: http://stackoverflow.com/a/48309550
has answer: http://stackoverflow.com/a/48308308
has answer: http://stackoverflow.com/a/48308339
has answer: http://stackoverflow.com/a/48311050

http://stackoverflow.com/comment/83344806
comment on: http://stackoverflow.com/q/48181508
score: 0
type: Comment
type: QuestionComment
has text: If you tried the linked solution, then please provide the code where you do so and describe the exact error you did observe.

http://stackoverflow.com/a/48209045
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48208866
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83399823
type: Answer
has body: The difference is that batch_x[i] is a numpy array (which has a reshape method), while the result of corrupt(...) is a Tensor object. As of tf 1.5, it doesn't have a reshape method. This won't throw an error: tf.reshape(corrupt(batch_x[i]), [28, 28])) But since your goal is to visualize the value, you should better avoid mixing up tensorflow and numpy operations and rewrite corrupt in terms of numpy only: def corrupt(x): noise = np.random.normal(size=x.shape, loc=0.0, scale=0.2) return x + noise
accepted answer of: http://stackoverflow.com/q/48208866

http://stackoverflow.com/comment/83574959
type: Comment
comment on: http://stackoverflow.com/q/48295229
type: QuestionComment
score: 0
has text: and if someone with higher reputation can add the new tag 'google-colab', that would be better

urllib2
tags question: http://stackoverflow.com/q/48236581
tag name: urllib2
tags question: http://stackoverflow.com/q/48307114
tags question: http://stackoverflow.com/q/48197999
type: Tag
tags question: http://stackoverflow.com/q/48237272
tags question: http://stackoverflow.com/q/48174702

http://stackoverflow.com/q/48289152
has answer: http://stackoverflow.com/a/48290642
tagged with: curl
type: Question
has title: Consistent way to get request payload in Flask
has body: I have a Flask view that accepts some POST data. I can post the data with curl as form-encoded or JSON. How can I get the data no matter which way the client posts it? from flask import request @app.route('/', methods=['GET', 'POST']) def refresh(): # empty when posted as JSON print(request.form) # empty when posted as form-encoded print(request.data) return 'Hello, World!' curl -XPOST -H "Content-Type: application/json" 'http://127.0.0.1:5000/?thing1=1' -d '{"thing2":2}' curl -XPOST 'http://127.0.0.1:5000/?thing1=1' -d '{"thing2":2}' curl -XGET 'http://127.0.0.1:5000/?thing1=1' -d '{"thing2":2}'
answer count: 1
has comment: http://stackoverflow.com/comment/83564157
downvote count: 0
upvote count: 1
tagged with: python
score: 1
tagged with: flask
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83563359
accepted answer: http://stackoverflow.com/a/48290642

http://stackoverflow.com/a/48307288
has body: tf.global_variables_initializer() should be called after all variables is created. In your example, prediction function defines w1 variable which is not initialized until ses.run(). You may create variables inside __init__ function like below: class NNclass: def __init__(self, state_d, action_d, state): self.s_dim = state_d self.a_dim = action_d self.state = state self.a = tf.constant(5, dtype=tf.float32) self.w1 = tf.Variable(np.random.normal(0, 1)) @property def prediction(self): return tf.add(self.a, self.w1)
has comment: http://stackoverflow.com/comment/83600154
downvote count: 0
type: Answer
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/48306763

http://stackoverflow.com/a/48178529
downvote count: 0
has body: This seems like an issue of multiple-class tags. I believe this question might help you figure out the solution.
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48178289

http://stackoverflow.com/comment/83468577
type: QuestionComment
has text: @sladomic I have the shape of X as (2327, 32, 32, 3) and the shape of Y as (2327,). Y should only contain the one hot encoded labels of the respective data so where exactly do you think the problem is? Are the shapes of X and Y both wrong? I have 2327 images for training and 200 for testing.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48242885

http://stackoverflow.com/q/48314268
type: UnansweredQuestion
tagged with: aws-glue
has body: After reading Amazon docs, my understanding is that the only way to run/test a Glue script is to deploy it to a dev endpoint and debug remotely if necessary. At the same time, if the (Python) code consists of multiple files and packages, all except the main script need to be zipped. All this gives me the feeling that Glue is not suitable for any complex ETL task as development and testing is cumbersome. I could test my Spark code locally without having to upload the code to S3 every time, and verify the tests on a CI server without having to pay for a development Glue endpoint.
tagged with: python
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/86846390
has answer: http://stackoverflow.com/a/48531207
has title: Can I test AWS Glue code locally?
has comment: http://stackoverflow.com/comment/91392784
has answer: http://stackoverflow.com/a/57723005
has answer: http://stackoverflow.com/a/48823484
has answer: http://stackoverflow.com/a/59171202
has answer: http://stackoverflow.com/a/58930648
downvote count: 0
has answer: http://stackoverflow.com/a/64016670
linked to: http://stackoverflow.com/q/42942620
score: 46
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86846025
has answer: http://stackoverflow.com/a/54096194
answer count: 9
upvote count: 46
has answer: http://stackoverflow.com/a/53972448
has answer: http://stackoverflow.com/a/64973646

http://stackoverflow.com/a/48211240
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83403711
score: 6
upvote count: 6
has body: Instead of setting the alignment of the text itself, you need to set the position of the text inside the table cell. This is determined by the cell's ._loc attribute. def set_align_for_column(table, col, align="left"): cells = [key for key in table._cells if key[1] == col] for cell in cells: table._cells[cell]._loc = align table._cells[cell]._text.set_horizontalalignment('left') Some complete example: from matplotlib import pyplot as plt data = [['x','x'] for x in range(10)] bbox = [0,0,1,1] tb = plt.table(cellText = data, cellLoc='right', bbox = bbox) plt.axis('off') # get rid of chart axis to only show table def set_align_for_column(table, col, align="left"): cells = [key for key in table._cells if key[1] == col] for cell in cells: table._cells[cell]._loc = align table._cells[cell]._text.set_horizontalalignment('left') set_align_for_column(tb, col=0, align="right") set_align_for_column(tb, col=1, align="left") plt.show() (The approach used here is similar to changing the cell padding as in this question: Matplotlib Text Alignment in Table)
type: Answer
accepted answer of: http://stackoverflow.com/q/48210749
has comment: http://stackoverflow.com/comment/117559175
downvote count: 0
answers question: http://stackoverflow.com/q/48210749

http://stackoverflow.com/q/48209914
has comment: http://stackoverflow.com/comment/83400862
answer count: 2
accepted answer: http://stackoverflow.com/a/48209944
has answer: http://stackoverflow.com/a/48209951
has title: dataframe to json file
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48209944
score: 4
has body: I want to convert dataframe to json file. Currently my dataframe looks like this: a b P1 7950 P2 1274 P3 6160 I want to conver this dataframe into json file in which values from first column would be keys and from second column would be values: so like {P1:7950, P2:1274, P3:6160) I tried this but it produces output in incorrect form (not the want I stated above) df.set_index('a').to_json()
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83400886
possible better answer: http://stackoverflow.com/a/48209951
has comment: http://stackoverflow.com/comment/83400915
tagged with: pandas
has comment: http://stackoverflow.com/comment/83400847
favorite count: 0
has comment: http://stackoverflow.com/comment/83400919
type: Question
upvote count: 4

http://stackoverflow.com/a/50933623
answers question: http://stackoverflow.com/q/48265646
has body: There is a general solution to this problem. Given a vector, a rotation axis and an anticlockwise angle, I wrote a simple code, which works of course also for the cases already mentioned. What it does is: projecting the vector onto the plane defined by the axis of rotation; rotating the component of the vector in the plane; finally reassembling all together to give the final result. import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib def rotve(v,erot,angle): rotmeasure=np.linalg.norm(erot) erot=erot/rotmeasure; norme=np.dot(v,erot) vplane=v-norme*erot plnorm=np.linalg.norm(vplane) ep=vplane/plnorm eo=np.cross(erot,ep) vrot=(np.cos(angle)*ep+np.sin(angle)*eo)*plnorm+norme*erot return(vrot) If you want, you can check with an example which plots the "umbrella" made by the rotations: axrot=np.array([1,0,1]); v=np.array([1.,1.,1.]) fig3 = plt.figure(3) ax3d = fig3.add_subplot(111, projection='3d') ax3d.quiver(0,0,0,axrot[0],axrot[1],axrot[2],length=.5, normalize=True, color='black') angles=np.linspace(0,2,10)*np.pi for i in range(len(angles)): vrot=rotve(v,axrot,angles[i]); ax3d.quiver(0,0,0,vrot[0],vrot[1],vrot[2],length=.1, normalize=True, color='red') ax3d.quiver(0,0,0,v[0],v[1],v[2],length=.1, normalize=True, color='blue') ax3d.set_title('rotations') fig3.show() plt.show()
upvote count: 1
score: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/48276658
upvote count: 3
has title: Python JPEG file carver takes incredibly long on small dumps
answer count: 1
accepted answer: http://stackoverflow.com/a/48276820
has answer: http://stackoverflow.com/a/48276820
favorite count: 0
type: Question
downvote count: 0
tagged with: python
type: AnsweredQuestion
score: 3
has body: I'm writing a JPEG file carver as a part of a forensic lab. The assignment is to write a script that can extract JPEG files from a 10 MB dd-dump. We are not permitted to assign the file to a memory variable (because if it were to be too big, it would cause an overflow), but instead, the Python script should read directly from the file. My script seems to work perfectly fine, but it takes extremely long to finish (upwards 30-40 minutes). Is this an expected behavior? Even for such a small 10 MB file? Is there anything I can do to shorten the time? This is my code: # Extract JPEGs from a file. import sys with open(sys.argv[1], "rb") as binary_file: binary_file.seek(0, 2) # Seek the end num_bytes = binary_file.tell() # Get the file size count = 0 # Our counter of which file we are currently extracting. for i in range(num_bytes): binary_file.seek(i) four_bytes = binary_file.read(4) whole_file = binary_file.read() if four_bytes == b"\xff\xd8\xff\xd8" or four_bytes == b"\xff\xd8\xff\xe0" or four_bytes == b"\xff\xd8\xff\xe1": # JPEG signature whole_file = whole_file.split(four_bytes) for photo in whole_file: count += 1 name = "Pic " + str(count) + ".jpg" file(name, "wb").write(four_bytes+photo) print name

http://stackoverflow.com/comment/83382513
score: 0
comment on: http://stackoverflow.com/q/48200355
type: Comment
type: QuestionComment
has text: Thank you so much for your help! I found it at the same time as you answered! This has fixed it.

http://stackoverflow.com/a/48232124
has comment: http://stackoverflow.com/comment/83446642
has comment: http://stackoverflow.com/comment/83446693
score: 2
has comment: http://stackoverflow.com/comment/83446620
has comment: http://stackoverflow.com/comment/83447222
type: Answer
has comment: http://stackoverflow.com/comment/83446716
has body: You can use a list comprehension: source = [......] indexes = [.......] filteredByIndexes = [source[i] for i in indexes]
has comment: http://stackoverflow.com/comment/83446558
answers question: http://stackoverflow.com/q/48232100
upvote count: 2
has comment: http://stackoverflow.com/comment/83446730
accepted answer of: http://stackoverflow.com/q/48232100
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83446742

http://stackoverflow.com/comment/83449196
comment on: http://stackoverflow.com/q/48233313
score: 0
has text: after `np.squeeze(np.array([[np.array([[12000000]])]], dtype=object))` I've got `array(12000000, dtype=object)`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83494643
has text: I followed reddit's documentation. I have also implemented this request in javascript(react native) . However I am keep getting stuck in python . https://www.reddit.com/dev/api/#POST_api_submit
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48255765
score: 0

http://stackoverflow.com/comment/83543008
type: QuestionComment
score: 0
has text: Is it part of your project?
comment on: http://stackoverflow.com/q/48273420
type: Comment

http://stackoverflow.com/comment/83590319
type: Comment
has text: @PatrickArtner else is for the contion frames are less than 3
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48302821

string
tags question: http://stackoverflow.com/q/48325601
tags question: http://stackoverflow.com/q/48320432
type: Tag
tags question: http://stackoverflow.com/q/48290101
tags question: http://stackoverflow.com/q/48215857
tags question: http://stackoverflow.com/q/48215072
tags question: http://stackoverflow.com/q/48240280
tags question: http://stackoverflow.com/q/48282109
tags question: http://stackoverflow.com/q/48259500
tags question: http://stackoverflow.com/q/48226330
tags question: http://stackoverflow.com/q/48278091
tags question: http://stackoverflow.com/q/48175689
tags question: http://stackoverflow.com/q/48201454
tags question: http://stackoverflow.com/q/48253396
tags question: http://stackoverflow.com/q/48296585
tags question: http://stackoverflow.com/q/48323850
tags question: http://stackoverflow.com/q/48243018
tags question: http://stackoverflow.com/q/48271169
tags question: http://stackoverflow.com/q/48256921
tags question: http://stackoverflow.com/q/48255244
tags question: http://stackoverflow.com/q/48230761
tags question: http://stackoverflow.com/q/48290671
tags question: http://stackoverflow.com/q/48242899
tags question: http://stackoverflow.com/q/48192862
tags question: http://stackoverflow.com/q/48222879
tags question: http://stackoverflow.com/q/48307584
tags question: http://stackoverflow.com/q/48211037
tags question: http://stackoverflow.com/q/48254504
tags question: http://stackoverflow.com/q/48272315
tags question: http://stackoverflow.com/q/48246021
tags question: http://stackoverflow.com/q/48254190
tags question: http://stackoverflow.com/q/48287736
tags question: http://stackoverflow.com/q/48241269
tags question: http://stackoverflow.com/q/48224245
tags question: http://stackoverflow.com/q/48242912
tags question: http://stackoverflow.com/q/48322566
tags question: http://stackoverflow.com/q/48290674
tags question: http://stackoverflow.com/q/48250995
tags question: http://stackoverflow.com/q/48184487
tags question: http://stackoverflow.com/q/48195857
tags question: http://stackoverflow.com/q/48197383
tags question: http://stackoverflow.com/q/48322058
tags question: http://stackoverflow.com/q/48238949
tags question: http://stackoverflow.com/q/48305298
tags question: http://stackoverflow.com/q/48216006
tags question: http://stackoverflow.com/q/48227649
tags question: http://stackoverflow.com/q/48255952
tags question: http://stackoverflow.com/q/48226041
tags question: http://stackoverflow.com/q/48291140
tags question: http://stackoverflow.com/q/48260253
tags question: http://stackoverflow.com/q/48260793
tag name: string
tags question: http://stackoverflow.com/q/48271195
tags question: http://stackoverflow.com/q/48235431
tags question: http://stackoverflow.com/q/48298389
tags question: http://stackoverflow.com/q/48303650
tags question: http://stackoverflow.com/q/48174271
tags question: http://stackoverflow.com/q/48251030
tags question: http://stackoverflow.com/q/48307819
tags question: http://stackoverflow.com/q/48258692
tags question: http://stackoverflow.com/q/48312957
tags question: http://stackoverflow.com/q/48233596
tags question: http://stackoverflow.com/q/48257116
tags question: http://stackoverflow.com/q/48194362
tags question: http://stackoverflow.com/q/48258371
tags question: http://stackoverflow.com/q/48243094
tags question: http://stackoverflow.com/q/48281837
tags question: http://stackoverflow.com/q/48300132

http://stackoverflow.com/a/48369962
score: 5
has body: You have to print the ggplot object. p = (ggplot(diamonds) + stat_summary(aes('clarity', 'price', fill='cut'), geom='col', position='dodge') + stat_summary(aes('clarity', 'price', color='cut'), geom='linerange', size=1, position=position_dodge(width=0.9)) + scale_color_hue(l=.3) + theme(figure_size=(11, 8)) ) print(p) IPython automatically prints the last result in cell for you. For other environments you have to do it explicitly
downvote count: 0
answers question: http://stackoverflow.com/q/48313654
upvote count: 5
type: Answer

http://stackoverflow.com/comment/83589620
has text: @glibdud Am sorry, I edited again just now and I posted a link for reference for the Ubidots and Raspberry Pi codes
comment on: http://stackoverflow.com/q/48302110
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/48210146
tagged with: python
has comment: http://stackoverflow.com/comment/83402110
has body: Following: live output from subprocess command. I would like to run a process with subprocess.Popen() and get both live STDOUT and STDERR. The problem is that if I do readline on one of them, it will block, and I won't be able to readline the other. I also don't want to unite them to one PIPE. Is there a simple way to do it without using 2 threads per process?
type: Question
linked to: http://stackoverflow.com/q/25750468
answer count: 0
has comment: http://stackoverflow.com/comment/83401643
linked to: http://stackoverflow.com/q/18421757
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83401920
has title: Python - subprocess Popen() get both live stdout and stderr

http://stackoverflow.com/q/48175689
upvote count: 0
score: -5
accepted answer: http://stackoverflow.com/a/48176702
has comment: http://stackoverflow.com/comment/83331402
answer count: 1
tagged with: regex
has body: textDoc= Line 1 "'"Here is my Text which Line 2 I now have *starred* the words which i would like accounted for" Line 3 I would like the end result to be Lines 3 Words 6. Line 4.Python Regular expression **rules** have me trying things that Line 5.I have listed below. All of them are usable but I would like Line 6 To understand how to customize it for **production** to use.""" //desiredoutput = Lines 3, Words 3 /* This is because the words: starred, rules, and production are on every other line and they contain more than 2 vowels all while being the fourth word on the line.*/ I can't seem to put it all together but some regular expression code that I am considering and has worked a litttle bit so far are: enumerate, .split. find.All [aeiou],[aeiou]{2}, textDoc = numOfLines = len(textDoc.splitlines()) print(numOfLines) split gets the list of words to a string. my guess is I will need a new string with every fourth word on every other line before I count them to accomplish my desired out put of Lines 3 Words 3
tagged with: string
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48176702
downvote count: 5
has comment: http://stackoverflow.com/comment/83331322
has comment: http://stackoverflow.com/comment/83331713
has title: Would like a reg ex expression to find (RE.FINDALL) words with two vowels[aeiou] every FOURTH word on every other (MULTILINE) string?
tagged with: python
tagged with: regex-group
type: AnsweredQuestion

http://stackoverflow.com/comment/83421134
score: 3
comment on: http://stackoverflow.com/a/48219676
has text: haha chill bro, we all learn from our mistakes only, when you come from a different programming language to python, we make this kind of mistakes, anyways glad to help you :)
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48227563
has comment: http://stackoverflow.com/comment/83446637
has comment: http://stackoverflow.com/comment/98184974
score: 2
accepted answer of: http://stackoverflow.com/q/48215392
upvote count: 2
has body: Content encoding is determined by Content-Type header which in turn uses mimetypes.guess_type for finding a type based on file extension. It does nothing with text character encoding. Figuring out plain text encoding is quite expensive procedure (need processing reading file content by tool like chardet) and not 100% stable (a file can contain multiple encoding). P.S. Static file support in aiohttp is for handling resources like images, not human readable plain texts. HTML should be rendered correctly though.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83446037
downvote count: 0
answers question: http://stackoverflow.com/q/48215392
type: Answer

http://stackoverflow.com/comment/83346104
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48182874
has text: Google it. It's an OS-thing, like caching (which makes it hard to analyze from within python only).

http://stackoverflow.com/comment/83593969
comment on: http://stackoverflow.com/a/48304473
type: AnswerComment
score: 0
has text: nitpicking: Using `...for i, _ in ...` instead makes it clear*er* that `_` will not be used.
type: Comment

http://stackoverflow.com/q/48318730
linked to: http://stackoverflow.com/q/2081586
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/83623423
possible better answer: http://stackoverflow.com/a/48318926
tagged with: python
type: AnsweredQuestion
score: 2
has body: I would like to automatically save the data of cities from this website: http://www.dataforcities.org/ I used beautifulsoup library to get data from a webpage http://open.dataforcities.org/details?4[]=2016 import urllib2 from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(urllib2.urlopen('http://open.dataforcities.org/details?4[]=2016').read()) If I follow the example in Web scraping with Python I got the following error: soup = BeautifulSoup(urllib2.urlopen('http://example.com').read()) for row in soup('table', {'class': 'metrics'})[0].tbody('tr'): tds = row('td') print tds[0].string, tds[1].string IndexError Traceback (most recent call last) &lt;ipython-input-71-d688ff354182&gt; in &lt;module&gt;() ----&gt; 1 for row in soup('table', {'class': 'metrics'})[0].tbody('tr'): 2 tds = row('td') 3 print tds[0].string, tds[1].string IndexError: list index out of range [1]: http://www.dataforcities.org/ [2]: http://open.dataforcities.org/ [3]: https://i.sstatic.net/qfQyG.png
answer count: 2
has title: Python: is it possible to scrape a very particular webpage?
upvote count: 3
accepted answer: http://stackoverflow.com/a/48318935
tagged with: web-scraping
has answer: http://stackoverflow.com/a/48318935
has answer: http://stackoverflow.com/a/48318926
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/48328378
type: Answer
has body: You can use a context manager: import contextlib @contextlib.contextmanager def aline(outfile, *files): final_data = zip(open(files[0]), open(files[1])) yield ['\n'.join([a, b]) for a, b in final_data] f = open(outfile, 'w') for a, b in final_data: f.write('\n'.join([a, b])+'\n\n') f.close() with aline('output.txt', *['data/data.txt', 'data/data2.txt']) as f: print(f) Output (int output.txt): feel my cold hands. ≥ª ¬˘ º’¿ª ¡ª ∏∏¡Æ∫¡. I love oranges. ∏«¸ ∫Ò«‡±‚∞° ∞≠¿ª ≥Øæ∆∞¨¥Ÿ. Mexico has a large surplus of oil. ∏ﬂΩ√ƒ⁄ø°¥¬ ¥Ÿ∑Æ¿« ø©∫–¿« ºÆ¿Ø∞° ¿÷¥Ÿ. Ink stains don't rub out. ¿◊≈© ¿⁄±π¿∫ ¥€æ∆µµ ¡ˆøˆ¡ˆ¡ˆ æ ¥¬¥Ÿ.
answers question: http://stackoverflow.com/q/48328187
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/83490002
has text: yes entire list in one cell ...well sir your program resulted in following:........ AttributeError: 'MySQLConverter' object has no attribute '_list_to_mysql'.......TypeError: Python 'list' cannot be converted to a MySQL type....... "Failed processing format-parameters; %s" % err) mysql.connector.errors.ProgrammingError: Failed processing format-parameters; Python 'list' cannot be converted to a MySQL type
comment on: http://stackoverflow.com/a/48253696
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83490615
has text: What are you trying to do?
type: QuestionComment
comment on: http://stackoverflow.com/q/48253823
type: Comment
score: 0

http://stackoverflow.com/comment/83577714
score: 0
type: Comment
type: AnswerComment
has text: Oh, sorry. I should have checked that. OK, now I have [this `script.py`](http://codepad.org/G3FkIxxM). Running it simply by using `python3 script.py` still makes the memory consumption grow. Any ideas?
comment on: http://stackoverflow.com/a/48269611

http://stackoverflow.com/q/48249812
score: 2
upvote count: 2
tagged with: arrays
downvote count: 0
tagged with: count
has comment: http://stackoverflow.com/comment/83482912
tagged with: python
has comment: http://stackoverflow.com/comment/83482419
type: AnsweredQuestion
has title: Replace last values by previous value
has comment: http://stackoverflow.com/comment/83482262
possible better answer: http://stackoverflow.com/a/48250012
has answer: http://stackoverflow.com/a/48250012
accepted answer: http://stackoverflow.com/a/48249935
has answer: http://stackoverflow.com/a/48249891
answer count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/83482243
has answer: http://stackoverflow.com/a/48249935
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83482410
has answer: http://stackoverflow.com/a/48250171
has body: I have array of uncomplete triples: a = np.arange(10) // 3 + 1 print (a) [1 1 1 2 2 2 3 3 3 4] Or: a1 = np.arange(11) // 3 + 1 print (a1) [1 1 1 2 2 2 3 3 3 4 4] Last value is 4, but I need change it by previous, here 3, because not triples. I try: unique, counts = np.unique(a, return_counts=True) print (unique) [1 2 3 4] print (counts) [3 3 3 1] Expected output for a: [1 1 1 2 2 2 3 3 3 3] and for a1: [1 1 1 2 2 2 3 3 3 3 3] If all triples, no value is changed: a2 = np.arange(12) // 3 + 1 print (a2) [1 1 1 2 2 2 3 3 3 4 4 4] I need some general solution, because triples should be changed to 4 or more.

http://stackoverflow.com/comment/83331795
type: Comment
comment on: http://stackoverflow.com/q/48173902
type: QuestionComment
score: 0
has text: FYI: This is not a good use case for multiprocessing. It's a perfect textbook case for `gevent` or `aiohttp`; I suggest you look at one of those instead.

http://stackoverflow.com/comment/83518824
comment on: http://stackoverflow.com/q/48266247
has text: Thanks I did that. I have to wait 2 days until I can mark it as correct.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48316666
has title: Move .png on desktop to new directory
has comment: http://stackoverflow.com/comment/83618805
accepted answer: http://stackoverflow.com/a/48316823
has comment: http://stackoverflow.com/comment/83619297
has comment: http://stackoverflow.com/comment/83618753
has answer: http://stackoverflow.com/a/48316823
has comment: http://stackoverflow.com/comment/83621884
type: Question
has comment: http://stackoverflow.com/comment/83618861
has comment: http://stackoverflow.com/comment/83618738
has body: Relatively new to python, trying to move files based on type from one directory to another. import shutil import os source = 'C:\Users\home\Desktop' Unsorted = 'C:\Users\home\Desktop\' Sorted = 'B:\Pictures' file = os.listdir(source) for f in file("Unsorted"): if file.endswith(".png",".jpg"): print(os.path.join("Sorted", file)) I would appreciate any help. Thank you. Edit Thank you for the help and the links. I really appreciate it. I am reading automatetheboringstuff, and Modern Python Cookbook (2018). import os source = 'C:\\Users\\home\\Desktop' sorted = 'B:\\Pictures' for f in os.listdir(source): if f.endswith((".png",".jpg",".jpeg")): print(os.path.join(sorted, f)) I believe it works, since I am not getting any errors, but it's not moving the files. It seems to work here: link. Maybe it doesn't work between drives? Anyway, thank you! EDIT I got it to work! import os import shutil source = os.path.join('C:\\Users\\home\\Desktop') sort = os.path.join('B:\\Pictures') for f in os.listdir(source): if f.endswith((".png",".jpg",".jpeg")): shutil.move(os.path.join(source, f), sort) Thank you everyone for your help! I hope you guys have a great rest of your day! Thanks. :D
has comment: http://stackoverflow.com/comment/83621747
has comment: http://stackoverflow.com/comment/83618760
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/31408680
has comment: http://stackoverflow.com/comment/83618831
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/83538708
type: AnswerComment
comment on: http://stackoverflow.com/a/48277391
score: 1
has text: Thanks I think I got the idea how to do that, it was my first question online , so I understand I didn't make it clear :) It's very sad that some people downvoted your answer .
type: Comment

http://stackoverflow.com/a/48282772
score: 0
has comment: http://stackoverflow.com/comment/83549348
answers question: http://stackoverflow.com/q/48282664
has body: Parentheses after a name means a function/method is called there. An object can be created by calling its constructor(__init__ function). Constructor is invoked by calling the class itself as a function Workbook() The functions or object methods are called similarly using parentheses.
type: Answer
has comment: http://stackoverflow.com/comment/83771945

http://stackoverflow.com/comment/83371362
has text: Are you assign your results of your interpolate back to your dataframe variable... ie. `df = df.interpolate(axis=1)` Or using the inplace=True?
type: QuestionComment
comment on: http://stackoverflow.com/q/48195226
type: Comment
score: 0

http://stackoverflow.com/q/48201821
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83384495
has comment: http://stackoverflow.com/comment/83384612
tagged with: python
has title: CNTK Crashes Python when imported : Fatal Python error: Py_Initialize: can't initialize sys standard streams
has body: I have installed CNTK CPU only version module using pip pip3 install https://cntk.ai/PythonWheel/CPU-Only/cntk-2.3.1-cp36-cp36m-win_amd64.whl When i imported in spyder IDE, it was working fine. But when i tried to install other modules likes pandas, numpy using pip it crashes Python and says stopped working. C:\Program Files\Python36\Scripts&gt;pip3 install pandas Fatal Python error: Py_Initialize: can't initialize sys standard streams Traceback (most recent call last): File "C:\Program Files\Python36\Lib\site-packages\cntk\io\__init__.py", line 1 3, in &lt;module&gt; ModuleNotFoundError: No module named 'cntk' It says There is no module names CNTK and crashes Python. I am unable to open Python IDE after this. Any idea why this happens? I uninstalled and installed for nearly 4 times. It still a problem.
score: 0
has comment: http://stackoverflow.com/comment/83392969
answer count: 0
tagged with: cntk
tagged with: pip
has comment: http://stackoverflow.com/comment/83384551
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83384647

http://stackoverflow.com/comment/107489257
has text: php buildpack and python buidpack combination is not working. throwing error
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/56570129
score: 0

argparse
tags question: http://stackoverflow.com/q/48322986
tags question: http://stackoverflow.com/q/48264081
tags question: http://stackoverflow.com/q/48272705
type: Tag
tag name: argparse
tags question: http://stackoverflow.com/q/48278187

http://stackoverflow.com/comment/83548981
has text: Cut and paste into an existing program -- my fault @Nae.
type: Comment
comment on: http://stackoverflow.com/a/48282550
type: AnswerComment
score: 1

http://stackoverflow.com/q/48235045
tagged with: python
tagged with: config
accepted answer: http://stackoverflow.com/a/48240578
type: Question
has answer: http://stackoverflow.com/a/48240578
score: 2
upvote count: 2
downvote count: 0
answer count: 1
tagged with: ini
has body: Trying to set an option in a pytest.ini file dynamically. The option testpaths determines what directories pytest will gather tests from. I want to give users the ability to select test directory a or b. conftest.py The first hook creates a parser option. The second hook pulls the parser option reads the value and adds the testpath to the testpaths option under the config object. @pytest.hookimpl() def pytest_addoption(parser): """Creates a parser option""" # Allows the user to select the test suite they want to run parser.addoption("--suite", action="store", default="None" , choices=['a', 'b'] , help="Choose which test suite to run.") @pytest.hookimpl() def pytest_configure(config): print("Determining test directory") suite = config.getoption("--suite") if suite == "a": config.addinivalue_line("testpaths", "tests/a") elif suite == "b": config.addinivalue_line("testpaths", "tests/b") So if i run pytest --suite a it should load all tests under the a test suite. It does not. It loads all tests like the option doesnt exist.
favorite count: 0
type: AnsweredQuestion
tagged with: pytest
has title: pytest.ini value not being set correctly

http://stackoverflow.com/comment/83552714
type: AnswerComment
comment on: http://stackoverflow.com/a/48284155
has text: Thank you Ajax1234, but problem - I don't know these group_names (for adding it to the script before)
score: 0
type: Comment

bioinformatics
tags question: http://stackoverflow.com/q/48302618
tag name: bioinformatics
tags question: http://stackoverflow.com/q/48244985
tags question: http://stackoverflow.com/q/48321543
tags question: http://stackoverflow.com/q/48311807
tags question: http://stackoverflow.com/q/48256088
type: Tag
tags question: http://stackoverflow.com/q/48263906

http://stackoverflow.com/q/48216921
has comment: http://stackoverflow.com/comment/83416199
score: 0
has comment: http://stackoverflow.com/comment/83416003
has comment: http://stackoverflow.com/comment/83416592
linked to: http://stackoverflow.com/q/6058019
has comment: http://stackoverflow.com/comment/83415866
has comment: http://stackoverflow.com/comment/83416272
has comment: http://stackoverflow.com/comment/83416033
tagged with: python
has comment: http://stackoverflow.com/comment/83416262
has body: I am very new to python and could use a little help, I created a password locker program to store and recall accounts, logins and passwords for various accounts which requires 1 password to view all the stored info. this is my first program involving the pickle module and could use some input on how to increase my efficiency in using it, also is there a way to increase the encryption of the stored info so words can't be seen in the pickle file. Thanks! here is what I have going on. #! python3 import sys import pickle PIK = "pickle.pkl" account = [] login = [] password = [] print('What is your password?') while True: p = input() if p == 'springtime': break else: print('Incorrect password') continue while True: try: with open(PIK, 'rb') as f: f.close() break except FileNotFoundError: with open(PIK, 'ab') as f: pickle.dump(account, f) pickle.dump(login, f) pickle.dump(password, f) f.close() break with open(PIK, 'rb') as f: while True: try: account = pickle.load(f) login = pickle.load(f) password = pickle.load(f) except EOFError: break def add(): while True: print('What type of account is this? CANCEL to menu') y = input() if y.lower() == 'cancel': menu() break elif y.lower() != 'cancel': print('Are you sure this is the account type?(y/n): ' + y) confirm = input() if confirm.lower() == 'y': account.append(y) break else: continue while True: print('What is the login for the account? CANCEL to menu') x = input() if x.lower() == 'cancel': menu() break elif x.lower() != 'cancel': print('Are you sure this is the login?(y/n): ' + x) confirm = input() if confirm.lower() == 'y': login.append(x) break else: continue while True: print('What is the password for the account? CANCEL to menu') z = input() if z.lower() == 'cancel': menu() elif x.lower != 'cancel': print('Are you sure this is the password?(y/n): ' + z) confirm = input() if confirm.lower() == 'y': password.append(z) print('Would you like to create another account?(y/n)') answer = input() if answer.lower() == 'y': add() …
has comment: http://stackoverflow.com/comment/83415899
type: Question
has comment: http://stackoverflow.com/comment/83418963
has comment: http://stackoverflow.com/comment/83416097
has comment: http://stackoverflow.com/comment/83416073
answer count: 0
has title: tips for pickling and hiding passwords
type: UnansweredQuestion
tagged with: encryption
linked to: http://stackoverflow.com/q/19147789

http://stackoverflow.com/comment/83420909
score: 0
has text: Mad Physicist is right, I missed the size= portion of the code when I read through it. D would be an array, which would mean the loop would be the same, D[i] would be the ith part of the array. Rereading the question, I'm also not sure why the loop is needed if you're just calculating r for one specific day.
type: Comment
comment on: http://stackoverflow.com/a/48219164
type: AnswerComment

http://stackoverflow.com/a/48312887
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48311704
has body: You should consider to pass the path to the loadTopic function as a parameter, and passing it on the call in Forum.py That way you don't have the absolute path hardcoded on the load module.

http://stackoverflow.com/q/48203840
tagged with: python
has answer: http://stackoverflow.com/a/53427945
score: 0
has title: Joblib error: TypeError: can't pickle _thread.lock objects
answer count: 1
has body: I am unable to run joblib using my function which takes a numpy array, list of trained Keras models and a list of strings as parameters. I tried creating the parameters as a namedtuple or even as a class with immutable properties. Any ideas ? Params = collections.namedtuple('Params',['inputs','y_list','trained_models']) p = Params(inputs, y_list, trained_models) or class Params: def __init__(self, inputs, mq_list,trained_models): super(Params , self).__setattr__("inputs", inputs) super(Params , self).__setattr__("y_list", y_list) super(Params , self).__setattr__("trained_models", trained_models) Function which i like to run in parallel: def predict(params): inputs = params.inputs y_list = params.y_list trained_models = params.trained_models # process and vectorize inputs X= new_X(inputs) X_vect= vect.transform(X) predictions = dict() for y in y_list: y_field = trained_models[y].predict(X_vect) # evaluate model if y_field[0] &gt; 0.05: return None, None predictions[y] = y_field[0] return X, predictions Parallelized calling of function: r= Parallel(n_jobs=4, verbose=5)( delayed(predict)(p) for c in range(100)) Error: TypeErrorTraceback (most recent call last) &lt;timed exec&gt; in &lt;module&gt;() ~/.conda/envs/mlgpu/lib/python3.6/site-packages/joblib/parallel.py in __call__(self, iterable) 787 # consumption. 788 self._iterating = False --&gt; 789 self.retrieve() 790 # Make sure that we get a last message telling us we are done 791 elapsed_time = time.time() - self._start_time ~/.conda/envs/mlgpu/lib/python3.6/site-packages/joblib/parallel.py in retrieve(self) 697 try: 698 if getattr(self._backend, 'supports_timeout', False): --&gt; 699 self._output.extend(job.get(timeout=self.timeout)) 700 else: 701 self._output.extend(job.get()) ~/.conda/envs/mlgpu/lib/python3.6/multiprocessing/pool.py in get(self, timeout) 642 return self._value 643 else: --&gt; 644 raise self._value 645 646 def _set(self, i, obj): ~/.conda/envs/mlgpu/lib/python3.6/multiprocessing/pool.py in _handl…
tagged with: joblib
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/83478344
comment on: http://stackoverflow.com/a/48247739
type: AnswerComment
has text: @OmarAdel Whatever works for you, but I am a bit confused since you said my answer worked perfectly.
score: 0
type: Comment

http://stackoverflow.com/comment/83879532
type: AnswerComment
score: 0
has text: Thanks for the self reply! I think I have a similar issue, however I couldnt understand how lambda fixed it. My problem is in here : https://stackoverflow.com/questions/48443572/using-multiple-filenames-as-wildcards-in-snakemake. Do you think I can apply the same solution as you did? Thanks again!
comment on: http://stackoverflow.com/a/48323515
type: Comment

http://stackoverflow.com/q/48244097
downvote count: 0
possible better answer: http://stackoverflow.com/a/48244132
has answer: http://stackoverflow.com/a/48244264
type: AnsweredQuestion
answer count: 3
tagged with: pandas
has title: Efficient way to find price momentum in python: averaging last n entries of a column
has body: I'm defining price momentum is an average of the given stock’s momentum over the past n days. Momentum, in turn, is a classification: each day is labeled 1 if closing price that day is higher than the day before, and −1 if the price is lower than the day before. I have stock change percentages as follows: df['close in percent'] = np.array([0.27772152, 1.05468772, 0.124156 , -0.39298394, 0.56415267, 1.67812005]) momentum = df['close in percent'].apply(lambda x: 1 if x &gt; 0 else -1).values Momentum should be: [1,1,1,-1,1,1]. So if I'm finding the average momentum for the last n = 3 days, I want my price momentum to be: Price_momentum = [Nan, Nan, 1, 1/3, 1/3, 1/3] I managed to use the following code to get it working, but this is extremely slow (the dataset is 5000+ rows and it takes 10 min to execute). for i in range(3,len(df)+1,1): data = np.array(momentum[i-3:i]) df['3_day_momentum'].iloc[i-1]=data.mean()
accepted answer: http://stackoverflow.com/a/48244129
tagged with: python
has answer: http://stackoverflow.com/a/48244129
has answer: http://stackoverflow.com/a/48244132
favorite count: 0
type: Question
score: 2
tagged with: numpy
upvote count: 2

http://stackoverflow.com/comment/83568369
type: QuestionComment
comment on: http://stackoverflow.com/q/48272785
score: 0
has text: Thank you. I am uploading an image to the post. @Silencer
type: Comment

http://stackoverflow.com/comment/83480059
comment on: http://stackoverflow.com/q/48248771
score: 0
type: Comment
has text: Well the only thing that comes to my mind would be having additional class that would contain user, his activities and his status.
type: QuestionComment

http://stackoverflow.com/q/48181518
has title: Django - ValueError: --enable-jpeg requested but jpeg not found, aborting
has answer: http://stackoverflow.com/a/48181778
tagged with: python
has body: I am a beginner in Django. I am trying to create an online shop. When I tried to install Pillow using "pip install Pillow==3.0.0" in Windows command prompt, the following error occurs: ValueError: --enable-jpeg requested but jpeg not found, aborting. Rolling back uninstall of pillow How can I fix this issue? Here is the complete code of the error: running install running build running build_py creating build creating build\lib.win32-3.6 creating build\lib.win32-3.6\PIL copying PIL\BdfFontFile.py -&gt; build\lib.win32-3.6\PIL copying PIL\BmpImagePlugin.py -&gt; build\lib.win32-3.6\PIL copying PIL\BufrStubImagePlugin.py -&gt; build\lib.win32-3.6\PIL copying PIL\ContainerIO.py -&gt; build\lib.win32-3.6\PIL copying PIL\CurImagePlugin.py -&gt; build\lib.win32-3.6\PIL copying PIL\DcxImagePlugin.py -&gt; build\lib.win32-3.6\PIL copying PIL\EpsImagePlugin.py -&gt; build\lib.win32-3.6\PIL copying PIL\ExifTags.py -&gt; build\lib.win32-3.6\PIL copying PIL\features.py -&gt; build\lib.win32-3.6\PIL copying PIL\FitsStubImagePlugin.py -&gt; build\lib.win32-3.6\PIL copying PIL\FliImagePlugin.py -&gt; build\lib.win32-3.6\PIL copying PIL\FontFile.py -&gt; build\lib.win32-3.6\PIL copying PIL\FpxImagePlugin.py -&gt; build\lib.win32-3.6\PIL copying PIL\GbrImagePlugin.py -&gt; build\lib.win32-3.6\PIL copying PIL\GdImageFile.py -&gt; build\lib.win32-3.6\PIL copying PIL\GifImagePlugin.py -&gt; build\lib.win32-3.6\PIL copying PIL\GimpGradientFile.py -&gt; build\lib.win32-3.6\PIL copying PIL\GimpPaletteFile.py -&gt; build\lib.win32-3.6\PIL copying PIL\GribStubImagePlugin.py -&gt; build\lib.win32-3.6\PIL copying PIL\Hdf5StubImagePlugin.py -&gt; build\lib.win32-3.6\PIL copying PIL\IcnsImagePlugin.py -&gt; build\lib.win32-3.6\PIL copying PIL\IcoImagePlugin.py -&gt; build\lib.win32-3.6\PIL copying PIL\Image.py -&gt; build\lib.win32-3.6\PIL copying PIL\ImageChops.py -&gt; build\lib.win32-3.6\PIL copying PIL\ImageCms.py -&gt; build\lib.win32-3.6\PIL copying PIL\ImageColor.py -&gt; build\lib.win32-…
has answer: http://stackoverflow.com/a/63409547
type: AnsweredQuestion
downvote count: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/48181778
score: 1
upvote count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/83343521
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48181985
possible better answer: http://stackoverflow.com/a/48181985

http://stackoverflow.com/q/48234609
has comment: http://stackoverflow.com/comment/83451851
has comment: http://stackoverflow.com/comment/83451981
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48234742
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83451930
tagged with: python
has answer: http://stackoverflow.com/a/72551961
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83451883
has comment: http://stackoverflow.com/comment/83451817
tagged with: python-3.6
has answer: http://stackoverflow.com/a/48234720
tagged with: programming-languages
has comment: http://stackoverflow.com/comment/83451970
has comment: http://stackoverflow.com/comment/83451909
score: 0
has comment: http://stackoverflow.com/comment/83451964
has body: So dumb question, but in the code below the guess_compare function is failing (I think because it can’t refer to the inputs ‘guess’ and ‘game word’. Any insights on how to fix? Code below: import random max_guesses=1 guess="" game_word="" def word_gen(): potential_guesses=["hello", "test", "never"] list_length=int(len(potential_guesses)) game_word=potential_guesses[random.randint(1-1,list_length-1)] print (game_word) def guesser(): guess=input("give a letter...") print(guess) def guess_compare(): if guess==game_word[0]: print("correct") else: print("wrong") guess_compare()
has title: Beginner python functions
answer count: 3
has comment: http://stackoverflow.com/comment/83451926

http://stackoverflow.com/q/48277850
has comment: http://stackoverflow.com/comment/83539750
favorite count: 0
has title: PyQt5 button background color not taking effect
type: AnsweredQuestion
score: 1
tagged with: pyqt5
has body: Here is the button's code: self.pushButton.setFont(font) self.pushButton.setStyleSheet("background-color: qlineargradient(spread:pad, x1:0.0568182, y1:0.126, x2:0.75, y2:0.227, stop:0.0738636 rgba(0, 255, 0, 255), stop:0.840909 rgba(0, 136, 0, 255));\n") self.pushButton.setFlat(True) self.pushButton.setObjectName("pushButton") Although I set a background gradient to this button, it's not taking effect. Here's the button normally: Here's when it's pressed down:
type: Question
has comment: http://stackoverflow.com/comment/83545597
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48281478
answer count: 1
accepted answer: http://stackoverflow.com/a/48281478
tagged with: python

http://stackoverflow.com/q/48305400
has body: I don't seem to be able to open the zip3.zip shape file I download from (http://www.vdstech.com/usa-data.aspx) Here is my code: import geopandas as gpd data = gpd.read_file("data/zip3.shp") this gives me the error: CPLE_AppDefinedError: b'Recode from CP437 to UTF-8 failed with the error: "Invalid argument".'
has title: can't open shape file with GeoPandas
has answer: http://stackoverflow.com/a/49525065
answer count: 4
has answer: http://stackoverflow.com/a/48326473
possible better answer: http://stackoverflow.com/a/48326473
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48327334
downvote count: 0
tagged with: geopandas
score: 7
upvote count: 7
has answer: http://stackoverflow.com/a/67027228
has comment: http://stackoverflow.com/comment/83639866
linked to: http://stackoverflow.com/q/47243879
favorite count: 0
tagged with: shapefile
type: Question
has answer: http://stackoverflow.com/a/48327334
tagged with: python

http://stackoverflow.com/comment/83464130
score: 0
has text: please go through the post again, i have added the code
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48240489

http://stackoverflow.com/comment/83446037
comment on: http://stackoverflow.com/a/48227563
has text: thanks! In my case, it looks like the problem is the encoding used when serving the webpack .js bundle. I tested serving this bundle with both nginx and node and the problem went away. Do you know how to use guess_type with .js files?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83629537
type: QuestionComment
score: 0
has text: "Probably, I am supposed to use for loop" - that is a good idea. You should learn how to use for loops (and other kinds of loops) in Python, for example [here](https://wiki.python.org/moin/ForLoop). Once that's done, learn how to plot a histogram with [matplotlib](https://matplotlib.org/gallery/statistics/hist.html), for example.
comment on: http://stackoverflow.com/q/48322071
type: Comment

http://stackoverflow.com/comment/83393077
type: Comment
type: QuestionComment
score: 0
has text: Is there any alternative to gmplot that does not overwrite previously printed lines on the map?
comment on: http://stackoverflow.com/q/48185281

http://stackoverflow.com/q/48272318
answer count: 1
type: AnsweredQuestion
tagged with: pandas
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/48272399
score: 0
accepted answer: http://stackoverflow.com/a/48272399
has body: I have a pandas dataframe that looks like this: Site City ... Year_Built Heritage_Site a Paris ... 1887 Yes b London ... 1858 No c Paris ... 1202 Yes d New York ... 1930 Yes I then used the following statement to calculate the means for some of the variables for each city df_mean = df.groupby('City').mean() However I would also like to add a column at the end of this second dataframe which basically counts the number of occurrences for 'Yes' (in the Heritage_Count column) for each city. Something like what is shown below: City ... Heritage_Count Paris ... 4 London ... 2 New York ... 0 What is the most efficient way to do this?
has title: Pandas counter column

http://stackoverflow.com/q/48295950
answer count: 1
has body: I wrote a little Python script that is supposed to run a webcam-preview and exit it when ESC is pressed (using Pygame). It kind of works, but more often than not it freezes the screen.. Does anyone see any issues with this code? #!/usr/bin/python3 from picamera import PiCamera camera = PiCamera() camera.start_preview() import pygame import subprocess def main(): pygame.init() screen = pygame.display.set_mode((10, 10)) while True: pressed = pygame.key.get_pressed() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: camera.stop_preview() return main()
has comment: http://stackoverflow.com/comment/83578895
has comment: http://stackoverflow.com/comment/83579124
has title: Simple Python Program freezes
type: Question
has answer: http://stackoverflow.com/a/48296026
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/83582406
type: UnansweredQuestion
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/83578837
has comment: http://stackoverflow.com/comment/83584750
score: 0
has comment: http://stackoverflow.com/comment/83576395

http://stackoverflow.com/a/48246152
upvote count: 2
score: 2
type: AcceptedAnswer
has body: It should be as simple as: B[A &gt; 4] = 0
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48246135
answers question: http://stackoverflow.com/q/48246135
type: Answer

http://stackoverflow.com/a/48276514
has body: Using Regex. import re a = ''' Apple iPhone 5s (Space Grey, 16 GB) ''' print re.sub("( )", "", a, flags=re.MULTILINE) Result: Apple iPhone 5s (Space Grey, 16 GB) Using lxml import lxml.etree as et x = et.fromstring(a, parser=et.HTMLParser(remove_comments=True)) print(et.tostring(x))
has comment: http://stackoverflow.com/comment/83549781
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/88617613
downvote count: 3
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48276477
has comment: http://stackoverflow.com/comment/104908613
answers question: http://stackoverflow.com/q/48276477

http://stackoverflow.com/comment/117565634
has text: Do you have any reference for this approach? I am trying to implement something similar (initializing an RNN with other data) and was surprised that I did not find a good reference for it.
comment on: http://stackoverflow.com/q/48233400
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83456767
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48236866
has text: Actually yes, it should be transform instead of fit_transform. But on another data somehow I don't get exactly the same data even when I use transform. But in this example it is ok.

http://stackoverflow.com/comment/83488220
score: 1
comment on: http://stackoverflow.com/q/48252855
type: QuestionComment
has text: Are you trying to search the keys or the values?
type: Comment

http://stackoverflow.com/q/48254575
upvote count: 0
has title: Count @ in all sheets in an excel file
has answer: http://stackoverflow.com/a/48254658
has comment: http://stackoverflow.com/comment/83491870
downvote count: 1
tagged with: excel
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48254658
tagged with: pandas
tagged with: python
has body: So I need to find how many @'s there are in a excel file. My current code return IF theres a @ in the file on the 1 sheet only. I need to find how many @ there is in total, and it should run though all sheets that exsits in the file (number/names can de different each time). Is this even possible? def excel_contains_str(filename, search='@'): return pd.read_excel(filename).astype(str).apply(lambda x: x.str.contains(search)).any().any()
possible better answer: http://stackoverflow.com/a/48254714
favorite count: 0
score: -1
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48254714
answer count: 2
has comment: http://stackoverflow.com/comment/83491893

http://stackoverflow.com/a/48364788
downvote count: 0
upvote count: 1
score: 1
has body: I haven't worked with that library, but I've written another python Knack API wrapper that should help: https://github.com/cityofaustin/knackpy The docs should get you where you want to go. Here's an example: &gt;&gt;&gt; from knackpy import Knack # download data from knack object # will fetch records in chunks of 1000 until all records have been downloaded # optionally pass a rows_per_page and/or page_limit parameter to limit record count &gt;&gt;&gt; kn = Knack( obj='object_3', app_id='someappid', api_key='topsecretapikey', page_limit=10, # not needed; this is the default rows_per_page=1000 # not needed; this is the default ) &gt;&gt;&gt; for row in kn.data: print(row) {'store_id': 30424, 'inspection_date': 1479448800000, 'id': '58598262bcb3437b51194040'},... Hope that helps. Open a GitHub issue if you have any questions using the package.
type: Answer
accepted answer of: http://stackoverflow.com/q/48283609
has comment: http://stackoverflow.com/comment/83785937
answers question: http://stackoverflow.com/q/48283609
type: AcceptedAnswer

http://stackoverflow.com/comment/83506397
has text: First, install this! [cpp build tools](http://landinghub.visualstudio.com/visual-cpp-build-tools). Then try again!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48261497

http://stackoverflow.com/q/48268935
tagged with: importerror
type: Question
tagged with: matplotlib
tagged with: python
type: UnansweredQuestion
tagged with: ubuntu
has answer: http://stackoverflow.com/a/48269212
score: -1
upvote count: 0
answer count: 1
downvote count: 1
has body: I installed matplotlib using conda: conda install matplotlib The following code failed: #!/usr/bin/env python import matplotlib import matplotlib.pyplot as plt With this error message: "ImportError: No module named 'matplotlib.pyplot'" I tried installing matplotlib with apt-get: sudo apt-get install python3-matplotlib I got the same error. I tried loading matplotlib with ubuntu application load and got the same error. I tried cloning from GitHub with: git clone git://github.com/matplotlib/matplotlib.git I got the same error. I looked at the matplotlib directory and did not see a pyplot.py entry. I did find pyplot.py in matplotlib/lib/matplotlib. I copied it to matplotlib. The error went away, but I got another module that pyplot was trying to include. I found it in matplotlib/lib/matplotlib. I copied it to matplotlib. Got another error for another module. Copied it. Eventually I got an error for a module I could not find. I do not know what to try next.
favorite count: 0
has title: Why is matplotlib failing on import matplotlib.pyplot as plt

http://stackoverflow.com/q/48320680
tagged with: keyerror
type: Question
has comment: http://stackoverflow.com/comment/83676954
has comment: http://stackoverflow.com/comment/83649854
type: UnansweredQuestion
tagged with: python
has title: Tensorflow KeyError in executing linearclassifier
has comment: http://stackoverflow.com/comment/83629876
score: 0
answer count: 0
has body: import numpy as np import pandas as pd import tensorflow as tf GENDATA = pd.read_csv('generator_info_labels.csv') GENDATA_SLICED = GENDATA'latitude','longitude','status' GENCLASSIFIER = GENDATA_SLICED.columns[-1] #this will obtain only the last column name only here it is status GENCONTINOUS_COLS = GENDATA_SLICED.columns[:-1] unique_ids = np.unique(GENDATA_SLICED[GENCLASSIFIER]) #this will help to convert the string values of the status values into unique ids automatically GENDICT = {v:k for k, v in enumerate(unique_ids)} label_col = 'status' GENDATA_SLICED[label_col] = [GENDICT[x] for x in GENDATA[GENCLASSIFIER].values.flatten()] feature_columns = [] for f in GENCONTINOUS_COLS: feature_columns += [tf.contrib.layers.real_valued_column(f)] model = tf.contrib.learn.LinearClassifier(feature_columns = feature_columns,n_classes=len(unique_ids)) def input_fn(df=GENDATA_SLICED): feature_cols = {k:tf.constant(df[k].values) for k in GENCONTINOUS_COLS} label = tf.constant(df[label_col].values) return feature_cols,label this is the fit function: model.fit(input_fn=input_fn,steps=3000) new_samples = np.array(([39.8070525,-5.698599],[43.8800776,4.654769]),dtype=np.float64) this is the estimator function: my_input_fn = tf.estimator.inputs.numpy_input_fn(x={"x":new_samples},y=None,num_epochs=2,shuffle=False) predictor function: pred = model.predict_classes(input_fn=my_input_fn) When executing the code I am getting an error which states that KeyError: 'latitude'. Tried to sort it out but not getting the cause of error. My dataset is of three column latitude, longitude and status in which the status is the label which ranges from zero to 3. the tracestack of this program is as follows: Traceback (most recent call last): File "modelfitterror.py", line 51, in &lt;module&gt; pred = model.predict_classes(input_fn=my_input_fn) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/util/deprecation.py", line 381, in new_func return func(*args, **kwargs) File "/usr/local/lib/py…
tagged with: tensorflow

http://stackoverflow.com/comment/83473016
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48244991
has text: I can post an answer if you clarify some things. If the array is length t, and the number of queries is n, which dominates?

http://stackoverflow.com/comment/83468303
has text: Exactly, its basically a shorter way to accomplish the same. If it's confusing you can simply continue using your IF-ELSE block and it'll work just fine.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48242667
type: AnswerComment

http://stackoverflow.com/q/48274851
score: 1
has comment: http://stackoverflow.com/comment/83556143
downvote count: 0
has comment: http://stackoverflow.com/comment/83533662
accepted answer: http://stackoverflow.com/a/48306185
upvote count: 1
has answer: http://stackoverflow.com/a/48306185
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48337499
tagged with: pyspark
tagged with: python
has body: I'm getting an error "int object is unsubscriptable" while executing the following script : element.reduceByKey( lambda x , y : x[1]+y[1]) with element is an key-value RDD and the value is a tuple. Example input: (A, (toto , 10)) (A, (titi , 30)) (5, (tata, 10)) (A, (toto, 10)) I understand that the reduceByKey function takes (K,V) tuples and apply a function on all the values to get the final result of the reduce. Like the example given in ReduceByKey Apache. Any help please?
has title: Error using reducebykey: int object is unsubscriptable
type: AnsweredQuestion
answer count: 2
tagged with: apache-spark
has answer: http://stackoverflow.com/a/48337499

http://stackoverflow.com/q/48197324
has answer: http://stackoverflow.com/a/48197521
accepted answer: http://stackoverflow.com/a/48197521
has answer: http://stackoverflow.com/a/51903541
has comment: http://stackoverflow.com/comment/95638472
favorite count: 0
tagged with: pdb
type: Question
tagged with: python-3.x
tagged with: debugging
has answer: http://stackoverflow.com/a/56083375
score: 5
upvote count: 5
possible better answer: http://stackoverflow.com/a/51903541
tagged with: python
has title: all variables are undefined in python debugger
has body: I'm facing a very strange issue on Python 3.6. In the middle of my code, I call import pdb; pdb.set_trace() to debug some code. And then I'm not able to debug properly, for instance: (Pdb) abc = 3 (Pdb) [abc for _ in range(2)] *** NameError: name 'abc' is not defined (Pdb) [abc, abc] [3, 3] It seems like whenever I use list comprehensions, there is an issue of variable not defined. However, if I call the debugger right after I open Python, I do not observe this behavior, everything runs fine. Any ideas why I'm having this issue?
answer count: 4
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/53126050

http://stackoverflow.com/comment/112948354
comment on: http://stackoverflow.com/a/48234567
type: Comment
type: AnswerComment
has text: As long as only as a single thread is writing through the connection in a given time, this is safe to use.
score: 4

scheduling
tags question: http://stackoverflow.com/q/48244542
tag name: scheduling
type: Tag

http://stackoverflow.com/comment/83559925
type: AnswerComment
has text: It's unbelievable.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48274120

http://stackoverflow.com/q/48211358
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/48211955
has body: I have a loop that read Excel sheets in a document. I want to store them all in a list: DF_list= list() for sheet in sheets: df= pd.read_excel(...) DF_list = DF_list.append(df) If I type: [df df df df] it works. Sorry I have a Matlab background and not very used to Python, but I like it. Thanks.
upvote count: 18
has comment: http://stackoverflow.com/comment/83403925
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83403935
has answer: http://stackoverflow.com/a/60344097
tagged with: list
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/48211955
has answer: http://stackoverflow.com/a/48211478
possible better answer: http://stackoverflow.com/a/48211478
favorite count: 0
type: Question
has title: Python: Store multiple dataframe in list
has answer: http://stackoverflow.com/a/48211403
answer count: 5
has answer: http://stackoverflow.com/a/53118089
score: 18
tagged with: store

http://stackoverflow.com/comment/83523543
type: QuestionComment
has text: I have changed to `x,y = event.x, event.y`, thanks. Still the have not found the right method to get the value of the clicked cell.
score: 0
comment on: http://stackoverflow.com/q/48268506
type: Comment

http://stackoverflow.com/q/48188284
has comment: http://stackoverflow.com/comment/83357001
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48190743
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/48190743
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83356494
tagged with: python
has comment: http://stackoverflow.com/comment/83360352
score: 2
type: AnsweredQuestion
has body: So... I am attempting to teach myself Python. In such, I am attempting to build something that I appear to have no clue about... I have a "workingdir" structure such as: / -- classes/ -- -- install -- myfile In myfile I am simply attempting to "import" the file install by using: import classes.install Which fails with: ImportError: No module named 'classes.install' I have attempted the following as well, and all end the same way, with the same error: import .classes.install sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import classes.install As well as putting an empty __init__.py file inside the classes directory the file install simply contains: class gyo_install(): inst = False # check if we have everything we need installed. def __init__(): print("Hello World") What am I doing wrong? I've searched and searched and searched, everything I see points to the same solutions I've attempted, and none of them work.
accepted answer: http://stackoverflow.com/a/48190297
has title: Python3 Imports Issue
has answer: http://stackoverflow.com/a/48190297
tagged with: ubuntu-16.04
has comment: http://stackoverflow.com/comment/83356696

http://stackoverflow.com/comment/83515759
type: Comment
has text: Thanks for answering. A bit of clarification - the sensor sends pulses and the c code needs to count how many since python's last request.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48266333

http://stackoverflow.com/q/48236030
tagged with: site-packages
has body: I am a python and ubuntu noob and everytime I write a program, I get an error like Traceback (most recent call last): File "demo.py", line 2, in &lt;module&gt; import cv2 ModuleNotFoundError: No module named 'cv2' I have opencv installed and it exists inside the site-packages directory inside the python directory, and I can use it if I go to that directory. How can I make it so I can run a program in my home directory without getting the module not found error?
has title: Python Programs won't access site-packages
has answer: http://stackoverflow.com/a/48236131
has comment: http://stackoverflow.com/comment/83491921
has comment: http://stackoverflow.com/comment/83530500
has comment: http://stackoverflow.com/comment/83455055
type: Question
has comment: http://stackoverflow.com/comment/83524976
has comment: http://stackoverflow.com/comment/83524829
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83562045
has comment: http://stackoverflow.com/comment/83454961
answer count: 1
has comment: http://stackoverflow.com/comment/83455802
tagged with: python
tagged with: ubuntu

http://stackoverflow.com/a/48271689
answers question: http://stackoverflow.com/q/48271167
has body: turns out, an iteration works fine (and quick with a pool.map trick) pool = ThreadPool(multiprocessing.cpu_count()) # get the number of CPU X = pool.map(GetColorHist,[regions[x] for x in range(regions.shape[0])]) X = np.array(X) pool.close() pool.join()
score: 0
type: Answer

http://stackoverflow.com/comment/83456216
comment on: http://stackoverflow.com/q/48235781
has text: Updated to numpy 1.14 and ran the same tests on the command line instead of spyder. The difference is still about a factor 1.7. Running python 2.7.13 (Anaconda custom (x86_64)). Any ideas on speeding this up?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48311795
upvote count: 2
has body: You should add format parameter when calling patch: response = self.client.patch(url, data=data, format='json') Default multipart format does not support nesting I think.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83631277
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48307041
type: Answer
answers question: http://stackoverflow.com/q/48307041

http://stackoverflow.com/q/48193767
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/7771011
has comment: http://stackoverflow.com/comment/83368282
duplicate of: http://stackoverflow.com/q/7771011
has comment: http://stackoverflow.com/comment/83368205
score: 0
tagged with: abstract-syntax-tree
answer count: 0
has body: I am working on the movies dataset and a column for Genres has a very complicated format. It is of type Object with an embedded dictionary. The format looks like JSON format. SO the genres column is a series of json values .A typical value in the first 2 cells are as follows: Cell1: '[{"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 28, "name": "Action"}]' Cell2: '[{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 80, "name": "Crime"}]' Now I want to extract these genres i.e values for the key name into a list. For eg: the first cell should contain [Adventre,Fantasy,Action] second cell should contain [Action,Adventure,Crime] I tried with some string methods, but it didn't work. I also read about the library ast, but I have no idea about the same. How do I achieve the above result?? Thanks
has title: How do I extract the values from the string i.e a syntax tree?
has comment: http://stackoverflow.com/comment/83385719
type: Question
has comment: http://stackoverflow.com/comment/83368249
has comment: http://stackoverflow.com/comment/83368164

http://stackoverflow.com/comment/83651930
type: QuestionComment
has text: Actually, I don't have any values to feed right now because I am using this as model for my android application. Please refer [link](https://blog.metaflow.fr/tensorflow-how-to-freeze-a-model-and-serve-it-with-a-python-api-d4f3596b3adc) for more information
comment on: http://stackoverflow.com/q/48325147
score: 0
type: Comment

http://stackoverflow.com/a/48203283
upvote count: 3
has comment: http://stackoverflow.com/comment/83387586
type: AcceptedAnswer
downvote count: 0
has body: If you simply want just 3 images (maybe it's newest, right), you just deliver your own images context from view to template. Maybe you're using ListView, then you have to use get_context_data to pass other context data. this is simple usage for get_context_data. If you want more info, you can check django official documents for simple mixins (Official docs are really helpful!) Your View example ... def get_context_data(self, **kwargs): context = super(YourListView).get_context_data(**kwargs) context['top_three_images'] = [ product.Image.url for product in Product.objects.exclude(Image=None)[:3] ] return context You can use your own code instead of list comprehension. Then You can simply use top_three_images in template. Your Template {% for image_url in top_three_images %} {% endfor %} p.s. I recommend you to use your model field starting with lower_case (i.e. name, category, image ...) Update You want to show just first three images inside the loop, right? If I understand correctly, I think foorloop.coutner maybe helps. In html, you can use {% if forloop.counter < 4 %} (forloop starts with 1) {% for obj in object_list %} {% if forloop.counter < 4 %} Shanghai, China {% endif %} {% endfor %} Hoping helpful.
answers question: http://stackoverflow.com/q/48203051
has comment: http://stackoverflow.com/comment/83608452
has comment: http://stackoverflow.com/comment/83387498
score: 3
has comment: http://stackoverflow.com/comment/83418844
has comment: http://stackoverflow.com/comment/83387538
type: Answer
has comment: http://stackoverflow.com/comment/83397978
accepted answer of: http://stackoverflow.com/q/48203051

http://stackoverflow.com/q/48313514
upvote count: 1
has answer: http://stackoverflow.com/a/48314836
has body: Plink.exe does not close when the process is finished. The code got stuck when trying to break the while loop by checking if output == ' ': break, but still no luck. I'm able to print the live output, but unable to break the loop when it's completed. #Establish ssh connection to a server def _establish_connection(self): connection='plink -ssh {}@{} -pw {}'.format(self.user,self.server,self.pw) self.sp = Popen(connection,stdin=PIPE,stdout=PIPE) #Trying to read live output from stdout and write to file def _test_create_log(self,_system,_logdir): self._establish_connection() self.sp.stdin.write(_command) timestr = time.strftime("%Y%m%d-%H%M%S") dir_to_log = os.path.join(_logdir,_system + '_' + timestr + '.txt') with open(dir_to_log,'w+') as myLog: while True: output = self.sp.stdout.readline() output.decode('ASCII') if output != '': myLog.write(output) print(output.strip()) else: #Code does not reach here, plink not killed. self.sp.kill() break
favorite count: 0
tagged with: plink
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1191374
tagged with: popen
score: 1
tagged with: ssh
tagged with: python
duplicate of: http://stackoverflow.com/q/1191374
has title: How to kill plink.exe when there's no output from stdout?
type: Question
tagged with: python-2.7
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/9470584
accepted answer: http://stackoverflow.com/a/48314836

http://stackoverflow.com/comment/83588082
comment on: http://stackoverflow.com/a/48301632
type: AnswerComment
has text: Wait, *confused*, so is `Counter()` ordered or not? Are you saying it's not but `print`/`repr` actually does the sorting but calling `.most_common()` under the hood?
score: 0
type: Comment

http://stackoverflow.com/comment/83537776
has text: I believe it's to do with how whole file is being split and that you iterate over it. However "We are not permitted to assign the file to a memory variable" -- isn't that exactly what you are doing with "whole_file"?
comment on: http://stackoverflow.com/a/48276820
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48216930
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48216975
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48216943
has title: pandas set column value based on two conditions
score: 1
tagged with: python
linked to: http://stackoverflow.com/q/36921951
type: Question
answer count: 2
has body: I have a pandas DataFrame. I would like to add a new column with a value of 1 for a new column, y, if the previous value of x is less than 50 and the current value is more than 50. I get this error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). code: import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(40,60,size=(10, 1)), columns=['x']) df['y'] = 1 if (df['x'].shift(1) &lt; 50) and (df['x'] &gt; 50) else 0
downvote count: 0
duplicate of: http://stackoverflow.com/q/36921951
has answer: http://stackoverflow.com/a/48216943
upvote count: 1
possible better answer: http://stackoverflow.com/a/48216975
favorite count: 0

http://stackoverflow.com/a/54864315
score: 2
upvote count: 2
downvote count: 0
has body: According to GIMP doc, we need to discard pixel colors at each end of the Red, Green and Blue histograms which are used by only 0.05% of the pixels in the image and stretch the remaining range as much as possible (Python code): import numpy as np import cv2 # opencv-python import matplotlib.pyplot as plt img = cv2.imread('test.jpg') x = [] # get histogram for each channel for i in cv2.split(img): hist, bins = np.histogram(i, 256, (0, 256)) # discard colors at each end of the histogram which are used by only 0.05% tmp = np.where(hist &gt; hist.sum() * 0.0005)[0] i_min = tmp.min() i_max = tmp.max() # stretch hist tmp = (i.astype(np.int32) - i_min) / (i_max - i_min) * 255 tmp = np.clip(tmp, 0, 255) x.append(tmp.astype(np.uint8)) # combine image back and show it s = np.dstack(x) plt.imshow(s[::,::,::-1]) The result is pretty the same as after GIMP's 'Colors -&gt; Auto -&gt; White Balance' UPD: we need np.clip() because OpenCV and numpy differently casts int32 to uint8: # Numpy np.array([-10, 260]).astype(np.uint8) &gt;&gt;&gt; array([246, 4], dtype=uint8) # but we need just [0, 255]
type: Answer
answers question: http://stackoverflow.com/q/48268068

http://stackoverflow.com/a/48196631
has comment: http://stackoverflow.com/comment/83374442
upvote count: 0
has comment: http://stackoverflow.com/comment/83374321
answers question: http://stackoverflow.com/q/48196412
has body: Actually, if you just put an empty file called __init__.py file, python will treat the directory as a package and you can import it with the dot notation. __init__.py custom_module2.py custom_module.py then from launcher.py from folder.custom_module import custom_function custom_function() The init.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, init.py can just be an empty file, but it can also execute initialization code for the package or set the all variable, described later. Source: https://docs.python.org/3/tutorial/modules.html#Packages
has comment: http://stackoverflow.com/comment/83374500
downvote count: 1
has comment: http://stackoverflow.com/comment/83374581
type: Answer
score: -1

http://stackoverflow.com/comment/83466928
has text: Added a clarification and changed the title to be more clear.
comment on: http://stackoverflow.com/q/48233796
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48197227
has title: Data Science Model and Training - Understanding
has comment: http://stackoverflow.com/comment/83375722
favorite count: 0
tagged with: jupyter-notebook
type: Question
has body: Coming from a programming background where you write code, test, deploy, run.. I'm trying to wrap my head around the concept of "training a model" or a "trained model" in data science, and deploying that trained model. I'm not really concerned about the deployment environment, automation, etc.. I'm trying to understand the deployment unit.. a trained model. What does a trained model look like on a file system, what does it contain? I understand the concept of training a model, and splitting a set of data into a training set and testing set, but lets say I have a notebook (python / jupyter) and I load in some data, split between training/testing data, and run an algorithm to "train" my model. What is my deliverable under the hood? While I'm training a model I'd think there'd be a certain amount of data being stored in memory.. so how does that become part of the trained model? It obviously can't contain all the data used for training; so for instance if I'm training a chatbot agent (retrieval-based), what is actually happening as part of that training after I'd add/input examples of user questions or "intents" and what is my deployable as far as a trained model? Does this trained model contain some sort of summation of data from training or array of terms, how large (deployable size) can it get? While the question may seem relatively simple "what is a trained model", how would I explain it to a devops tech in simple terms? This is an "IT guy interested in data science trying to understand the tangible unit of a trained model in a discussion with a data science guy". Thanks
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83375776
downvote count: 2
has comment: http://stackoverflow.com/comment/83375754
tagged with: machine-learning
has answer: http://stackoverflow.com/a/54176655
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/50946421
tagged with: data-science
has comment: http://stackoverflow.com/comment/83375603
answer count: 3
has comment: http://stackoverflow.com/comment/83375499
has answer: http://stackoverflow.com/a/48197823
upvote count: 1
tagged with: artificial-intelligence

http://stackoverflow.com/q/48285891
tagged with: python
has body: I have a time series with over a hundred million rows of data. I am trying to reshape it to include a time window. My sample data is of shape (79499, 9) and I am trying to reshape it to (79979, 10, 9). The following for loop works fine in numpy. def munge(data, backprop_window): result = [] for index in range(len(data) - backprop_window): result.append(data[index: index + backprop_window]) return np.array(result) X_train = munge(X_train, backprop_window) I have tried a few variations with dask, but all of them seem to hang without giving any error messages, including this one: import h5py import dask.array as da f1 = h5py.File("data.hdf5") X_train = f1.create_dataset('X_train',data = X_train, dtype='float32') x = da.from_array(X_train, chunks=(10000, d.shape[1])) result = x.compute(munge(x, backprop_window)) Any wise thoughts appreciated.
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48290165
upvote count: 1
has answer: http://stackoverflow.com/a/48290165
favorite count: 0
type: Question
has title: For loops with Dask arrays and/or h5py
tagged with: numpy
tagged with: dask
tagged with: h5py

http://stackoverflow.com/comment/83440006
comment on: http://stackoverflow.com/q/48227999
type: QuestionComment
score: 0
has text: @A. Leistra: I am trying to build a random forest on each of the chunks with col4 as my dependent variable, and i am trying to have as much uniform representation of col4 in each of the chunks as possible
type: Comment

http://stackoverflow.com/q/48241666
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83473279
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83465954
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/48242520
has answer: http://stackoverflow.com/a/48242520
has title: Understanding the shape of tensorflow placeholders
type: AnsweredQuestion
has body: I am reading this code and I would like to understand about its implementation. One of the first things that I would like to know, is that what is the shape of some tensor objects (placeholders) such as x_init, xs, h_init, y_init, y_sample, etc. I wrote a line of code such as print(xs.shape) but it wont work. How can I understand the shape of these parameters (tensors)? And can I write something like the following in NumPy? The part of code that defines these tensors look like this: x_init = tf.placeholder(tf.float32, shape=(args.init_batch_size,) + obs_shape) xs = [tf.placeholder(tf.float32, shape=(args.batch_size, ) + obs_shape) for i in range(args.nr_gpu)] # if the model is class-conditional we'll set up label placeholders + # one-hot encodings 'h' to condition on if args.class_conditional: num_labels = train_data.get_num_labels() y_init = tf.placeholder(tf.int32, shape=(args.init_batch_size,)) h_init = tf.one_hot(y_init, num_labels) y_sample = np.split( np.mod(np.arange(args.batch_size * args.nr_gpu), num_labels), args.nr_gpu) h_sample = [tf.one_hot(tf.Variable( y_sample[i], trainable=False), num_labels) for i in range(args.nr_gpu)]
has comment: http://stackoverflow.com/comment/83466363
score: 1

http://stackoverflow.com/a/48253818
answers question: http://stackoverflow.com/q/48253582
has body: If you want to make your code more efficient, it is important, that you state with respect to what you want to make it more efficient. Besides terrible solutions, there is often a trade-off between space (memory) and time (cycles, functions calls) among the reasonable solutions. Aside from efficiency, you should also take readability and maintainability into account. Before doing any kind of optimizations. Tuples like dicts in Python are very efficient, because they are used internally all over place. Most function calls in Python involve tuple creation (for positional arguments) under the hood. As to your concrete example, you can use a generator expression to avoid the temporary list: entries = ((k, v) for k, l in dic.items() for v in l) You still have the intermediate tuples, but they are computed on the fly, while you iterate over the dictionary items. This solution would be more memory efficient than an explicit list, especially if you have lots of entries. You could also just put the nested loop directly into the with body: with open(index_filename,'wb') as out: csv_out=csv.writer(out, delimiter='|') csv_out.writerow(['identifier','descriptor']) for k, v in dic.items(): for ID in v: csv_out.writerow((k, ID)) To avoid the repeated function calls to writerow, you could also resort to writerows, which might be faster. with open(index_filename,'wb') as out: csv_out=csv.writer(out, delimiter='|') csv_out.writerow(['identifier','descriptor']) csv_out.writerows((k, v) for k, l in dic.items() for v in l) If you are really interested in, which method is the fastest, you can use Python's timeit module to make measurements.
type: Answer
score: 0

http://stackoverflow.com/q/48217172
tagged with: django
type: AnsweredQuestion
score: 0
tagged with: python
type: Question
has title: Django ORM: get queryset of one field type
accepted answer: http://stackoverflow.com/a/48217274
tagged with: django-orm
answer count: 1
has answer: http://stackoverflow.com/a/48217274
has body: I have a model ProblemVote which contains user (ForeignKey), problem (ForeignKey) and status field. I need all the problems (which has been voted) with status 'AC' and 'R'. I am able to fetch all the required problems in a Python list. However, i want to know if there is a better way using queryset methods. Part of my code: all_votes = ProblemVote.objects.filter( user=user).select_related("problem").filter(problem__stage='PV') all_votes_problems = [vote.problem for vote in all_votes] accepted_problems = [vote.problem for vote in all_votes if vote.status == 'AC'] rejected_problems = [vote.problem for vote in all_votes if vote.status == 'R'] Getting the problem as a queryset will help me in finding the count as queryset.count() and in finding queryset differences like queryset.difference(another_queryset).

http://stackoverflow.com/a/48296508
has body: Try this: interest = a.findAll("td", {'class': [None, 'indent']}, limit=6) Pass multiple classes as a list (with , separator not with |) Select empty classes with None
type: Answer
has comment: http://stackoverflow.com/comment/83577674
upvote count: 4
has comment: http://stackoverflow.com/comment/83577634
downvote count: 0
answers question: http://stackoverflow.com/q/48296381
score: 4

http://stackoverflow.com/a/48200501
score: 0
answers question: http://stackoverflow.com/q/48200441
type: Answer
has body: This is a problem with the path. I assume your file testfile.txt is located in the same directory where you run your script, called the working directory. Please, try ./testfile.txt. This should work.

http://stackoverflow.com/a/48329424
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48328572
type: Answer
has body: b[b &lt;= a] = np.nan Demo: &gt;&gt; import numpy as np &gt;&gt; a = np.array([3, 7, 8, 9, 2], dtype=float) &gt;&gt; b = np.array([5, 6, 7, 10, 3], dtype=float) &gt;&gt; b[b &lt;= a] = np.nan &gt;&gt; b array([ 5., nan, nan, 10., 3.])
score: 1

http://stackoverflow.com/a/48173646
has comment: http://stackoverflow.com/comment/83326822
accepted answer of: http://stackoverflow.com/q/48173610
score: 1
has comment: http://stackoverflow.com/comment/83326883
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48173610
upvote count: 1
has body: Essentially you didn't initialize the variable has_message in memory. Just add it like so. async def on_reaction_add(self, reaction, user): has_message = None server = reaction.message.server msg = reaction.message if server.id not in self.settings: return if msg.channel.id in self.settings[server.id]["ignore"]: return if not await self.check_roles(user, msg.author, server): return react =self.settings[server.id]["emoji"] if react in str(reaction.emoji): threshold = self.settings[server.id]["threshold"] count = await self.get_count(server, msg) if await self.check_is_posted(server, msg): channel = self.bot.get_channel(self.settings[server.id]["channel"]) msg_id, count = await self.get_posted_message(server, msg) if msg_id is not None: msg_edit = await self.bot.get_message(channel, msg_id) await self.bot.edit_message(msg_edit, new_content="{} **#{}**".format(reaction.emoji, count-1)) return if count &lt; threshold and threshold != 0: store = {"original_message":msg.id, "new_message":None,"count":count+1} for message in self.settings[server.id]["messages"]: has_message = None if msg.id == message["original_message"]: has_message = message if has_message is not None: self.settings[server.id]["messages"].remove(has_message) self.settings[server.id]["messages"].append(store) dataIO.save_json("data/star/settings.json", self.settings) else: self.settings[server.id]["messages"].append(store) dataIO.save_json("data/star/settings.json", self.settings) return if threshold == 0: count = 2 # else:
type: Answer

http://stackoverflow.com/q/48330766
has comment: http://stackoverflow.com/comment/83651784
has comment: http://stackoverflow.com/comment/83647447
type: Question
tagged with: python-3.x
tagged with: sql-server
has comment: http://stackoverflow.com/comment/83685073
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83647713
tagged with: python
tagged with: pyodbc
has body: I'm trying to automate a large database process that is run at the beginning of every month. This is done, currently, with a bunch of stored procedures that are already in the database. My task is currently to get these stored procedures to run via Python's pyodbc. The tricky part about these stored procedures is I need to run them one-at-a-time so they don't hog all of the database's resources. So, to check to see if the stored procedures have been run I created a table that is updated, changing a flag called "IsFinished" to False at the beginning of the procedure to True at the end. The problem occurs when I try to query the database again. The activity monitor in SQL server is showing that my query against the Tracking table as SUSPENDED and blocked by the stored procedure call. I've even gone so far as to create a new database so that I can call both of the databases independently just to further make sure I'm not competing for resources... but I still am competing for resources. I'm using Python 3.6.4 and the pyodbc module. Here's my code. It should be noted that connect_db_1() and connect_db_2() point to two separate databases. conn = connect_db_1() conn.execute("{call dbo.StoredProcedure}") conn2 = connect_db_2() start_time = time.time() finished = False while finished is False: print("Looping") time.sleep(120) cursor = conn2.execute( "SELECT IsFinished from dbo.Tracking where StoredProcedureName='dbo.StoredProcedure'") results = cursor.fetchall() if results[0][0] == True: finished = True print(results) print(f"dbo.StoredProcedure finished in {time_diff(start_time)} seconds.") cursor.close() EDIT: Added a sanitized version of my code.
has answer: http://stackoverflow.com/a/48332357
has title: Python queries are getting gridlocked on SQL Server
score: 0
answer count: 1

http://stackoverflow.com/q/48198413
score: 0
tagged with: ordereddictionary
has comment: http://stackoverflow.com/comment/83378158
answer count: 0
has comment: http://stackoverflow.com/comment/83378350
duplicate of: http://stackoverflow.com/q/21303224
has body: I have an nested OrderedDict data: OrderedDict([('6', OrderedDict([('idx2', ['6', '6', '6']), ('val2', ['A', 'T', 'T']), ('val1', ['C', 'A', 'T']), ('pos', ['11', '15', '23']), ('idx1', ['4', '4', '4'])])), ('3', OrderedDict([('idx2', ['3', '3']), ('val2', ['G', 'C']), ('val1', ['A', 'G']), ('pos', ['28', '34']), ('idx1', ['4', '4'])])), ('4', OrderedDict([('idx2', ['4', '4']), ('val2', ['T', 'C']), ('val1', ['C', 'C']), ('pos', ['41', '51']), ('idx1', ['4', '4'])]))]) I can access the key, value pairs for each keys like: for k, v in grouped_data.items(): print(k, v) and further nests using: for k, v in grouped_data.items(): print(k, v) for x in v.items(): print(x) for z in x: print(z) But, to process my data I need to access two consecutive keys at a time in a for loop: first 6-3 and then 3-4 and so on until the end. I was thinking if I can index the key and get the keys, values after it: for k, v in grouped_data.items(): print(k, v) ind = grouped_data.keys().index(k) Or, for k, v in grouped_data.items(): print(k, v) print(next(k))
has comment: http://stackoverflow.com/comment/83378331
type: Question
has title: Call two keys at a same time from a dictionary on a for-loop
tagged with: for-loop
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/21303224

http://stackoverflow.com/a/71803885
score: 2
upvote count: 2
downvote count: 0
has body: You can now use ThreadingHTTPServer class http.server.ThreadingHTTPServer(server_address, RequestHandlerClass) This class is identical to HTTPServer but uses threads to handle requests by using the ThreadingMixIn. This is useful to handle web browsers pre-opening sockets, on which HTTPServer would wait indefinitely. New in version 3.7.
answers question: http://stackoverflow.com/q/48308487
type: Answer

http://stackoverflow.com/comment/83405103
type: Comment
type: QuestionComment
has text: Uninstall all and re-install?
score: 2
comment on: http://stackoverflow.com/q/48211174

http://stackoverflow.com/q/48311259
tagged with: vigenere
tagged with: python
tagged with: python-3.6
possible better answer: http://stackoverflow.com/a/48311489
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48311489
has body: I'm a beginner in coding and in Python too. Right now I'm working on a Vigenère cipher. I've gotten far enough to encrypt the message using a key. I added comments on each section of code for reference. Here is my code. My question is below the code. # Ask user for message print('type a message.') message = input() # print a white line for neatness print() # ask user for a key print('give your key') key = input() # create a range with the length of the message ran = range(len(message)) # Iterate though the range and therefor show all the letters for i in ran: # get current letters for this iteration currentLetter = message[i] currentKeyLetter = key[i % len(key)] # Get corresponding numbers numberLetter = ord(currentLetter) numberKeyLetter = ord(currentKeyLetter) # Add two letters sumTwoLetters = numberLetter + numberKeyLetter # Get the number of the encrypted letter newNumberLetter = sumTwoLetters % 128 # Get the encrypted number based on number newLetter = chr(newNumberLetter) # print out the result printText = currentLetter + "(" + str(numberLetter) + ") + " printText += currentKeyLetter + "(" + str(numberKeyLetter) + ") = " printText += newLetter + "(" + str(newNumberLetter) + ")" print(printText) The code asks for the user's input for the message and key. The ran variable creates a range with the length of the message. After that, the for loop encrypts the message with the key using ord and chr The encrypted letter is stored in the variable newLetter the user can see what the program has done with printText However, my question is: How can I make the encrypted text appear on a single string. I tried to do it in a loop. I failed miserably (so much so that I don't want to show it) Does anyone have any suggestions on how to make the encrypted message appear in a single line of text?
has answer: http://stackoverflow.com/a/48311484
has title: Vigenère cipher: How to make it so that the encrypted message appears in a print function?
type: Question
accepted answer: http://stackoverflow.com/a/48311484
tagged with: encryption

http://stackoverflow.com/q/48242912
has answer: http://stackoverflow.com/a/48243071
answer count: 2
upvote count: 0
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/83468382
tagged with: python
tagged with: string
has title: How to print a list of different objects in python?
accepted answer: http://stackoverflow.com/a/48243071
has comment: http://stackoverflow.com/comment/83468657
favorite count: 0
has comment: http://stackoverflow.com/comment/83468393
type: AnsweredQuestion
tagged with: list
tagged with: printing
tagged with: oop
possible better answer: http://stackoverflow.com/a/48243020
has answer: http://stackoverflow.com/a/48243020
has body: I have a list (River) of randomly selected objects(Bear and Fish) and I want to print the list with the following format: [B, F, B, ...] (is an example of randomly selected objects). However when I print my River instance I get: [&lt;class '__main__.Bear'&gt;, &lt;class '__main__.Fish'&gt;, &lt;class '__main__.Fish'&gt;, &lt;class '__main__.Fish'&gt;, &lt;class '__main__.Bear'&gt;, ....] Why is this happening? any suggestions? class Bear: def __init__(self): print() def __str__(self): return str('B') def __repr__(self): return self class Fish: def __init__(self): print() def __str__(self): return str('F') def __repr__(self): return self class River: #simulate based on river length INITIAL_RIVER_LENGTH=20 def __init__(self): self._river=[None]*self.INITIAL_RIVER_LENGTH def __str__(self): return str([i for i in self._river]) def __repr__(self): return str(self) def fillRiver(self): self._river=[random.choice([Bear,Fish]) for i in range(0,self.INITIAL_RIVER_LENGTH)] riv=River() riv.fillRiver() print(riv)
type: Question

http://stackoverflow.com/a/48329076
has comment: http://stackoverflow.com/comment/83903360
has body: This is a result of using fork() in the process handler. gRPC Python doesn't support this use case.
type: Answer
answers question: http://stackoverflow.com/q/48174240
score: 2
accepted answer of: http://stackoverflow.com/q/48174240
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83369532
type: Comment
has text: I dunno, what linter are you using? This isn't an error, really...
comment on: http://stackoverflow.com/q/48194381
score: 1
type: QuestionComment

http://stackoverflow.com/q/48214980
score: -1
has comment: http://stackoverflow.com/comment/83411829
upvote count: 0
has title: python nested list format, search for values greater than or latest
answer count: 1
downvote count: 1
tagged with: formatting
has body: Below is in which I have data. a = [{'ID': 319684283, 'ID1': 1025018, 'date': '2018-01-07 17:39:46', 'rate': 9.639e-05, 'amount': 410.84392747, 'total': 0.03960124, 'order': 16532584965, 'type': 'A', 'category': 'website'}, {'ID': 319684282, 'ID1': 1025017, 'date': '2018-01-07 17:39:46', 'amount': 24.84386425, 'total': 0.00239445, 'order': 16532584965, 'type': 'phone', 'category': 'exchange'}, {'ID': 319684281, 'ID1': 1125117, 'date': '2018-01-17 17:39:16', 'amount': 14.8138145, 'total': 0.10239445, 'order': 16512581965, 'type': 'phone', 'category': 'exchange'}] How do I pull record which is latest of these. I tried for c in a: print(min(c['date'] It failed as it is not able to traverse all the elements. How do I achieve the below out put, limited values: d = { 'date': '2018-01-17 17:39:16', 'amount': 14.8138145, 'total': 0.10239445, 'order': 16512581965} Here d should have only the latest value based on date.
has answer: http://stackoverflow.com/a/48215109
duplicate of: http://stackoverflow.com/q/5320871
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83411899
tagged with: nested-lists
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48220660
tagged with: machine-learning
tagged with: keras
tagged with: tensorflow
type: Question
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48225470
has body: I'm trying to implement a NN model with pairwise samples. Details are shown in follows: Original data: X_org with shape of (100, 50) for example, namely 100 samples with 50 features. Y_org with shape of (100, 1). Processing these original data for real training: Select 2 samples from X_org randomly (so we have 100*99/2 such combinations) to form a new 'pairwise' sample, and the prediction target, namely the new y label is the subtraction of the two corresponding y_org labels (Y_org_sample1 - Y_org_sample2). Now we have new X_train and Y_train. I need a more a NN model (DNN, CNN, LSTM, whatever ...), with which I can pass the first sub_sample of one pairwise sample from X_train into the model and will get one result, same step for the second sub_sample. By calculating the subtraction of the two results, I can get the prediction of this pairwise sample. This prediction will be the one compared with the corresponding Y label from Y_train. Overall, I need to train a model (update the weights) after feeding it a 'pairwise' sample (two successive sub samples). The reason why I don't choose a 'two-arm' model (e.g. merge two arms by xxx.sub()) is that I will only feed one sub sample during test process. I will just use the model to predict one sub-sample finally. So I will use the data from X_train during train step, while use X_org-like data format during test step. It looks a bit complex. Looks like Tensorflow would be more feasible for this task, if keras also works, please kindly share your idea.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48225470
tagged with: deep-learning
has title: Using tensorflow or keras to build a NN model by feeding 'pairwise' samples
answer count: 1

http://stackoverflow.com/q/48236584
has comment: http://stackoverflow.com/comment/83458581
answer count: 2
has comment: http://stackoverflow.com/comment/83457026
has comment: http://stackoverflow.com/comment/83456836
has comment: http://stackoverflow.com/comment/83456324
has body: My installation of Anaconda has gone sideways for some reason. I noticed it when I tried to open Jupyter. The start menu shortcut was broken. When I clicked on it, I got the infamous opening and closing of a command line window. I can start it by clicking on the executable but this winds up with the notebook opening in a weird location that I can't move out of. When I try to uninstall and reinstall, I get the same behavior as before. I did some googling and found some Stackoverflow questions like this (which I've since lost so can't post the link), but when I followed the solutions offered, I just get more of the same. I thought there might be something that needed to be blown away from appdata but that didn't seem to fix the issue either.
possible better answer: http://stackoverflow.com/a/53272056
has comment: http://stackoverflow.com/comment/83456880
tagged with: python
has comment: http://stackoverflow.com/comment/83455878
has answer: http://stackoverflow.com/a/53272056
linked to: http://stackoverflow.com/q/29337928
has comment: http://stackoverflow.com/comment/83455888
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83458287
tagged with: anaconda
has answer: http://stackoverflow.com/a/48238444
accepted answer: http://stackoverflow.com/a/48238444
score: 7
has comment: http://stackoverflow.com/comment/83458377
downvote count: 1
has comment: http://stackoverflow.com/comment/83457066
has comment: http://stackoverflow.com/comment/83455882
has comment: http://stackoverflow.com/comment/83458388
upvote count: 8
favorite count: 0
has title: Python - How can I completely uninstall Anaconda on Windows 10?
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/83578376
comment on: http://stackoverflow.com/a/48291478
type: Comment
type: AnswerComment
score: 0
has text: this is the kind of this I was thinking of, yes. I guess there is no better way then. Thanks

http://stackoverflow.com/q/48311594
downvote count: 0
tagged with: error-handling
has title: How to test code throws a `cv2.error` in OpenCV
favorite count: 0
tagged with: unit-testing
type: Question
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48311894
has body: I am using OpenCV for a project (version 3.2.0) and I have a part of my code that calls cv2.grabCut on an image, as in import cv2 cv2.grabCut(image, mask, None, bgd_model, fgd_model, 5, cv2.GC_INIT_WITH_MASK) which fails in the case of images which are somehow too small for it to compute anything. In these cases, the error thrown by OpenCV is cv2.error: /tmp/opencv3-20170714-64983-13zymq9/opencv-3.2.0/modules/imgproc/src/grabcut.cpp:379: error: (-215) !bgdSamples.empty() &amp;&amp; !fgdSamples.empty() in function initGMMs Now, I need to write a unit test that checks this really happens and I'm using unittest for it. How would I go about catching this error? assertRaises isn't looking promising for the job.
has answer: http://stackoverflow.com/a/48311894
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83609279
score: 1
answer count: 1

http://stackoverflow.com/a/48203111
has body: Assuming old_arr and new_arr are the same length, you could do something like this: old_arr = [[8,8,8,8,0,0,0,0,6,6,5,5], [8,8,7,0,0,0,0,0,6,6,5,5]] new_arr = [[9,9,6,7,3,6,5,0,6,4,3,4], [9,0,6,7,4,6,5,0,6,4,3,4]] new_arr = [[x if old[i] else 0 for i, x in enumerate(new)] for old, new in zip(old_arr, new_arr)] print(new_arr) which outputs: [[9, 9, 6, 7, 0, 0, 0, 0, 6, 4, 3, 4], [9, 0, 6, 0, 0, 0, 0, 0, 6, 4, 3, 4]] UPDATE: Here is a brute force solution that deals with neighbouring cells: old_arr = [[8,8,8,8,0,0,0,0,6,6,5,5], [8,8,8,8,0,0,0,0,6,6,5,5], [8,8,8,8,0,0,0,0,6,6,5,5], [8,8,8,8,0,0,0,0,6,6,5,5]] new_arr = [[9,9,6,7,3,6,5,0,6,4,3,4], [9,9,6,7,3,6,5,0,6,4,3,4], [9,9,6,7,3,6,5,0,6,4,3,4], [9,9,6,7,3,6,5,0,6,4,3,4]] def first_last(row, next_row, old, new): for i in range(len(new[row])): count = 0 if old[row][i] == 0: if old[row][i-1] == 0: count += 1 if old[row][i+1] == 0: count += 1 if old[next_row][i] == 0: count += 1 if old[next_row][i-1] == 0: count += 1 if old[next_row][i+1] == 0: count += 1 if count &gt; 4: new[row][i] = 0 def middle(old, new): for i, l in enumerate(new[1:-1]): for j in range(len(l)): count = 0 if old[i][j] == 0: if old[i][j-1] == 0: count += 1 if old[i][j+1] == 0: count += 1 if old[i-1][j] == 0: count += 1 if old[i-1][j-1] == 0: count += 1 if old[i-1][j+1] == 0: count += 1 if old[i+1][j] == 0: count += 1 if old[i+1][j-1] == 0: count += 1 if old[i+1][j+1] == 0: count += 1 if count &gt; 4: l[j] = 0 # first row first_last(0, 1, old_arr, new_arr) # middle rows middle(old_arr, new_arr) # last row first_last(-1, -2, old_arr, new_arr) print(new_arr) Which Outputs: [[9, 9, 6, 7, 3, 0, 0, 0, 6, 4, 3, 4], [9, 9, 6, 7, 0, 0, 0, 0, 6, 4, 3, 4], [9, 9, 6, 7, 0, 0, 0, 0, 6, 4, 3, 4], [9, 9, 6, 7, 3, 0, 0, 0, 6, 4, 3, 4]] Note: This could be made better, but you can optimize it to your liking.
has comment: http://stackoverflow.com/comment/83429876
type: Answer
has comment: http://stackoverflow.com/comment/83397151
has comment: http://stackoverflow.com/comment/83391675
upvote count: 3
has comment: http://stackoverflow.com/comment/83428409
has comment: http://stackoverflow.com/comment/83395725
downvote count: 0
has comment: http://stackoverflow.com/comment/83430191
has comment: http://stackoverflow.com/comment/83429042
answers question: http://stackoverflow.com/q/48202943
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83431868
has comment: http://stackoverflow.com/comment/83432066
accepted answer of: http://stackoverflow.com/q/48202943
score: 3

http://stackoverflow.com/q/48228804
tagged with: python
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/83440057
score: 0
has comment: http://stackoverflow.com/comment/83440166
tagged with: file
tagged with: global-variables
has body: I do not really understand how python handles global variables if the code is split into different files. Assuming I have 3 files: class1.py, class2.py, main.py In main.py I define a global variable from class1 import Class1 from class2 import Class2 global sys sys = constructor() This object contains information about the system which I simulate and is used and manipulated by the classes defined in class1.py and in class2.py. One could of course argue that this is bad style and one should avoid exploiting global variables like this, but this is not the point here. If now I use sys in either class, it is unknown. To use a global variable one could of course define them somewhere and then include this file. But then, the changes that are made by the classes would not effect each other, so I don't want to do this. Another way would be to define a new Class SuperClass where sys is a member. If now Class1 and Class2 are inherited from SuperClass, I could probably do some stuff with the super keyword. I do not really want to do this... Long story short... Is there a way to define an python object such, that it behaves similar to a C-style global variable? Maybe it helps if I give an example: sys includes the system frequency a function of Class1 changes the system frequency a function of Class2 simulates stuff and uses the system frequency based on this the system power is changed in sys a function of Class1 performs a task with updated system power
has answer: http://stackoverflow.com/a/48229151
has comment: http://stackoverflow.com/comment/83440314
type: Question
has title: change global variable in different files
has comment: http://stackoverflow.com/comment/83439970

http://stackoverflow.com/q/48204558
has comment: http://stackoverflow.com/comment/83391811
downvote count: 0
tagged with: python
has body: I have a dataframe like this data_dict = {'Date': [2010,2010,2010], 'Description': ['ZZ','XX','YY'], 'Value': [10,20,30], 'ID':[1,2,3]} df = pd.DataFrame(data_dict) Date Description ID Value 0 2010 ZZ 1 10 1 2010 XX 2 20 2 2010 YY 3 30 I now want to pivot my data like this df_piv = df.pivot(index='Date', columns='Description', values='Value') which gives me this Description XX YY ZZ Date 2010 20 30 10 How can I instead of having a alphabetic column order, order my columns by my ID column to get Description ZZ XX YY Date 2010 10 20 30 Possible solution: description = list(df['Description']) df_piv[description]
has title: Column order when pivoting dataframe
score: 2
type: AnsweredQuestion
tagged with: pandas
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/48250641
accepted answer: http://stackoverflow.com/a/48205394
has answer: http://stackoverflow.com/a/48250641
favorite count: 0
has answer: http://stackoverflow.com/a/48205394
type: Question
answer count: 2
upvote count: 2
tagged with: pivot

http://stackoverflow.com/q/48208905
answer count: 1
favorite count: 0
type: Question
has body: I have problem with find href values in BeautifulSoup` from urllib import urlopen from bs4 import BeautifulSoup import re html = urlopen("https://www.google.pl/search?q=sprz%C4%99t+dla+graczy&amp;client=ubuntu&amp;ei=4ypXWsi_BcLZwQKGroW4Bg&amp;start=0&amp;sa=N&amp;biw=741&amp;bih=624") bsObj = BeautifulSoup(html) for link in bsObj.find("h3", {"class":"r"}).findAll("a"): if 'href' in link.attrs: print(link.attrs['href']) all the time I have error: "AttributeError: 'NoneType' object has no attribute 'findAll'
has comment: http://stackoverflow.com/comment/83398789
upvote count: 1
has comment: http://stackoverflow.com/comment/83398834
tagged with: web-scraping
tagged with: python
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/48209267
type: AnsweredQuestion
has title: Google Scraping href values
accepted answer: http://stackoverflow.com/a/48209267
linked to: http://stackoverflow.com/q/58612344
tagged with: python-2.7
downvote count: 0
score: 1

http://stackoverflow.com/q/48248076
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: permutation
has answer: http://stackoverflow.com/a/48248513
favorite count: 0
has comment: http://stackoverflow.com/comment/83478729
has comment: http://stackoverflow.com/comment/83478763
tagged with: indexing
has title: Generate permutations of indices of identical items
tagged with: python
has comment: http://stackoverflow.com/comment/83478685
type: Question
has body: I have a list a = ['A', 'B', 'A', 'A', 'C'] and I want to generate all possible permutations of item indices for identical items in a list [0,1,2,3,4] [2,1,0,3,4] [3,1,2,0,4] [0,1,3,2,4] [2,1,3,0,4] [3,1,0,2,4] How to do this in a most pythonic way?
linked to: http://stackoverflow.com/q/104420
upvote count: 2
score: 2

http://stackoverflow.com/q/48266653
has title: simple-itk: reading a sequence from a single tiff file
tagged with: simpleitk
answer count: 1
score: 1
favorite count: 0
type: Question
has body: I've got a tif file which contains a series of images. It is a 3D volume of pixels, produced by a CT-scan. But after reading the image with simple-itk, there is only a single layer: reader = sitk.ImageFileReader() reader.SetFileName("FILENAME.tif") img = reader.Execute() img.GetDepth() # 0 arr = sitk.GetArrayFromImage(img) arr.shape # (512, 512, 4) How can I configure simple-itk to read the whole sequence of images from the tif file ? Reading the docs for simple-itk shows how to read sequences of images, from sequences of files. That's not what I need, there is a single tif file for the 3D data. I am able to read this with the tifffile module, it is able to see the correct number of slices and the plots look good, too. So the data itself seems to be valid. I'm afraid since this is medical data, it's not possible for me to provide a sample. I'm just interested in the corresponding simple-itk documentation.
tagged with: tiff
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
tagged with: performance
tagged with: pandas
has answer: http://stackoverflow.com/a/48287913

http://stackoverflow.com/q/48291996
score: 2
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/html
has body: So I have several images using the same line of code to refer to html image links on a page: &lt;a href="#" class="sh-mo__image" data-image="http://somejpgimage.jpeg"&gt; I would like to retrieve the link only but just can't seem to navigate beyond the class to the link. Can anyone help? Also I have "n" number of links which I would like to retrieve separately.
favorite count: 0
tagged with: beautifulsoup
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/83570694
has answer: http://stackoverflow.com/a/48292226
possible better answer: http://stackoverflow.com/a/48292226
has answer: http://stackoverflow.com/a/48295724
accepted answer: http://stackoverflow.com/a/48295724
has title: How to exract link to image "a href" & "class" in a html page using beautifulsoup
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83569094

http://stackoverflow.com/a/48181015
has comment: http://stackoverflow.com/comment/83341877
has comment: http://stackoverflow.com/comment/83341991
answers question: http://stackoverflow.com/q/48181014
type: Answer
score: 0
upvote count: 1
has body: I'm trying to think how a socket works. I think the moment I create one, it choses a tcp source port, Between creating a socket using the socket() system call and using it to create an outgoing connection with the connect() system call, there is an opportunity to optionally use the bind() system call to set source IP address and/or port if you want to. If you don't use bind(), the operating system will automatically bind the socket to the first available port in the appropriate range when you use the connect() system call. In this case, the source IP address is normally selected to match the network interface that provides the shortest route to the specified destination according to the routing table. At least, that's how it works at the system call level. Some programming languages or libraries may choose to combine some of these operations into one. To your actual question, man 7 ip says: A TCP local socket address that has been bound is unavailable for some time after closing, unless the SO_REUSEADDR flag has been set. Care should be taken when using this flag as it makes TCP less reliable. The idea is to delay the re-use of a port until any possible re-sent copies of packages that belonged to the closed connection have for sure expired on the network. According to the bind() man page, trying to re-bind a socket that is already bound to an address will result in an EINVAL error. So "recycling" a socket using bind(socket, INADDR_ANY, 0) (after ending a connection that used SO_REUSEADDR) does not seem to be possible. And even if that would be possible, when you're using multiple threads on a modern multi-core system, you end up (very probably) doing multiple things in parallel. A socket can be used for just one outgoing connection at a time. Each of your scan threads will need its own socket.
has comment: http://stackoverflow.com/comment/83343672
downvote count: 1

http://stackoverflow.com/a/48190676
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48190397
has body: You can use ipython having googleapiclient installed - with something like: sudo pip install --upgrade google-api-python-client You can go to interactive python console and do: from googleapiclient import discovery dir(discovery) help(discovery) dir - gives all entries that object has - so: a = '' dir(a) Will tell what you can do with string object. Doing help(a) will give help for string object. You can do dipper: dir(discovery) # and then for instance help(discovery.re) You can call your script in steps, and see what is result print it, do some research, having something - do %history to printout your session, and have solution that can be triggered as a script.
score: 1
downvote count: 0

http://stackoverflow.com/comment/83473087
has text: @KennyOstrom I have used binary search for sorted indices that contains 1. However that will not work because of the updates of 1 to 0,there will be a need to pop indices that have changed to zero .
comment on: http://stackoverflow.com/q/48244991
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48317127
score: -4
linked to: http://stackoverflow.com/q/26337003
has comment: http://stackoverflow.com/comment/83620540
downvote count: 5
upvote count: 1
tagged with: python
has body: i'm aware this question may look stupid but really i don't get the logic. This is really simple i want to do a program that write or read a file. So i ask the person to enter 'w' or 'r' with an input. As long as the input in not 'w' or 'r' i keep asking. the code below works and i tried diferent ways, but i don't get why it works with a 'and' as for me it should be a 'or': re=input("type w for write , r for read\n") while re != 'w' and re!='r': re=input("type w or r") print("ok")
has comment: http://stackoverflow.com/comment/83619732
has comment: http://stackoverflow.com/comment/83619782
has answer: http://stackoverflow.com/a/48317173
duplicate of: http://stackoverflow.com/q/26337003
has title: and or operator python
has answer: http://stackoverflow.com/a/48317814
has comment: http://stackoverflow.com/comment/83619886
has comment: http://stackoverflow.com/comment/83619794
has comment: http://stackoverflow.com/comment/83620429
tagged with: operators
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83620078
type: UnansweredQuestion

mouseevent
tags question: http://stackoverflow.com/q/48322332
type: Tag
tags question: http://stackoverflow.com/q/48315063
tag name: mouseevent

http://stackoverflow.com/q/48176034
has title: Batch create campaigns via Facebook ads API with Python?
downvote count: 0
has body: I'm trying to build an API tool for creating 100+ campaigns at a time, but so far I keep running into timeout errors. I have a feeling it's because I'm not doing this as a batch/async request, but I can't seem to find straightforward instructions specifically for batch creating campaigns in Python. Any help would be GREATLY appreciated! I have all the campaign details prepped and ready to go in a Google sheet, which my script then reads (using pygsheets) and attempts to create the campaigns. Here's what it looks like so far: from facebookads.adobjects.campaign import Campaign from facebookads.adobjects.adaccount import AdAccount from facebookads.api import FacebookAdsApi from facebookads.exceptions import FacebookRequestError import time import pygsheets FacebookAdsApi.init(access_token=xxx) gc = pygsheets.authorize(service_file='xxx/client_secret.json') sheet = gc.open('Campaign Prep') tab1 = sheet.worksheet_by_title('Input') tab2 = sheet.worksheet_by_title('Output') # gets range size, offsetting it by 1 to account for the range starting on row 2 row_range = len(tab1.get_values('A1', 'A', returnas='matrix', majdim='ROWS', include_empty=False))+1 # finds first empty row in the output sheet start_row = len(tab2.get_values('A1', 'A', returnas='matrix', majdim='ROWS', include_empty=False)) def create_campaigns(row): campaign = Campaign(parent_id=row[6]) campaign.update({ Campaign.Field.name: row[7], Campaign.Field.objective: row[9], Campaign.Field.buying_type: row[10], }) c = campaign.remote_create(params={'status': Campaign.Status.active}) camp_name = c['name'] camp_id = 'cg:'+c['id'] return camp_name, camp_id r = start_row # there's a header so I have the range starting at 2 for x in range(2, int(row_range)): r += 1 row = tab1.get_row(x) camp_name, camp_id = create_campaigns(row) # pastes the generated campaign ID, campaign name and account id back into the sheet tab2.update_cells('A'+str(r)+':C'+str(r).format(r),[[camp_id, camp_name, row[6].rsplit('_',1)[1]]]) I've …
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/68813247
type: UnansweredQuestion
tagged with: facebook-ads-api
tagged with: facebook-marketing-api
has answer: http://stackoverflow.com/a/48397018
tagged with: python
has comment: http://stackoverflow.com/comment/83332529
answer count: 2
has comment: http://stackoverflow.com/comment/83359233
score: 1

http://stackoverflow.com/q/48218019
type: Question
answer count: 2
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48218552
has body: I was wondering why the following works: def wrapper(): def wrap(p=10): def f(): print(p) f() return wrap f2 = wrapper() f2() But this doesn't: def f(): print(p) def enhance(f): def wrap(p=10): f() return wrap f2 = enhance(f) f2() # NameError: name 'p' is not defined Is there a way I can modify the second scenario so that variable p is defined? I was playing around with function decorators but couldn't figure it out how to expose the variables to the function I'm passing into the decorators.
has title: Define variables for a Python function that is implemented outside of the current scope
score: 1
has answer: http://stackoverflow.com/a/48218089

scroll
type: Tag
tag name: scroll
tags question: http://stackoverflow.com/q/48246360

http://stackoverflow.com/a/48234553
score: -1
upvote count: 0
has body: You can use dict.items(): x = {1: {2: 4, 3: 6}, 5: {2:6, 10: 25, 14: 12}} final_x = set(i for b in [b.keys() for i, b in x.items()] for i in b) Output: set([2, 3, 10, 14])
downvote count: 1
has comment: http://stackoverflow.com/comment/83451663
answers question: http://stackoverflow.com/q/48234438
type: Answer

http://stackoverflow.com/q/48238599
tagged with: class
tagged with: binding
score: 1
has title: Python class binding not working, throws errors
answer count: 1
has comment: http://stackoverflow.com/comment/83459886
favorite count: 0
type: Question
type: UnansweredQuestion
has body: So I've been watching a video tutorial on classes in Python, and the code looks like this: class MyPythonClass(): def _init_(self, msg): self.msg = msg self.print_msg() def print_msg(self): print(self.msg) inst = MyPythonClass('hello') That's copied pretty much verbatim, and the code works in the video. But when using it as above in Eclipse workspace, i get the following error: TypeError: object() takes no parameters And, when using it with the class method print_msg('hello') instead, I get the following error: TypeError: say_hello() takes 1 positional argument but 2 were given I only passed 1 string argument, not 2 arguments, right.. Btw, the tutorial I think uses around Python 3.1, while I'm using Python 3.6. Why do I get these errors?
downvote count: 0
has comment: http://stackoverflow.com/comment/83459529
has answer: http://stackoverflow.com/a/48238628
upvote count: 1
tagged with: python

http://stackoverflow.com/a/48261315
type: Answer
has body: well, in Python you need to use def functionname(): to define a function, you also need to indent code inside function
answers question: http://stackoverflow.com/q/48260756
score: 0

http://stackoverflow.com/comment/83404581
comment on: http://stackoverflow.com/a/48211285
has text: Thanks very much. Exactly what i NEEDED.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48176093
has comment: http://stackoverflow.com/comment/83337952
score: 0
answers question: http://stackoverflow.com/q/48175322
type: Answer
has body: A simple way to get this to work would be writing to a new .csv as you iterate over the first. though, it does look like you're intending to use pandas so why not load it into a dataframe, modify it within the frame and save it back to the file.

http://stackoverflow.com/q/48199775
tagged with: django
has comment: http://stackoverflow.com/comment/83380830
type: AnsweredQuestion
score: 0
has title: Django switch the primary server to secondary along with mysql db
has comment: http://stackoverflow.com/comment/83380710
tagged with: python
tagged with: mysql
has body: I'm completely new to Django. I have developed a simple web application in Django and hosted it on external server. And that web application uses default mysql database. Now, I want to switch to a secondary server if my primary server goes down. Copying and running the same code is not the option. Can anyone explain how do I do it along with an example ?
accepted answer: http://stackoverflow.com/a/48200661
tagged with: failover
has answer: http://stackoverflow.com/a/48200661
type: Question
answer count: 1

http://stackoverflow.com/comment/83603042
has text: @Jeff My solution is to fetch required `input` by single XPath expression. The second (additional) solution is just to explain why OP failed with its initial code
comment on: http://stackoverflow.com/a/48248042
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83574739
has text: The usage and example are good. I learned a new approach to same problem with this. Thanks for your kind efforts.
comment on: http://stackoverflow.com/a/48274031
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48295855
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48295750
has body: You can use lxml for this. Something like this: from lxml import html import request response = request.get('&lt;your url&gt;') tree = html.fromstring(response.text) href = tree.xpath('//a[@class="subnav__item"]/@href') This should get you all the href in from the class "subnav__item"

http://stackoverflow.com/q/48323349
has title: How do I get python to only accept alphabet inputs?
has comment: http://stackoverflow.com/comment/83631990
has comment: http://stackoverflow.com/comment/83632147
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83631979
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48323426
linked to: http://stackoverflow.com/q/23294658
type: UnansweredQuestion
score: -2
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/83632162
has body: I'm a noob at programming but I wanted the script to only accept alphabet inputs rather than numbers too. Especially only one alphabet. Thanks for x in range (0, 90000): ("Type alphabet") cha1=input() complete = choice(list1) if (cha1) == (complete): print ("Try again") if (cha1) != (complete): print (complete)

http://stackoverflow.com/comment/83615028
comment on: http://stackoverflow.com/a/48294752
score: 0
type: Comment
type: AnswerComment
has text: is there a way to only limit to rows which contains (?) , the current solution returns all the rows

http://stackoverflow.com/comment/83518351
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48267586
has text: ':' is a place holder for [all of them](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html)

http://stackoverflow.com/comment/83388927
has text: @devlincarnateMy requirements at different of your example, and I can't use it. I must try with other method.
score: 0
comment on: http://stackoverflow.com/q/48192535
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48307084
score: 0
type: Answer
has body: You can use the total_seconds method in datetime type print datetime.timedelta(0, 65912).total_seconds() 65912.0
answers question: http://stackoverflow.com/q/48306958
has comment: http://stackoverflow.com/comment/83600604

http://stackoverflow.com/a/74716581
answers question: http://stackoverflow.com/q/48286217
has body: You also can do it in this way: import boto3 def copy_file_to_public_folder(): s3 = boto3.resource('s3') src_bucket = s3.Bucket("source_bucket") dst_bucket = "destination_bucket" for obj in src_bucket.objects.filter(Prefix=''): # This prefix will got all the files, but you can also use: # (Prefix='images/',Delimiter='/') for some specific folder print(obj.key) copy_source = {'Bucket': "source_bucket", 'Key': obj.key} # and here define the name of the object in the destination folder dst_file_name = obj.key # if you want to use the same name s3.meta.client.copy(copy_source, dst_bucket, dst_file_name) This basically will take all the objects in the origin bucket and copy to the next one.
score: 0
type: Answer

http://stackoverflow.com/a/48320350
score: 1
answers question: http://stackoverflow.com/q/48320167
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/88388773
type: Answer
has comment: http://stackoverflow.com/comment/83822689
has body: I set this on top of the python script and the output started showing on the Jenkins Console: #!/usr/bin/env python -u

http://stackoverflow.com/q/48194362
has comment: http://stackoverflow.com/comment/83401614
type: Question
has comment: http://stackoverflow.com/comment/83369647
has body: The following code gives an error: filename='foo.txt' sed_str = 'PROJECT_DIR=\$\{PROJECT_DIR:-{}\}'.format(filename) print (sed_str) Results in: --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-12-9ac4d7cde75e&gt; in &lt;module&gt;() 1 filename='foo.txt' ----&gt; 2 sed_str = 'PROJECT_DIR=\$\{PROJECT_DIR:-{}\}'.format(filename) 3 print (sed_str) KeyError: 'PROJECT_DIR' Why am I seeing a KeyError?
has comment: http://stackoverflow.com/comment/83401086
has answer: http://stackoverflow.com/a/48231375
score: 1
has comment: http://stackoverflow.com/comment/83400868
tagged with: python
has comment: http://stackoverflow.com/comment/83369376
has comment: http://stackoverflow.com/comment/83369401
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83369819
answer count: 2
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83400583
has title: Key Error in Python string with format call
tagged with: string
has answer: http://stackoverflow.com/a/48209976
favorite count: 0

http://stackoverflow.com/q/48233313
has comment: http://stackoverflow.com/comment/83449363
has answer: http://stackoverflow.com/a/54709677
has answer: http://stackoverflow.com/a/48233689
accepted answer: http://stackoverflow.com/a/48233689
tagged with: python
upvote count: 4
has title: How to efficiently extract values from nested numpy arrays generated by loadmat function?
has comment: http://stackoverflow.com/comment/83449377
answer count: 4
tagged with: scipy
linked to: http://stackoverflow.com/q/37996883
has comment: http://stackoverflow.com/comment/83449442
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48233482
possible better answer: http://stackoverflow.com/a/48233482
has body: Is there a more efficient method in python to extract data from a nested python list such as A = array([[array([[12000000]])]], dtype=object). I have been using A[0][0][0][0], it does not seem to be an efficinet method when you have lots of data like A. I have also used numpy.squeeeze(array([[array([[12000000]])]], dtype=object)) but this gives me array(array([[12000000]]), dtype=object) PS: The nested array was generated by loadmat() function in scipy module to load a .mat file which consists of nested structures.
tagged with: nested-lists
has comment: http://stackoverflow.com/comment/83449196
has comment: http://stackoverflow.com/comment/83449298
downvote count: 0
has answer: http://stackoverflow.com/a/57814205
score: 4
has comment: http://stackoverflow.com/comment/83449413
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/q/48233613
has title: 2 tkinter files cannot communicate with each other
tagged with: python
has comment: http://stackoverflow.com/comment/83456043
has comment: http://stackoverflow.com/comment/83461076
has comment: http://stackoverflow.com/comment/83460359
has comment: http://stackoverflow.com/comment/83456074
type: Question
tagged with: tkinter
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48239383
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/83461061
has body: I'm very new Python coding and I'm having trouble linking my tkinter files, currently have 2 files 1 is the welcomescreen.py where user selects the form they wish to fill out, now I want user to go to the form they have selected do the activity and comebck to welcome, like press the quit button. from tkinter import * from tkinter import ttk from tkinter import messagebox class Feedback: def __init__(self, master): #CODING #at the end def main(): root = Tk() feedback = Feedback(root) root.mainloop() if __name__ == "__main__":main() and second file is something like this, actually i coded it pretty much in the same manner from tkinter import * from tkinter import ttk from tkinter import messagebox class Proj_pres: """Defininf clickable labels in frame""" # CODES # CODES # at the end def main(): root = Tk() proj_pres = Proj_pres(root) root.mainloop() if __name__ == '__main__':main() I tried the exec command but it didn't help.

http://stackoverflow.com/a/48284830
answers question: http://stackoverflow.com/q/48284548
type: Answer
has body: I know you said you prefer to not have to remove the "nan". However, I know of no other way to get the line to connect (without interpolation, or filling the data somehow). So, I suspect the easiest options might be to remove the "nan" from y and the corresponding index in x. &gt;&gt;&gt; del x[y.index("nan")] &gt;&gt;&gt; x [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12] &gt;&gt;&gt; y.remove("nan") &gt;&gt;&gt; y [1, 2, 5, 4, 7, 4, 2, 5, 4, 4, 1]
has comment: http://stackoverflow.com/comment/83562506
score: 0

http://stackoverflow.com/comment/83395528
type: QuestionComment
type: Comment
has text: I don't see any calling convention defined...
score: 0
comment on: http://stackoverflow.com/q/48204483

http://stackoverflow.com/comment/83463558
score: 0
type: Comment
type: QuestionComment
has text: Yes, exactly. The `data` dictionary should contain a `'name':'value'` item for every input.
comment on: http://stackoverflow.com/q/48235445

google-bigquery
tags question: http://stackoverflow.com/q/48225833
tags question: http://stackoverflow.com/q/48246346
tags question: http://stackoverflow.com/q/48265989
tags question: http://stackoverflow.com/q/48193436
tags question: http://stackoverflow.com/q/48191376
tags question: http://stackoverflow.com/q/48184120
tags question: http://stackoverflow.com/q/48287942
type: Tag
tag name: google-bigquery

timer
tag name: timer
tags question: http://stackoverflow.com/q/48232001
tags question: http://stackoverflow.com/q/48293224
type: Tag

http://stackoverflow.com/q/48234438
has title: set of keys for nested dictionaries
type: Question
has body: I have a couple lines to populate a set. x = {1: {2: 4, 3: 6}, 5: {2:6, 10: 25, 14: 12}} keys = set() for y in x: for z in x[y]: keys.add(z) # keys is now `set([2, 3, 10, 14])` I can't shake the feeling that I can do this better, but nothing I come up with is seems great. Most implementations build a list first, which is annoying. There are lots of x in y, and most y have the same z. # Builds a huuuuge list for large dicts. # Adapted from https://stackoverflow.com/a/953097/241211 keys = set(itertools.chain(*x.values())) # Still builds that big list, and hard to read as well. # I wrote this one on my own, but it's pretty terrible. keys = set(sum([x[y].keys() for y in x], [])) # Is this what I want? # Finally got the terms in order from https://stackoverflow.com/a/952952/241211 keys = {z for y in x for z in x[y]} Is the original code the "most pythonic" or is one of the one-liners better? Something else?
tagged with: set-comprehension
tagged with: python
has answer: http://stackoverflow.com/a/48234553
has answer: http://stackoverflow.com/a/48234563
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/48234565
accepted answer: http://stackoverflow.com/a/48234565
answer count: 3
has comment: http://stackoverflow.com/comment/83451715
linked to: http://stackoverflow.com/q/952914
possible better answer: http://stackoverflow.com/a/48234563

http://stackoverflow.com/q/48234274
has body: Why does WHERE index = ? run more quickly than WHERE prop_link = ? Imagine the following table: Name: addresses Columns: idx (INTEGER PRIMARY KEY), full_street (TEXT), prop_link (TEXT) Length: 100 million rows Now imagine the following two lines of code. cursor.execute("UPDATE addresses SET full_street = ? WHERE prop_link = ?", (street_var, property_link_var)) cursor.execute("UPDATE addresses SET full_street = ? WHERE idx = ?", (street_var, idx_var)) I have had to deal with this table a lot over the past few days. For several of those days I was stuck because my code was freezing on the 'WHERE prop_link = ?' line and even waiting for an hour, it wouldn't unfreeze and I couldn't figure out why. When I tried using the 'WHERE idx = ?' line, surprisingly, my code began completing in fractions of a millisecond. Why is that? I have looked at https://sqlite.org/queryplanner.html and https://sqlite.org/optoverview.html and https://docs.python.org/3/library/sqlite3.html#connection-objects and maybe I missed it, but I wasn't able to find why the speed-up is so drastic. My guess is either some type of hash-map or a binary search, but I want to be able to better understand it so I can write performant code (100 million rows).
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/83451554
tagged with: sqlite
has comment: http://stackoverflow.com/comment/83452166
tagged with: database-performance
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83451234
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83451254
tagged with: python
score: 2
has title: Python SQLite3 UPDATE performance
has comment: http://stackoverflow.com/comment/83451198

http://stackoverflow.com/comment/83447317
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48199138
has text: Are you counting the total IDs per group?

http://stackoverflow.com/q/48235676
has comment: http://stackoverflow.com/comment/83454019
type: Question
has answer: http://stackoverflow.com/a/48235898
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83454729
tagged with: sys
has answer: http://stackoverflow.com/a/48235734
has title: How do you read output (assign output to variables) printed data in python?
has comment: http://stackoverflow.com/comment/83454419
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/37847232
downvote count: 6
linked to: http://stackoverflow.com/q/30664263
has body: Let's say I wrote the following python script: print("Hello") print("Line 2") print("Goodbye") The output would of course be: Hello Line 2 Goodbye After printing this data is there any way I could read it? In other words, can you read printed data with python?
answer count: 2
linked to: http://stackoverflow.com/q/6086047
score: -5
has comment: http://stackoverflow.com/comment/83453978
favorite count: 0

http://stackoverflow.com/q/48300027
upvote count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83584539
tagged with: python
has comment: http://stackoverflow.com/comment/83584981
downvote count: 1
has comment: http://stackoverflow.com/comment/83584587
possible better answer: http://stackoverflow.com/a/48301736
has body: I have an array in which URLs are stored like this: ['https://techcrunch.com', 'https://techcrunch.com/event-info/sessions-robotics/ ', 'mashable.com', 'mashable.com/2018/01/09/fighting-robot-toy-ces-zeus/ ', 'http://tech.co'] Now, what I would like to do is to remove those URLs if their blog version is available. For example techcrunch blog (https://techcrunch.com/event-info/sessions-robotics/) is already presented in the array so I want to remove (https://techcrunch.com). Similarly, for the mashable. But, not for the (http://tech.co) as there is no blog version availble from this domain name in the array. The end result that I want should be from this: ['https://techcrunch.com', 'https://techcrunch.com/event-info/sessions-robotics/ ', 'mashable.com', 'mashable.com/2018/01/09/fighting-robot-toy-ces-zeus/ ', 'http://tech.co'] To this: ['https://techcrunch.com/event-info/sessions-robotics/','mashable.com/2018/01/09/fighting-robot-toy-ces-zeus/ ', 'http://tech.co']
has comment: http://stackoverflow.com/comment/83585316
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83585580
favorite count: 0
score: -1
accepted answer: http://stackoverflow.com/a/48300765
has title: Removing only the root domains from the array
has comment: http://stackoverflow.com/comment/83586520
has comment: http://stackoverflow.com/comment/83585034
has answer: http://stackoverflow.com/a/48301736
has answer: http://stackoverflow.com/a/48300765
type: Question

http://stackoverflow.com/comment/137129089
has text: Check [this answer](https://stackoverflow.com/a/68666505/3322273). In short, when you use PyInstaller, they provide you with kind of a hook that you should use within your application, to close the splash screen at the exact moment that you desire.
type: Comment
comment on: http://stackoverflow.com/a/68616926
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83336567
type: QuestionComment
has text: Furthermore the answers [there](https://stackoverflow.com/questions/17346950/how-to-import-a-single-function-to-my-main-py-in-python-from-another-module) are both garbage. New dupe is better, though.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48178011

http://stackoverflow.com/a/48309853
has comment: http://stackoverflow.com/comment/83628200
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83607168
has comment: http://stackoverflow.com/comment/83624383
has body: The error in your code is from appending to results list with an incorrect number of arguments. results.append(url, word + ' YES') can be written as appending a joined string of url, word and verdict delimited by ,: results.append(','.join((url, word, 'YES'))) BONUS: Things that can change in your code The following code block: url = line.strip().split(',')[0] word = line.strip().split(',')[1] can be rewritten as: url, word = line.strip().split(',') to save from splitting line twice The following blocks can be removed as context managers handle file closing implicitly. if not inputfile.closed: inputfile.close() print '&gt;&gt;&gt;' + inputfile + ' closed: ' + inputfile.closed And if not outputfile.closed: outputfile.close() print '&gt;&gt;&gt;' + outputfile + ' closed: ' + outputfile.closed Lastly, out_f isn't being written to. That's a potential AttributeError calling write on a string.
accepted answer of: http://stackoverflow.com/q/48307114
has comment: http://stackoverflow.com/comment/83627184
has comment: http://stackoverflow.com/comment/83623731
type: Answer
answers question: http://stackoverflow.com/q/48307114
has comment: http://stackoverflow.com/comment/83607030
has comment: http://stackoverflow.com/comment/83618720
score: 0

http://stackoverflow.com/comment/83435747
has text: Not deep learning, just the methods commonly used by opencv, is there a GPU mode?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48226996
type: AnswerComment

google-cloud-storage
tags question: http://stackoverflow.com/q/48240489
tags question: http://stackoverflow.com/q/48303791
tags question: http://stackoverflow.com/q/48285212
tags question: http://stackoverflow.com/q/48305785
tags question: http://stackoverflow.com/q/48279061
type: Tag
tags question: http://stackoverflow.com/q/48314092
tag name: google-cloud-storage
tags question: http://stackoverflow.com/q/48275475
tags question: http://stackoverflow.com/q/48294492

http://stackoverflow.com/comment/83438623
type: AnswerComment
has text: It does answer the question if you understood it. The problem is that there are 5 inputs that all have the same ID on the page but only one of them will be visible at any given time. As the site size changes, the element that is displayed changes. This approach is flexible yet still simple and finds only the displayed input and will do so no matter the size/mode of the site. The first line gets all 5 inputs and filters them down to only the one that is displayed. The second line just gets the first (and only) element in the list and sends the text to it.
comment on: http://stackoverflow.com/a/48180526
type: Comment
score: 0

http://stackoverflow.com/comment/83383091
comment on: http://stackoverflow.com/a/48200773
type: Comment
has text: Wow. thanks for all the options. How would you rank as speed wise?
score: 0
type: AnswerComment

http://stackoverflow.com/q/48189750
tagged with: list
has title: Manipulating list of dictionary in a single line list comprehension
score: 1
has body: I have a list like below: l = [{'Value': 'value1', 'Key': 'key1'}, {'Value': 'value2', 'Key': 'key2'}, {'Value': 'value3', 'Key': 'key3'}] I want a output list as below: lst = [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}] My code is as below: lst = [] for item in l: key = item["Key"] value = item["Value"] dict = {} dict[key] = value lst.append(dict) Is it possible to do the same in a single line with list comprehension?
answer count: 1
tagged with: python
tagged with: list-comprehension
favorite count: 0
accepted answer: http://stackoverflow.com/a/48189806
type: Question
has answer: http://stackoverflow.com/a/48189806
upvote count: 3
downvote count: 2
tagged with: dictionary
type: AnsweredQuestion

http://stackoverflow.com/q/48253733
downvote count: 1
has body: I have the following piece of web page's HTML code: Also, I have the list of link names as follows: links_dict = {} links = ["Slack","Twitter","Telegram"] I want to extract href values for each corresponding link. If there is no href (see Slack in the sample code above), it means that there is no link. The expected output is the following: "Slack" -> "None" "Twitter" -> "https://twitter.com/abc" "Telegram" -> "https://t.me/abc" I cannot access a href just by a, because there are many other div elements with other a. I would like to use BeautifulSoap or Selenium with PhantomJS. This is what I tried: BeautifulSoap: res = requests.get("https://myurl.com") soup = BeautifulSoup(res.content,'html.parser') tags = soup.find_all(class_="align-center") for tag in tags: print tag.text.strip() Selenium: driver = webdriver.PhantomJS() driver.set_window_size(1120, 550) driver.get("https://mytest.com") tags = driver.find_elements_by_class_name("align-center") for tag in tags: tag.find_element_by_tag_name("a").click() url = driver.current_url print(url) driver.quit()
favorite count: 0
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/48254351
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/83534611
tagged with: python
has title: How to extract a href from a given div?
has answer: http://stackoverflow.com/a/48259099
has comment: http://stackoverflow.com/comment/83539350
tagged with: phantomjs
type: AnsweredQuestion
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/48254351
tagged with: selenium
has answer: http://stackoverflow.com/a/48254078
possible better answer: http://stackoverflow.com/a/48254078
upvote count: 1

http://stackoverflow.com/q/48246644
has answer: http://stackoverflow.com/a/48247185
answer count: 1
tagged with: python
favorite count: 0
type: Question
has title: list of dates, how to get count of individual quarters
type: UnansweredQuestion
has body: i have list of date, how to get count of individual quarters 1Q2015 2Q2015 3Q2015 4Q2015 1Q2016 2Q2016 3Q2016 4Q2016 1Q2017 2Q2017 list of data 10 1Q2016 11 1Q2017 12 1Q2015 13 1Q2016 14 1Q2016 15 2Q2017 16 1Q2016 17 4Q2016 18 1Q2016 19 4Q2017 20 1Q2016 21 1Q2016 22 1Q2016 23 1Q2016 24 1Q2016 25 1Q2016 26 1Q2016 27 1Q2016 28 1Q2016 29 1Q2016 ... 53 2Q2016 54 2Q2015 55 2Q2016 56 2Q2016 57 2Q2017 58 2Q2016 59 2Q2016 how to split them into sublist of 1Q2015 2Q2015 3Q2015 4Q2015 1Q2016 2Q2016 3Q2016 4Q2016 1Q2017 2Q2017 I am new to python it worked with below code from collections import Counter pidx2 = Counter((quarter))
downvote count: 6
has comment: http://stackoverflow.com/comment/83475982
score: -5
upvote count: 1

http://stackoverflow.com/comment/83563191
has text: @jpaugh Ideally, I would like to be able to pull that class="result-win" as I only care about the result of the game, not the score itself. I appreciate you working with me on this as I'm at a roadblock right now with how to go about parsing this table. Thanks.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48216663
score: 0

http://stackoverflow.com/comment/83500409
has text: Thanks for the help. Here's the answer. newDF = df2.sort_values(df2.columns.tolist()).reset_index(drop=True).apply(lambda x: x.drop_duplicates()) print(newDF)
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48257936

http://stackoverflow.com/comment/83404733
score: 0
type: Comment
type: QuestionComment
has text: Can you post your expect output. Also, use `df.head().to_dict()` to provide some initial data for testing.
comment on: http://stackoverflow.com/q/48211344

http://stackoverflow.com/q/48282281
has comment: http://stackoverflow.com/comment/83550882
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/92962700
has comment: http://stackoverflow.com/comment/93434423
has body: Question is stupid, by i cant find solution. What a valid format for saving nested array of time from simple form text field? I have ArrayField like this: schedule = ArrayField( ArrayField( ArrayField( models.TimeField(null=True), ), size=2, null=True, ), size=7, null=True, blank=True, ) When i am trying to save it from django admin like: ((09:00, 09:00), (09:00, 09:00), (09:00, 09:00), (09:00, 09:00), (09:00, 9:00), (9:00, 9:00), (9:00, 9:00)) I'm getting errors Item 0 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 1 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 2 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 3 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 4 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 5 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 6 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 7 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 8 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 9 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 10 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 11 in the array did not validate: Item 0 in the arra…
has comment: http://stackoverflow.com/comment/93471863
score: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/68157723
has title: Django ArrayField. How to save nested array of time?
upvote count: 1
favorite count: 0
type: Question
tagged with: postgresql
type: UnansweredQuestion

http://stackoverflow.com/comment/83645458
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48327765
type: Comment
has text: @Nae Sorry for the poor question at first! I have updated the information, with a simple example. I looked at your link as well, but I don't think it solves my issues! Please let me know if you have any more input!

http://stackoverflow.com/q/48246674
accepted answer: http://stackoverflow.com/a/48249948
has comment: http://stackoverflow.com/comment/83476159
has title: Group Multiple pytest cases for the same function
type: AnsweredQuestion
upvote count: 0
tagged with: pytest
has body: How to group multiple pytests for the same function? The naming convention test_&lt;function name&gt;_case_&lt;test description&gt; would work. But this looks kind of tedious when there are lots of function and lots of test cases for each function. Parameterization won't help in this case because different test case perform different check for the function. Current method (naming convention): import pytest class apple(): def __init__(*args): ... def eat(food): ... def test_apple_case_color_is_red(): """test if color is red""" assert apple().color == "red" def test_apple_case_edible(): """test if apple is edible""" assert eat(apple) Can't group the two tests together by parametrization because the two tests do different checks. unittest can group the test cases: import unittest class TestApple(unittest.TestCase): def test_color(): """check if color is red""" assert apple().color == "red" def test_edible(): """check if edible""" assert eat(apple)
has comment: http://stackoverflow.com/comment/83482232
has answer: http://stackoverflow.com/a/48249948
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83476179
type: Question
has comment: http://stackoverflow.com/comment/83476190
answer count: 2
has answer: http://stackoverflow.com/a/51200167
possible better answer: http://stackoverflow.com/a/51200167
has comment: http://stackoverflow.com/comment/83482134
has comment: http://stackoverflow.com/comment/83482317
has comment: http://stackoverflow.com/comment/83476135
tagged with: python
score: -1

http://stackoverflow.com/q/48325478
accepted answer: http://stackoverflow.com/a/48325571
tagged with: while-loop
has answer: http://stackoverflow.com/a/48325571
has comment: http://stackoverflow.com/comment/83636690
has comment: http://stackoverflow.com/comment/83636495
tagged with: python
has title: Excel export using While loop
has answer: http://stackoverflow.com/a/48326435
has body: I am new to Python. I am working on a large analytic program, and this is a snippet of it. Right now, this snippet exports multiple excel files. Is it possible to save what is done per loop on a sheet within a single excel document? So basically right now, it exports 5 files, rather than exporting 5 separate files, can I use this loop and export 1 file, that has 5 sheets? x = 0 y = 0 #these are empty variables for the while loop #while loop that loops up to the system amount #breaks up df into systems #exports excel for each system while x &lt; int(SystemCount): x += 1 y += 1 System = minus4[minus4['System'] == "System " + str(y)] System.to_excel('U4Sys' + str(y) + '.xlsx', sheet_name='sheet1', index=False) print(System.head()) the print at the end prints this email System test1@test.com System 1 test2@test.com System 1 test3@test.com System 1 test4@test.com System 1 test5@test.com System 1 email System test1@test.com System 2 test2@test.com System 2 test3@test.com System 2 test4@test.com System 2 test5@test.com System 2 email System test1@test.com System 3 test2@test.com System 3 test3@test.com System 3 test4@test.com System 3 test5@test.com System 3 Thank you for taking your time to read this!
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/83636734
tagged with: pandas
score: 0
possible better answer: http://stackoverflow.com/a/48326435
tagged with: excel
tagged with: export-to-excel
type: Question
linked to: http://stackoverflow.com/q/14225676

http://stackoverflow.com/a/48331105
upvote count: 1
has comment: http://stackoverflow.com/comment/83653562
type: Answer
has comment: http://stackoverflow.com/comment/83648555
has body: I would split the image into smaller windows. So long as you know the windows overlap (I assume you have an idea of the lateral shift) the match in any window will be valid. You can even use this as a check, the translation between feature points in any part of the image must be the same for the transform to be valid
answers question: http://stackoverflow.com/q/48331004
score: 1
downvote count: 0

http://stackoverflow.com/q/48300412
tagged with: ssl
tagged with: python
score: 2
upvote count: 2
has title: python-requests library throws error in https connection
downvote count: 0
answer count: 0
type: UnansweredQuestion
has body: In my production server suddenly python-requests library throws this error on making https connection with 3rd party application. raised unexpected: SSLError(SSLError(SSLError("bad ca_certs: '/home/ubuntu/.virtualenvs/api/local/lib/python2.7/site-packages/requests/cacert.pem'", Error([('system library', 'fopen', 'No such file or directory'), ('BIO routines', 'BIO_new_file', 'no such file'), ('x509 certificate routines', 'X509_load_cert_crl_file', 'system lib')],)),),) please suggest some solutions and reason behind this exception. Edit: Traceback (most recent call last): File "/home/ubuntu/.virtualenvs/api/local/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/home/ubuntu/.virtualenvs/api/local/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/opt/vogo/api/api/api/celery.py", line 146, in spreadsheets_management ss = gs.open_by_key("10K_0JGCVZjngWo7dr1CTeRJ1rAhMWxAGxHbl_NworeU") File "/home/ubuntu/.virtualenvs/api/local/lib/python2.7/site-packages/gspread/client.py", line 105, in open_by_key feed = self.get_spreadsheets_feed() File "/home/ubuntu/.virtualenvs/api/local/lib/python2.7/site-packages/gspread/client.py", line 155, in get_spreadsheets_feed r = self.session.get(url) File "/home/ubuntu/.virtualenvs/api/local/lib/python2.7/site-packages/gspread/httpsession.py", line 73, in get return self.request('GET', url, params=params, **kwargs) File "/home/ubuntu/.virtualenvs/api/local/lib/python2.7/site-packages/gspread/httpsession.py", line 65, in request response = func(url, data=data, params=params, headers=request_headers, files=files, json=json) File "/home/ubuntu/.virtualenvs/api/local/lib/python2.7/site-packages/requests/sessions.py", line 480, in get """ File "/home/ubuntu/.virtualenvs/api/local/lib/python2.7/site-packages/requests/sessions.py", line 468, in request :param allow_redirects: (optional) Set to True by default. Fi…
has comment: http://stackoverflow.com/comment/83585330
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83587157
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83587317

http://stackoverflow.com/q/48177046
has comment: http://stackoverflow.com/comment/83334334
has comment: http://stackoverflow.com/comment/83334164
upvote count: 0
has body: I'm looking for a way I can package a tool I've built for use by my colleagues. In order to run it requires modules that are currently only found on my own workstation. Adding the modules to other workstations is not possible because it's explicitly prohibited. So far I've been unable to locate any way to accomplish my goal without using a module or other software that converts the script into an exe. My work-site has strict rules for executable software. I am prohibited from creating anything that requires installation, makes any changes to the registry, and/or has exe as its native file extension. I'm hoping someone here might know a way to get around this restriction while still adhering to that policy. Bending or breaking these rules, even for a moment, would be met with harsh consequences for myself.
has answer: http://stackoverflow.com/a/48177190
answer count: 1
has comment: http://stackoverflow.com/comment/83334193
favorite count: 0
has comment: http://stackoverflow.com/comment/83335218
score: -6
tagged with: software-distribution
type: Question
has title: Is it possible to create a python standalone script that is NOT an executable?
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83335146
has comment: http://stackoverflow.com/comment/83334240
has comment: http://stackoverflow.com/comment/83334380
downvote count: 6

http://stackoverflow.com/comment/83374971
score: 0
comment on: http://stackoverflow.com/q/48196907
has text: When I comment out that line, and the other two that reference `image1`, I get no error; the game hangs with a white screen.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83432319
comment on: http://stackoverflow.com/a/48219200
has text: Thank you for your comment. Only one thing it's not correct. Ip addresses from the 'log' aren't in order in the 'output.txt' file. Neither from the top nor from the bottom. Do you have any idea why?
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/48314387
tagged with: python
has comment: http://stackoverflow.com/comment/83615411
tagged with: properties
score: 4
has comment: http://stackoverflow.com/comment/83614738
has comment: http://stackoverflow.com/comment/83614712
accepted answer: http://stackoverflow.com/a/48315622
has comment: http://stackoverflow.com/comment/83615032
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48315622
has comment: http://stackoverflow.com/comment/83616304
tagged with: metaclass
has body: Currently I have the following Django model class TestUser(models.Model): name = models.CharField(max_length=250) email = models.CharField(max_length=250) ... class Meta: db_table = 'temp_user' and I've the following method. def print_name(self): return self.name I want to add this method as a property to TempUser model. I know this can be done by putting the method inside TempUser class and user @property. But I want to do it dynamically. I tried this from python shell. In [10]: TempUser.print_name = property(print_name) In [11]: TempUser.print_name Out[11]: &lt;property at 0x7efc374e7c58&gt; In [12]: user = TempUser.objects.get(pk=1) In [13]: user.print_name Out[13]: u'Test User' But once I exit the shell, I loose the property. Is there any way to add the property permanently.
has comment: http://stackoverflow.com/comment/83614867
has comment: http://stackoverflow.com/comment/83615078
answer count: 1
has comment: http://stackoverflow.com/comment/83614583
has comment: http://stackoverflow.com/comment/83614717
has comment: http://stackoverflow.com/comment/83614636
favorite count: 0
has comment: http://stackoverflow.com/comment/83614513
type: Question
upvote count: 4
has title: Dynamically add properties to Django model
has comment: http://stackoverflow.com/comment/83614675
has comment: http://stackoverflow.com/comment/83614560
linked to: http://stackoverflow.com/q/1325673
has comment: http://stackoverflow.com/comment/83614510
downvote count: 0
tagged with: django

http://stackoverflow.com/q/48211844
score: 2
has comment: http://stackoverflow.com/comment/83438514
has body: On Elastic Beanstalk I'm using the following Python code to handle a POST request and upload a file to a S3 bucket. However, I get the following error: fileobj must implement read after reading Flask's FileStorage documentation, I've tried to substitute f with f.stream, but then I've got: expected string or buffer I'm using Werkzeug 0.10.1. How can I fix this? from flask import Flask, render_template, request from werkzeug.utils import secure_filename from s3upload.helpers import * application = Flask(__name__) application.config.from_object('s3upload.config') ALLOWED_EXTENSIONS = ('pdf','p') def allowed_file(filename): if filename.rsplit('.')[1].lower() in ALLOWED_EXTENSIONS: return True def upload_file_to_s3(f, bucket_name, acl='public-read'): try: s3.upload_fileobj(f, bucket_name, f.filename, ExtraArgs={ "ACL": acl, "ContentType": f.content_type }) except Exception as e: return "Something bad happened while uploading {} in {}: {} {}".format(f.filename, bucket_name, e) return '{}{}'.format(application.config['S3_LOCATION'], f.filename) @application.route('/', methods=['POST','GET']) def upload_file(): if request.method == 'POST': if 'file' not in request.files: return "No file key in request.files" f = request.files['file'] if f.filename == '': return "Please select a file." if allowed_file(f.filename): f.filename = secure_filename(f.filename) out = upload_file_to_s3(f, application.config['S3_BUCKET']) return str(out) else: return "File type not allowed." return render_template('index.html') if __name__ == '__main__': application.run()
answer count: 0
tagged with: amazon-s3
downvote count: 0
tagged with: amazon-elastic-beanstalk
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: flask
has title: fileobj must implement read

http://stackoverflow.com/comment/83628952
type: Comment
score: 0
type: AnswerComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/163412/discussion-between-joppich-and-dann-m).
comment on: http://stackoverflow.com/a/48319115

http://stackoverflow.com/q/48329002
has body: Here is my python code to convert my .png image to base64 encoding: import base64 email_img = base64.b64encode(open('rmh.png', 'rb').read()).decode('utf-8').replace('\n','') img_tag = '&lt;img alt="" src="data:image/png;base64,{}"/&gt;'.format(email_img) This code is running without error and is properly storing the base64 encoding in the email_img variable. However, I have been unable to display the image in an outlook email. Here is an abbreviated version of my code relevant to the image: import win32com.client as win32 outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.To = email[0] mail.Subject = "UTAS Job Matches" mail.HtmlBody = """\ &lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;p&gt;{}&lt;br&gt; &lt;/p&gt; &lt;/body&gt; &lt;/html&gt; """.format(img_tag) mail.Display(True) I have tried both .format and the %s method for inserting the variables and neither work. The resulting email shows a box with a red X where the image should be. I have not had any trouble with the text I am displaying in my email.
linked to: http://stackoverflow.com/q/48272100
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/83643706
score: 0
has comment: http://stackoverflow.com/comment/83644002
answer count: 0
has comment: http://stackoverflow.com/comment/83643831
has title: Trying to use python to embed a .png image into an Outlook email using base64 encoding, but the image will not display
has comment: http://stackoverflow.com/comment/83644001
type: Question

http://stackoverflow.com/a/48198934
has comment: http://stackoverflow.com/comment/83380050
answers question: http://stackoverflow.com/q/48198810
type: Answer
has body: One can consider this data as nested dictionaries and use it: outlist = [v["4. close"] for v in mydict["Time Series (Daily)"].values()] print(outlist) Output: ['242.7100', '242.9000'] Data: mydict = { "Meta Data": { "1. Information": "Daily Prices (open, high, low, close) and Volumes", "2. Symbol": "SPY", "3. Last Refreshed": "2018-01-10", "4. Output Size": "Compact", "5. Time Zone": "US/Eastern" }, "Time Series (Daily)": { "2017-08-18": { "1. open": "242.9000", "2. high": "244.1900", "3. low": "242.2000", "4. close": "242.7100", "5. volume": "136748000" }, "2017-08-21": { "1. open": "242.6400", "2. high": "243.2000", "3. low": "241.8300", "4. close": "242.9000", "5. volume": "65469700" }}}
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48198810
score: 0

http://stackoverflow.com/comment/83598184
type: Comment
comment on: http://stackoverflow.com/a/48306200
score: 0
type: AnswerComment
has text: Well, looks like he's adding edges to a graph, then tests whether that was a good idea, and takes them back out if not. Might be simpler to write that way. Though I suspect since he wants speed, he should use a smarter algorithm instead. Like using union-find instead of the shortest_path searches.

dll
tags question: http://stackoverflow.com/q/48208724
tags question: http://stackoverflow.com/q/48255196
tag name: dll
type: Tag
tags question: http://stackoverflow.com/q/48328067
tags question: http://stackoverflow.com/q/48189689

http://stackoverflow.com/comment/83429845
comment on: http://stackoverflow.com/a/48213273
type: AnswerComment
has text: Thank you :) I tried it => session = boto3.session.Session(aws_access_key_id = ' ', aws_secret_access_key = ' ') => s3 = session.resource('s3', endpoint_url='http://127.0.0.1:4569') => print(s3.get_available_subresources()) and it worked just fine i get what i asked for ( an array of all the subresources available ) **BUT** when i tried to use one of that subresources to upload a file => s3.Object(BUCKET_NAME, FILE_NAME).put(Body=open(FILE_NAME, 'rb')) i get this error message => ('Connection aborted.', ConnectionRefusedError(111, 'Connection refused'))
score: 0
type: Comment

http://stackoverflow.com/comment/83470306
has text: Check your indentation. as shown, F_ALL would only contain a single element
type: QuestionComment
comment on: http://stackoverflow.com/q/48243541
type: Comment
score: 0

http://stackoverflow.com/q/48279284
accepted answer: http://stackoverflow.com/a/48279345
has comment: http://stackoverflow.com/comment/83542135
possible better answer: http://stackoverflow.com/a/48279456
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83542105
has answer: http://stackoverflow.com/a/48279456
answer count: 3
has body: input = 3136 -2 1806481261 191415576 883713178 259822501 0 79439 0 0 0 I want to extract the value 259822501 from the above input. I can extract it using following regex : \d+\s-?\d+\s+\d+\s+\d+\s+\d+\s+(\d+)[\d\\s]+.* If you clearly see in the above regex, the pattern "\d+\s+" is repetitive. Looking for more efficient regular expression here.
has answer: http://stackoverflow.com/a/48279348
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/83542389
has answer: http://stackoverflow.com/a/48279345
type: Question
score: 0
has title: python regex to replace repetitive pattern "number and space"

http://stackoverflow.com/comment/83604079
comment on: http://stackoverflow.com/a/48308058
type: Comment
has text: good point. In french, the operation is "soustraction", that's why. Lesson learned, thanks.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48179906
has title: Reshaping data in CSV to multiple columns
possible better answer: http://stackoverflow.com/a/48180019
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/48180026
type: Question
answer count: 2
has body: 0 19 1 19 2 19 3 19 How can i change this above csv data in python to - 0 19 1 19 2 19 3 19 now i need help with reshaping my dataset which looks like this - 0 100 1 100 2 100 3 100 4 100 5 100 6 200 7 200 8 200 9 200 0 200 1 200 ..... I want to reshape my dataset in the following format - 0 100 1 100 2 100 3 100 4 100 5 100 .. 6 200 7 200 8 200 9 200 0 200 1 200 ...
accepted answer: http://stackoverflow.com/a/48180026
tagged with: reshape
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/48180019

http://stackoverflow.com/comment/83390328
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48204602
has text: problem is, that I need the column 'starts with' for boolean masking
type: Comment

http://stackoverflow.com/q/48214158
answer count: 3
possible better answer: http://stackoverflow.com/a/48214232
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/48214261
type: Question
score: 2
has answer: http://stackoverflow.com/a/48214458
has answer: http://stackoverflow.com/a/48214261
upvote count: 3
has answer: http://stackoverflow.com/a/48214232
downvote count: 1
has body: I am trying to add values for duplicate keys in a dictionary. I am not sure why my code isn't working. d = {'inds': [], 'vals': []} d['inds'] = [0, 3, 7, 3, 3, 5, 1] d['vals'] = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0] I would like to get a list with the added values as result at index 3 and 0 for an index that doesn't exist: desired_output=[1.0, 7.0, 0.0, 11.0, 0.0, 6.0, 0.0, 3.0] My code: I am making list of zeros and adding dictionary in a loop. d = {'inds': [], 'vals': []} d['inds'] = [0, 3, 7, 3, 3, 5, 1] d['vals'] = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0] length=len(d['inds']) a=[0]*(length) for key,val in d.items(): a[key]= a[key] + d[val] It's throwing an error: TypeError: list indices must be integers or slices, not str Appreciate your help.
has title: Loop through Dictionary and add values
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/83561064
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48287703
type: AnswerComment
has text: Where is the script running in - in your desktop or in an amazon EC2 instance?

http://stackoverflow.com/q/48305125
has comment: http://stackoverflow.com/comment/83600544
score: 2
has comment: http://stackoverflow.com/comment/83595912
upvote count: 3
has body: I have the following Excel sheet with the following cells: 'A' 'B' 'C' 1 S 2 T 2 E F D 3 K L M 4 N D F 5 P E M I would like to delete the first j lines from column 'B', where j is a list length. list=['2','F','L'] Any idea how this can be accomplished? I would prefer to use openpyxl for this action. Best regards, Dan
answer count: 1
has answer: http://stackoverflow.com/a/48307593
has title: delete content of particular Excel cells python
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
downvote count: 1
tagged with: excel

http://stackoverflow.com/comment/83412973
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48215440
has text: Perfect, thank you! Most importantly, it makes sense reading it. Thanks everyone
type: Comment

polar-coordinates
tags question: http://stackoverflow.com/q/48218555
tag name: polar-coordinates
type: Tag
tags question: http://stackoverflow.com/q/48192743

http://stackoverflow.com/q/48314755
answer count: 3
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83615222
has answer: http://stackoverflow.com/a/48314817
has comment: http://stackoverflow.com/comment/83738770
has body: How to find a specific key in a nested dictionary in python without using a for loop and directly accessing that variable. I have a json file which looks similar to a nested dictionary. How could i find a specific keyword in it? data={ u'session': { u'new': True, u'sessionId': u'amzn1.echo-api.session.fae41185-1c00-4463-b890-0833c32a2b43', u'user': { u'userId': u'amzn1.ask.account.AHEEJXVACGJ2XZV4QRNFSIW7LDHAXEUB7WTZXC6777CLHLS4ITEWD6RMQLNXG5ECXFP3WRAQDH53EZUZ2GOFC52SNZ5NI5L7LXG3HMS6ORA2DNVT3TFYL5N5WE4GTSFM4PS7TGYXXQYCMOCRVBEPXBNHV2G6DPIUP3XPHCSIKJF26SOSZZAD4TRLHJA66JPEVDWJMRBH7AL2WUA' }, u'application': { u'applicationId': u'amzn1.ask.skill.ec977129-bcaf-462c-85ce-03c1f7a2b1f8' } }, u'version': u'1.0', u'request': { u'locale': u'en-IN', u'timestamp': u'2018-01-12T10:11:46Z', u'dialogState': u'STARTED', u'intent': { u'slots': { u'product': { u'name': u'product', u'confirmationStatus': u'NONE' }, u'subcategories': { u'resolutions': { u'resolutionsPerAuthority': [ { u'status': { u'code': u'ER_SUCCESS_MATCH' }, u'values': [ { u'value': { u'name': u'milk', u'id': u'ecbdb882ae865a07d87611437fda0772' } } ], u'authority': u'amzn1.er-authority.echo-sdk.amzn1.ask.skill.ec977129-bcaf-462c-85ce-03c1f7a2b1f8_Certification.subcategories' } ] }, u'name': u'subcategories', u'value': u'milk', u'confirmationStatus': u'NONE' }, u'brand': { u'resolutions': { u'resolutionsPerAuthority': [ { u'status': { u'code': u'ER_SUCCESS_MATCH' }, u'values': [ { u'value': { u'name': u'nestle', u'id': u'099e3726deeeb0f04f86d49093eebbb2' } } ], u'authority': u'amzn1.er-authority.echo-sdk.amzn1.ask.skill.ec977129-bcaf-462c-85ce-03c1f7a2b1f8_Certification.brand' } ] }, u'name': u'brand', u'value': u'nestle', u'confirmationStatus': u'NONE' }, u'categories': { u'name': u'categories', u'confirmationStatus': u'NONE' }, u'more_n_repeat': { u'name': u'more_n_repeat', u'confirmationStatus': u'NONE' } }, u'name': u'user_says', u'confirmationStatus': u'NONE' }, u'requestId': u'amzn1.echo-api.request.432d4866-f7…
type: Question
has title: Find keys in nested dictionary
downvote count: 5
tagged with: python
tagged with: dictionary
score: -4
possible better answer: http://stackoverflow.com/a/48314921
has answer: http://stackoverflow.com/a/48314921
accepted answer: http://stackoverflow.com/a/48314906
linked to: http://stackoverflow.com/q/22162321
has answer: http://stackoverflow.com/a/48314906
type: AnsweredQuestion

http://stackoverflow.com/comment/83420512
has text: `list(Exception)` doesn't work. Are you looking at [this answer](https://stackoverflow.com/questions/17157753/get-the-error-code-from-tweepy-exception-instance)?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48219349

http://stackoverflow.com/comment/83647453
comment on: http://stackoverflow.com/a/48329645
type: Comment
type: AnswerComment
score: 0
has text: Okay, that does help. Could you edit your original question to include this information? Also, if you could add the code from test_suite.py that you are using to call test_website_loads.py, that could also help.

sys
tags question: http://stackoverflow.com/q/48191985
type: Tag
tags question: http://stackoverflow.com/q/48278187
tag name: sys
tags question: http://stackoverflow.com/q/48198974
tags question: http://stackoverflow.com/q/48235676
tags question: http://stackoverflow.com/q/48306212

http://stackoverflow.com/comment/83368112
type: Comment
has text: `turtle` uses `tkinter` behind the scenes.
score: 1
comment on: http://stackoverflow.com/q/48193290
type: QuestionComment

http://stackoverflow.com/comment/83408042
type: QuestionComment
has text: do you have more than one installation of python. i.e. both base python, and conda?
comment on: http://stackoverflow.com/q/48213190
score: 0
type: Comment

http://stackoverflow.com/comment/83523899
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48269712
has text: Thank you for taking the time to answer but that does not work. Neither surrounding the expression with braces. I thought the "$" and {braces} are only used when making system calls!

http://stackoverflow.com/comment/83340511
comment on: http://stackoverflow.com/q/48180251
has text: Which OS are you using?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48191115
has body: Re: class pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)[source] And: classmethod DataFrame.from_records(data, index=None, exclude=None, columns=None, coerce_float=False, nrows=None)[source] Is the data parameter evaluated lazily? e.g. if I call it with a data parameter that is a generator, will it totally consume the generator or only read it when required. e.g. Suppose I have this snippet: import csv csvinput = (row["line"] for index, row in InputDataSet.iterrows()) rdr = csv.reader(csvinput) OutputDataSet = pandas.DataFrame().from_records(rdr) (Note that it's not reading CSV data per se that I'm asking about. Granted there are probably other, better ways to do that). Where InputDataSet is another DataFrame. The code works fine, but might have scalability problems if the row sets are eagerly evaluated. Imagine that InputDataSet is retrieving rows in csv format from some source -- perhaps a file or web site or who knows what. Ideally (for me, that is), the iterrows() call on the InputDataSet dataframe would be lazily evaluated -- that is one row at a time as needed. Similarly for the OutpuDataSet. It would be great if the from_records method was lazy. Then I could have another section lazily reading the OutputDataSet. This question came about while playing with Python support in SQL Server 2017. For large row sets, eager evaluation will be a problem for this sort of code. just did a dead-easy test: &gt;&gt;&gt; g = ((x, x+1) for x in range(5)) &gt;&gt;&gt; d = pandas.DataFrame.from_records(g) &gt;&gt;&gt; next(g) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration So, that says to me that the from_records method is eager, which is disappointing.
type: UnansweredQuestion
score: 0
answer count: 1
tagged with: sql-server
has comment: http://stackoverflow.com/comment/83367539
tagged with: pandas
has answer: http://stackoverflow.com/a/48193608
tagged with: python
has title: Is the data parameter for pandas.DataFrame lazily evaluated?
type: Question

http://stackoverflow.com/a/48542322
has body: Well, i don't know what actually was the reason behind the error, i tried every possible solution i found on the web but none worked for me. I know that this is not a suitable solution for most of others facing the same issue, however I solved the problem by installing a fresh copy of windows 7 professional and the installing Anaconda, I think trying to install and remove Anaconda multiple times during the error fixing process made that somehow. Anyway, Thanks for contributers.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48282596

http://stackoverflow.com/comment/83481076
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48245057
has text: I was to set content type: 'content-Type' : 'application/json' in the main.py not in the downloader.py, right? Could you provide updated version to be sure and I'll double check :). adding that to self.headers.get would create unshashable type dict
type: Comment

http://stackoverflow.com/comment/83650673
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48332060
type: Comment
has text: Ok I see this it's about 0.68 for 48 and 32 for 52.

http://stackoverflow.com/comment/83377542
type: QuestionComment
comment on: http://stackoverflow.com/q/48197747
score: 0
type: Comment
has text: Or, use `lambda row: sum(row, 9, 3)` , i.e. use partial application....

http://stackoverflow.com/a/48258698
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48256873
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48256873
score: 1
type: Answer
has body: It is not tkinter but OOP problem. You have to use self. to create variable which exists in all methods in class self.e1 = Entry() and later self.e1.get() Currently e1 is local variable which exists only in init_window

http://stackoverflow.com/a/48208088
type: Answer
has body: To stay simple, we'll stay 2D and assume rows.shape = cols.shape. (You can break this rule with broadcasting, but for now we won't). We'll call this shape (I, J) then y = x[rows, cols] is the same as: y = np.empty((I, J)) for i in range(I): for j in range(J): y[i, j] = x[rows[i, j], cols[i, j]]
answers question: http://stackoverflow.com/q/48207685
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/83512316
comment on: http://stackoverflow.com/a/48247219
type: AnswerComment
has text: Thank you so much for your answer. Problem 2 has been fixed. I wrote a shameful code, but it works, I'll clear up it later. As for issue 1 I'm trying to use your suggestions. I like the first proposal you gave me but I have some trouble in access 'layer4_actv' since it appears as 'not defined'.
score: 0
type: Comment

http://stackoverflow.com/comment/83544700
type: QuestionComment
score: 0
has text: @charlietfl Thank you anyway.
comment on: http://stackoverflow.com/q/48273815
type: Comment

http://stackoverflow.com/a/48306371
has body: type the following: for search_result in search: text = str("Score:", search_result.score, "| URL:", search_result.url,) from tknter import * root = Tk() label = Label(root, text = text) label.pack() root.mainloop()
score: 0
answers question: http://stackoverflow.com/q/48306087
type: Answer

http://stackoverflow.com/a/48287827
type: AcceptedAnswer
downvote count: 0
score: 3
type: Answer
has body: Yes, by calling set_index on the column that you wish to sort. On a single machine it uses your hard drive intelligently for excess space.
answers question: http://stackoverflow.com/q/48287766
accepted answer of: http://stackoverflow.com/q/48287766
upvote count: 3

http://stackoverflow.com/q/48252698
has body: Given a URL like this: http://..../search/?foo=a&amp;foo=B&amp;bar=whatever In my View, I want to filter the QuerySet for CASE-INSENSITIVE matches of "foo". There's a handy "in" operator that I could use on my list of "foo", but it doesn't support case-insensitivity. To be clear, this (elegant code) performs a CASE-SENSITIVE match. (It doesn't match "foo=b".) I do not want this: queryset = queryset.filter(foo__in=role) # case-sensitive My solution is to create a list of QuerySets, one for each "foo" match, and then to create return a final "union()" of the results. def get_queryset(self, **kwargs): queryset = super(PeopleListView, self).get_queryset() foo = self.request.GET.getlist('foo') if (len(foo) == 1): queryset = queryset.filter(foo__iexact=role[0]) # case-insensitive elif (len(foo) &gt; 1): qs_list = [] for _foo in foo: qs_list.append(queryset.filter(foo__iexact=_foo)) queryset = Person.objects.none() # EmptyQuerySet for qs in qs_list: queryset = queryset.union(qs) bar = self.request.GET.get('bar') if bar is not None: queryset = queryset.filter(bar__iexact=bar) # Easy This results in an error: django.db.utils.DatabaseError: ORDER BY not allowed in subqueries of compound statements. Is there a way to do this with "Q" objects? If not, I think the "right" solution would involve converting the match patterns to lower-case, then using QuerySet::raw() to convert the database values to lower-case as well. I'm a bit over my head there... Thanks for your help!
downvote count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 2
has title: Django QuerySet.union() -or- QuerySet.raw() to Achieve Case-Insensitive Mutli-Search
tagged with: django-queryset
tagged with: case-insensitive
answer count: 1
has answer: http://stackoverflow.com/a/48252808
accepted answer: http://stackoverflow.com/a/48252808
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/comment/83506448
has text: @Dark, i think the diff should be either `0` or `1`, if its `2` then there was a jum from `001` to `003` and `002` is missing
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48261668
type: AnswerComment

http://stackoverflow.com/a/48234530
answers question: http://stackoverflow.com/q/48234166
downvote count: 1
has comment: http://stackoverflow.com/comment/83451772
has comment: http://stackoverflow.com/comment/83460150
type: Answer
has body: Assuming you want to remove single occurrences in the list, can be done in one line: [lst.remove(c) for c in set(lst)] This does not return the answer, but modifies your list in place, so lst is now trimmed. Or wrapped into a potentially more useful function: def remove_first_occurence(lst): l = lst.copy() [l.remove(c) for c in set(l)] return l
score: -1
upvote count: 0

http://stackoverflow.com/comment/83396680
type: QuestionComment
has text: Thanks for the info... The problem in this simple example was the mask generation in the np.ma.masked_where. I shouldn't have multiplied with the image, since it can be 0 as well. So this is a correct version: m_img_col = np.ma.masked_where( np.atleast_3d(mask2D)*np.ones_like(img), img) Anyway, in my real application, I already have the masks provided, so this is not the issue, but Thank you for spotting it :)
score: 1
comment on: http://stackoverflow.com/q/48206605
type: Comment

http://stackoverflow.com/q/48178484
linked to: http://stackoverflow.com/q/3599524
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48491047
tagged with: django
tagged with: python
tagged with: django-custom-tags
has answer: http://stackoverflow.com/a/48178563
score: 0
tagged with: django-templates
answer count: 3
has title: Django - Creating a Custom Template Tag to show Model Name
has answer: http://stackoverflow.com/a/50467301
has body: I have a model: class Survey(models.Model): name = models.CharField(max_length = 200) def __str__(self): return self.name And in my template I want to show the name of the current Survey model: &lt;h1&gt; &lt;/h1&gt; I'm using a custom template tag/filter to display that name; however, it is showing as 'str' instead of the name of the current Survey model. Here is the filter code: from django import template register = template.Library() @register.filter def name(value): return value.__class__.__name__ What am I doing wrong here?

http://stackoverflow.com/a/48212634
upvote count: 2
downvote count: 0
has body: you can use dataframe.where(dataframe == 0).count() This will return the count of number of zeros in your dataframe For more details you can check out the dosumentation : https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html Thewhere condition returns a dataframe which is the same type as caller with all the rows having zeros and then you just call .count() on it But with this remember that if there are two zeros in the same row then it will be counted as one zero So you can specify the axis where you want to look for the condition to be satisfied
type: Answer
answers question: http://stackoverflow.com/q/48212428
score: 2

http://stackoverflow.com/comment/83641734
score: 0
type: Comment
has text: Thank you. I will try it. I will keep you posted.
type: AnswerComment
comment on: http://stackoverflow.com/a/48311489

http://stackoverflow.com/comment/83456267
comment on: http://stackoverflow.com/q/48221731
has text: python3 default. When I do 'python -V', it just shows me 'python 2.7.10'
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/q/48180935
tagged with: pandas
has body: I've a Panda's data Frame and I need to load it to cassandra database. It is also okay if the dataframe is pyspark dataframe. I followed this link but that is for scala. Is there any way simillar to the below link? Is there any way to Load Spark SQL resultset (data frames ) back to cassandra?
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/83341826
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48181258
upvote count: 0
has title: Is there any way to insert pandas dataframe to cassandra db?
tagged with: pyspark
has comment: http://stackoverflow.com/comment/83341742
has comment: http://stackoverflow.com/comment/83341812
has answer: http://stackoverflow.com/a/48181258
tagged with: python
has comment: http://stackoverflow.com/comment/83348056
linked to: http://stackoverflow.com/q/42994053
score: -3
type: AnsweredQuestion
tagged with: cassandra

http://stackoverflow.com/comment/83345066
type: Comment
comment on: http://stackoverflow.com/q/48181613
score: 0
has text: my programming ability is not good...
type: QuestionComment

http://stackoverflow.com/comment/83475906
comment on: http://stackoverflow.com/a/48246562
type: AnswerComment
score: 0
type: Comment
has text: ValueError: Path should have format /bucket/filename but got https://storage.googleapis.com/bucket-name-12345.appspot.com/test.txt

http://stackoverflow.com/q/48255053
has body: I'm trying to write some code that will create a matrix of alternating 1/-1 and 0 i.e: [-1 0 -1 0 1 0 1 0 -1 0] [ 0 1 0 -1 0 1 0 -1 0 1] [ 1 0 1 0 -1 0 -1 0 -1 0] [ 0 1 0 -1 0 -1 0 -1 0 1] [ 1 0 1 0 1 0 1 0 1 0] I've created a class that generates a matrix of zeroes and appends it with 1 or -1 and I have tried messing with my for loop and slicing my matrix but I can't seem to generate the matrix I'd like above. I have an intermediate level of python knowledge so I appreciate that a solution to my problem using the code I've created might not be particularly elegant but any help would be greatly appreciated. import numpy as np import scipy as sp import matplotlib.pyplot as plt import random #constants N = 10 #dimensions of matrix class initial_lattice: def __init__(self,N): #create initial matrix of size NxN self.N=N self.matrix_lattice() def matrix_lattice(self): self.lattice = np.zeros((N,N), dtype=int) #creates initial matrix of zeroes for x in range(0,N): for y in range(0,N): self.lattice[x,y]=random.choice([1,-1]) #randomly chooses values of 1 and -1 and appends matrix lattice1=initial_lattice(N) print lattice1.lattice
favorite count: 0
tagged with: numpy
has answer: http://stackoverflow.com/a/48255301
has answer: http://stackoverflow.com/a/48258137
has answer: http://stackoverflow.com/a/48255505
answer count: 5
upvote count: 3
type: UnansweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/14651025
has comment: http://stackoverflow.com/comment/83492907
type: Question
has answer: http://stackoverflow.com/a/48255192
has title: Create a matrix of alternating zeroes and random numbers?
has answer: http://stackoverflow.com/a/48256452
tagged with: matrix
score: 3
tagged with: python

http://stackoverflow.com/comment/83376123
score: 2
type: Comment
type: QuestionComment
has text: You have a pathological regex. Look that up. You probably want `[a-z]+(-+[a-z]+)*$`.
comment on: http://stackoverflow.com/q/48197501

http://stackoverflow.com/comment/83374623
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48196711
has text: Consider the 0-9 range, as shown in the posted data. wlog, assume that the first number is 5. For the second number, we roll a D9, numbered 0-8 ... but we map `5` (the number already chosen) to `9`. The second numbers are evenly balanced.

http://stackoverflow.com/comment/134705571
type: AnswerComment
has text: Instead `log` just use `print` statement if you are not using logger in your project.
score: 0
comment on: http://stackoverflow.com/a/68666505
type: Comment

http://stackoverflow.com/q/48236516
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48236554
tagged with: python
score: -1
has body: In this code I can't see why it isn't printing a hexagon 24 times. I tell it to make a 6 sided shape with 60 degrees between lines ( a hexagon) and tell it do turn 15 degrees each time. This ends up being a even 24 for the picture I'm trying to draw. import turtle Hex_Count = 0 x = turtle.Turtle() x.speed(.25) def Hexagon(): for i in range(24): for i in range(6): x.forward(100) x.left(60) Hex_Count = Hex_Count + 1 x.left(15) print(Hex_Count) Hexagon But, for some reason, when I run this code the turtle screen pops up for about a half second then closes. How do I get it to perform in the way I want it to?
answer count: 4
upvote count: 0
has answer: http://stackoverflow.com/a/48237751
has title: Get Python turtle window to display graphics and remain open
has answer: http://stackoverflow.com/a/48236557
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48236549
tagged with: turtle-graphics

http://stackoverflow.com/a/48209997
answers question: http://stackoverflow.com/q/48209796
has body: In python, a string is like a "instance of class str". To order to compare if the "content" within the input was a string, you can make something like... a = input("Put something...") if isinstance(a, str): print("Error caught, a string was given...") else: print ("Now your number is", a, "and its type is" , type(a))
score: 1
type: Answer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83402324

http://stackoverflow.com/a/48254239
has body: I too tried to look at broadcast_arrays: In [121]: X,Y = np.broadcast_arrays(np.arange(4)[:,None], np.arange(1000)) In [122]: timeit X+Y 10.1 µs ± 31.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [123]: X,Y = np.broadcast_arrays(np.arange(1000)[:,None], np.arange(4)) In [124]: timeit X+Y 26.1 µs ± 30.6 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [125]: X.shape, X.strides Out[125]: ((1000, 4), (4, 0)) In [126]: Y.shape, Y.strides Out[126]: ((1000, 4), (0, 4)) np.ascontiguousarray converts the 0 strided dimensions into full ones In [132]: Y1 = np.ascontiguousarray(Y) In [134]: Y1.strides Out[134]: (16, 4) In [135]: X1 = np.ascontiguousarray(X) In [136]: X1.shape Out[136]: (1000, 4) Operating with the full arrays is faster: In [137]: timeit X1+Y1 4.66 µs ± 161 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) So there's some sort of time penalty to using the 0-strided arrays, even if it doesn't explicitly expand the arrays first. And cost is tied to the shapes, and possibly which dimension is expanded.
answers question: http://stackoverflow.com/q/48253210
type: Answer
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/83980926
downvote count: 0

http://stackoverflow.com/comment/97944327
type: Comment
score: 0
type: AnswerComment
has text: If you want to have multiple IPython kernels for different virtual envs or condo environments, you will need to specify unique names for the kernelspecs. You can check the command in https://ipython.readthedocs.io/en/stable/install/kernel_install.html
comment on: http://stackoverflow.com/a/55579997

http://stackoverflow.com/a/48341409
score: 1
answers question: http://stackoverflow.com/q/48329092
has body: You should not assume the content of a DICOM file by its name or position in the directory structure. Instead, the root of the DICOM folder should contain a DICOMDIR file, which contains the list of files and their relationship (e.g., patient objects contain studies objects which contain series and then images). I don't know if VTK offers a way of reading and interpreting DICOMDIR files; if not then you could try to interpret them with dcmtk or Imebra. Disclosure: I'm the author of Imebra
has comment: http://stackoverflow.com/comment/83670809
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/83466063
has text: Perfect, that's why I asked
type: AnswerComment
comment on: http://stackoverflow.com/a/48241720
score: 0
type: Comment

http://stackoverflow.com/q/48290997
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: python
score: -1
tagged with: lambda
has title: How do I read this piece of this python using lambda example?
type: Question
has body: Do you know how to read this piece of this python example? dual = Graph([f_edges,lambda f1,f2: set(f1).intersection([(e[1],e[0]) for e in f2])]) I'd like to see exactly what contains the parameter of the Sage project. The code has been taken from here: - https://trac.sagemath.org/ticket/6236 And the Sage documentation of the Graph function is here: http://doc.sagemath.org/html/en/reference/graphs/sage/graphs/graph.html#graph-format
upvote count: 0
accepted answer: http://stackoverflow.com/a/48291235
answer count: 1
has answer: http://stackoverflow.com/a/48291235

http://stackoverflow.com/comment/83510864
comment on: http://stackoverflow.com/a/48262732
type: Comment
type: AnswerComment
has text: If you just want to calculate the mean of a list you can use `sum` and `len` to calculate it. Otherwise you should explain what you want in another question
score: 0

http://stackoverflow.com/q/48209401
has answer: http://stackoverflow.com/a/48209631
accepted answer: http://stackoverflow.com/a/48209631
tagged with: pandas-groupby
tagged with: pandas
score: 1
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has title: Create a dataframe based on column values of another dataframe
downvote count: 0
tagged with: python
has body: I have a dataframe as 20000 X 50. Two of the columns are Date and Time (represented as hour). Remaining columns have observations of some parameters during the time. What I am trying to achieve is create a new dataframe which averages all the remaining column values for every 3 hours per day and creates a an ID columns for this which can be numbers from 1 to 8. Each representing 3 hour range. I have enclosed an image of the source and what should be result. Any help is very much appreciated. Data
type: AnsweredQuestion

http://stackoverflow.com/comment/83594096
has text: Does `ai` mean index 0 and `aj` index 1?
type: Comment
comment on: http://stackoverflow.com/q/48304365
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83490010
comment on: http://stackoverflow.com/a/48245716
type: Comment
has text: You are right, `AsDict()` is more appropriate here but does not change anything performancewise. I will have a deeper look at the Post you linked and try this out, it seems this could be a solution (re-using the `mappingTable`). I'll post my results here.
score: 0
type: AnswerComment

http://stackoverflow.com/a/48277628
has body: Look at the output that zip returns. &gt;&gt;&gt; list(zip(*sorted(enumerate(l), key=lambda x: x[1], reverse=True))) [(5, 4, 3, 2, 1, 0), (21, 15, 10, 6, 3, 1)] It's always going to be a list of 2 tuples - one tuple being the argsorted indices, and the other being the actual sorted items. First up, you don't realise this because you're hashing a generator inside a set... but when you decide to exhaust the generator, be prepared for a ValueError: too many values to unpack (expected 2) In summary, you're iterating over zip incorrectly. You don't even need to iterate over zip, if it's just the first tuple you're interested in. What you should instead do, is use next; &gt;&gt;&gt; my_set.add(next(zip(*sorted(enumerate(l), key=lambda x: x[1], reverse=True)))) &gt;&gt;&gt; my_set {(5, 4, 3, 2, 1, 0)} Which gets you just the first tuple.
upvote count: 3
score: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83539959
has comment: http://stackoverflow.com/comment/83539881
answers question: http://stackoverflow.com/q/48277417
type: Answer
accepted answer of: http://stackoverflow.com/q/48277417

http://stackoverflow.com/q/48227586
linked to: http://stackoverflow.com/q/48143308
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Using itertools to generate combinations from 2 lists
duplicate of: http://stackoverflow.com/q/533905
downvote count: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/48228032
has body: I have two lists [1,2,3] and [4,5,6]. I'd like to generate a list of all combinations as follows using itertools ResultingList = [[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]] So far I've only investigated the itertools.combinations function which seems that it can only handle something like this: list(itertools.combinations([1,2,3,4,5,6],2)) Which outputs an incorrect result. How can I generate ResultingList above? Thanks
has answer: http://stackoverflow.com/a/48228032
favorite count: 0
has comment: http://stackoverflow.com/comment/83437248
type: Question
tagged with: python-itertools
has answer: http://stackoverflow.com/a/48347988
linked to: http://stackoverflow.com/q/12935194
has answer: http://stackoverflow.com/a/48227627
accepted answer: http://stackoverflow.com/a/48227627
linked to: http://stackoverflow.com/q/533905
tagged with: python

http://stackoverflow.com/q/48186658
type: AnsweredQuestion
score: 1
tagged with: python
has title: Logical operations in django filter
type: Question
downvote count: 0
upvote count: 1
tagged with: django-q
has answer: http://stackoverflow.com/a/48186735
answer count: 1
accepted answer: http://stackoverflow.com/a/48186735
tagged with: django
has body: I need to get my queryset where: (a="a" AND b=None) OR (a=None AND b="b") I know about Q objects in django, but this syntax doesn't works: cls.objects.filter(models.Q(a="a", b=None) | models.Q(a=None, b="b")) I am absolutely sure my database contains expected objects. But all I get is the empty queryset. I guess there is some problem with syntax here. But where? excepted rows picture. i need only first one and second one
favorite count: 0

http://stackoverflow.com/q/48193316
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83367864
tagged with: django
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83416756
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/83385281
has comment: http://stackoverflow.com/comment/83425764
has answer: http://stackoverflow.com/a/64367023
possible better answer: http://stackoverflow.com/a/64367023
tagged with: python
has body: I have a nested dictionary, which I want to pass to a web service (written in PHP) and am struggling, as I can't access the data I need. The dictionary looks something like import requests from nested_dict import nested_dict data = nested_dict() data['name'] = 'test' data['cookies']['PHPSESSID']['name'] = 'PHPSESSID' data['cookies']['PHPSESSID']['essential'] = 'Essential' data['cookies']['CookieNotice']['name'] = 'CookieNotice' data['cookies']['CookieNotice']['essential'] = 'Essential' Then I make my request: r = requests.post('someurl.com', data = data) In the receiving url someurl.com (written in PHP), I can access the first level no problem eg header('Content-Type: application/json'); $data = $_REQUEST; $response['content'] = $data['name']; $response = $response['content']; echo json_encode($response); The problem is trying to access the data in the nested dict. I don't know what form this is arriving in when it hits someurl.com, and as a result I can't use to produce a loop. What I want to do is this: header('Content-Type: application/json'); $data = $_REQUEST; $response['content'] = $data['name']; foreach ($data['cookies'] as $k =&gt; $v): $response['content'] .= $k." ".$v; endforeach; $response = $response['content']; echo json_encode($response); When the response is printed out in the template, there is content present for the nested section ... Any help much appreciated! UPDATE I have tried many permutations but still struggling! I just need to be able to pass a nested dict (or json) to my receiving url 'someurl.com' and be able to (json) decode that in PHP eg $d = json_decode($_POST) this 'works' but I can't 'do' anything with the response: dat = json.dumps(data) req = requests.get('someurl.com',params=dat) I can't do anything when trying to use requests.post, and if I pass the original dictionary or convert it to json. Many thanks
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48252360
answer count: 2
has title: Passing a nested dictionary to requests module
accepted answer: http://stackoverflow.com/a/48252360

python-packaging
type: Tag
tags question: http://stackoverflow.com/q/48278377
tag name: python-packaging

http://stackoverflow.com/comment/83526990
comment on: http://stackoverflow.com/q/48266472
has text: ok, I think I get it, they're something that will become a query. and I'm not forcing it because I'm not manually flushing. So when the flush happens because of the commit, it happens in the same thread as where I created the session, and that's fine. Not safe, but fine in this case. But the objects were created and added to the session in the other thread... (?)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83333753
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48175011
has text: yes I have updated the OP to show the changes I have made, I still get 400 errors
type: Comment

http://stackoverflow.com/comment/83489212
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48253335
has text: Did you active the virtualenv using `source env/bin/activate`
score: 0

http://stackoverflow.com/comment/90270816
type: AnswerComment
has text: On the other hand going to your answer I recommend calling clear () before adding the new elements because for example if in the combobox first there are numbers from 1 to 5, and in a first select flames to 4 then in the second combobox will be the 5, if in the second selection you select item 2 with your answer you would get items 2,3,4,5 and 5 in the second combobox, as you can see there are duplicate items.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51653372

http://stackoverflow.com/comment/83614076
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48313897
type: QuestionComment
has text: the if ca.validate(captcha) statement is okey, i am sure. I think maybe because I lost a return in the if request.method == 'POST' statement. I added a return in the if request.method == 'POST', but still don't set the variable..

http://stackoverflow.com/comment/91079879
comment on: http://stackoverflow.com/a/48258973
type: Comment
type: AnswerComment
has text: You might be banned. Try changing your proxies and headers.
score: 0

http://stackoverflow.com/a/70178382
answers question: http://stackoverflow.com/q/48230370
score: 1
type: Answer
has body: Recently I am facing the same problem and take me too much time to figure out what's going on, in my situation facing the problem, I did not close the chrome process after using it, so you should check the process exit or not when you exit the app, this is my last worked Python 3 code demo, hope it will help others: @staticmethod def fetch_music_download_url(music_name: str): chrome_driver_service = Service(ChromeDriverManager(chrome_type=ChromeType.GOOGLE).install()) chrome_options = Options() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--remote-debugging-port=9230") driver = webdriver.Chrome(service=chrome_driver_service, options=chrome_options, executable_path="/usr/local/bin/chromedriver") try: driver.maximize_window() driver.get('http://tool.example.cn/music/?page=audioPage&type=migu&name=' + music_name) driver.implicitly_wait(5) driver.find_element(By.CSS_SELECTOR, ".aplayer-list-download.iconfont.icon-xiazai").click() urls = [a.get_attribute('href') for a in driver.execute_script('return document.querySelectorAll(".modal-body a[href*=\'http\']")')] for url in urls: if "listenSong.do" in url: logger.info("fetched url:" + url) FetchMusic.do_save_music_download_url(url) except Exception as e: logger.error("scrapy impl error", e) finally: driver.stop_client() driver.close() driver.quit() chrome_driver_service.stop()
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48324072
has answer: http://stackoverflow.com/a/48327769
upvote count: 2
answer count: 1
downvote count: 0
has title: How to save iterative models and best model in tensorflow?
tagged with: machine-learning
has body: I'm trying to save iterative checkpoints of my models, but also the model that achieved the best score on an independent validation dataset. My checkpoints however, overwrite my best model. Effectively, I'm using something like: saver = tf.train.Saver() with tf.Session() as sess: for epoch in range(20): # Train model [...] # and save a checkpoint saver.save(sess, "iter", global_step=epoch) if best_validiation_acc &lt; last_validation_acc: saver.save(sess, "best_model") How do I get my best model to not be overwritten by my iterated saves?
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/83639342
type: Question
type: AnsweredQuestion
tagged with: cross-validation
tagged with: python
score: 2
accepted answer: http://stackoverflow.com/a/48327769

http://stackoverflow.com/q/48237272
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/83466788
has answer: http://stackoverflow.com/a/48241379
tagged with: urllib2
has comment: http://stackoverflow.com/comment/83458315
tagged with: href
tagged with: python
has title: Python Dell driver download
has body: I have been trying my best to get all the dl for drivers using Beautifulsoup4. however it returns links I don't need. I think they are somehow hidden and for the life of me I can not get them out. here is the page I'm attempting to scrap: http://www.dell.com/support/home/us/en/19/product-support/servicetag/1h1c5p1/drivers from bs4 import BeautifulSoup import urllib2 resp = urllib2.urlopen("http://www.gpsbasecamp.com/national-parks") soup = BeautifulSoup(resp, from_encoding=resp.info().getparam('charset')) for link in soup.find_all('a', href=True): print link['href']
accepted answer: http://stackoverflow.com/a/48241379
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/83547926
comment on: http://stackoverflow.com/a/48268487
type: Comment
type: AnswerComment
has text: +1 "Which sort of indicates that you should consider another model." I have done just that. I have been relying on the pythons multiprocessing ability, instead of thinking in-terms of separate scripts and allowing the OS to deal with it. Thanks for the wake-up call.
score: 0

http://stackoverflow.com/q/48270534
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48270629
upvote count: 2
score: 2
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: numpy
has title: How to have matplotlib's imshow generate an image without being plotted
tagged with: python-imaging-library
tagged with: matplotlib
has body: Matplotlib's imshow does a nice job of plotting a numpy array. This is best illustrated by this code: from PIL import Image import matplotlib.pyplot as plt import numpy as np rows, cols = 200, 200 mat = np.zeros ((rows, cols)) for r in range(rows): for c in range(cols): mat[r, c] = r * c # Handle with matplotlib plt.imshow(mat) and the figure it creates: , which is about what I want. What I want is the image without axes, so by googling around I was able to assemble this function: def create_img (image, w, h): fig = plt.figure(figsize=(w, h), frameon=False) canvas = FigureCanvas(fig) #To make the content fill the whole figure ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) plt.grid(False) ax.imshow(image, aspect='auto', cmap='viridis') canvas.draw() buf = fig.canvas.tostring_rgb() ncols, nrows = fig.canvas.get_width_height() a = np.fromstring(buf, dtype=np.uint8).reshape(nrows, ncols, 3) plt.close() plt.pause(0.01) return Image.fromarray(a) It generates an image from a numpy matrix. And it does not plot, well almost. It plots for a brief moment but then the image closes. I next can save the image what was the reason for all this hassle. I wondered whether there was a simpler method to reach the same goal. I tried to use pillow, by adding some statements behind the code of the first example: # Handle with pillow.Image img = Image.fromarray(mat, 'RGB') img.show() img.save('/home/user/tmp/figure.png') But that generates an incomprehensive image. Probably due to some mistake of mine but I do not know which. I do not know how to get an image of a numpy array with similar output like imshow by other means, for example by pillow. Does someone know how I can generate an image from a numpy matrix in the same way as matplotlibs imshow() without the flashing plots? And in a simpler way than I have concocted with the create_img function?
tagged with: python
accepted answer: http://stackoverflow.com/a/48270629

sockets
tags question: http://stackoverflow.com/q/48175427
tags question: http://stackoverflow.com/q/48257793
tags question: http://stackoverflow.com/q/48283577
tags question: http://stackoverflow.com/q/48309432
tags question: http://stackoverflow.com/q/48266026
tags question: http://stackoverflow.com/q/48249498
tags question: http://stackoverflow.com/q/48181014
tags question: http://stackoverflow.com/q/48244322
tags question: http://stackoverflow.com/q/48205406
tags question: http://stackoverflow.com/q/48181950
tags question: http://stackoverflow.com/q/48198107
tags question: http://stackoverflow.com/q/48283433
tag name: sockets
tags question: http://stackoverflow.com/q/48178136
tags question: http://stackoverflow.com/q/48293456
tags question: http://stackoverflow.com/q/48281230
tags question: http://stackoverflow.com/q/48248567
tags question: http://stackoverflow.com/q/48244782
tags question: http://stackoverflow.com/q/48303173
tags question: http://stackoverflow.com/q/48318266
tags question: http://stackoverflow.com/q/48265319
tags question: http://stackoverflow.com/q/48302294
tags question: http://stackoverflow.com/q/48254937
type: Tag
tags question: http://stackoverflow.com/q/48278859
tags question: http://stackoverflow.com/q/48200630
tags question: http://stackoverflow.com/q/48306528
tags question: http://stackoverflow.com/q/48237282
tags question: http://stackoverflow.com/q/48231573
tags question: http://stackoverflow.com/q/48319759

http://stackoverflow.com/a/48244242
type: Answer
answers question: http://stackoverflow.com/q/48244194
has body: You can't reference an element in a list/string unless such an element exists - i.e row[5] will throw an exception unless there are at least 6 elements in row. You probably mean something like: if len(row) &lt; 6
score: 0
has comment: http://stackoverflow.com/comment/83471025

http://stackoverflow.com/comment/83499908
type: Comment
score: 0
has text: have you read the [configobj documentation](https://configobj.readthedocs.io/en/latest/configobj.html#string-interpolation)?
type: QuestionComment
comment on: http://stackoverflow.com/q/48258642

pymysql
tags question: http://stackoverflow.com/q/48203150
tags question: http://stackoverflow.com/q/48278418
tag name: pymysql
tags question: http://stackoverflow.com/q/48245794
type: Tag
tags question: http://stackoverflow.com/q/48306958
tags question: http://stackoverflow.com/q/48252564
tags question: http://stackoverflow.com/q/48223764

http://stackoverflow.com/q/48212302
tagged with: crm
tagged with: odoo
score: 1
has comment: http://stackoverflow.com/comment/83406977
tagged with: python
tagged with: module
tagged with: http://stackoverflow.com/tag/xml
has body: I am trying to make some changes in the crm.lead model or more precisely inside the form view of opportunity. In the original, i have 2 buttons like "Mark as Win" and "Mark as Lost". I replaced these buttons with other 4 buttons like "FFS - Win", "FFS - Lost", "Package - Win", and "Package - Lost". Now i want to replace label "Won" and "Lost", which is displayed on the green or red background with 4 other label, equal to buttons. At this moment i did: Inherited view(XML) cmp.crm.lead.form crm.lead FFS - Lost Package - Lost FFS - Success Package - Success Model(Python) class CrmLead(models.Model): _inherit = 'crm.lead' ffs_success = fields.Boolean(default=False, readonly=True) ffs_lost = fields.Boolean(default=False, readonly=True) package_success = fields.Boolean(default=False, readonly=True) package_lost = fields.Boolean(default=False, readonly=True) It worked until i added invisible attribute. Now i cant enter to the form view, because i am getting an error: Uncaught Error: Unknown field ffs_lost in domain "ffs_lost","=",false The problem concerns to the every of these 4 fields in the model. Module is updated, fields exists in the database, and i can see them in the developer mode, but odoo still cant recognize them.
answer count: 0
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has title: Odoo Unknown field in domain
has comment: http://stackoverflow.com/comment/83433846
favorite count: 0
type: Question

http://stackoverflow.com/comment/83374388
comment on: http://stackoverflow.com/a/48196588
type: Comment
type: AnswerComment
has text: thanks for your replay, i got this error ( AttributeError: module 'pandas' has no attribute 'rolling')
score: 0

http://stackoverflow.com/comment/83909251
type: Comment
has text: that works, thank you.
type: QuestionComment
comment on: http://stackoverflow.com/q/48279902
score: 0

http://stackoverflow.com/comment/83686187
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48246780
score: 0
has text: All the AT commands should be LTE compatible (some of them have visible traces of that in the `<AcT>` *access technology of the registered network* parameter). Of course the networks might be configured with different supports, but not supporting SMS messages seems wierd.

http://stackoverflow.com/comment/108097871
type: AnswerComment
has text: I tried pyinstaller and it creates .exe but when I run it, nothing happens. Can not see my GUI what could be the reason?
score: 2
type: Comment
comment on: http://stackoverflow.com/a/48360061

http://stackoverflow.com/q/48280807
type: AnsweredQuestion
score: 0
has title: Loading json from unicode string
has comment: http://stackoverflow.com/comment/83546118
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has body: I have a json dumped string dumped in a file. Here is the file format - { u'key1':u'abc' } It's invalid json because its should have double quotes. How do I convert this into valid json?
type: Question
has answer: http://stackoverflow.com/a/48280940
has comment: http://stackoverflow.com/comment/83545162
tagged with: python
accepted answer: http://stackoverflow.com/a/48280940

http://stackoverflow.com/comment/83528665
type: Comment
score: 0
has text: Could you share the full code?
comment on: http://stackoverflow.com/q/48272426
type: QuestionComment

http://stackoverflow.com/comment/83584447
comment on: http://stackoverflow.com/q/48299596
score: 0
type: Comment
type: QuestionComment
has text: It should be `extra_kwargs`, not `extera_kwargs`! Is this typo only here in the question or also in your code?

http://stackoverflow.com/q/48178569
tagged with: python
score: -1
favorite count: 0
has comment: http://stackoverflow.com/comment/83337228
type: Question
upvote count: 0
type: UnansweredQuestion
has title: How to Run a Command in the Computer Terminal Through Python
tagged with: text-to-speech
has answer: http://stackoverflow.com/a/48178732
has comment: http://stackoverflow.com/comment/83337239
downvote count: 1
has body: I am trying to make a TTS (Text to Speech) program and I have found an easy way to do that is to run the "say ''" command in the terminal. However, when I looked to see how to run the terminal command through python I found this:import os os.system("echo 'hello world'") it doesn't seem to work with my laptop (I'm running Linux). Any suggestions?
tagged with: terminal
tagged with: linux
answer count: 1

http://stackoverflow.com/comment/83357019
has text: Possible duplicate of [ElementNotVisibleException : Selenium Python](https://stackoverflow.com/questions/47108512/elementnotvisibleexception-selenium-python)
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48188620

http://stackoverflow.com/comment/83332569
comment on: http://stackoverflow.com/a/48176298
has text: Thank you for the suggestion, I've just posted an alternative non-recursion way of doing it using a forever loop.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48304333
has comment: http://stackoverflow.com/comment/83593675
tagged with: python
score: 2
tagged with: list
downvote count: 2
duplicate of: http://stackoverflow.com/q/4948293
has body: For example, if I write only : l = [1, 2, 3] l[1:2] Is the slice from the list saved in memory? Does it take any space in memory?
tagged with: memory
tagged with: slice
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
has title: Does slicing a list without assignmnet require space in memory?
linked to: http://stackoverflow.com/q/4948293
has comment: http://stackoverflow.com/comment/83593554
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/83582599
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48298833
has text: i think u didn't read my question properly.. that link is one of the first few i saw... besides i already said i been stuck for sometime.. i obviously googled it first.. don't know still downvote no comments to you..
score: 0

http://stackoverflow.com/comment/83635794
type: AnswerComment
comment on: http://stackoverflow.com/a/48325059
type: Comment
has text: The default for the `speed` argument is set before any instances of `Cheetah` are defined; you *have* to do it this way.
score: 2

http://stackoverflow.com/a/77447733
answers question: http://stackoverflow.com/q/48293627
score: 2
upvote count: 2
downvote count: 0
has body: You can use pytest_django.asserts.assertRedirects instead: from pytest_django.asserts import assertRedirects @pytest.mark.django_db def test_redirection_to_home_when_group_does_not_exist(create_social_user): """Some docstring defining what the test is checking.""" c = Client() c.login(username='TEST_USERNAME', password='TEST_PASSWORD') response = c.get(reverse('pledges:home_group', kwargs={'group_id': 100}), follow=True) assertRedirects(response, reverse('pledges:home'))
type: Answer

http://stackoverflow.com/q/48211609
tagged with: app-engine-ndb
has answer: http://stackoverflow.com/a/48214081
score: 0
tagged with: google-app-engine
has answer: http://stackoverflow.com/a/48212940
tagged with: python
has title: How to track a page view using google app engine?
tagged with: analytics
has body: I have a web app which lets users submit a blog post. I would like to track the page views of every blog post page. So when some visits: /post/123 A user's visitor should see the number of people who have visited this page. One seemingly unscalable solution I thought of is to add a page_views property to the Blog kind: class Blog(ndb.Model): title = ndb.StringProperty() page_views = ndb.IntegerProperty() Then, whenever the page is visited, just do blog.page_views plus 1. Then blog.put(). However, this attempt would mean that we would be writing too frequently to the db. Is there a better way?
type: Question
answer count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/83543822
comment on: http://stackoverflow.com/a/48279662
has text: Thanks. It was my mistake. Fixed. I was calling another function internally by passing the arguments as $1, $2, $3, .. etc. When I should've quoted the arguments that might have whitespaces like $1, $2, "$3" .. etc. Thanks!
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83549139
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48282388
has text: Is that really a list though, Data in his first message seems to be a string to be parsed.

http://stackoverflow.com/a/48316232
has comment: http://stackoverflow.com/comment/83620525
answers question: http://stackoverflow.com/q/48273815
has body: CSRF token is essentially a cookie which is retrievable. By default, the name of this cookie is csrftoken for every django app. You need to change the name of at least one of the cookies with the CSRF_COOKIE_NAME setting (in your settings.py). Then your colleagues can retrieve that cookie with the following AJAX call: // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie &amp;&amp; document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i &lt; cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('name_of_your_token'); For more complicated uses check the documentation: https://docs.djangoproject.com/en/2.0/ref/csrf/ A similar case: Multiple Django sites on the same domain - CSRF fails
has comment: http://stackoverflow.com/comment/83621476
has comment: http://stackoverflow.com/comment/83660496
type: Answer
has comment: http://stackoverflow.com/comment/83621139
has comment: http://stackoverflow.com/comment/83618387
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/83618470
has comment: http://stackoverflow.com/comment/83620111
downvote count: 0
has comment: http://stackoverflow.com/comment/83661743

http://stackoverflow.com/comment/83355659
type: Comment
type: AnswerComment
has text: What about "[Do not get logger at the module level unless disable_existing_loggers is False](https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/)"?
score: 0
comment on: http://stackoverflow.com/a/48187704

http://stackoverflow.com/a/48309343
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83605406
has body: You would be able to assign data to an empty dataframe using following df = pd.DataFrame() df['newcol'] = pd.Series() df['othercol'] = pd.Series() df.loc[0, 'newcol'] = 1 df.loc[1, 'newcol'] = 5 df.loc[0, 'othercol'] = 12 df.loc[1, 'othercol'] = -10 newcol othercol 0 1.0 12.0 1 5.0 -10.0
score: 3
answers question: http://stackoverflow.com/q/48309282
type: Answer
accepted answer of: http://stackoverflow.com/q/48309282
upvote count: 3

http://stackoverflow.com/comment/83651766
has text: Its not just the standardize method but there are various other methods which are using numpy.I had already tried the above approach but there was a difference in output values. Thanks for the solution
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48325613

http://stackoverflow.com/comment/83665662
type: Comment
type: QuestionComment
score: 0
has text: The context is a health care domain. The mathematical model: earliestVisit ~ Binomial(n=14,p=0.5) medsRunOut ~ DiscreteUniform(lower = 0, upper = 89) PostponeProb ~ ... Jeffery's prior for Geometric Distribution. numDecisions ~ Geometric(PostponeProb) nonExceptionalVisitDate = medsRunOut - earliestVisit + numDecisions – 1 nonExceptionalVisitDateMod90 ~ DensityDist(lamba x: pm.math.logsumexp([nonExceptionalVisitDate.logp(x)) p = some small constant probability visitDate ~ Mixture([p, 1-p], [ DiscreteUniform(lower = 0, upper = 89), nonExceptionalVisitDateMod90 ]) visitDate is observeddata
comment on: http://stackoverflow.com/q/48295093

http://stackoverflow.com/comment/83387059
comment on: http://stackoverflow.com/q/48202943
score: 0
type: Comment
type: QuestionComment
has text: By "array list", do you mean "list"? or "list of lists"? because you don't mean "array list".

http://stackoverflow.com/a/71413670
answers question: http://stackoverflow.com/q/48238445
type: Answer
score: 0
has body: Use this simple function: def location(update: Update, context: CallbackContext): current_pos = (update.message.location.latitude,update.message.location.longitude) print(current_pos) dp.add_handler(MessageHandler(Filters.location, location))

http://stackoverflow.com/comment/83466277
comment on: http://stackoverflow.com/q/48241888
has text: @Stack That is what I'm doing.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48307499
answers question: http://stackoverflow.com/q/48307390
downvote count: 1
score: 2
upvote count: 3
has body: You've defined a function called request, which has therefore hidden the global request variable. Rename your route function.
type: Answer

http://stackoverflow.com/a/48271698
answers question: http://stackoverflow.com/q/48271046
score: 2
upvote count: 2
downvote count: 0
type: Answer
has body: Tkinter widgets cannot represent the value None. Tkinter is just a thin python wrapper around a tcl interepter, and the tcl language has no notion of None or a null value. Since str(None) returns the string "None", that is what the widget is set to when you give it the value of None. You'll have to come up with some custom way to handle that yourself, such as inserting an empty string if the value is actually None.

http://stackoverflow.com/a/48200506
answers question: http://stackoverflow.com/q/48199033
has body: The problem is that you have several event loops that are executed consecutively. That means the first for event in pygame.event.get(): loop will have emptied the queue when you enter the game_loop and you see only events that are added in the short time between the first event loop and the second event loop. A quick fix would be to assign the events to a variable in the outer event loop (pygame.event.get returns a list), use this list in the first event loop and then pass it to the game_loop function where you can iterate over it a second time. events = pygame.event.get() for event in events: # ... if ready: game_loop(events) In the game_loop function: def game_loop(events): # ... for event in events:
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/83382640

http://stackoverflow.com/q/48197618
type: Question
upvote count: 2
has body: I am trying to find out how to check if there is any row within my dataframe which has every item reflected in a dictionary. The dictionary may have more items which are not expressed in the dataframe rows. For example, import pandas as pd validCombinations = { 'combo1':{ 'prop1': 'X', 'prop2':'Y', 'prop3': 'Z' }, 'combo2':{ 'prop1': 'U', 'prop3': 'Z' }, 'combo3':{ 'prop1': 'X', 'prop2':'X' }, 'combo4':{ 'prop1': 'X', 'prop2':'Y', 'prop3': 'U' } } df = pd.DataFrame.from_dict( { k: validCombinations[k] for k in validCombinations.keys() }, orient='index') print df &gt;&gt; prop1 prop2 prop3 combo1 X Y Z combo2 U NaN Z combo3 X X NaN combo4 X Y U mydict = { 'prop1': 'X', 'prop2':'Y', 'prop3': 'Z', 'prop4': 'V' } I now want a function that returns True or False depending on whether a complete row from df was expressed by mydict, dfRowMatchedMyDict( df, mydict) --&gt; this should return True since combo1 in df has all items expressed in mydict I am really not sure if I should be converting mydict to a dataframe first, or how to go about solving this in a clean way?
has answer: http://stackoverflow.com/a/48197687
downvote count: 0
accepted answer: http://stackoverflow.com/a/48197727
tagged with: python
favorite count: 0
has title: How to search for a row in a dataframe that has all elements expressed by a dictionary?
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48197669
possible better answer: http://stackoverflow.com/a/48197669
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/48197727
has comment: http://stackoverflow.com/comment/83376418

http://stackoverflow.com/q/48263906
has answer: http://stackoverflow.com/a/48281332
type: Question
has title: Error in NGSLIB PACKAGE INSTALLATION
tagged with: bioinformatics
type: UnansweredQuestion
tagged with: annotations
tagged with: python
has body: I am trying to install ngslib python package for oncotator 1.9.5.0 . But every time installation failed due to some reason (mentioned below). I have tried all possible methods like pip install ngslib directly or python -m pip install --upgrade pip pip install ngslib or git clone https://github.com/tsznxx/ngslib Everytime I am getting the following error: Collecting ngslib Using cached ngslib-1.1.20.tar.gz Complete output from command python setup.py egg_info: Compile KentLib ... cd lib &amp;&amp; make make[1]: Entering directory `/tmp/pip-build-d1JyTR/ngslib/external/KentLib/lib' gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 chainToPsl.c -o chainToPsl.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 vGfx.c -o vGfx.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 psPoly.c -o psPoly.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 obscure.c -o obscure.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 mgTimes14.c -o mgTimes14.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 fuzzyShow.c -o fuzzyShow.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 sqlList.c -o sqlList.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 seqOut.c -o seqOut.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 verbose.c -o verbose.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 memgfx.c -o memgfx.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 tabRow.c -o tabRow.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 phyloTree.c -o phyloTree.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 servmsII.c -o servmsII.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 vPng.c -o vPng.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 servcl.c -o servcl.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 xa.c -o xa.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 mgTimes12.c -o mgTimes12.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 hmmstats.c -o hmmstats.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 mgTimes8.c -o mgTimes8.o gcc -c -fPIC -Wall -I../inc -DMACHTYPE_x86_64 bwgQuery.c -o bwgQuery.o gcc -c -fPIC -Wall -I../inc -DMACHT…
score: 0
tagged with: genome
answer count: 2
has answer: http://stackoverflow.com/a/48268902

http://stackoverflow.com/q/48229592
has comment: http://stackoverflow.com/comment/83441413
has comment: http://stackoverflow.com/comment/83445606
answer count: 1
has comment: http://stackoverflow.com/comment/83441627
accepted answer: http://stackoverflow.com/a/48235874
tagged with: asynchronous
upvote count: 10
downvote count: 1
tagged with: socket.io
favorite count: 0
score: 9
type: Question
tagged with: python-3.x
has title: Understanding async await in python socket io / aiohttp server
has comment: http://stackoverflow.com/comment/83442371
has body: I am trying to setup an socket.io server using python-socketio. Here is a minimal working example: import asyncio from aiohttp import web import socketio import random sio = socketio.AsyncServer(async_mode='aiohttp') app = web.Application() sio.attach(app) @sio.on('connect') def connect(sid, environ): print("connected: ", sid) @sio.on('sendText') async def message(sid, data): print("message ", data) # await asyncio.sleep(1 * random.random()) # print('waited', data) @sio.on('disconnect') def disconnect(sid): print('disconnect ', sid) if __name__ == '__main__': web.run_app(app, host='0.0.0.0', port=8080) This runs fine, and I can execute (here in node.js) for instance const io = require('socket.io-client'); const socket = io('ws://localhost:8080'); socket.emit('sendText', 'hey 1') socket.emit('sendText', 'hey 2') socket.emit('sendText', 'hey 3') If I run the server and run the node script above I get server-side connected: c1e687f0e2724b339fcdbefdb5aaa8f8 message hey 1 message hey 2 message hey 3 However, if I uncomment the lines with await sleep in the code, I only receive the first message: connected: 816fb6700f5143f7875b20a252c65f33 message hey 1 waited hey 1 I don't understand why the next messages are not appearing. Can only one instance of async def message run at the same time? Or why? I am sure that I am not understanding something very fundamental about how this works. I would be very grateful if someone could point out what I am not understanding.
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/83442849
has comment: http://stackoverflow.com/comment/83443821
tagged with: python
has comment: http://stackoverflow.com/comment/83445317
has comment: http://stackoverflow.com/comment/83444623
has comment: http://stackoverflow.com/comment/83441661
has comment: http://stackoverflow.com/comment/83441364
has answer: http://stackoverflow.com/a/48235874
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83445645
has comment: http://stackoverflow.com/comment/83445447
has comment: http://stackoverflow.com/comment/83441744
has comment: http://stackoverflow.com/comment/83441590
has comment: http://stackoverflow.com/comment/83441705

http://stackoverflow.com/comment/89299438
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48182628
type: AnswerComment
has text: @philshem Correction - it is in the admin SDKs now (at least node and Java), but they have different method names in different languages. Don't know about python.

http://stackoverflow.com/q/48271169
answer count: 4
has answer: http://stackoverflow.com/a/48271193
has body: s="|0000011111111|" print s.replace(s[9:12],' ') ...output is |00000 11| s="|0000012345678|" print s.replace(s[9:12],' ') ...output is |00000123 78| I only want to replace s[9:12] to three spaces, why is the first output incorrect?
type: AnsweredQuestion
score: 3
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48271246
possible better answer: http://stackoverflow.com/a/48271186
upvote count: 3
has comment: http://stackoverflow.com/comment/83526112
favorite count: 0
type: Question
tagged with: replace
has answer: http://stackoverflow.com/a/48271212
has answer: http://stackoverflow.com/a/48271186
downvote count: 0
accepted answer: http://stackoverflow.com/a/48271193
tagged with: python
has title: Python replace function outputs different results
tagged with: string

http://stackoverflow.com/comment/83572348
type: QuestionComment
has text: each page, thx.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48293173

dmg
type: Tag
tag name: dmg
tags question: http://stackoverflow.com/q/48247534

http://stackoverflow.com/a/48253665
answers question: http://stackoverflow.com/q/48253310
upvote count: 1
has body: Try this. print('Hello {0}'.format(name)) and make sure using terminal to run your .py file
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/83490034
has comment: http://stackoverflow.com/comment/83489906
score: 0

http://stackoverflow.com/comment/83565068
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48272389
has text: Possible duplicate of [Python: sort function breaks in the presence of nan](https://stackoverflow.com/questions/4240050/python-sort-function-breaks-in-the-presence-of-nan)

http://stackoverflow.com/q/48307955
tagged with: python
type: Question
upvote count: 0
answer count: 2
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/48309351
has answer: http://stackoverflow.com/a/48372189
possible better answer: http://stackoverflow.com/a/48372189
favorite count: 0
has comment: http://stackoverflow.com/comment/83601241
has body: I'm new here, and to python also.. The if statments in the following code are not running. does anyone know why? This is a camel game I need to submit by sunday. import random from Tkinter import * print "Welcome to Camel!" print "You have stolen a camel to make your way across the great Mobi desert." print "The natives want their camel back", print "and are chasing you down! Survive your" print "desert trek and out run the natives." print "" summ = 0 done = False miles = 0 thirst = 0 tiredness = 0 distance = 20 drinks = 3 window = Tk() window.title("Camel") def A(): global drinks if drinks &gt; 0: drinks -= 1 thirst = 0 else: print "You ran out of drinks!" done = True def B(): global summ, thirst, tiredness, distance miles = random.randint(5, 12) summ += miles print "miles traveled: ", miles print "Total miles traveled: ", summ print "" thirst += 1 tiredness += 1 distance -= random.randint(7, 14) distance += miles def C(): global summ, thirst, tiredness, distance miles = random.randint(10, 20) summ += miles print "Miles traveled: ", miles print "Total miles traveled: ", summ print "" thirst += 1 tiredness += random.randint(1, 3) distance -= random.randint(7, 14) distance += miles def D(): global distance tiredness = 0 print "Your Camel is happy." print "" distance -= random.randint(7, 14) def E(): print "Total miles traveled: ", summ print "Drinks in canteen: ", drinks print "The natives are %i miles behind you." % (distance) print "" def Q(): exit() A = Button(window, text = "A. Drink from your canteen.", command = A) B = Button(window, text = "B. Ahead moderate speed.", command = B) C = Button(window, text = "C. Ahead full speed.", command = C) D = Button(window, text = "D. Stop for the night.", command = D) E = Button(window, text = "E. Status check.", command = E) Q = Button(window, text = "Q. Quit.", command = Q) A.pack() B.pack() C.pack() D.pack() E.pack() Q.pack() if thirst &gt; 4 and thirst &lt;= 6: print "You are thirsty." print "" elif thirst &gt; 6: prin…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83601648
has title: Python - If statments not working in Tkinter
downvote count: 3
has answer: http://stackoverflow.com/a/48309351
has comment: http://stackoverflow.com/comment/83601696
score: -3
has comment: http://stackoverflow.com/comment/83601263
has comment: http://stackoverflow.com/comment/83601635

http://stackoverflow.com/comment/83592306
comment on: http://stackoverflow.com/a/48279714
type: AnswerComment
has text: Sure. Have a happy day
score: 0
type: Comment

http://stackoverflow.com/comment/83564988
type: QuestionComment
comment on: http://stackoverflow.com/q/48289923
type: Comment
has text: If you want a function that creates a new instance of the same class every time it is called, such a function already exists: the class itself.
score: 0

http://stackoverflow.com/comment/105279859
comment on: http://stackoverflow.com/q/48201729
type: Comment
has text: np.multiply(a,b) gives a vector of (ai x bi), while np.dot gives the sum of those vector elements, so your code shows the equivalence `np.sum(np.multiply(a,b))=np.dot(a,b)` .Incidentally a*b will give the same as np.multiply(a,b)
score: 0
type: QuestionComment

http://stackoverflow.com/q/48259470
has body: I have OHLC data. The candle can be either 'green' (if the close is above open) or 'red' (if the open is above the close). The format is: open close candletype 0 542 543 GREEN 1 543 544 GREEN 2 544 545 GREEN 3 545 546 GREEN 4 546 547 GREEN 5 547 542 RED 6 542 543 GREEN What I would like is to count the number of consecutive green or red candles for n-previous rows. Lets say I want to identify rows preceded by 3 green candles. That the desired output would be: open close candletype pattern 0 542 543 GREEN Toofewrows 1 543 544 GREEN Toofewrows 2 544 545 GREEN Toofewrows 3 545 546 GREEN 3-GREEN-CANDLES-IN-A-ROW 4 546 547 GREEN 3-GREEN-CANDLES-IN-A-ROW 5 547 542 RED 3-GREEN-CANDLES-IN-A-ROW 6 542 543 GREEN No pattern I know how to get the solution by extracting the row number, applying a custom function to candletype series with that row number and looking at n previous rows within that custom function, creating a n-item list and checking for isAll('GREEN') but I WAS WONDERING IF THERE IS AN ELEGANT ONE LINER APPLY SOLUTION?
has answer: http://stackoverflow.com/a/48259523
answer count: 3
tagged with: pandas
score: 1
linked to: http://stackoverflow.com/q/45990648
upvote count: 1
accepted answer: http://stackoverflow.com/a/48259523
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48261273
has answer: http://stackoverflow.com/a/48259948
downvote count: 0
linked to: http://stackoverflow.com/q/27626542
tagged with: python
tagged with: data-science
has title: Pandas number of consecutive occurrences in previous rows
possible better answer: http://stackoverflow.com/a/48261273
type: AnsweredQuestion

http://stackoverflow.com/q/48190135
upvote count: 1
tagged with: python
has title: How to get web scraped data from Python/Beautiful Soup into a MySQL database
has comment: http://stackoverflow.com/comment/83361376
has comment: http://stackoverflow.com/comment/83361620
answer count: 1
has comment: http://stackoverflow.com/comment/83361177
tagged with: mysql
has comment: http://stackoverflow.com/comment/83361647
score: 1
has answer: http://stackoverflow.com/a/48191407
favorite count: 0
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/83362281
type: UnansweredQuestion
has body: Although I am getting over 10 items as results in Python, right now I am only able to get the last product to appear in my MySQL database (with an id of 12 along with its information like price, picture, etc). I need to fix it so that they all appear and not just one product. Python code is below. import requests from bs4 import BeautifulSoup import mysql.connector url = 'https://www.newegg.com/Video-Cards-Video-Devices/Category/ID-38?Tpk=graphics%20card' source = requests.get(url).text soup = BeautifulSoup(source, 'lxml') conn = mysql.connector.connect(host='127.0.0.1', user='x', database='scrape',password="x") cursor = conn.cursor() item_container = soup.find_all('div', class_='item-container') def get_data(): lists = [] for index, item_name in enumerate(item_container): name = item_name.find_all('a', class_='item-title')[0].text lists.append({'name': name}) lists[index]['index'] = index for index, item_price in enumerate(item_container): price = item_price.find('li', class_='price-current').find('strong') if price == None: price == ('Not Available') lists[index]['price'] = price else: price = ('$' + price.text +'.99') prices = [] lists[index]['price'] = price for index, item_picture in enumerate(item_container): picture = 'http:' + item_picture.find('img', class_='lazy-img')['data-src'] lists[index]['picture'] = picture for index, item_shipping in enumerate(item_container): shipping = (item_shipping.find('li', class_='price-ship').text).strip() lists[index]['shipping'] = shipping def create_table(): val_index = lists[index]['index'] val_name = lists[index]['name'] val_picture = lists[index]['picture'] val_price = lists[index]['price'] val_shipping = lists[index]['shipping'] add_item = ("INSERT INTO newegg " "(id, itemname, itempic, itemprice, itemshipping) " "VALUES (%s, %s, %s, %s, %s)") data_item = (val_index, val_name, val_picture, val_price, val_shipping) cursor.execute("DELETE FROM newegg ") conn.commit() cursor.execute(add_item, data_item) conn.commit() cur…
has comment: http://stackoverflow.com/comment/83362581
downvote count: 0
has comment: http://stackoverflow.com/comment/83361944

cursor
tags question: http://stackoverflow.com/q/48203150
tags question: http://stackoverflow.com/q/48326859
type: Tag
tag name: cursor

http://stackoverflow.com/comment/83508043
has text: `top = 3` means that the content of the figure is 300% larger than the figure itself. Hence only its bottom part is shown. The second picture seems to be the desired outcome so it's unclear what the question really is here.
type: Comment
comment on: http://stackoverflow.com/q/48262442
type: QuestionComment
score: 2

data-science
tags question: http://stackoverflow.com/q/48290983
tags question: http://stackoverflow.com/q/48265201
tags question: http://stackoverflow.com/q/48327766
tags question: http://stackoverflow.com/q/48195863
tags question: http://stackoverflow.com/q/48256956
tags question: http://stackoverflow.com/q/48315094
tags question: http://stackoverflow.com/q/48259470
type: Tag
tags question: http://stackoverflow.com/q/48178286
tags question: http://stackoverflow.com/q/48323556
tags question: http://stackoverflow.com/q/48261685
tags question: http://stackoverflow.com/q/48184833
tag name: data-science
tags question: http://stackoverflow.com/q/48177087
tags question: http://stackoverflow.com/q/48290068
tags question: http://stackoverflow.com/q/48257321
tags question: http://stackoverflow.com/q/48197227
tags question: http://stackoverflow.com/q/48319827

http://stackoverflow.com/comment/83480035
comment on: http://stackoverflow.com/q/48248323
type: QuestionComment
score: 1
has text: Can you add user and profile models?
type: Comment

http://stackoverflow.com/comment/83471034
comment on: http://stackoverflow.com/a/48243958
has text: @BinyaminEven no problem , happy coding
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83524976
comment on: http://stackoverflow.com/q/48236030
type: QuestionComment
type: Comment
score: 0
has text: Since you're a self-described Python noob, I would recommend using a normal Python install instead of using miniconda, unless you have some specific reason to be doing so. (If so, just ignore this comment.) Since it looks like you already have it installed (which is usually the case with Linux distros), you'll want to make the system install the one called by the "python" or "python3" commands, as described in this answer to another question: https://askubuntu.com/questions/320996/how-to-make-python-program-command-execute-python-3/475815#475815

http://stackoverflow.com/a/59281001
type: Answer
score: 36
downvote count: 0
answers question: http://stackoverflow.com/q/48174935
upvote count: 36
has body: Check if Conda is installed conda -V Check if Conda is up to date conda update conda Create a virtual environment conda create -n yourenvname python=x.x anaconda Activate your virtual environment source activate yourenvname Install additional Python packages to a virtual environment conda install -n yourenvname [package] Deactivate your virtual environment source deactivate Delete the virtual environment conda remove -n yourenvname --all

http://stackoverflow.com/comment/83365075
has text: I think you mean: `[d['Name'] for d in list_of_dicts]`
type: Comment
comment on: http://stackoverflow.com/a/48192272
score: 0
type: AnswerComment

http://stackoverflow.com/comment/139639574
type: AnswerComment
has text: Please give credit to the people you copy from or consider just linking to it in a comment. https://stackoverflow.com/a/72737752/7365866
type: Comment
comment on: http://stackoverflow.com/a/77593653
score: 0

http://stackoverflow.com/a/48696259
type: Answer
answers question: http://stackoverflow.com/q/48232561
downvote count: 0
upvote count: 6
score: 6
has body: Use pip install libvirt-python to install libvirt bindings. Then libvirt_connection = libvirt.open('qemu:///system') to create connection to libvirt. Get the vm vm_dom = libvirt_connection.lookupByUUIDString(domain_uuid) (domain_uuid is a string that contains UUID of your domain). And finally call vm_dom.snapshotCreateXML( SNAPSHOT_XML_TEMPLATE.format(snapshot_name=snapshot_name), libvirt.VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC ) where SNAPSHOT_XML_TEMPLATE looks like this: SNAPSHOT_XML_TEMPLATE = """&lt;domainsnapshot&gt; &lt;name&gt;{snapshot_name}&lt;/name&gt; &lt;/domainsnapshot&gt;""" This will create disc and ram snapshot with given name. libvirt-python compatible with python3 and python2.

http://stackoverflow.com/comment/83365668
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48192535
has text: I'm no doctor, but 45s for 200k markers sounds alright.
score: 1

http://stackoverflow.com/a/48295606
has comment: http://stackoverflow.com/comment/83575809
answers question: http://stackoverflow.com/q/48295547
has comment: http://stackoverflow.com/comment/83575977
score: 2
has comment: http://stackoverflow.com/comment/83576300
upvote count: 2
type: AcceptedAnswer
has body: You can use a list of tuple to store your data. Ex: res = [] with open('files.txt', 'r') as f: for line in f: line = line.strip() img, gt = line.split() img_path = data_dir + img gt_path = data_dir + gt res.append((img_path, gt_path)) for i,v in res: print("Image Path {0}".format(i)) print("label Path {0}".format(v)) Using a Dictionary(as requested in comments) res = {} c = 0 with open('files.txt', 'r') as f: for line in f: line = line.strip() img, gt = line.split() img_path = data_dir + img gt_path = data_dir + gt res[c] = {"img_path": img_path, "gt_path": gt_path} c += 1 print res
downvote count: 0
has comment: http://stackoverflow.com/comment/83576244
has comment: http://stackoverflow.com/comment/83576038
has comment: http://stackoverflow.com/comment/83576338
has comment: http://stackoverflow.com/comment/83575872
has comment: http://stackoverflow.com/comment/83575758
accepted answer of: http://stackoverflow.com/q/48295547
type: Answer

http://stackoverflow.com/comment/83600041
score: 0
type: Comment
has text: It does not, it gives the error "'C:\Users\Username\Desktop\Practice' is not recognized as an internal or external command, operable program or batch file."
type: AnswerComment
comment on: http://stackoverflow.com/a/48304713

http://stackoverflow.com/q/48184120
score: 0
has body: I have a numpy matrix as output in DataLab. How can I get it as a table in BigQuery? so far it seems that I need to translate it into JSON, save in the Storage and upload from there. Is there a simpler way to get this done? Thanks
accepted answer: http://stackoverflow.com/a/48203463
has answer: http://stackoverflow.com/a/48203463
tagged with: python
tagged with: google-bigquery
type: Question
tagged with: google-cloud-datalab
has title: Upload Numpy matrix from DataLab to BigQuery
answer count: 1
has comment: http://stackoverflow.com/comment/83362617
type: AnsweredQuestion

http://stackoverflow.com/q/48220410
linked to: http://stackoverflow.com/q/44093705
type: Question
has comment: http://stackoverflow.com/comment/83478222
has comment: http://stackoverflow.com/comment/83459304
answer count: 0
type: UnansweredQuestion
has title: Iterate Through Matplotlib Subplot For Loop
duplicate of: http://stackoverflow.com/q/44093705
has comment: http://stackoverflow.com/comment/83429781
has body: I want to iterate through matplotlib subplots, plotting one trace, tr in each subplot. However, the output that I currently am getting plots all 8 traces in each subplot. How do I plot just one trace into their own subplots? I suspect it has something to do with my for loop indexing, but I can't seem to determine where this issue lies. Thanks. The simplified code is below: traces = glob.glob('*.data') fig,ax = plt.subplots(nrows=4, ncols=2) index = 0 for index, ix in enumerate(traces): tr = obspy.read(traces[index])[0] *do stuff* for i in range(4): for j in range(2): ax[i, j].plot(time,tr.data, color='k') index+=1 EDIT: THE CODE BELOW HAS SOLVED THIS QUESTION. traces = glob.glob('*.data') fig,axes = plt.subplots(nrows=4, ncols=2) index = 0 for tr, ax in zip(traces, axes.reshape(-1)): ** do stuff ** tr = obspy.read(traces[index])[0] ax.plot(time,tr_trim.data, color='k') ax.set_ylabel("Raw Data") ax.set_xticks([]); index +=1 plt.show()
has comment: http://stackoverflow.com/comment/83430204
tagged with: python
has comment: http://stackoverflow.com/comment/83425867
has comment: http://stackoverflow.com/comment/83459829
score: 0
has comment: http://stackoverflow.com/comment/83430117
has comment: http://stackoverflow.com/comment/83425287
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83456286

http://stackoverflow.com/comment/83623260
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48318892
type: QuestionComment
has text: How should I load this data then? Its works fine when i do this: `X,Y = np.meshgrid(Xcoor, Ycoor) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) ax.plot_surface(Xcoor, Ycoor, Z)`

http://stackoverflow.com/comment/83360961
type: AnswerComment
score: 1
type: Comment
has text: Using `shutil.move` is not the only issue with your code, I also pointed out you are renaming the files incorrectly; you are ignoring the file modified time, and have inserted an arbitary filename. You do need to read the question more carefully, you have missed a few important details.
comment on: http://stackoverflow.com/a/48190109

http://stackoverflow.com/a/48314078
has body: How about rearranging columns within data frame df as needed, and then write to excel. That way you don't have to worry about excel end. NOTE: Values in columns are fictitious. &gt;&gt;&gt; df = df'Seq Label', 'TP', 'TN', 'FP', 'FN' &gt;&gt;&gt; df Seq Label TP TN FP FN 0 if &gt;= 1 1 1 1 1 1 if &gt;= 2 2 2 2 2 2 if &gt;= 3 3 3 3 3 3 if &gt;= 4 4 4 4 4 4 if &gt;= 5 5 5 5 5 5 if &gt;= 6 6 6 6 6 6 if &gt;= 7 7 7 7 7 &gt;&gt;&gt; df.to_excel('Book10.xlsx', sheet_name='sheet1', index=False) Result
has comment: http://stackoverflow.com/comment/83613931
type: Answer
answers question: http://stackoverflow.com/q/48313756
accepted answer of: http://stackoverflow.com/q/48313756
has comment: http://stackoverflow.com/comment/83613956
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83613878
downvote count: 0
has comment: http://stackoverflow.com/comment/83613864
score: 3

http://stackoverflow.com/comment/83482919
has text: this code is short and sweet 'msg = input("Please type: ") print("Capital Letters: ", len([x for x in msg if x.isupper()])) print("even numbers:", len([y for y in filter(lambda x: x.isdigit(), msg) if int(y)%2 ==0]))'
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48249696
type: Comment

http://stackoverflow.com/comment/83549658
type: QuestionComment
score: 0
has text: `data = {"file1": [1, 4, 10], "file2": [99, 400]}`
comment on: http://stackoverflow.com/q/48282894
type: Comment

http://stackoverflow.com/comment/83509132
has text: Why are you redefining `Generator` in every iteration? Move the function definition out of the `while True` loop
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48262991
type: QuestionComment

http://stackoverflow.com/comment/83453733
type: Comment
comment on: http://stackoverflow.com/a/48217448
has text: I am accepting your answer because i have a new issue <record id="confirm_sale_order" model="ir.actions.server"> Confirm Sale Orders action = { "type": "ir.actions.act_window", "view_mode": "tree", "res_model": object.sale.order, "res_id": object.action_confirm_sale_order, }
score: 0
type: AnswerComment

http://stackoverflow.com/a/48296156
accepted answer of: http://stackoverflow.com/q/48295984
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83586580
score: 3
answers question: http://stackoverflow.com/q/48295984
has body: if cards variable contains the labels of the cards you want to add then you can write the following code: sum_of_cards = sum([d[i] for i in cards])
type: Answer

http://stackoverflow.com/comment/83516688
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48264536
type: Comment
has text: Try installing `google-cloud-firestore` instead of (or in addition to?) `firebase-admin`, as per the error message.

http://stackoverflow.com/q/48195759
answer count: 1
tagged with: logstash
has title: How to configure native python logging library with logstash and elastic?
tagged with: logging
has answer: http://stackoverflow.com/a/48197310
type: AnsweredQuestion
upvote count: 3
score: 3
has body: I'm new to the ELK stack and am trying to learn how to configure the native python logging function to update my Elastic DB with the help of LogStash. The resources I've found haven't been too clear to me, and I was wondering if anyone on here could help me with the basic steps. Am I on the right track in starting with these couple steps? Setup of Config File for LogStash Retrieve a 'logger' [logging.getLogger()] and add a Logstash Handler to it where the host is the Elastic DB URL? Next steps? Any help would be greatly appreciated, thanks.
downvote count: 0
tagged with: elastic-stack
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/48197310
type: Question

http://stackoverflow.com/comment/83616733
type: QuestionComment
has text: Apart from my answer below, I guess your main problem is that you get `twinx()` wrong. What you probably think it does is actually done by `sharex=True` but this has other issues (see answer).
comment on: http://stackoverflow.com/q/48256413
score: 0
type: Comment

http://stackoverflow.com/q/48267586
has comment: http://stackoverflow.com/comment/83518392
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48267706
has title: Is this type of indexing a transposition of Numpy array?
tagged with: transpose
has comment: http://stackoverflow.com/comment/83518351
duplicate of: http://stackoverflow.com/q/40574982
tagged with: python
tagged with: numpy-slicing
score: 0
linked to: http://stackoverflow.com/q/40574982
answer count: 2
has answer: http://stackoverflow.com/a/48267733
has body: I'm following certain tutorials for science proposals in Python and I've encounter this way of using indexing: import numpy as np l=np.array([8,5,2,3]) print(l[:,None]) What this print returns is: [[8] [5] [2] [3]] It is obvious what this code does and I find it very useful for my proposal but It would never have occurred to me using it because I don't understand what this slicing syntax is saying. Anyone can explain me how this type of slicing works? Thanks in advance.
linked to: http://stackoverflow.com/q/29241056
type: Question
tagged with: numpy

http://stackoverflow.com/q/48269125
has body: I just switched over from PyCharm to ST3 for Python development. I've installed Anaconda for autocompletion (and I've also tried SublimeCodeIntel). Here is the issue that I have having. If I type in the following import numpy as np both packages suggest 'numpy' after the 'as' and, if I am not paying attention, when I hit enter, the statement is now changed to this: import numpy as numpy This also happens with say import pandas as pd which becomes import pandas as pandas Is there a way to change this behavior? For now, I have to remember to hit space so that my statements remain as I type this. This behavior is annoying and I have not experienced this with any other editor (PyCharm, Spyder.) Thanks for the help.
tagged with: python
tagged with: sublimetext3
score: 2
upvote count: 2
downvote count: 0
answer count: 1
has title: Sublime Text 3 and Anaconda / SublimeCodeIntel Autocompletion
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/57699439
tagged with: anaconda
type: UnansweredQuestion

http://stackoverflow.com/comment/83650748
type: Comment
has text: @jack6e, that's exactly what I've been doing. However, (a) code gets messy with these loops (counters which aren't part of logic), (b) you also have to modify x depending on number of items in your input.
type: QuestionComment
comment on: http://stackoverflow.com/q/48327545
score: 0

http://stackoverflow.com/a/48281313
score: 0
has body: The None appeared because delay_print was returning no values. import time import sys def delay_print(s): for c in s: if c: sys.stdout.write(c) sys.stdout.flush() time.sleep(0.50) return '' #delay_print("hello world") GetUp=input(delay_print("\nGET UP? Y/N: "))
answers question: http://stackoverflow.com/q/48281034
type: Answer

http://stackoverflow.com/q/48300157
tagged with: django-forms
has comment: http://stackoverflow.com/comment/83585625
favorite count: 0
type: Question
has body: Here is what I'm trying to achieve. I want to replace 3 static html inputs (checkboxes) with django form fields (forms.Form). When I render this piece of django template: I get the following result: But I was expecting something as the original html: Seems to me django is introducing some double quotes during the field rendering. Anyone knows how to work around this? I'm open to any suggestions. PS: I inherited this html from a legacy PHP code that I'm trying to convert to python Django for new features and easier maintanance :/
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83585341
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83585774
downvote count: 0
tagged with: django
score: 2
has title: Django: how to render form field without double quotes
tagged with: python

http://stackoverflow.com/q/48324203
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83655557
downvote count: 0
type: UnansweredQuestion
has body: I'm having issues with this example code of how to read text from images using Python, OpenCV and OCR. This code was built with python 2.7, and I'm using python 3.6 so maybe I'm missing some changes between these versions. import cv2 import numpy as np import pytesseract from PIL import Image src_path = "C:/Users/crist/Desktop/borrar/lectura/" def get_string(img_path): # Read image with opencv img = cv2.imread(img_path) # Convert to gray img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply dilation and erosion to remove some noise kernel = np.ones((1, 1), np.uint8) img = cv2.dilate(img, kernel, iterations=1) img = cv2.erode(img, kernel, iterations=1) # Write image after removed noise cv2.imwrite(src_path + "removed_noise.png", img) # Apply threshold to get image with only black and white #img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 2) # Write the image after apply opencv to do some ... cv2.imwrite(src_path + "thres.png", img) # Recognize text with tesseract for python result = pytesseract.image_to_string(Image.open(src_path + "thres.png")) #os.remove(temp) return result print ('--- Start recognize text from image ---') print (get_string(src_path + "2.png")) print ("------ Done -------") Errors: --- Start recognize text from image --- Traceback (most recent call last): File "C:/Users/crist/PycharmProjects/LectorTexto/lectorCapcha.py", line 40, in &lt;module&gt; print (get_string(src_path + "2.png")) File "C:/Users/crist/PycharmProjects/LectorTexto/lectorCapcha.py", line 31, in get_string result = pytesseract.image_to_string(Image.open(src_path + "thres.png")) File "C:\Users\crist\AppData\Local\Programs\Python\Python36\lib\site-packages\pytesseract\pytesseract.py", line 122, in image_to_string config=config) File "C:\Users\crist\AppData\Local\Programs\Python\Python36\lib\site-packages\pytesseract\pytesseract.py", line 46, in run_tesseract proc = subprocess.Popen(command, stderr=subprocess.PIPE) File "C:\Users\crist\AppDa…
has title: FileNotFoundError: [WinError 2] | Errors reading text from image with Python, OpenCV and OCR
tagged with: python
has comment: http://stackoverflow.com/comment/83671303
has comment: http://stackoverflow.com/comment/83669963
has comment: http://stackoverflow.com/comment/83655541
tagged with: opencv
score: 1
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/54799257
has comment: http://stackoverflow.com/comment/83670400
tagged with: ocr
favorite count: 0
type: Question

http://stackoverflow.com/a/48292260
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48286457
type: Answer
has comment: http://stackoverflow.com/comment/83579476
has body: Your configuration sounds correct. You should test the configuration to see whether you can access any public Internet sites, then test connecting to AWS. You could either write a Lambda function that attempts such connections or you could use lambdash that effectively gives you a remote shell running on Lambda. This way, you can easily test connectivity from the command line, such as curl.

http://stackoverflow.com/q/48282762
has comment: http://stackoverflow.com/comment/83579593
tagged with: jupyter-notebook
tagged with: nvidia
type: Question
has comment: http://stackoverflow.com/comment/83549408
type: UnansweredQuestion
tagged with: python
has body: I made a very interesting observation while trying to tune my recommendation engine on a Tesla K80 housed on Google Cloud Platform. Unfortunately I have been unsuccessful at finding any literature which might point me in the right direction. Here is my predicament ... I run the same code for fitting a fully connected model using a python script and a jupyter notebook. What is surprising is that with the same hyper-parameters (batch size etc.), the code runs faster using the jupyter notebook kernel and uses more memory on the GPU than when I fit the model using a python code invoked from the shell. Since, I want my code to run in the least possible time and jupyter often ends up closing the connection when unattended due to web socket time-out, is there any way I can increase the amount of memory a python process can use on the GPU ? Open to any alternating way of making this work. Thanks in advance.
score: 0
has title: Python process vs Jupyter notebook acces to GPU memory
answer count: 0
tagged with: deep-learning

http://stackoverflow.com/a/48254027
score: 0
has comment: http://stackoverflow.com/comment/83502100
type: Answer
has body: Most likely, all you want is this single task: - script: "/home/oded/Sandbox/ansible/pyScript/test.py " when: corename is defined It will pass the inventory names, members of the all group, as space-separated arguments to the script. Add quotes around, if you need. It's hard to comment on all the mistakes in the code you posted... Semantic error in the first method: var: "{{ ips }}" should be var: ips. Expectation of facts having a common value across all hosts (while a fact holds a different value on each distinct host). Misuse of register with debug in the second method. That’s what set_fact is for. Trying to pass a Python object as a command line argument. Using item outside of loops.
has comment: http://stackoverflow.com/comment/83540274
answers question: http://stackoverflow.com/q/48251026

http://stackoverflow.com/comment/126969208
type: AnswerComment
comment on: http://stackoverflow.com/a/59383258
score: 0
type: Comment
has text: please note currently, `restore_best_weights=False` by default!

http://stackoverflow.com/q/48272023
tagged with: firebase-storage
has comment: http://stackoverflow.com/comment/83528090
has comment: http://stackoverflow.com/comment/83528498
has comment: http://stackoverflow.com/comment/83528065
tagged with: firebase-realtime-database
has comment: http://stackoverflow.com/comment/83528162
downvote count: 0
has answer: http://stackoverflow.com/a/48272761
upvote count: 1
tagged with: python
has body: I am stuck with it for a long time now, must be something silly!!! I have this simple code that uses pyrebase to connect to Firebase: db = firebase.database() auth = firebase.auth() storage = firebase.storage() user = auth.sign_in_with_email_and_password('user','pwd') tok = user['idToken'] try: files = db.child("files").get(tok) l = [] for f in files.each(): l = f.val() print(l) storage.child(l).download(l,token=tok) # url = storage.child(l).get_url(tok) -----This line gets the proper URL except Exception as e: print(e) I am getting data correctly accessed from DB, but the download task does nothing. I have no idea what I am doing wrong here. Thanks in advance! EDIT 1: as per suggestion: Database structure: { "files" : { "-L2vvsSL3l95QZqMILRb" : "car_WIFI_6cf4d4f1-4bfe-488b-b671-d0f816cd5e65.txt", "-L2vvsSScNqiUZ-HYTM1" : "car_GPS_6cf4d4f1-4bfe-488b-b671-d0f816cd5e65.txt" } } And storage structure:
tagged with: firebase
has comment: http://stackoverflow.com/comment/83528295
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83528236
has title: Unable to download files from firebase through pyrebase
accepted answer: http://stackoverflow.com/a/48272761
has comment: http://stackoverflow.com/comment/83527961
has comment: http://stackoverflow.com/comment/83528913
score: 1
has comment: http://stackoverflow.com/comment/83529276
answer count: 1
has comment: http://stackoverflow.com/comment/83528096
favorite count: 0
type: Question

http://stackoverflow.com/a/48301668
type: Answer
answers question: http://stackoverflow.com/q/48301468
score: 0
has body: If you do want to be able to pass a nind when calling the function, but would like the default to be the length of indel when not specifying nind, you could do something like this: def func(indel, nind=None): nind = len(indel) if nind is None else nind when you do not specify nind when calling, then nind is None, which subsequently changed to len(indel) when yo DO specify nind when calling, then nind is the value of what you are calling with (exception is the "value" of None)

http://stackoverflow.com/comment/83429973
has text: @StefanPochmann, you're right. I had the precedence of `/`/`*` the wrong way round. Brackets added.
comment on: http://stackoverflow.com/a/48215779
type: Comment
score: 0
type: AnswerComment

color-theory
type: Tag
tag name: color-theory
tags question: http://stackoverflow.com/q/48218555

http://stackoverflow.com/q/48221070
downvote count: 0
tagged with: python
has body: I am trying to filter using a list of user_id's and a mask. Here is the input with two user_id's: data = np.array([['user_id','comment','label'], [100,'First comment',0], [101,'Buy viagra',1], [100,'Buy viagra two',1], [101,'Third comment',0], [100,'Third comment two',0], [101,'Buy drugs',1], [100,'Buy drugs two',1], [101,'Buy icecream',1], [100,'Buy icecream two',1], [101,'Buy something',1], [100,'Buy something two',1]]) The desired output is: 0 100 First comment 0 1 101 Buy viagra 1 2 100 Buy viagra two 1 3 101 Third comment 0 4 100 Third comment two 0 5 101 Buy drugs 1 6 100 Buy drugs two 1 7 101 Buy icecream 1 8 100 Buy icecream two 1 By passing a list of user_id's, I am getting an incorrect output. m = df.user_id.isin([100,101]) &amp; df.label.eq('1') i = df[m].head(3) j = df[~m] df = pd.concat([i, j]).sort_index() print (df) However, if I pass just one user_id as below, I get correct output. Can you please suggest me what's wrong? Thanks. m = df.user_id.eq('101') &amp; df.label.eq('1')
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48221147
accepted answer: http://stackoverflow.com/a/48221147
has title: Filter a Pandas dataframe using a list
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/comment/83478800
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48247729
type: Comment
has text: please include your `models.py`

http://stackoverflow.com/comment/83506496
type: Comment
comment on: http://stackoverflow.com/a/48261522
type: AnswerComment
has text: I was trying following:
score: 0

http://stackoverflow.com/comment/83558796
comment on: http://stackoverflow.com/q/48286606
score: 0
type: Comment
type: QuestionComment
has text: the fix that you posted and removed has resolved the error but files are not uploaded anymore

http://stackoverflow.com/comment/83350629
has text: Dupe list updated with: https://stackoverflow.com/questions/29975835/how-to-create-pandas-groupby-plot-with-subplots
score: 0
comment on: http://stackoverflow.com/q/48184930
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83505334
comment on: http://stackoverflow.com/q/48248771
score: 0
type: Comment
has text: Sorry for late answer, was busy, I don't have much experience working in Python but if I had similar problem in kotlin or java I would definitely make another class. Python has ability to add functionality to instances which you are using right now, I'm not sure if that is considered best practice, for me its a bit odd, but if your project is small keep it this way, its simple and understandable, if you have to add more functionalities then make class which wraps all needed data together.
type: QuestionComment

http://stackoverflow.com/q/48317367
has comment: http://stackoverflow.com/comment/83640800
has comment: http://stackoverflow.com/comment/83620384
score: 0
has title: How to reduce lag when using QStackedWidget in PyQt5
answer count: 0
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/83642226
has comment: http://stackoverflow.com/comment/83642775
has body: I'm attempting to make an application in PyQt5 that will display lots of images in a QStackedWidget, with a separate widget for each image. The images are being scraped from a website and saved to a temp directory on a separate QThread and then the image location is sent back to the main thread using a signal/slot. When the signal is received by the main thread, the image is added to a scroll area on the widget using setWidget(). I'm using a QListWidget for switching the currently displayed page. My application is working perfectly as expected but I am encountering an annoying lag when switching between items in the QStackedWidget, especially when there's a large number of items in the stack (around 2000 currently). Strangely, this lag seems to go away if I move back through items that have already been the currently displayed item. Is a QStackedWidget the best way for displaying a large number of widgets like this? Is there possibly something I can do to give priority to switching the currently displayed widget?
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83643167

http://stackoverflow.com/comment/83503298
type: Comment
has text: @TomBaker actually you can change `last_field` argument to whatever field you prefer!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48249538

http://stackoverflow.com/q/48225388
type: Question
has answer: http://stackoverflow.com/a/48225650
tagged with: netflix-eureka
tagged with: python
type: AnsweredQuestion
score: 0
has title: Register, Deregister, perform all operations on eureka discovery from python web-services
answer count: 1
accepted answer: http://stackoverflow.com/a/48225650
has body: I developed python web api to do some task which i need to register on spring eureka server for the discovery. Libraries are not available for it and available stuff of google is not helpful.

http://stackoverflow.com/comment/83624692
type: Comment
has text: thanks! does this answer entails that you will always use all aggregators on each of the columns? is that that really scalable? what if we have 100 columns and require a different aggregation on each?
comment on: http://stackoverflow.com/a/48317770
type: AnswerComment
score: 0

http://stackoverflow.com/a/48198436
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48197857
type: AcceptedAnswer
has body: Welcome to the wild world of Python's import system! To expand on freude's answer a little bit, you've ran into one of the most consistently confusing portions of the Python language: relative vs absolute imports. While the import examples that you gave are syntactically fine, they hide some of the complexity what's going on behind the scenes. When you run: from django.views.generic import TemplateView, ListView Python searches through the PYTHONPATH (which you can see with something like print(sys.path)) for a package or module named django. It end up finding one somewhere among your installed libraries. Similarly, when you run: from project.app.views import view It searches those same paths, but instead finds the project package in the directory that the Python interpreter is currently executing in. However, if you had installed a library named project, how would it know which one you actually meant? This is generally solved by using absolute imports and by being explicit if you intend to use relative imports like this. If you wanted to be more precise in your example, you would specify that you wanted to import it relative to the current module by using a . - like so: from .project.app.views import view You can even see this in action in an example in the django tutorial. See this classic answer on the subject for more detailed information.
type: Answer
accepted answer of: http://stackoverflow.com/q/48197857

http://stackoverflow.com/q/48204633
has answer: http://stackoverflow.com/a/48204763
possible better answer: http://stackoverflow.com/a/48204975
has comment: http://stackoverflow.com/comment/83390404
tagged with: python
has comment: http://stackoverflow.com/comment/83390276
tagged with: list-comprehension
upvote count: 11
score: 9
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48204763
answer count: 3
linked to: http://stackoverflow.com/q/21112814
downvote count: 2
has comment: http://stackoverflow.com/comment/83390318
has answer: http://stackoverflow.com/a/48204975
has body: list_a = [2, 4, 3, 6, 3, 8, 5] list comprehension is very useful. list_b = [a**2 for a in list_a] I want to know how to write a self-reference in the list comprehension. For example: list_c = [a**2 if i == 0 else a*2 + (itself[i-1]) for i, a in enumurate(list_a)] how to write the part of itself[i-1]?
has title: How to refer to itself in the list comprehension?
has comment: http://stackoverflow.com/comment/83390275
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48205010
duplicate of: http://stackoverflow.com/q/21112814
tagged with: self-reference
has comment: http://stackoverflow.com/comment/88580031

http://stackoverflow.com/q/48274947
favorite count: 0
type: Question
has body: Is there any way to reduce the size of .xls file which was generated through an automated shell or tcl so that I can send it over mail automatically. As of now I am manually converting .xls file into .xlsb which reduce its size from 25 mb to 5 mb and then sending report daily to required person. So is there any esay way to do this?
has comment: http://stackoverflow.com/comment/83533454
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48275286
tagged with: python
linked to: http://stackoverflow.com/q/6442698
has title: Convert file from xls to xlsb to reduce its size
tagged with: sql
score: 0
tagged with: java
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83533486
downvote count: 1

http://stackoverflow.com/comment/83463562
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48240355
has text: Thanks for responding ... but unfortunately I get the same error as before. ModuleNotFound

http://stackoverflow.com/comment/83432482
type: Comment
comment on: http://stackoverflow.com/a/48212323
type: AnswerComment
has text: Thank you for your help it is now working. Since I'm trying to plot 2 lists vs each other, one of my list is 20 characters long and the other is 50 characters long. What do you suggest to do since when you have two lists that aren't the same value will give you an error? (I'm trying to plot bad facts vs epochs to show convergence)
score: 0

http://stackoverflow.com/comment/83496940
type: QuestionComment
comment on: http://stackoverflow.com/q/48257072
score: 0
type: Comment
has text: https://www.tutorialspoint.com/python/file_readlines.htm , Check the example here for more understanding.

http://stackoverflow.com/comment/83465866
type: Comment
has text: @dkato He says X and Y are dense. Furthermore, i don't think there is symmetry-exploitation in scipy's sparse-matrices.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48241601

http://stackoverflow.com/q/48266026
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48266697
has answer: http://stackoverflow.com/a/48266697
tagged with: sockets
has title: Socket Java client - Python Server
tagged with: python
upvote count: 6
has body: I'm tring to implement a java - python client/server socket. The client is in java and the server is write in python Java Client import java.io.*; import java.net.*; import java.lang.*; public class client { public static void main(String[] args) { try{ Socket socket=new Socket("localhost",2004); DataOutputStream dout=new DataOutputStream(socket.getOutputStream()); DataInputStream din=new DataInputStream(socket.getInputStream()); dout.writeUTF("Hello"); dout.flush(); System.out.println("send first mess"); String str = din.readUTF();//in.readLine(); System.out.println("Message"+str); dout.close(); din.close(); socket.close(); } catch(Exception e){ e.printStackTrace();} } } Python server import socket soc = socket.socket() host = "localhost" port = 2004 soc.bind((host, port)) soc.listen(5) while True: conn, addr = soc.accept() print ("Got connection from",addr) msg = conn.recv(1024) print (msg) print(len(msg)) if "Hello"in msg: conn.send("bye".encode('UTF-8')) else: print("no message") The first message from client to server was delivery correctly but the second from server to client no. Using telnet I check that sever send the message but the client goes in deadlock and don't receive message. I don't understand why. Thanks
type: AnsweredQuestion
tagged with: client-server
tagged with: java
answer count: 1
downvote count: 0
score: 6

http://stackoverflow.com/comment/83590474
comment on: http://stackoverflow.com/q/48285058
has text: ˋdef issue_ago(date): today = datetime.today() if type(date) == str: date = datetime.strptime(date, '%Y-%m-%d %H:%M:%S.%f') #print date epoch = datetime(1970, 1, 1) diff = today - date date = diff.days /365.25 return date else: return dateˋ
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83396173
has text: I think it is a problem "X, Y" from a file, we could do the same with other questions and say it is another question, you have a problem reading data, check if it meets the requirements of the other question, that is, if the matrices have an adequate size.
score: 0
comment on: http://stackoverflow.com/q/48195213
type: Comment
type: QuestionComment

qtcharts
tags question: http://stackoverflow.com/q/48285256
type: Tag
tag name: qtcharts

http://stackoverflow.com/a/55956676
has comment: http://stackoverflow.com/comment/98565529
has body: I had a similar problem and create a classifier for JSON files following this documentation. When I executed the crawler, I added the classifier and like as magic all the JSON structure was in a relation model to be stored in a Redshift cluster database.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48232314

http://stackoverflow.com/a/48348862
accepted answer of: http://stackoverflow.com/q/48256569
type: Answer
has comment: http://stackoverflow.com/comment/83814596
answers question: http://stackoverflow.com/q/48256569
has comment: http://stackoverflow.com/comment/83818981
has comment: http://stackoverflow.com/comment/83811451
downvote count: 0
has comment: http://stackoverflow.com/comment/83811330
has comment: http://stackoverflow.com/comment/83813672
type: AcceptedAnswer
has body: Your flask server works fine for me, after I run python teletubbies.py to initialize the sqlite database. However, if I remove the tellytubbies.db file that was created by running the script directly, the flask server fails with the same exception you quote. Something to consider here is that when you run tellytubbies.py, the database file tellytubbies.db will be created in whatever directory you run it from. If you then run server.py from a different directory - for instance, if your IDE is running it - it won't find the other tellytubbies.db, so a new one will be created; but becase the tables were only created in your __main__ section in tellytubbies.py, the tables won't be created. So your flask server needs to do some of the initialization that teletubbies.py is doing. I replaced the if __name__ == '__main__': section of your server.py with the following and it it works. It will work whether you keep the same database file or remove it between runs to start from scratch. I've added a check to make sure the same rows don't get inserted repeatedly. if __name__ == '__main__': from teletubbies import add_tellytubbies, TellyTubby db_proxy.connect() db_proxy.create_tables([TellyTubby], safe=True) if TellyTubby.select().count() == 0: add_tellytubbies() app.run(debug=True, use_reloader=True)
has comment: http://stackoverflow.com/comment/83819059
has comment: http://stackoverflow.com/comment/83809994
upvote count: 3
score: 3

http://stackoverflow.com/comment/83602078
has text: Please show your efforts.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48308229
type: QuestionComment

http://stackoverflow.com/comment/105411425
type: AnswerComment
score: 0
has text: the `chat.postMessage` is working only when the input holds only 1 recipient (e.g. @FirstName.LastName) How can the slackbot send it to multiple users at once ?
type: Comment
comment on: http://stackoverflow.com/a/48212916

http://stackoverflow.com/comment/83590748
type: Comment
comment on: http://stackoverflow.com/q/48302932
score: 0
has text: Cześć. spójrz na link u góry mojego postu. jest cały kod uruchomiony. `dodane_pary` to lista, do której dobrymi wartościami dodaje się w kolejnych krokach.
type: QuestionComment

http://stackoverflow.com/q/48309590
downvote count: 0
upvote count: 1
duplicate of: http://stackoverflow.com/q/47152691
has title: create pivot table with multilevel index in pandas
favorite count: 0
type: Question
has body: Dataframe is setup like so. I want a pivot table with a multi-level index of account, pseudo. I want the columns to be the individual weeks, and the values to be sales. The data is pseudo x week x account so I shouldn't need to aggregate any data. How can I accomplish? pseudo week account sales 0 31527 2017-12-30 4430012511 2.79 1 145584 2017-12-16 4430012511 8.37 2 31608 2017-12-23 4430012511 19.53 3 6362 2017-12-16 4430012511 5.58
accepted answer: http://stackoverflow.com/a/48309834
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/48309834
tagged with: reshape
tagged with: python
type: AnsweredQuestion
tagged with: pivot
linked to: http://stackoverflow.com/q/47152691
tagged with: pivot-table
answer count: 1

iis
tags question: http://stackoverflow.com/q/48257830
tags question: http://stackoverflow.com/q/48278192
tag name: iis
type: Tag

http://stackoverflow.com/comment/83556507
type: QuestionComment
has text: You want `prev` to start out pointing at the same object as `head`. That doesn't happen when you create two separate `Node(0)` objects.
score: 0
comment on: http://stackoverflow.com/q/48284147
type: Comment

http://stackoverflow.com/comment/83482172
comment on: http://stackoverflow.com/a/48249769
type: AnswerComment
score: 1
type: Comment
has text: @internet_user It's convenient, yes. But it seems quite clear OP doesn't have a lot of experience. So it's worth stating how to manually check for duplicates.

http://stackoverflow.com/a/48556493
type: Answer
score: 0
has body: It sounds like your virtualenv pip version may be using pip3 instead of pip2: Make sure you are using the correct python version in your project that you mean to, and using the same version of pip in your virtualenv. (Note that you use pip above once, then you used pip3 outside your virtualenv.) Check your pip version from inside the virtualenv: workon (your env name) which pip pip -V Output should look something like: $ which pip /home/yourname/.virtualenvs/testenv/bin/pip $ pip -V pip 9.0.1 from /home/yourname/.virtualenvs/testenv/local/lib/python2.7/site-packages (python 2.7) It should tell you you're using pip inside your virtualenv, and the correct python version. If that looks correct, install your packages. pip install (whatever) Check they are installed with pip freeze. Run your project. :)
answers question: http://stackoverflow.com/q/48299528

http://stackoverflow.com/a/48300836
has comment: http://stackoverflow.com/comment/83624336
has comment: http://stackoverflow.com/comment/83625830
has comment: http://stackoverflow.com/comment/83624272
has body: well, Pandas has it's own beautiful DataFrame.to_sql() method, which takes care of NaN --> NULL conversion automatically: df.to_sql('tab_name', sql_alchemy_conn, if_exists='append', index=False) PS in case your DF has string (object) columns - use dtype parameter (see an example in this answer)
has comment: http://stackoverflow.com/comment/83623380
has comment: http://stackoverflow.com/comment/83625603
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/48299282
downvote count: 0

http://stackoverflow.com/comment/83453310
comment on: http://stackoverflow.com/q/48235048
type: Comment
type: QuestionComment
score: 0
has text: You don't have to close the file, flushing is enough. I.e. file.flush()

http://stackoverflow.com/comment/83581764
type: Comment
has text: Thanks for changing the code. This is what I'm getting now: `'{country: this is the country field with annotations , ''something'': ''something''}'`
type: AnswerComment
comment on: http://stackoverflow.com/a/48298354
score: 0

http://stackoverflow.com/q/48237024
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/48237236
tagged with: pandas
has body: I have a for-loop that computes DataFrames and outputs them to an excel sheet. Right now, I am able to export one full DF to one excel sheet. As shown below, I am trying to add code inside the for-loop so that it can do this computation for many DFs and export each DF to a separate excel worksheet within the same workbook, delineated by the sheet_name. list = ["AUD_JPY", "AUD_USD"] granularity = "D" bar_count = 5000 MA_list = [20, 50] writer = pd.ExcelWriter('BT.xlsx') resultsDF = pd.DataFrame(columns = ['instrument', 'Start date', 'End date'] for MA in MA_list: for instrument in list: ... data = {'instrument': [instrument], 'Start date': [startDate], 'End date': [endDate]} resultsDF = resultsDF.append(data, ignore_index=True) instrument=+1 resultsDF.to_excel(writer, sheet_name='Price_Over_SMA{0}_{1}'.format(MA, granularity)) writer.save() MA=+1 This only exports the first DF from the 'instrument' loop to the excel sheet. I get this worksheet: But I also want to export another worksheet next to that one that should be called 'Price_Over_SMA50_D' in this case. Not sure what I am doing wrong. Thanks
tagged with: dataframe
type: Question
tagged with: for-loop
has answer: http://stackoverflow.com/a/48237236
has title: How to write to separate excel worksheets within the same workbook in a for loop?
tagged with: python
tagged with: excel
has comment: http://stackoverflow.com/comment/83456742
linked to: http://stackoverflow.com/q/14225676
has answer: http://stackoverflow.com/a/48240080
possible better answer: http://stackoverflow.com/a/48240080
type: AnsweredQuestion

http://stackoverflow.com/q/48238227
type: AnsweredQuestion
tagged with: python
has body: I have a tensor , which is an intermediate result produced during a set of operation . It is a 2D matrix ( tensor ) , I want to reshape it into 3d but in a specific way . How could I do that . This is an example. The shape of K = [ 10 , 12 ]. I want to convert it into ( 3 x 10 x 4 ) matrix , Here my batch_size = 3 , sequence_length = 4 . In nutshell, the essence is splitting a 2D matrix along the column ( vertically ) at positions after ( 3 (before 4) , 7 ( before 8), because my sequence_length = 4 ), so that we finally have 3 matrix of size 10 X 4 each , which when packed together becomes 3D matrix ( 3 x 10 x 4). Any suggestions will be appreciated. K = array([[1, 9, 5, 9, 9, 2, 0, 9, 1, 9, 0, 6], [0, 4, 8, 4, 3, 3, 8, 8, 7, 0, 3, 8], [7, 7, 1, 8, 4, 7, 0, 4, 9, 0, 6, 4], [2, 4, 6, 3, 3, 7, 8, 5, 0, 8, 5, 4], [7, 4, 1, 3, 3, 9, 2, 5, 2, 3, 5, 7], [2, 7, 1, 6, 5, 0, 0, 3, 1, 9, 9, 6], [6, 7, 8, 8, 7, 0, 8, 6, 8, 9, 8, 3], [6, 1, 7, 4, 9, 2, 0, 8, 2, 7, 8, 4], [4, 1, 7, 6, 9, 4, 1, 5, 9, 7, 1, 3], [5, 7, 3, 6, 6, 7, 9, 1, 9, 6, 0, 3]]) #### I am expecting it to reshaped as follows K_new = [ 1, 9, 5, 9, 0, 4, 8, 4, 7, 7, 1, 8, 2, 4, 6, 3, 7, 4, 1, 3, 2, 7, 1, 6, 6, 7, 8, 8, 6, 1, 7, 4, 4, 1, 7, 6, 5, 7, 3, 6, 9, 2, 0, 9, 3, 3, 8, 8, 4, 7, 0, 4, 3, 7, 8, 5, 3, 9, 2, 5, 5, 0, 0, 3, 7, 0, 8, 6, 9, 2, 0, 8, 9, 4, 1, 5, 6, 7, 9, 1, 1, 9, 0, 6 7, 0, 3, 8 9, 0, 6, 4 0, 8, 5, 4 2, 3, 5, 7 1, 9, 9, 6 8, 9, 8, 3 2, 7, 8, 4 9, 7, 1, 3 9, 6, 0, 3 ]
type: Question
score: 0
has title: How to slice matrices from a 2D matrix along column (vertically) and create a 3D in tensorflow?
has answer: http://stackoverflow.com/a/48239159
accepted answer: http://stackoverflow.com/a/48239159
tagged with: deep-learning
tagged with: matrix
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/83463025
comment on: http://stackoverflow.com/q/48240351
type: QuestionComment
score: 0
has text: You are probably looking for something like ```train[train['age'] > -1]``` (but i didn't use much pandas recently). This has not much to do with seaborn and you really should grab some pandas basics! From a python-view: ```'age' > -1``` is evaluated before anything else happens; and a string does not compare to an int; therefore the error! The above, which maybe is valid, would grab the column and use it's values for comparison to -1, which might be ok, given the column type is a valid type.
type: Comment

http://stackoverflow.com/a/48173633
accepted answer of: http://stackoverflow.com/q/48173470
has comment: http://stackoverflow.com/comment/83329405
has comment: http://stackoverflow.com/comment/83326892
downvote count: 0
answers question: http://stackoverflow.com/q/48173470
has comment: http://stackoverflow.com/comment/83326945
type: AcceptedAnswer
score: 4
type: Answer
upvote count: 4
has body: AKA, dot product. i = df'A'.values j = df'B'.values.T i.dot(j) array([[ 0.25, 1.25, 0.75, 0.25], [ nan, nan, nan, nan], [ nan, nan, nan, nan], [ 0.2 , 1. , 0.6 , 0.2 ]]) If you want the result as a DataFrame, do this - df'A'.dot(df'B'.values.T) Or, df'A'.dot(df['B'].values[None, :]) # thanks to Zero for the alt 0 1 2 3 0 0.25 1.25 0.75 0.25 1 NaN NaN NaN NaN 2 NaN NaN NaN NaN 3 0.20 1.00 0.60 0.20 You can then call mean or nanmean on the result - df'A'.dot(df'B'.values.T).mean(0) 0 0.225 1 1.125 2 0.675 3 0.225 dtype: float64

http://stackoverflow.com/q/48198834
has comment: http://stackoverflow.com/comment/83379185
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83379160
favorite count: 0
tagged with: hive
has title: ProgrammingErrorL(The SQL contains 0 parameter markers, but 1 parameter were supplied, 'HY000')
linked to: http://stackoverflow.com/q/49908818
tagged with: python
has comment: http://stackoverflow.com/comment/83378937
tagged with: odbc
type: Question
has answer: http://stackoverflow.com/a/53125353
has answer: http://stackoverflow.com/a/48216371
score: 0
answer count: 2
has body: I'm passing data to database for querying the database but I have run into following error. &gt;&gt;&gt; my_cursor.execute(my_query, var1) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000') my codes are import pyodbc import pandas as pd var1 = 'UCSB' my_connection = pyodbc.connect('DSN=MapR-64-Hive', autocommit=True) my_cursor = my_connection.cursor() my_query = """ select * from polaris_datasets.snmaster where parent_pid rlike '%s' and created_date &gt;= "2017-12-01 00:00:00" """ my_cursor.execute(my_query, var1) Does anyone know what would cause this issue?

http://stackoverflow.com/a/48184302
has body: What's your custom job user model? Maybe you inherit AbstractUser or AbstractBaseUser. But when you need to use groups, ou have to inherit PermissionsMixin from django.contrib.auth.models import PermissionMixin you can check in django github code here here's part of the code class PermissionsMixin(models.Model): """ Add the fields and methods necessary to support the Group and Permission models using the ModelBackend. """ is_superuser = models.BooleanField( _('superuser status'), default=False, help_text=_( 'Designates that this user has all permissions without ' 'explicitly assigning them.' ), ) groups = models.ManyToManyField( Group, verbose_name=_('groups'), blank=True, help_text=_( 'The groups this user belongs to. A user will get all permissions ' 'granted to each of their groups.' ), related_name="user_set", related_query_name="user", ) Hope solving well! Adding This is my part of user model. You should inherit both BaseUser and PermissionsMixin. Then you can use groups from PermissionsMixin. class JobUser(AbstractBaseUser, PermissionsMixin, TimeStampedModel): email = models.EmailField( verbose_name="Email", max_length=255, unique=True, db_index=True, ) user_type = models.PositiveIntegerField( verbose_name="User type", # 0 - staff # 1 - employer # 2 - employee choices=CHOICES.USER_CHOICES, default=2, ) ... So your User model will be like... class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) email = models.EmailField(max_length=255, unique=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) # active = models.BooleanField(default=True) #can login staff = models.BooleanField(default=False) #staff not superuser admin = models.BooleanField(default=False) #superuser ... Also don't forget import PermissionMixin in top of your code. Hope solving well!
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83378991
has comment: http://stackoverflow.com/comment/83379032
upvote count: 5
answers question: http://stackoverflow.com/q/48178942
type: Answer
has comment: http://stackoverflow.com/comment/83352155
accepted answer of: http://stackoverflow.com/q/48178942

http://stackoverflow.com/a/48672736
has body: Just use price = client.get_spot_price(currency_pair = 'LTC-EUR') instead of LTC-EUR you can use any pair that exists on Coinbase.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48178269

fluentd
tag name: fluentd
type: Tag
tags question: http://stackoverflow.com/q/48304577

http://stackoverflow.com/comment/83538570
has text: @YuryChu Thank you so much for your help, I have solved the problem!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48275038

http://stackoverflow.com/q/48232451
answer count: 1
downvote count: 3
has body: I've realized that in some circumstances (version of python and type) the id built-in function is yielding a 15 digit number, rather than the mostly seen 10 digits. I was wondering if it might be long as the Documentation mentions that, but that's not the case id: Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. Here is what I've tried: Python 2.7.5 - GCC 4.8.3 Linux 2 &gt;&gt;&gt; print(id(3)) 18705464 &gt;&gt;&gt; print(id('2')) 139621043310840 Python Python 2.7.14 - GCC 4.2.1 Compatible Apple LLVM 9.0.0 &gt;&gt;&gt; print(id('1')) 4318307312 &gt;&gt;&gt; print(id(1)) 140699106326584 As you can see, in two different minor versions on two operating systems I have a slightly different behaviour. In one case a str object yields 15 digits in the other case an int. In Python 3 I couldn't reproduce it, they are all 10 digits.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83447213
has comment: http://stackoverflow.com/comment/83447265
upvote count: 2
has comment: http://stackoverflow.com/comment/83447423
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48232502
has comment: http://stackoverflow.com/comment/83447330
has title: When does id() yield 10 or 15 digits?

http://stackoverflow.com/a/48246709
has body: There is another nice answer posted while I was typing this out -- this is a simple implementation without imports. full_list = [] for x in range(0, len(new)): if 'NN' in new[x] and ('IN' in new[x-1] or 'TO' in new[x-1]): temp_list = [new[x]] temp_index = x+1 while 'NN' in new[temp_index]: temp_list.append(new[temp_index]) temp_index += 1 full_list.append(temp_list)
answers question: http://stackoverflow.com/q/48246653
type: Answer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/83841387
type: Comment
type: QuestionComment
has text: I'm seeing the exact issue; in Python, when executing the command that is listed in the Google documentation, the pipeline executes right away and there is nothing in my templates folder in GCS. Upvoted to hopefully get some traction.
comment on: http://stackoverflow.com/q/48308693
score: 1

http://stackoverflow.com/comment/83512615
has text: Thanks, but cannot read the file in total as the file has varying numbers of fields.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48264598

http://stackoverflow.com/a/48222045
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48222013
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48222013
has body: Use apply with join and then Series.to_dict: d = df.apply(','.join).to_dict() print (d) {'ColA': 'AD,BD,CD,DD', 'ColB': 'AC,BC,CC,CD'} Detail: print (df.apply(','.join)) ColA AD,BD,CD,DD ColB AC,BC,CC,CD dtype: object But if want lists use DataFrame.to_dict: print (df.to_dict(orient='list')) {'ColA': ['AD', 'BD', 'CD', 'DD'], 'ColB': ['AC', 'BC', 'CC', 'CD']}
type: Answer
score: 1

http://stackoverflow.com/q/48219591
has body: I want to draw italic text with PIL/ImageDraw. Someone says use italic fonts, but my font is just only one ttf file. No italic font file. fontName = 'malgun.ttf' # One of Korean fonts. fontSize = 25 imgMode = 'RGBA' fillColor = (0, 0, 0) bgColor = (255, 255, 255) font = ImageFont.truetype(os.path.join(os.environ['WINDIR'], 'fonts', fontName), fontSize) img = Image.new(imgMode, font.getsize(c), bgColor) draw = ImageDraw.Draw(img) draw.text((0, 0), c, fill=fillColor, font=font) According to PIL documents, there are some additional options using libraqm, but that not support MS Windows. Anyone help me?
favorite count: 0
type: Question
tagged with: python-imaging-library
type: UnansweredQuestion
tagged with: windows
tagged with: python
tagged with: italic
upvote count: 3
score: 3
has title: How to draw italic text with PIL/ImageDraw?
answer count: 0
downvote count: 0

http://stackoverflow.com/a/48348717
has body: The replace message that you are using is called on the string that you want to replace and not on the str type itself. In your case that is the word parameter that you are providing. So if you replace the instances of str.replace with word.replace your code will run. However, it doesn't create an anagram yet. The algorithm is still lacking.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48325862

http://stackoverflow.com/comment/83566119
comment on: http://stackoverflow.com/q/48285971
type: QuestionComment
type: Comment
score: 0
has text: Try using an HTTP client like Postman or Insomnia and see if you can recreate the login request first before you get into python. When doing this kind of stuff it helps to start small and incrementally add in the layers so you know where the problems originate at.

http://stackoverflow.com/comment/83607396
score: 0
type: Comment
type: QuestionComment
has text: How do you actually *merge* something here?
comment on: http://stackoverflow.com/q/48310814

http://stackoverflow.com/comment/83546098
comment on: http://stackoverflow.com/q/48221046
score: 0
type: Comment
type: QuestionComment
has text: @user8150031 I actually found that quite frustrating with OSRM. In graphhopper, for example, it was easy to set a radius flag for bad lat/long data so that it didn't snap to a coastal road after a certain distance. OSRM seems more fault tolerant when I had hoped it would throw an error (I imagine there is a flag somewhere to set, but I had no success doing it). Eventually it does give up looking for a road though, and these locations were way out to sea

http://stackoverflow.com/q/48178002
has comment: http://stackoverflow.com/comment/83336846
accepted answer: http://stackoverflow.com/a/48192585
type: Question
has answer: http://stackoverflow.com/a/48192585
type: AnsweredQuestion
score: 0
tagged with: network-programming
answer count: 3
has answer: http://stackoverflow.com/a/48178028
has comment: http://stackoverflow.com/comment/83336615
has title: code change - using python2 changing to python3
tagged with: python
has comment: http://stackoverflow.com/comment/83336201
has body: This is a piece of Sample code from O'Reily Twisted Network programming essentials book. the line "h = HeadlineRetriever() is causing issues. The error log says 'HeadlineRetriever' is not defined. Is this due to changes in py3? How would I fix the issue? Tried: unindenting the line h = HeadlineRetrieveer() but then the line d.addCallbacks(printData, printError) Did not recognize parameters. from twisted.internet import reactor, defer class HeadlineRetriever(object): def processHeadline(self, headline): if len(headline) > 50: self.d.errback( b"The headline ''%s'' is too long!" % (headline,)) else: self.d.callback(headline) def _toHTML(self, result): return " %s " % (result,) def getHeadline(self, input): self.d = defer.Deferred() reactor.callLater(1, self.processHeadline, input) self.d.addCallback(self._toHTML) return self.d def printData(result): print(result) reactor.stop() def printError(failure): print(failure) reactor.stop() h = HeadlineRetriever() d = h.getHeadline("Breaking News: Twisted Takes Us to the Moon!") d.addCallbacks(printData, printError) reactor.run() Error log: Traceback (most recent call last): File "C:/Users/jessica/Twisted/3.4asynchronousHeadlineRetriever.py", line 3, in <module> class HeadlineRetriever(object): File "C:/Users/jessica/Twisted/3.4asynchronousHeadlineRetriever.py", line 28, in HeadlineRetriever h = HeadlineRetriever() NameError: name 'HeadlineRetriever' is not defined
has comment: http://stackoverflow.com/comment/83336738
has answer: http://stackoverflow.com/a/48178341
has comment: http://stackoverflow.com/comment/83336982
possible better answer: http://stackoverflow.com/a/48178028
has comment: http://stackoverflow.com/comment/83336586
tagged with: twisted
has comment: http://stackoverflow.com/comment/83336587
has comment: http://stackoverflow.com/comment/83336290
has comment: http://stackoverflow.com/comment/83336572

http://stackoverflow.com/comment/90896466
type: Comment
has text: Thanks for looking into that. The accuracy of a measured interval t2 - t1 will depend on the stability of the clock and the clock's precision or resolution (the smallest time increment), but not on whether time1 and time2 "true" clock times wrt an authoritative clock. Of course, Python could run on a wide variety of systems, and time.time() depends on the system dependent C program of that name, so it could just be an open-ended caveat.
type: AnswerComment
comment on: http://stackoverflow.com/a/48196198
score: 0

http://stackoverflow.com/comment/83378130
type: QuestionComment
has text: Are you able to post the full contents of your server.start() file? This looks a lot like a server being destroyed prematurely.
comment on: http://stackoverflow.com/q/48174240
score: 1
type: Comment

http://stackoverflow.com/q/48252357
has title: default parameters and inheritance in python
has comment: http://stackoverflow.com/comment/83487203
has body: Parameter x1 is given a default value in ParentClass and is inherited in SubClass. Is this the cleanest way to initialize x1 in SubClass? Specifically, I have assigned value inaccessible value and sub value to x1 in SubClass, and only sub value is accessible. Wondering if I missed a more canonical way to do this. class ParentClass(object): def __init__(self, x1='parent value'): self.x1 = x1 class SubClass(ParentClass): def __init__(self, x1='inaccessible value', x2='sub value'): super().__init__(x1='sub value') self.x2 = x2
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83487160
tagged with: python
tagged with: inheritance
score: 0
answer count: 0

http://stackoverflow.com/q/48311776
has comment: http://stackoverflow.com/comment/83626734
has body: I'm working through a tutorial and the code is: import numpy as np from scipy import misc from skimage import data photo_data = misc.imread('foo.jpg') This didn't work and stack overflow searches suggested I needed to install scikit-image. I installed it, but that still didn't work. More searching said I also need to install Pillow. Installed Pillow and that still didn't work. More searching suggested I needed to write the code as: import scipy.misc from scipy.misc.pilutil import imread No error from that (!) but then the code I to read in the photo doesn't work: photo_data=misc.imread('foo.jpg') error: module.scipy.misc has no attribute imread if I try: photo_data = misc.pilutil.imread('foo.jpg') error is very ugly and talks about imread being deprecated and the errors are a LOT more complicated. Is there is simple way to read this photo in? Thanks.
tagged with: python
has title: scipy.misc.pilutil import imread works but still can't read in data
score: 0
has comment: http://stackoverflow.com/comment/83610561
answer count: 0
tagged with: scikit-image
type: Question
tagged with: imread
type: UnansweredQuestion

selenium-webdriver
tags question: http://stackoverflow.com/q/48216563
tags question: http://stackoverflow.com/q/48236271
tags question: http://stackoverflow.com/q/48192999
tags question: http://stackoverflow.com/q/48246345
tags question: http://stackoverflow.com/q/48209959
tags question: http://stackoverflow.com/q/48322719
tags question: http://stackoverflow.com/q/48267633
tags question: http://stackoverflow.com/q/48236886
type: Tag
tags question: http://stackoverflow.com/q/48224350
tags question: http://stackoverflow.com/q/48233504
tags question: http://stackoverflow.com/q/48257080
tags question: http://stackoverflow.com/q/48259782
tags question: http://stackoverflow.com/q/48273491
tags question: http://stackoverflow.com/q/48230370
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/48270721
tags question: http://stackoverflow.com/q/48319723
tags question: http://stackoverflow.com/q/48293590

http://stackoverflow.com/comment/83554503
has text: The process of dividing the line segment into pieces still applies, the question is when to count the length of a piece toward the intersection. I trust `encloses` to do the right thing there, whatever the right thing is.
comment on: http://stackoverflow.com/a/48272108
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48249893
upvote count: 2
type: UnansweredQuestion
has title: Running celery with supervisord unable to discover tasks
tagged with: django
tagged with: python
has body: I am using celery 4.1.0 with Django-1.11 and supervisor 3.3.1. For some reason celery is unable to discover the tasks in apps (which are listed in INSTALLED_APPS) when I run celery worker via supervisor. When I run celery from command line it does show the tasks. For example, when I run celery from command line here is the output: Running from command line: /home/ubuntu/Env/oba/bin/celery worker -A oba -l DEBUG - ** ---------- .&gt; transport: amqp://***:**@localhost:***// - ** ---------- .&gt; results: disabled:// - *** --- * --- .&gt; concurrency: 1 (prefork) -- ******* ---- .&gt; task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .&gt; celery exchange=celery(direct) key=celery [tasks] . celery.accumulate . celery.backend_cleanup . celery.chain . celery.chord . celery.chord_unlock . celery.chunks . celery.group . celery.map . celery.starmap . contact.tasks.send_email_to_admin_for_member . contact.tasks.send_email_to_admin_for_visitor But when run via supervisord, the output from celery is: - ** ---------- .&gt; transport: amqp://***:**@localhost:***// - ** ---------- .&gt; results: disabled:// - *** --- * --- .&gt; concurrency: 1 (prefork) -- ******* ---- .&gt; task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .&gt; celery exchange=celery(direct) key=celery [tasks] . celery.accumulate . celery.backend_cleanup . celery.chain . celery.chord . celery.chord_unlock . celery.chunks . celery.group . celery.map . celery.starmap The configuration for supervisord looks something like this: [program:celery] command=/home/ubuntu/Env/oba/bin/celery -A oba worker -l DEBUG environment=PATH="/home/ubuntu/Env/oba/bin" directory=/home/ubuntu/oba autostart=true autorestart=true startretries=3 stdout_logfile=/var/log/celery/%(program_name)s.log stdout_logfile_maxbytes=50MB stderr_logfile=/var/log/celery/%(program_name)s.log stderr_logfile_maxbytes=50MB user=celery numprocs=1 process_n…
score: 2
answer count: 2
has answer: http://stackoverflow.com/a/48250515
has comment: http://stackoverflow.com/comment/83862054
downvote count: 0
tagged with: supervisord
has comment: http://stackoverflow.com/comment/83915654
has answer: http://stackoverflow.com/a/56728816
tagged with: celery
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83858726

http://stackoverflow.com/a/48269254
has body: I found a solution, cast the label to int64 befor use it in tf.equal(). ... image, label = ... logits = model(image) cor_pre = tf.equal(tf.argmax(logits, 1), tf.cast(label, tf.int64)) ...
score: 0
has comment: http://stackoverflow.com/comment/83523319
type: Answer
answers question: http://stackoverflow.com/q/48268918

http://stackoverflow.com/comment/83552001
type: Comment
comment on: http://stackoverflow.com/q/48283960
type: QuestionComment
score: 0
has text: I suggest removing the C and C++ tags since this is a Python question.

http://stackoverflow.com/q/48291272
tagged with: fedora-27
downvote count: 1
upvote count: 4
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48726460
answer count: 2
tagged with: dnf
has body: I had to install pytorch with conda, and next I had this error when trying to upgrade system : sudo dnf upgrade Traceback (most recent call last): File "/bin/dnf", line 57, in &lt;module&gt; from dnf.cli import main File "/usr/lib/python3.6/site-packages/dnf/__init__.py", line 31, in &lt;module&gt; import dnf.base File "/usr/lib/python3.6/site-packages/dnf/base.py", line 26, in &lt;module&gt; from dnf.comps import CompsQuery File "/usr/lib/python3.6/site-packages/dnf/comps.py", line 29, in &lt;module&gt; import dnf.util File "/usr/lib/python3.6/site-packages/dnf/util.py", line 32, in &lt;module&gt; import librepo ModuleNotFoundError: No module named 'librepo' I saw some answer that uses yum-deprecated for re install python, but it seems I don't have it on my machine. I don't want to reinstall linux another time, and I'm searching for kind an answer for that problem. When installing pytorch via conda, it also installed cuda. Maybe it can be a problem ? Before this, I remember (not sure, but kind of) I was running with python2.7 by default, and now it is python 3.6..
tagged with: python
has answer: http://stackoverflow.com/a/51515458
possible better answer: http://stackoverflow.com/a/51515458
tagged with: conda
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48726460
has title: no module librepo after installing pytorch on fedora27

http://stackoverflow.com/q/48294028
type: UnansweredQuestion
has title: how to execute erlang command using python
tagged with: python
tagged with: erlang
has comment: http://stackoverflow.com/comment/83573469
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48295131
has body: I want to execute some erlang commands, the shell can be launched by some command : /opt/myserver/bin/myserver remote_console Above command will launch a shell where I can execute erlang commands. I want to do the same thing from my python script. I tried to do this using subprocess, but that does not seem to have worked. import shlex from subprocess import Popen, PIPE cmd = '/opt/myserver/bin/myserver remote_console' proc = Popen(shlex.split(cmd), stdin=PIPE, stdout=PIPE, stderr=STDOUT) er_cmd = web_api_handler:process_rfid(30001,&lt;&lt;“RC“&gt;&gt;,arg). out = proc.communicate(input=er_cmd) Above method executes the erlang command but it fails with some reason. However I'm able to execute the same command when shell is launched without using python subprocess. I tried using proc.stdin.write() and then use proc.communicate() as well, that did not work as well.
tagged with: shell
type: Question
tagged with: linux
has answer: http://stackoverflow.com/a/48312845

http://stackoverflow.com/comment/83518386
type: Comment
has text: This is impressive though I find it really difficult to read! I also get different results when I start with a list in a different order, e.g., `s = ['Leonardo Da Vinci', 'Al Pacino', 'Madonna', 'Scarlett Johansson', 'Matt Damon', 'Robert Downey Jr']`.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48250903

http://stackoverflow.com/q/48264698
has comment: http://stackoverflow.com/comment/83514601
possible better answer: http://stackoverflow.com/a/48264739
has comment: http://stackoverflow.com/comment/83512185
has body: Is there a way to use named arguments in C function? Something like function with prototype void foo(int a, int b, int c); and I want to call it with foo(a=2, c=3, b=1); [replaced the order of b &amp; c and used their names to distinguish] Motivation: I want a more Pythonic C, where I can easily manipulate my function arguments without mixing them by mistake
answer count: 3
has comment: http://stackoverflow.com/comment/83514597
has comment: http://stackoverflow.com/comment/83520899
accepted answer: http://stackoverflow.com/a/48264760
has answer: http://stackoverflow.com/a/48264739
has answer: http://stackoverflow.com/a/48264760
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/83512236
favorite count: 0
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/72588347
has comment: http://stackoverflow.com/comment/83512124
has comment: http://stackoverflow.com/comment/83514484
has title: A way to emulate named arguments in C
downvote count: 0
has comment: http://stackoverflow.com/comment/83512150
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/83514379
type: AnsweredQuestion

http://stackoverflow.com/comment/83544687
comment on: http://stackoverflow.com/a/48280014
has text: Alright man. This makes perfect sense.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48191310
score: 0
has title: How I can stop a script using another script
has body: I'm looking to control a script via Zigbee/XBee using X-CTU. I've created a script called zb_control.py. Now I'm trying to start and stop another script within this script. A script adxl345test.py is used to collect data from an attached accelerometer on my Raspberry Pi. The idea behind the zb_control.py script is that I run it and then if I type "run" in X-CTU the script will start running adxl345test.py and collect data. I've figured out how to start a script within a script however I can't get it to work when I try to stop the adxl345test.py again. As you can tell I've tried different things: import serial, time, sys, os, subprocess from subprocess import check_call from subprocess import call while True: ser=serial.Serial('/dev/ttyUSB0',9600,timeout=2) inc=ser.readline().strip() if inc=='run': print("---------------") print("Collecting data”) print("---------------") call(["python", "adxl345test.py"]) elif inc=='stop': # check_call(["pkill", "-9", "-f", adxl345test.py]) # serial.write('\x03') # os.system("pkill –f adxl345test.py") # call(["killall", "adxl345test.py"]) print("-----------------------") print("Script has been stopped") print("-----------------------") Any suggestions on how I could stop the adxl345test.py script from running and then still have the zb_control.py running ready to recieve new input from X-CTU?
linked to: http://stackoverflow.com/q/4789837
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83363023
has comment: http://stackoverflow.com/comment/83368965
type: Question

http://stackoverflow.com/q/48264080
tagged with: python
tagged with: tcpclient
tagged with: vb.net
has body: I have .NET client/server applications that communicate with a line protocol using TcpClient and an SSLStream. Basically they exchange some information and then enter a heartbeat loop where the client periodically sends a message to the server and receives an answer. This works well and can do so for days, but sometimes the connection breaks with a Socket error code of either 10054 or 10060, saying the host is unresponsive. For testing I got rid of most code and tried it with the very minimal components. On the server I use a TcpListener and run this code for new clients in a new task (please note that I have stripped logging code from the example): Private Sub HandleClient(c As TcpClient) c.NoDelay = True 'I tried with and without this algorithm Dim stream = c.GetStream Dim buffer(1024) As Byte c.ReceiveTimeout = 60000 Do Dim value As Integer = 0 Try value = stream.Read(buffer, 0, buffer.Length) Catch ex As Exception End Try For i = 0 To value - 1 buffer(i) = 0 'Just to get rid of residuals for error checking Next stream.Write({1, 45, 26}, 0, 3) Loop End Sub Most is just logging, the values I send are just some random numbers. So here I read the values from a NetworkStream and write some numbers back. Note: In the real application I use WriteLine and ReadLine. The client code is equally short, it is also started in a new task: Private Sub Connect() 'Get the ip to connect to from the command line, or use localhost Dim ip = If(My.Application.CommandLineArgs.Count &gt; 0, My.Application.CommandLineArgs(0), "127.0.0.1") log("Trying to parse " &amp; ip) Dim parsed As IPAddress = Nothing If IPAddress.TryParse(ip, parsed) = False Then parsed = IPAddress.Parse("127.0.0.1") Dim c As New TcpClient() c.NoDelay = True c.Connect(parsed, 16543) Dim stream = c.GetStream Dim buffer(1024) As Byte Do stream.Write({33, 75, 123, 3}, 0, 4) Dim value As Integer Try value = stream.Read(buffer, 0, buffer.Length) Catch ex As Exception End Try For i = 0 To value - 1 buffer(i) = 0 'Just to g…
score: 0
answer count: 0
has title: .NET TcpClient disconnects while Python stays connected
has comment: http://stackoverflow.com/comment/83536922
type: Question
has comment: http://stackoverflow.com/comment/83515167
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83514292

http://stackoverflow.com/q/48326979
tagged with: indexing
accepted answer: http://stackoverflow.com/a/48327501
type: AnsweredQuestion
has body: I am using python 2.7 I have an array of indices created by ids=np.indices((20,20)) ids[0] is filled with all the vertical coordinates and ids1 is filled with all the horizontal coordinates ids has a shape of (2,20,20) I have a boolean mask of shape (20,20) I need to have a list of ids that correspond to the ones marked as true in the mask. I am trying to do this by mid=ids[:,mask].T which gives me a list of this sort [2,17] [4,6] [1,19] [18,4] and so on. They are saved in an array called mid Then, I need all those coordinates in mid to find the values in another array. Meaning I need anotherarray([2,17]) I have not managed to take the list of mid to use them in a fancy indexing way, can someone help me? I have anotherarray[mid[0],mid[1]] and it doesnt work. I also have anotherarray[tuple(mid)] and it doesn't work Edit (read only if you care about context): I wanted to add context to show why I think I need the extra indices. Maybe I don't, that is what I want to fin out to make this efficient. This is a registration problem, a ver simple one. I have two images. A reference and a floating as seen below. Reference to the left, and floating to the right. The reference image and the floating image are in different coordinate spaces. I have points marked as you can see in the images. I find an affine transformation between each other. The region delimited by the line is my region of interest. I send the coordinates of that region in the floating space to the reference space. There in the reference space, I find what pixels are found inside the region and they become the mask array, containing the information of both in and outer pixels. But I only care about those inside, so I want only the indices of those pixels inside the mask in the reference space and save them using mid=ids[:,mask] . Once I have those points, I transform them back to the floating space, and in those new indices I need to look for the intensity. Those intensities are the ones who will be written ba…
score: 0
has answer: http://stackoverflow.com/a/48327501
tagged with: python
tagged with: image-registration
tagged with: numpy
answer count: 1
has comment: http://stackoverflow.com/comment/83639293
has title: Indexing numpy indices like array with list of 2D points
type: Question

http://stackoverflow.com/comment/83547919
type: QuestionComment
comment on: http://stackoverflow.com/q/48281837
score: 0
has text: This isn't an MCVE, for example, `Array` is not defined, and your example list is not a valid literal, containing many undefined names like `Document` and `Place`... but anyway, you should be *parsing* your csv, not just dumping each line into a list of lines. Then you could simply append your extra value trivially...
type: Comment

http://stackoverflow.com/comment/83462048
type: QuestionComment
has text: did you see something like this in any other program ?
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48239889

http://stackoverflow.com/comment/83555504
has text: calling just a variable, or a function like `type(x)` prints only the most recent command unless it is assigned to something
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48285034

http://stackoverflow.com/comment/84105254
type: AnswerComment
has text: Could you please tell me how to add this .env file? Thank you.
type: Comment
comment on: http://stackoverflow.com/a/48518528
score: 0

http://stackoverflow.com/comment/83596312
type: Comment
comment on: http://stackoverflow.com/q/48305527
type: QuestionComment
has text: try to set your datecolumn as the index before defining the lag etc.. `y = y.set_index('lastSaleDate')`
score: 3

http://stackoverflow.com/comment/83385427
type: Comment
has text: @Tai Well, in that case, I might be mistaken as to how object columns are treated. I'm pretty sure your example is in alignment with this line of thinking, but my conclusion may need a little adjustment.
type: AnswerComment
comment on: http://stackoverflow.com/a/48201760
score: 0

http://stackoverflow.com/q/48209410
has comment: http://stackoverflow.com/comment/83399770
has body: I'm trying to execute a sh file from script python. My script python os.system('sh run.sh') My sh file echo 'The house is blue' | /opt/palavras/por.pl &gt; output.txt Error: sh: 0: Cant' open run.sh How can I fix it?
tagged with: python
linked to: http://stackoverflow.com/q/18357655
accepted answer: http://stackoverflow.com/a/48209488
possible better answer: http://stackoverflow.com/a/48209470
has answer: http://stackoverflow.com/a/48209488
has answer: http://stackoverflow.com/a/48209470
type: AnsweredQuestion
answer count: 2
score: 2
downvote count: 0
tagged with: shell
favorite count: 0
type: Question
has title: Can't open sh file
upvote count: 2

http://stackoverflow.com/a/48213229
upvote count: 1
has comment: http://stackoverflow.com/comment/83408066
has body: Must solve the problem: def generate(): list_path = filedialog.askopenfilename(title = "Open list from",filetypes = (("WSP list files","*.list"),("All files","*.*"))) print('List opened for generation: ' + list_path) with open(list_path, 'r') as fd: lines = fd.readlines() print(lines) print(lines[0]) if generation1[0] == '#DOCTYPE_LIST!2.0\n': print('valid doc') else: print('unvalid doc')
type: Answer
answers question: http://stackoverflow.com/q/48213126
score: 1
downvote count: 0

http://stackoverflow.com/q/48235613
has title: If in working unexpectedly python 2.7.14
has comment: http://stackoverflow.com/comment/83453989
upvote count: 1
has body: I made this code the other day. It works fine except for the menu selection. Whenever I test it no matter what option I do for the menu it does reset password! So, if I inserted 'Ill do a newgame!' it would respond with 'INSERT PASSWORD: ', beginning the reset password sequence. I have all my code below: import pickle import time # Beginning of program. print ("Welcome to The Maze!") time.sleep(2) print ("Please enter your password to continue, or create a new one.") has_pass = "false" pass_correct = "false" pass_input = "null" password = "null" with open('save_pass.dat', 'r') as sp: password, has_pass = pickle.load(sp) if has_pass=="true": while pass_correct=="false": pass_input = raw_input("INSERT PASSWORD: ") if pass_input==password: pass_correct = "true" print ("Password Correct") elif has_pass=="false": password = raw_input("CREATE A NEW PASSWORD: ") has_pass = "true" with open('save_pass.dat', 'w') as sp: pickle.dump([password, has_pass], sp, protocol=2) # Defining loadGame() def loadGame(): pass # Defining newGame() def newGame(): print("Are you sure? You will overwrite any existing data.") reset = raw_input() if "no" or "No" in reset: menu() if "yes" or "Yes" in reset: level = 0 points = 0 with open('level_save.dat', 'w') as ls: pickle.dump([level, points], ls, protocol=2) loadGame() # Defining menu() def menu(): print 10 * "~" , "Menu" , 10 * "~" print("1. New game\n2. Load previous game\n3. Reset password\n4. Exit") print("~" * 26) time.sleep(6) menu_select = raw_input("Please choose an option: ") It works well up to here... if "3" or "reset" or "Reset" in menu_select: with open('save_pass.dat', 'r') as sp: password, has_pass = pickle.load(sp) pass_correct = "false" if has_pass=="true": while pass_correct=="false": pass_input = raw_input("INSERT PASSWORD: ") if pass_input==password: pass_correct = "true" print ("Password Correct") password = raw_input("CREATE A NEW PASSWORD: ") has_pass = "true" with open('save_pass.dat', 'w') as f: pickle.dump([password, …
downvote count: 1
linked to: http://stackoverflow.com/q/15112125
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83453982
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/15112125
tagged with: python
has comment: http://stackoverflow.com/comment/83454278
has comment: http://stackoverflow.com/comment/83454178
has comment: http://stackoverflow.com/comment/83453826
has comment: http://stackoverflow.com/comment/83454037
has comment: http://stackoverflow.com/comment/83454217
has comment: http://stackoverflow.com/comment/83453947
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/83454026
has comment: http://stackoverflow.com/comment/83454161
answer count: 0

http://stackoverflow.com/a/48285470
type: Answer
answers question: http://stackoverflow.com/q/48284642
has body: bruno's approach is very good for removing these extra lines of code givenText = "2 | 848 | Seconds | 660.00 | 900.00 | OK" desiredText = [] givenTextList = givenText.split("|") for i in givenTextList: desiredText.insert(len(desiredText), i.strip()) print(desiredText) Here split is used to return a list from given string according to the given parameter And strip is used to remove all those extra spaces at the end
score: 0

http://stackoverflow.com/q/48303370
type: AnsweredQuestion
score: 0
answer count: 1
upvote count: 1
tagged with: design-patterns
downvote count: 1
has title: Long list of parameters of class method in Python: local, argument or class atribute?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83620805
has body: I have a Python class with a number of functions. Evaluating each function requires a long list of constants (a few dozen); the constants are different for each function. Each function will be called many times (millions), so performance is a major concern. What is the proper way to handle this situation, both in terms of readability and in terms of speed? (I'm relatively new to python) I could make the constants class attributes, but this seems to clash with the safety provided by scopes (each constant is used only locally in a single function). Also, it would be convenient to be able to use the same variable names in different functions. Besides, I find that all the self.s make the code unreadable, especially when trying to keep line length under 79. I now have the constants defined locally at the start of each function. This is reasonably clear, but I'm not sure if it's optimal in terms of performance? Is new memory allocated and freed for every function call? Especially since you apparently can't declare proper constants in Python. Maybe it's better to put the parameters for each function in a separate class and pass an object of this class as an argument? This would maintain the proper scopes while ensuring each constant is defined only once?
tagged with: python
accepted answer: http://stackoverflow.com/a/48339764
has comment: http://stackoverflow.com/comment/83626607
has answer: http://stackoverflow.com/a/48339764

http://stackoverflow.com/comment/83471463
type: Comment
has text: What are you even talking about? What do you mean by "there is more minimal values on first k- positions which belong to a"? Matching the elements up pairwise, b has 3 smaller elements and a has two, so that's not it. The minimum element across both lists is 0, and all 0s are in b, so that's not it either. What are you trying to ask?
comment on: http://stackoverflow.com/q/48244462
type: QuestionComment
score: 3

http://stackoverflow.com/comment/83553012
comment on: http://stackoverflow.com/q/48282935
type: Comment
type: QuestionComment
has text: I have verified that R is in fact in that form. I will experiment with the top left element of K as you suggested and get back to you. However, since you helped me with calculating the K matrix last time (https://stackoverflow.com/questions/48240239/python-calibrate-camera), do you have any ideas why I am getting such a huge value for the top left element of K? And if I add the flag to have an aspect ratio of 1, I no longer get a fixed value of the K matrix for different squares, as we discussed. Is there any way to fix both of these issues at once?
score: 0

http://stackoverflow.com/comment/83535596
has text: Will you know why it doesn't show me the other users?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48276042

http://stackoverflow.com/q/48175726
type: Question
has body: I have a raspberry Pi that i had added an shutdown button on the GPIO using this script: import RPi.GPIO as GPIO import os gpio_pin_number=21 GPIO.setmode(GPIO.BCM) GPIO.setup(gpio_pin_number, GPIO.IN, pull_up_down=GPIO.PUD_UP) try: GPIO.wait_for_edge(gpio_pin_number, GPIO.FALLING) os.system("sudo shutdown -h now") except: pass GPIO.cleanup() It works like a charm, but more than once i had pressed the button by accident, so to avoid this problem, i want to mod the script so it requires you to hold the button for N seconds instead just pressing it. So if any one can point me in the right direction (i'm not very good in python) i would be glad.
tagged with: raspberry-pi
has title: Raspberry pi shutdown button with a delay
answer count: 1
accepted answer: http://stackoverflow.com/a/48175881
type: AnsweredQuestion
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/48175881

http://stackoverflow.com/comment/83336574
comment on: http://stackoverflow.com/q/48176724
has text: You could use `t_span = [0, T]`, where `T` is the period of the time-varying input, e.g. `2*pi` for sint(t).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48287127
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
has title: Adding internal brackets to a list with a tuple
tagged with: python
type: Question
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/83559136
has answer: http://stackoverflow.com/a/48287244
accepted answer: http://stackoverflow.com/a/48287244
upvote count: 1
has comment: http://stackoverflow.com/comment/83559057
answer count: 1
downvote count: 1
has body: I am using a for i in range loop to add the text logging which update it is ("this is change", counter). I want the section to be inserted into brackets next to the text "for section". Currently I have tried a few changes with this code: changes.append(('This is change',counter,'for section',(i))) Which works fine, except for the i being inserted in brackets. I know I could potentially try something like this: changes.append((counter,'This is change',i, counter,'for section(',i,')')) Except the output is not directly in the format I want as the output is, when print(changes) is used, ('This is change',counter,'for section(',1,')') [when i= 1], whilst I want the output to be: ('This is change',counter,'for section(1)'). Therefore my question is this: how do you insert internal brackets in a list without the quotation marks. My full code is this: change_log= [1,2,3] #I shall get a file output in here later, but for now I've filled it with generic stuff changes=[] counter= 0 for i in range(1,len(change_log)): changes.append(('This is change',counter,'for section',(i))) counter+=1 print(changes)

http://stackoverflow.com/comment/83514627
has text: @nwp yes the size is same and both calls succeed. I have edited my question with the code snippet. To verify the timing I use a for loop for 1000 times, and push the time in a list or vector respectively, and finally I print the average and the whole list/vector.
type: QuestionComment
comment on: http://stackoverflow.com/q/48265569
score: 0
type: Comment

http://stackoverflow.com/comment/83339898
type: AnswerComment
has text: I don't think so. If you are truly stuck you should open another question so this thread doesn't go off topic.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48178968

http://stackoverflow.com/a/48176442
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48175892
type: Answer
has body: You can also try this. df = pd.DataFrame({'Country': ['US', 'US', 'CA', 'CA', 'BE', 'BE', 'BE', 'MX'], 'Language': ['en', 'es', 'en', 'fr', 'nl', 'fr', 'de', 'es']}) First find unique languages for each country with groupby and unique(). df2 = pd.DataFrame(df.groupby(["Country"])["Language"].unique().reset_index()) # df2 # Country Language # 0 BE [nl, fr, de] # 1 CA [en, fr] # 2 MX [es] # 3 US [en, es] # Then split Language column into 3 columns langs = df2.Language.values.tolist()).add_prefix('Lang') # concat two df to get the desired output pd.concat([df2.Country, langs], axis=1) Country Lang0 Lang1 Lang2 0 BE nl fr de 1 CA en fr None 2 MX es None None 3 US en es None

http://stackoverflow.com/a/48248035
has body: Try This One def all_perms(the_string): all_perm=[''] if len(the_string)==1: all_perm.append(the_string) return all_perm else: for char in the_string: for word in all_perms(the_string.replace(char,'')): all_perm.append(char+word) return all_perm the_string="hey" print(sorted(all_perms(the_string)[1:],key=len))
answers question: http://stackoverflow.com/q/48247954
has comment: http://stackoverflow.com/comment/83492577
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/83504646

http://stackoverflow.com/a/48256228
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83590320
has comment: http://stackoverflow.com/comment/83496377
has body: General advice Please show some attempts and make sure your problem is well-defined! Without the former people are not that motivated as they assume you did not even try. The latter asks for solutions to a problem never asked for! I'm assuming, your objective is to maximize f9 + f10 + f11. Advice part 2 To be honest: in Linear-programming, this problem is quite simple and does not have complex constraint conditions! To tackle tasks like these, make sure to understand the standard-form of LPs which is more or less everything you need to do here (and linprog's API is even easier to use than a real standard-form). Code-intro As mentioned: all we need to do is to model an LP for this. The basic idea here: introduce helper-variables which mimic your intermediate-values used in other constraints a good solver with presolving capabilities will not be hurt by those introduced variables (which will easy the formulation) scipy's linprog has two different solvers: as far as i know: only the IPM-one has (advanced-) presolving but for your model-size: no need for presolving: it's trivial! Remark: i did not check the result maybe i switched some 0/1; but the code will show you how to tackle the problem! i did not check the general idea of your optimization-problem (i assume it makes sense!) if this is a correct interpretation of your problem, you now also have your answer to: what approach to take? as LPs are very very fast to solve and a lot of free software is available linprog faster &amp; more robust (see remark at the end) than scipy's (more general nonlinear-based) minimize optimal solution (if there is one) guaranteed to be found (in contrast to your alternative approach mentioned) Code import numpy as np from scipy.optimize import linprog """ Create LP in (modified) standard-form for linprog-API """ # VARIABLES # --------- # vars: 9 # auxiliary/helper-vars: 12 -&gt; c9, c10, c11, ..., f9, f10, f11 # all vars: 21 # layout x VECTOR: c6, c7, c8, d6, d7, d8, e6, e7, e8, # con…
score: 3
has comment: http://stackoverflow.com/comment/83509727
accepted answer of: http://stackoverflow.com/q/48252227
type: Answer
has comment: http://stackoverflow.com/comment/83590860
has comment: http://stackoverflow.com/comment/83496284
answers question: http://stackoverflow.com/q/48252227
has comment: http://stackoverflow.com/comment/83590920
has comment: http://stackoverflow.com/comment/83496316
upvote count: 3
has comment: http://stackoverflow.com/comment/83590086

http://stackoverflow.com/comment/83482614
has text: @Elmex80s - problem should be only in last group, so never this data.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48249935

http://stackoverflow.com/q/48298074
upvote count: 3
has title: Writing yaml file: attribute error
tagged with: yaml
has answer: http://stackoverflow.com/a/48298332
downvote count: 0
accepted answer: http://stackoverflow.com/a/48298354
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48298354
tagged with: python
has body: I'm trying to read a yaml file, replacing part of it and write the result it into the same file, but I get an attribute error. Code import yaml import glob import re from yaml import load, dump from yaml import CLoader as Loader, CDumper as Dumper import io list_paths = glob.glob("my_path/*.yaml") for path in list_paths: with open(path, 'r') as stream: try: text = load(stream, Loader=Loader) text = str(text) print text if "my_string" in text: start = "'my_string': '" end = "'" m = re.compile(r'%s.*?%s' % (start,end),re.S) m = m.search(text).group(0) text[m] = "'my_string': 'this is my string'" except yaml.YAMLError as exc: print(exc) with io.open(path, 'w', encoding = 'utf8') as outfile: yaml.dump(text, path, default_flow_style=False, allow_unicode=True) Error I get this error for the yaml_dump line AttributeError: 'str' object has no attribute 'write' What I have tried so far Not converting the text to a string, but then I get an error on the m.search line: TypeError: expected string or buffer Convert first to string and then to dictagain, but I get this error from the code text: dict(text) : ValueError: dictionary update sequence element #0 has length 1; 2 is required Yaml file my string: something string2: something else Expected result: yaml file my string: this is my string string2: something else
type: AnsweredQuestion
score: 3
tagged with: python-2.7
answer count: 2
possible better answer: http://stackoverflow.com/a/48298332

http://stackoverflow.com/comment/83458067
has text: one more question, any idea how do get both array a and b after rolling them into one dimensional array?
comment on: http://stackoverflow.com/q/48237735
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48253244
has title: Compare Excel cells Python
upvote count: 0
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48253726
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83642283
has comment: http://stackoverflow.com/comment/83489228
type: UnansweredQuestion
has body: I would like to compare two parts of two different columns from an Excel file that have a different number of elements. The comparison should be made between a part of Column 3 and a part of Column 2. Column 3 part has a length of j elements and Column 2 has a length of k elements(k>j). Column 2 part starts from row "j+1" and column 3 part starts from row 1. If an element from column 3 part is matching an element from column 2 part, then should check if the element from column1, before the j row, which has the same index as matched item from column 3 part is matching with the element from Column 1 part between j+1 and k, which has the same index as matched item from column 2 part. If yes, then should be written the element from Column 4 with the same index as matched element from column 2 part in a new Excel sheet. Example: Column3[1]==Column2[2](which represents element 'A') => Column1[1]==Column1[j+2](which represents element 'P') => Column4[j+2] should be written in a new sheet. Column 1 Column 2 Column 3 Column 4 P F A S B G X T C H K V D I M W P B R B P A R D C D H E D E J k E M K W F F L Q Q F K Q For reading the Excel sheet cells from original sheet, I have used the df27.ix[:j-1,1]. One part of the code which reads the values of the mention part from column 3 and column 2 might be: for j in range(1,j): c3=sheet['B'+str(j)].value for k in range(j,j+k): c2=sheet['B'+str(k)].value Any hint how I can accomplish this? UPDATED I have tried a new code which takes in consideration that we have '-', like joaquin mentioned in his example. Joaquin's example: C1 C2 C3 C4 0 P - A - 1 B - X - 2 C - K - 3 D - M - 4 P B - B 5 P A - D 6 C D - E 7 D E - k 8 E M - W 9 F F - Q 10 Q F - Q New code: from pandas import DataFrame as df import pandas as pd import openpyxl wb=openpyxl.load_workbook('/media/sf_vboxshared/x.xlsx') sheet=wb.get_sheet_by_name('Sheet1') C13=[] C12=[] C1=[] C2=[] C3=[] for s in range(2, sheet.max_row+1): C1second=sheet['A'+str(s)].value C2second=sheet['B'+s…
tagged with: python
score: -1
tagged with: excel
has comment: http://stackoverflow.com/comment/83489233

http://stackoverflow.com/comment/83359558
has text: as the above text is not formatted , please find the input and output data like below in the attached image , input.jpeg , ouput.jpeg
comment on: http://stackoverflow.com/a/48186104
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83489674
score: 3
has text: Try `"In year " + str(today.year) + " I should learn more Python"`.
comment on: http://stackoverflow.com/q/48253554
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83489731
has text: No, a regular array.
comment on: http://stackoverflow.com/q/48253612
type: QuestionComment
type: Comment
score: 0

flask-restless
type: Tag
tag name: flask-restless
tags question: http://stackoverflow.com/q/48187843

http://stackoverflow.com/q/48259515
has comment: http://stackoverflow.com/comment/83550504
has title: decoding issue while parsing JSON [python]
has comment: http://stackoverflow.com/comment/83501880
has comment: http://stackoverflow.com/comment/83503532
tagged with: python
has comment: http://stackoverflow.com/comment/83502933
tagged with: character-encoding
tagged with: utf-8
has comment: http://stackoverflow.com/comment/83503586
has comment: http://stackoverflow.com/comment/83503550
has body: I am reading a JSON file in Python which has lots of fields and values (~8000 records). Env: windows 10, python 3.6.4; code: import json json_data = json.load(open('json_list.json')) print (json_data) With this I get an error. Below is the stack trace: json_data = json.load(open('json_list.json')) File "C:\Program Files (x86)\Python36-32\lib\json\__init__.py", line 296, in load return loads(fp.read(), File "C:\Program Files (x86)\Python36-32\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 0x81 in position 7977319: character maps to &lt;undefined&gt; Along with this I have tried import json with open('json_list.json', encoding='utf-8') as fd: json_data = json.load(fd) print (json_data) with this my program runs for a long time then hangs with no output. I have searched almost all topics related to this and could not find a solution. Note: The JSON data is a valid one as when I see it on Postman/any REST client it doesn't report any anomalies. Any help on this or alternative solution on how can I load my JSON data (any way by converting it to string then back to JSON etc) will be of great help. Here is what the file looks like around the reported error: &gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; f = open('C:/Users/c5242046/Desktop/test2/dblist_rest.json', 'rb') &gt;&gt;&gt; f.seek(7977319) 7977319 &gt;&gt;&gt; pprint(f.read(100)) (b'\x81TICA EL ABGEN INGL\xc3\x83\xc2\x89S, S.A.","memory_size_gb":"64","since' b'":"2017-04-10","storage_size_gb":"84.747')
has comment: http://stackoverflow.com/comment/83505603
has comment: http://stackoverflow.com/comment/83502874
has comment: http://stackoverflow.com/comment/83502400
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83550078
has comment: http://stackoverflow.com/comment/83503531
has comment: http://stackoverflow.com/comment/83503461
has comment: http://stackoverflow.com/comment/83548970
accepted answer: http://stackoverflow.com/a/48283480
has comment: http://stackoverflow.com/comment/83549447
has comment: http://stackoverflow.com/comment/83549340
linked to: http://stackoverflow.com/q/46180610
has answer: http://stackoverflow.com/a/48283480
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/83550410
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83549084
has comment: http://stackoverflow.com/comment/83515342
upvote count: 1
has comment: http://stackoverflow.com/comment/83503632
has comment: http://stackoverflow.com/comment/83549839
has comment: http://stackoverflow.com/comment/83503168
has comment: http://stackoverflow.com/comment/83502327
has comment: http://stackoverflow.com/comment/83502932
has comment: http://stackoverflow.com/comment/83503356
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83539545
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83550635

http://stackoverflow.com/q/48290687
has title: Merging All Columns of Pandas DataFrames
accepted answer: http://stackoverflow.com/a/48290789
has comment: http://stackoverflow.com/comment/83566445
has answer: http://stackoverflow.com/a/48290789
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/83566485
has comment: http://stackoverflow.com/comment/83566509
tagged with: performance
has comment: http://stackoverflow.com/comment/83566606
has comment: http://stackoverflow.com/comment/83566561
has comment: http://stackoverflow.com/comment/83566529
has body: I have many pandas DataFrames for stocks. They all have the form: df_asset = pd.DataFrame(data=np.random.random((5,4)), index=[0, 1, 2, 3, 4], columns=['Open', 'High', 'Low', 'Close']) I have stored the asset names and their DataFrames in the dictionary: stock_data = {'AAPL' : df_AAPL, 'CSCO' : df_CSCO ...} I want to join all of these DataFrames to create a MultiIndexed DataFrame of the form: df = pd.DataFrame(data=np.random.random((15,4)), index=pd.MultiIndex.from_product([list(range(1,6)), ['AAPL', 'CSCO', 'AMZN']]), columns=['Open', 'High', 'Low', 'Close']) What is the most elegant (and hopefully efficient) way to do this? Thanks for any help, Jack
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/83639716
type: Comment
comment on: http://stackoverflow.com/a/48327074
has text: Thanks it helps a lot! May I ask what's the @src for?
score: 0
type: AnswerComment

traceback
tags question: http://stackoverflow.com/q/48179932
tag name: traceback
type: Tag
tags question: http://stackoverflow.com/q/48185422

http://stackoverflow.com/comment/83484656
type: Comment
has text: They can be renamed but I don't think it's essential to the question.
comment on: http://stackoverflow.com/a/48251097
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83389044
comment on: http://stackoverflow.com/a/48203724
type: AnswerComment
has text: Let me know your findings. I'm curious. I'm also thinking one potential case for modifying `intercept_scaling` is if your other features in X are just horrible. Maybe run with a dataset where the features in X are good for discriminating classes, and another dataset where the features in X are bad for discriminating classes.
score: 0
type: Comment

http://stackoverflow.com/comment/83498066
type: AnswerComment
comment on: http://stackoverflow.com/a/48257417
type: Comment
has text: Huh? No, being explicit about what you search means `pattern = re.compile(r'^[^ .]+')` like I wrote in a previous comment
score: 0

http://stackoverflow.com/q/48294013
possible better answer: http://stackoverflow.com/a/59279182
has comment: http://stackoverflow.com/comment/83574989
has comment: http://stackoverflow.com/comment/83574881
tagged with: hdf5
has title: How to store my own class object into hdf5?
accepted answer: http://stackoverflow.com/a/48300846
downvote count: 0
has comment: http://stackoverflow.com/comment/83653812
has answer: http://stackoverflow.com/a/48300846
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83573108
score: 5
tagged with: h5py
linked to: http://stackoverflow.com/q/39124934
upvote count: 5
has answer: http://stackoverflow.com/a/59279182
tagged with: python
has comment: http://stackoverflow.com/comment/83598131
has body: I created a class to hold experiment results from my research (I'm an EE phd student) like class Trial: def __init__(self, subID, triID): self.filePath = '' # file path of the folder self.subID = -1 # int self.triID = -1 # int self.data_A = -1 # numpy array self.data_B = -1 # numpy array ...... It's a mix of many bools, int, and numpy arrays. You get the idea. I read that it is faster when loading if the data is in hdf5 format. Can I do it with my data, which is a python list of my Trial object? Note that there is a similar question on stackoverflow. But it only has one answer, which doesn't answer the question. Instead, it breaks down the OP's custom class into basic data types and store them into individual datasets. I'm not against doing that, but I want to know if it's the only way because it's against the philosophy of object oriented.
has comment: http://stackoverflow.com/comment/83598994
has comment: http://stackoverflow.com/comment/83573150
tagged with: numpy
has comment: http://stackoverflow.com/comment/83575548
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83584512
answer count: 2

http://stackoverflow.com/comment/83911788
type: AnswerComment
comment on: http://stackoverflow.com/a/48441424
type: Comment
has text: I try it before, but not it working, I will updating my question with result of this options.
score: 0

http://stackoverflow.com/comment/83612459
type: Comment
type: QuestionComment
has text: `netcat` isn't magic. If you're already writing in Python, just use Python's socket module; it's not going to be any slower than spawning a `netcat` process and piping data to it. Or investigate a messaging library like [zmq](http://zeromq.org/) if you want something higher level than raw sockets.
score: 0
comment on: http://stackoverflow.com/q/48312816

http://stackoverflow.com/q/48176651
type: UnansweredQuestion
tagged with: arrays
has comment: http://stackoverflow.com/comment/83333581
tagged with: python
has comment: http://stackoverflow.com/comment/83334988
answer count: 2
tagged with: array-broadcasting
has comment: http://stackoverflow.com/comment/83335605
score: 1
has comment: http://stackoverflow.com/comment/83333993
has answer: http://stackoverflow.com/a/48177899
has comment: http://stackoverflow.com/comment/83333540
downvote count: 0
has answer: http://stackoverflow.com/a/48179354
upvote count: 1
has title: Sparse logical comparison of numpy arrays
tagged with: sparse-matrix
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83334449
has body: I have two numpy arrays, A and B, representing coordinates of points in a 2D plane. Let's say A is 10000-by-2, and B is 20000-by-2. Both have float64 dtype. I want to find out which of the points in first array, A, are in the second (B). Doing this with a for loop would be very slow. I came up with the following broadcasting scheme to perform the comparison (ignoring the floating point equality vs closeness issue for the moment): x_bool_array = A[:,0][numpy.newaxis,...] == B[:,0][...,numpy.newaxis] y_bool_array = A[:,1][numpy.newaxis,...] == B[:,1][...,numpy.newaxis] bool_array = numpy.logical_and(x_bool_array, y_bool_array) indices = numpy.where(bool_array) However this would result in very large, 20000-by-10000, boolean arrays which are mostly sparse, i.e, the number of Trues is much much less than the number of Falses. I'm wondering if there's a way to keep them sparse through some switch or property? Or if there is a better way to do this that is fast and doesn't consume a lot of memory? (doing it piece-wise is probably another option, but I guess I'm looking for elegance as well, besides, speed and low-memory). Edit: Responding to @Tai's comment for clarification, let's take a small example: A = numpy.array([[0.1, 0.2], [0.34, 0.44], [0.5, 0.6]]) B = numpy.array([[0.05, 0.05], [0.1, 0.2], [0.7, 0.8], [0.5, 0.6]]) In other words, A is an array of 3 2D points (3-by-2), and B is one with 4 2D points (4-by-2). We can see that B[1,:] is same as A[0,:], and B[3,:] is same as A[2,:]. So we have two matches. The final result, indices, would be as follows: (array([1, 3]), array([0, 2])) Edit 2: Previously I said piece-wise is an option. I tried it and it is not any better. Essentially I split one of the two arrays into 100 chunks, ran the logical comparison on each chunk against the full second array, and consolidated the results, in a for loop. Unfortunately, there is no way to let the interpreter know that it can use the previous memory (i.e., you cannot explicitly co…

http://stackoverflow.com/q/48246636
has comment: http://stackoverflow.com/comment/83476225
has comment: http://stackoverflow.com/comment/83476454
has comment: http://stackoverflow.com/comment/83476038
score: 1
has comment: http://stackoverflow.com/comment/83481411
tagged with: reload
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83476292
has comment: http://stackoverflow.com/comment/83476053
type: Question
has comment: http://stackoverflow.com/comment/83476411
has body: "reload" function cannot delete variable which have loaded into memory if you delete it in your module before reload. In another words, even if you delete the variable before reload, it will still exist. According to the (DOCS): When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Here's a simple example: import importlib import time def main(): import ex1 i = 0 while True: importlib.reload(ex1) ex1.x = ex1.x + 1 i = i + 1 print("loop:%d" %i) print("x:%d" %ex1.x) print(dir(ex1)) time.sleep(5) ex1 module's content before reload: x = 1 y = 1 Then delete x and reload ex1 and we will find that x is still in the dir(ex1) So, my question is how can I get a dict in which x is not in the dir after delete and reload?
upvote count: 2
has comment: http://stackoverflow.com/comment/83476403
has comment: http://stackoverflow.com/comment/83476422
has comment: http://stackoverflow.com/comment/83476096
tagged with: python
accepted answer: http://stackoverflow.com/a/48246704
has comment: http://stackoverflow.com/comment/83476244
has answer: http://stackoverflow.com/a/48246704
has title: After delete a variable and then reload the module,how can I make the namespace not retain this variable?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83476241

http://stackoverflow.com/a/48290628
has body: Do you just want the file names? Not the full path? for root, dirs, files in os.walk(base_path): if root == base_path: continue # skip iterating through base_path in case any of those files are a positive match else: for file in files: if 'foo' in root and file.endswith('.jsonl'): # You're now in a foo directory foo_files.append(file) elif 'bar' in root and file.endswith('.jsonl'): # You're now in a bar directory bar_files.append(file) If you actually wanted the full path, do a os.path.join(root, file) within the append() function. Edit: In case you're actually looking for the extension .json, just update to .endswith('.jsonl') on both conditions.
has comment: http://stackoverflow.com/comment/83567447
has comment: http://stackoverflow.com/comment/83567224
type: Answer
has comment: http://stackoverflow.com/comment/83566681
score: 0
answers question: http://stackoverflow.com/q/48290326
has comment: http://stackoverflow.com/comment/83567482

http://stackoverflow.com/q/48302783
has comment: http://stackoverflow.com/comment/83590333
has comment: http://stackoverflow.com/comment/83590298
has comment: http://stackoverflow.com/comment/84313061
has comment: http://stackoverflow.com/comment/84192317
answer count: 1
downvote count: 3
favorite count: 0
type: Question
tagged with: opencv
tagged with: python-imageio
accepted answer: http://stackoverflow.com/a/48305174
upvote count: 12
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/83670107
has answer: http://stackoverflow.com/a/48305174
has title: Three different types of output when reading an image with three different libraries in Python
tagged with: python
has body: I am reading an image in python with three different libraries imageio PIL.Image cv2. The output I am getting on reading image with each one of these libraries is different. For example On reading with imageio a = imageio.imread('test_img.png') The output is of type - uint8 and size is (500,334,4) using Image b = Image.open('test_img.png') type - Image, size (334,500) using cv2 c = cv2.imread('test_img.png') type- uint8, size (500,334,3) Why I am getting three different size for same image when using three different libraries? Please, help me in understanding the difference.
score: 9
type: AnsweredQuestion

http://stackoverflow.com/comment/83373375
has text: Can you not merge or join all the dataframes and then drop what you don't need?
type: Comment
comment on: http://stackoverflow.com/q/48196115
type: QuestionComment
score: 0

http://stackoverflow.com/a/48250515
score: 0
type: Answer
has body: The doc of Celery 4.1 is different: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) The difference with your is the lambda function for app.autodiscover_tasks() If that does not fix your problem maybe you need to show how you're declaring your celery tasks.
answers question: http://stackoverflow.com/q/48249893
has comment: http://stackoverflow.com/comment/83483686

http://stackoverflow.com/comment/83452898
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48228862
type: AnswerComment
has text: But with this solution I will get only the half of my dataset! How I will load the other half to the training set?

http://stackoverflow.com/comment/83373052
type: Comment
type: QuestionComment
score: 2
has text: I've got another result `>>>> time() - time() -1.9073486328125e-06`. Maybe your computer is too fast (:
comment on: http://stackoverflow.com/q/48196000

http://stackoverflow.com/q/48325147
has comment: http://stackoverflow.com/comment/83636247
type: UnansweredQuestion
answer count: 1
tagged with: python
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/43824665
has title: How to convert tensorflow variable to numpy array
has body: I am trying to create a model graph where my input is tensorflow variable which I am inputting from my java program In my code, I am using numpy methods where I need to convert my tensorflow variable input to numpy array input Here, is my code snippet import tensorflow as tf import numpy as np eps = np.finfo(float).eps EXPORT_DIR = './model' def standardize(x): med0 = np.median(x) mad0 = np.median(np.abs(x - med0)) x1 = (x - med0) / (mad0 + eps) return x1 #tensorflow input variable a = tf.placeholder(tf.float32, name="input") with tf.Session() as session: session.run(tf.global_variables_initializer()) #Converting the input variable to numpy array tensor = a.eval() #calling standardize method numpyArray = standardize(tensor) #converting numpy array to tf tf.convert_to_tensor(numpyArray) #creating graph graph = tf.get_default_graph() tf.train.write_graph(graph, EXPORT_DIR, 'model_graph.pb', as_text=False) I am getting error: InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'input' with dtype float in line tensor = a.eval() When I am giving constant value in place of placeholder then it's working and generating the graph. But I want to input from my java code. Is there any way to do that or do I need to convert all my numpy methods to tensorflow methods
tagged with: tensorflow
has answer: http://stackoverflow.com/a/48325613
has comment: http://stackoverflow.com/comment/83651930
score: 0

http://stackoverflow.com/comment/83783931
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48276504
has text: hmmm, source of data is not important, but if need convert `json` or `dict` column use `df['Modes'] = df['Modes'].apply(pd.io.json.loads)`.
type: Comment

http://stackoverflow.com/q/48246370
has answer: http://stackoverflow.com/a/48246569
has answer: http://stackoverflow.com/a/48246722
tagged with: python-3.x
has body: I wanted to supply python with a windows 'data path' that could be used to set up input processing. I googled this with no luck, and now figure I am on my own. There appears to be many ways of reading in a file with python, and after some frustration with "\" and "/" and windows path names I found a way to get my data path set up. It is not a general approach but should serve me well. Related Questions: Is this code ugly? Is this a nonstandard method? Are there elegant features in 3.6 that should be used? ### Title: Process an input file using a 'data path' for a user on windows import sys import os print("OK, starting program...") file_processed = False for path, dirs, files in os.walk("/Users/Mike"): if file_processed: break for file in files: if file_processed: break if file == 'seriousdata.txt': my_path = os.path.abspath(path) my_dsn = os.path.join(my_path, file) print("Opening txt file " + my_dsn + " for input.") with open(my_dsn) as da_lines: textlines = (line.rstrip('\r\n') for line in da_lines) for line in textlines: print(line) file_processed = True if file_processed: pass else: print("File not found") print("OK, program execution has ended.") sys.exit() # END SAMPLE CODE SNIPPET
type: Question
answer count: 2
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/9880540
tagged with: file-io
has title: Data Path for File Input Processing
score: 0
has comment: http://stackoverflow.com/comment/83475513

http://stackoverflow.com/q/48324056
tagged with: python
linked to: http://stackoverflow.com/q/7505988
has comment: http://stackoverflow.com/comment/83633481
type: AnsweredQuestion
has body: Imagine a folder structure as follows: project/ grandparent.py folder1/ parent.py folder2/ sibling.py current.py If I am in current.py I can import from the other files using relative paths as follows: from .sibling import * from ..parent import * How can I import from grandparent.py ? (I've tried ...grandparent and ../..grandparent )
answer count: 2
tagged with: python-import
has comment: http://stackoverflow.com/comment/89101667
upvote count: 3
has answer: http://stackoverflow.com/a/48324248
accepted answer: http://stackoverflow.com/a/48324248
downvote count: 0
tagged with: relative-path
has title: In Python, how can I import from a grandparent folder with a relative path?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48324302
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48324302
has comment: http://stackoverflow.com/comment/89224669
score: 3
has comment: http://stackoverflow.com/comment/89097202

http://stackoverflow.com/q/48248072
downvote count: 0
answer count: 1
tagged with: django
upvote count: 1
tagged with: python
has title: Admin css won't load when deploying Django project on pythonanywhere
favorite count: 0
has comment: http://stackoverflow.com/comment/83487793
has answer: http://stackoverflow.com/a/48253911
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83488002
score: 1
has body: So I had some trouble with static files when I tried deploying them... Thing is that I manage to server the main static files and everything is working except for the admin. I think maybe something is wrong with my configuration. Here is screenshot of my web: https://i.sstatic.net/rYxTm.png This is my settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') SECRET_KEY = 'ie&amp;_vj_d)t5itbpun3%58tlw(3=ptn1^5qj43kgm^&amp;_z^!5(' DEBUG = False ALLOWED_HOSTS = ['danielcirstea.pythonanywhere.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rango', 'registration' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware' ] ROOT_URLCONF = 'tango_with_django_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR, ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media' ], }, }, ] WSGI_APPLICATION = 'tango_with_django_project.wsgi.application' LANGUAGE_CODE = 'ro' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [STATIC_DIR, ] STATIC_URL = …
accepted answer: http://stackoverflow.com/a/48253911
tagged with: pythonanywhere
has comment: http://stackoverflow.com/comment/83487002
type: Question

http://stackoverflow.com/a/48287019
type: Answer
answers question: http://stackoverflow.com/q/48275609
score: 0
has body: Strange, it seems to be offering split() for me properly in Eclipse/PyDev. Can you post a screenshot with the completion you're having there to help diagnosing the issue?

http://stackoverflow.com/comment/83363166
type: Comment
has text: And I just saw [here, that even Tukey's HSD in statsmodels](https://stackoverflow.com/a/21177789/8881141) doesn't calculate the p value. Meh.
comment on: http://stackoverflow.com/q/48190140
score: 0
type: QuestionComment

http://stackoverflow.com/q/48238171
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48238245
answer count: 2
has answer: http://stackoverflow.com/a/48238245
has body: I'm getting string data into my python code.Some time data is coming with an extra "and" or " or for example Tom and Mark and in this case I need to remove the last "and" &amp; final outcome will look like Tom and Mark But when data will come like this Harry and John Then I will consider the data without removing the "and" Can you suggest me how to do that?
score: -3
possible better answer: http://stackoverflow.com/a/48238217
has comment: http://stackoverflow.com/comment/83458725
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48238217
type: AnsweredQuestion
downvote count: 4
has comment: http://stackoverflow.com/comment/83458733
has title: Remove last and from a python string if it's there

http://stackoverflow.com/comment/83649323
has text: Try creating virtual environments and then install different versions in different virtualenv. See here for details. http://docs.python-guide.org/en/latest/dev/virtualenvs/
type: QuestionComment
comment on: http://stackoverflow.com/q/48331023
score: 0
type: Comment

http://stackoverflow.com/comment/83364605
score: 0
has text: 1 - Why won't you try for yourself, don't see why wouldn't it work except for performance issues. 2 - how many good and bad (different!) samples did you use to train your cascade?
comment on: http://stackoverflow.com/q/48191975
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48267483
has body: When executing applymap on a masked subset of df datetime columns, two of the four columns are converted to timedelta. Can't figure out what might be happening, perhaps an error similar to https://github.com/pandas-dev/pandas/issues/18493? But why only two of the four?! print time_data.dtypes, time_data[nt].dtypes time_data[nt] = time_data[nt].applymap(lambda x: x.strftime('%I:%M:%S %p') if pd.notnull(x) else pd.NaT) time_data['Total Clock Time'] = time_data['Total Clock Time'].apply(lambda x: x.seconds/3600) print time_data.dtypes, time_data[nt].dtypes Date object Name object In AM datetime64[ns] Out AM datetime64[ns] In PM datetime64[ns] Out PM datetime64[ns] Sick Time datetime64[ns] Total Clock Time object dtype: object In AM datetime64[ns] Out AM datetime64[ns] In PM datetime64[ns] Out PM datetime64[ns] Sick Time datetime64[ns] dtype: object Date object Name object In AM object Out AM object In PM timedelta64[ns] Out PM timedelta64[ns] Sick Time datetime64[ns] Total Clock Time float64 dtype: object In AM object Out AM object In PM timedelta64[ns] Out PM timedelta64[ns] Sick Time datetime64[ns] dtype: object the data look like this: Date Name In AM Out AM \ 0 2017-11-06 AUSTIN LEWIS 1900-01-01 06:10:24 1900-01-01 12:03:23 1 2017-11-06 FRED MOORE 1900-01-01 06:58:37 1900-01-01 12:12:11 2 2017-11-06 KERRIE PAUSSA 1900-01-01 11:58:48 1900-01-01 19:39:49 3 2017-11-06 OMAR CUELLAR NaT NaT 4 2017-11-07 AUSTIN LEWIS 1900-01-01 07:07:27 1900-01-01 12:06:43 In PM Out PM Sick Time 0 1900-01-01 12:32:03 1900-01-01 17:31:50 NaT 1 1900-01-01 12:42:53 1900-01-01 17:31:50 NaT 2 NaT NaT NaT 3 1900-01-01 20:00:19 1900-01-01 23:59:41 NaT 4 1900-01-01 12:35:26 1900-01-01 17:33:20 NaT
has comment: http://stackoverflow.com/comment/83524464
type: AnsweredQuestion
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48270730
answer count: 1
has title: Pandas df.applymap() produces unwanted type conversion of datetime64[ns] to timedelta
has comment: http://stackoverflow.com/comment/83524124
type: Question
tagged with: datetime
has answer: http://stackoverflow.com/a/48270730
tagged with: python

http://stackoverflow.com/comment/83743621
type: Comment
type: QuestionComment
has text: Building a Cartesian product or mission orders would actually be one of the easiest ways to implement programmatically, but I presume it would be a very inefficient way of testing, as it would include scenarios like "add marker", "delete marker", "add marker","delete marker" x10.
comment on: http://stackoverflow.com/q/48258421
score: 0

http://stackoverflow.com/a/48280539
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48212173
answers question: http://stackoverflow.com/q/48212173
type: Answer
has body: Posting as an answer, since there is no accepted answer yet :) class ObjectAdmin(MarkdownxModelAdmin): ... Should do it.
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48252809
score: 2
type: AnsweredQuestion
tagged with: list
answer count: 2
upvote count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/48252868
favorite count: 0
has body: The easiest way to explain this is to show a simple example: x = [0] f = 4 if (x) &amp; (f &lt; 6): print("yes") The idea is simple, check if a list contains any content and if some other variable is less than some number. The solution yields the following error and I'm not entirely sure what the solution is. TypeError: unsupported operand type(s) for &amp;: 'list' and 'bool'
type: Question
has comment: http://stackoverflow.com/comment/83488131
tagged with: typeerror
has title: Attempting to check if a list isn't empty AND some other condition within the same if statement
tagged with: if-statement
has answer: http://stackoverflow.com/a/48252868
tagged with: python
has answer: http://stackoverflow.com/a/48252838
accepted answer: http://stackoverflow.com/a/48252838

http://stackoverflow.com/comment/83507449
has text: everything works perfectly with this but I don't want to pass column 's' to the function. So is there a way to eliminate column s from kwargs
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48261961

http://stackoverflow.com/q/48328012
tagged with: logistic-regression
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48328564
has body: I have a model built with Python scikit-learn. I understand that the models can be saved in Pickle or Joblib formats. Are there any existing methods out there to save the jobs in JSON format? Please see the model build code below for reference: import pandas from sklearn import model_selection from sklearn.linear_model import LogisticRegression import pickle url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data" names =['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] dataframe = pandas.read_csv(url, names=names) array = dataframe.values X = array[:,0:8] Y = array[:,8] test_size = 0.33 seed = 7 X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size, random_state=seed) # Fit the model on 33% model = LogisticRegression() model.fit(X_train, Y_train) filename = 'finalized_model.sav' pickle.dump(model, open(filename, 'wb'))
has answer: http://stackoverflow.com/a/48328564
tagged with: http://stackoverflow.com/tag/json
answer count: 1
tagged with: python
upvote count: 11
favorite count: 0
type: Question
downvote count: 0
tagged with: scikit-learn
score: 11
has title: Python scikit-learn to JSON

text
tags question: http://stackoverflow.com/q/48309143
tags question: http://stackoverflow.com/q/48205032
tags question: http://stackoverflow.com/q/48324107
tags question: http://stackoverflow.com/q/48228783
tags question: http://stackoverflow.com/q/48230230
tags question: http://stackoverflow.com/q/48201634
tags question: http://stackoverflow.com/q/48280759
type: Tag
tag name: text
tags question: http://stackoverflow.com/q/48312954
tags question: http://stackoverflow.com/q/48305837

http://stackoverflow.com/comment/83329992
comment on: http://stackoverflow.com/q/48174702
type: QuestionComment
score: 0
has text: This is yet another case that Python 3 handles better (clearer errors when it fails, and better defaults so it doesn't fail).
type: Comment

http://stackoverflow.com/comment/83443904
type: Comment
type: QuestionComment
score: 0
has text: Like beautifulsoup, lxml, or the standard library's xml.etree
comment on: http://stackoverflow.com/q/48230761

http://stackoverflow.com/q/48331023
has title: Linking to python libraries from different python executables on Windows 10
type: Question
type: UnansweredQuestion
tagged with: python
has body: I am relatively new to Python and trying to figure out how to set up my different implementations of Python. To run different packages, I have multiple installations of python 2.7 and 3.6, both 32-bit and 64-bit. For example, I run some GIS software that uses its own implementation of python (OSGEO4W) that I run from the installation location (32-bit Python 2.7). This python executable has a package (otbApplication), that doesn't really install from pip or conda. However, I mainly run python (also 32-bit Python 2.7) from Anaconda. When I am running from Anaconda, is there a way to have otbApplication and other libraries in OSGEO4W implementation of Python available?
has comment: http://stackoverflow.com/comment/83649323
linked to: http://stackoverflow.com/q/37006114
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83713906
tagged with: anaconda
has comment: http://stackoverflow.com/comment/83682760
has answer: http://stackoverflow.com/a/48363554
score: 0
answer count: 1

http://stackoverflow.com/q/48284569
tagged with: django-rest-framework
has body: I am attempting to build a REST API in Django for a Google Spreadsheet with Gspread, I'm running into a lot of issues (so if anyone happens to have a full example lying around, feel free to share... please? :)). One of those issues it that I'm trying to receive JSON for a POST request (and later on other requests, of course). This is, however, failing. This is my code: view.py (I'm aware that that IF-statement is not how it works elif request.method == 'POST': received_json_data = json.loads(request.body.decode("utf-8")) content = received_json_data['content'] if content != "": worksheet.insert_row([content["date"], content["days"], content["firstname"], content["lastname"], content["team"], content["training"], content["company"], content["city"], content["cost"], content["invoice"], content["info"]], 1) return JsonResponse(content, safe=False, status=status.HTTP_201_CREATED) else: return JsonResponse([], safe=False, status=status.HTTP_400_BAD_REQUEST) A test that has been written for this: def test_post_all_training_returns_201_when_correct_format(self): """ A POST request on /trainings/ should create a new training """ headers = {'content-type': 'application/json'} response = self.client.post('/trainings/', json=json.dumps(self.training_json_body), headers=headers, format="json") self.assertEqual(response.status_code, status.HTTP_201_CREATED) The contents of the training_json_body: self.training_json_body = { "date": "1/1/2018", "days": 1, "firstname": "Data", "lastname": "Data", "team": "Data", "training": "Data", "company": "Data", "city": "Data", "cost": 1, "invoice": "Data", "info": "Data" } Traceback Traceback (most recent call last): File "C:\Python\backend\unleashedapp\trainings\tests.py", line 64, in test_post_all_training_returns_201_when_correct_format response = self.client.post('/trainings/', json=json.dumps(self.training_json_body), headers=headers, format="json") File "C:\Users\yanni\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83553349
tagged with: rest
answer count: 3
upvote count: 5
tagged with: python
tagged with: gspread
has comment: http://stackoverflow.com/comment/83555410
favorite count: 0
type: Question
has title: Get JSON data from POST in Django with REST Framework
has answer: http://stackoverflow.com/a/56067534
has comment: http://stackoverflow.com/comment/83553404
accepted answer: http://stackoverflow.com/a/48285761
possible better answer: http://stackoverflow.com/a/56114342
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/83555877
has answer: http://stackoverflow.com/a/48285761
tagged with: django
has answer: http://stackoverflow.com/a/56114342

http://stackoverflow.com/a/48194603
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48194545
score: 2
upvote count: 2
has body: df'Actual', 'Predicted' only has two columns (Actual and Predicted), so you cannot group that dataframe by Crop and Years. I think that you first need to group by crop and years and then select the columns that you want to calculate the mean for: df.groupby(['Crop', 'Years'])'Actual', 'Predicted'.mean()
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48194545

http://stackoverflow.com/q/48203126
type: Question
has comment: http://stackoverflow.com/comment/83387481
answer count: 0
has comment: http://stackoverflow.com/comment/83387600
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83387204
has comment: http://stackoverflow.com/comment/83387413
has comment: http://stackoverflow.com/comment/83387458
has title: Match a completed string with regex pattern
has comment: http://stackoverflow.com/comment/83387423
has comment: http://stackoverflow.com/comment/83387289
score: 0
has comment: http://stackoverflow.com/comment/83387210
has comment: http://stackoverflow.com/comment/83387169
has comment: http://stackoverflow.com/comment/83387153
has comment: http://stackoverflow.com/comment/83387484
has body: I have a string, s = '`re.``search`(*pattern*, *string*, *flags=0*)', Easily it produces such a result using sub In [100]: re.sub(r'[`*]','',s) Out[100]: 're.search(pattern, string, flags=0)' I'd like to refactor it by writing a whole regex pattern instead of substituting. In [101]: re.search(r'[^`*]+',s) Out[101]: &lt;_sre.SRE_Match object; span=(1, 4), match='re.'&gt; It stops at first match 're., while I intend to retrieve the completed. How to accomplish such a task?
tagged with: python
tagged with: regex

http://stackoverflow.com/a/73822364
answers question: http://stackoverflow.com/q/48299129
score: 0
type: Answer
has body: Use this line of code to extract the coordinates errorCode, sensor_handle = vrep.simxGetObjectHandle(clientID, 'GPS', vrep.simx_opmode_oneshot_wait)

http://stackoverflow.com/comment/83445961
has text: @cᴏʟᴅsᴘᴇᴇᴅ There is date, identifier(loc in example) and a value for each row
type: Comment
comment on: http://stackoverflow.com/q/48231758
type: QuestionComment
score: 0

http://stackoverflow.com/q/48311831
upvote count: 6
type: Question
has body: I am sorting a query on a timefield from a manytomany object but have trouble during pagination. models.py: class Validated(models.Model): job_id_list = models.ManyToManyField(JobId , related_name='JobId', blank=True) class JobId(models.Model): user = models.ForeignKey(User, blank=True, null=True, default=None) job_time = models.DateTimeField(auto_now_add=True) views.py: results_list = Validated.objects.filter(job_id_list__user=request.user).\ distinct().order_by('-job_id_list__job_time') My problem is that pagination is messed up and I get duplicates in my pagination output, even when the query output is ok. (other have this problem too) I tried several solutions but my issue does not get solved as sorting is bases on a field from a many-to-many object order_by('job_id_list__job_time') I was thinking of a work-around through creating an annotation to my model by the use of a Model.Manager. Inside this annotation, i try to add the job_time which is a result of a function inside the model. In that way, the job_time would be easily accessible: for i in result_list: job_time_from_model = result_list[i].job_time I would do this as followed but I don't know how to incorporate the %%function logic%% inside the annotation. Is this even possible in this way or is another approach required? models.py: class ValidatedManager(models.Manager): **%%function-logic%%** def date(self, user, id): xlinkdatabase_validated_object = self.get(id=id) job_id_list = xlinkdatabase_validated_object.\ job_id_list.all().order_by('-job_time') date_added = None for item in job_id_list: if item.user == user: date_added = item.job_time break return date_added def get_queryset2(self, user): qs = super(XlinkdatabaseValidatedManager, self).\ get_queryset().annotate(job_date= **%%function-logic%%**, output_field=DateTimeField()) return qs views.py: results_list = xlinkdatabase_validated.objects.get_queryset2(request.user).\ filter(job_id_list__user=request.user).distinct().order_by('-job_date')
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/31736700
downvote count: 0
tagged with: django
linked to: http://stackoverflow.com/q/22898097
score: 6
favorite count: 0
has title: django duplicates in pagination with order_by() on manytomany field
linked to: http://stackoverflow.com/q/5044464
tagged with: sql-order-by
tagged with: pagination
tagged with: python
tagged with: annotate

http://stackoverflow.com/q/48314971
has body: I have tried many times, but seems the 'replace' can NOT work well after use 'loc'. For example I want to replace the 'conlumn_b' with an regex for the row that the 'conlumn_a' value is 'apple'. Here is my sample code : df.loc[df['conlumn_a'] == 'apple', 'conlumn_b'].replace(r'^11*', 'XXX',inplace=True, regex=True) Example: conlumn_a conlumn_b apple 123 banana 11 apple 11 orange 33 The result that I expected for the 'df' is: conlumn_a conlumn_b apple 123 banana 11 apple XXX orange 33 Anyone has meet this issue that needs 'replace' with regex after 'loc' ? OR you guys has some other good solutions ? Thank you so much for your help!
possible better answer: http://stackoverflow.com/a/48315104
tagged with: python
has answer: http://stackoverflow.com/a/48315104
upvote count: 13
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48315254
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/128859715
downvote count: 0
score: 13
has title: Pandas how can 'replace' work after 'loc'?
accepted answer: http://stackoverflow.com/a/48315086
favorite count: 0
linked to: http://stackoverflow.com/q/48258466
type: Question
has answer: http://stackoverflow.com/a/48315086

http://stackoverflow.com/q/48211348
downvote count: 0
has body: it is driving me nuts that the annotate arrow in the screenshot below is not straight. What am I missing? I'm suspecting it has to do with the way I specify the xy and xytext position, yet they both have the same y. This is how I'm specifying the annotate: plt.annotate('Head Motion Cutoff', xy=[data.shape[0], motion_cutoff], xytext=[data.shape[0]+12, motion_cutoff], fontsize=14, arrowprops=dict(fc='#A9A9A9', ec='#A9A9A9', arrowstyle='simple', shrinkA=4, shrinkB=4))
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/48216502
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/48212623
possible better answer: http://stackoverflow.com/a/48212623
has title: Control angle of arrow in matplotlib.pyplot.annotate
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/83403872
accepted answer: http://stackoverflow.com/a/48216502
upvote count: 3

http://stackoverflow.com/comment/83467876
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48242431
has text: Still no success?

http://stackoverflow.com/comment/83831302
type: QuestionComment
comment on: http://stackoverflow.com/q/48328365
type: Comment
has text: I am using the system version of python version 2.7.1, I do not have any other installed.
score: 0

http://stackoverflow.com/q/48200787
has title: how to implement the switch case in python..?
linked to: http://stackoverflow.com/q/60208
upvote count: 1
has body: Check this below code: var = input("enter a number between 1 and 12") def switch_demo(var): switcher = { 1: "Jan" 2: "Feb" 3: "March" 4: "April" 5: "May" 6: "June" 7: "July" 8: "August" 9: "Sept" 10: "Oct" 11: "Nov" 12: "Dec" } print switcher.get(var,"Invalid Month") I am getting Syntax Error at line 5 How can I solve the error?
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48206143
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/83382736
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48200883
duplicate of: http://stackoverflow.com/q/60208
answer count: 2

libsvm
tags question: http://stackoverflow.com/q/48302463
type: Tag
tag name: libsvm

http://stackoverflow.com/a/48241245
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48241191
upvote count: 1
has comment: http://stackoverflow.com/comment/83465272
has body: You can use a context manager to ensure that the file is closed at the end of each operation: import contextlib @contextlib.contextmanager def write_to(filename, ops = 'a'): f = open(filename, ops) yield f f.close() for chunk in data: with write_to('filename.txt') as f: f.write(chunk)
type: Answer
answers question: http://stackoverflow.com/q/48241191

http://stackoverflow.com/comment/83650489
score: 0
comment on: http://stackoverflow.com/q/48330505
type: Comment
type: QuestionComment
has text: The problem is indeed unclear. The code you show does produce a plot of the matrix. It would also produce this plot if the whole thing was embedded into PyQt. If that fails for you you need to show the code that you have the problem with.

http://stackoverflow.com/q/48195863
has comment: http://stackoverflow.com/comment/83374061
tagged with: xgboost
favorite count: 0
has title: XGBoost running slow on my machine, is it normal?
has answer: http://stackoverflow.com/a/76077614
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/83373774
has comment: http://stackoverflow.com/comment/83374012
type: UnansweredQuestion
has body: I am using XGBoost to train 1 million rows and ~15 features from Kaggle project Rossmann Store Sales. It appears very slow. It took 30 mins to train model with no parameter tuning. If I run GridSearchCV to train model with 3 folds and 6 learning rate values, it will take more than 10 hours to return. As it is my first time to use XGBoost, I don't know if this is normal or not. I can't imagine how many days it will take to tune all the parameters of XGBoost model. Please help me. The model prarameters: XGBRegressor(learning_rate = 0.1,max_depth = 5,n_estimators = 1165,subsample=0.8,colsample_bytree=0.8,seed=27). I use n_estimators 1165 because it is returned by xgboost.train as best iterations. Also change nthread from 1 to 4 and it doesn't improve performace at all. My computer configuration is; CPU:intel i7 6500U (2cores 4threads) Memory: 8GB OS: windows 10
downvote count: 2
tagged with: python
tagged with: data-science
score: 2
has comment: http://stackoverflow.com/comment/83373914
has comment: http://stackoverflow.com/comment/83374268
has comment: http://stackoverflow.com/comment/83374681
has comment: http://stackoverflow.com/comment/83373633
answer count: 1

http://stackoverflow.com/comment/83519872
score: 1
type: Comment
type: QuestionComment
has text: Here are some examples: https://stackoverflow.com/questions/47483951/how-to-define-a-threshold-value-to-detect-only-green-colour-objects-in-an-image/47483966#47483966, https://stackoverflow.com/questions/48109650/how-to-detect-two-different-colors-using-cv2-inrange-in-python-opencv/48117624#48117624
comment on: http://stackoverflow.com/q/48268272

http://stackoverflow.com/a/48296849
answers question: http://stackoverflow.com/q/48296726
score: 3
has body: This is due to np.array being defaulted at float. If you want to make the array into an integer format, just do this: foo = np.array([1, 3, 5, 7]) bar = foo.astype(int)
accepted answer of: http://stackoverflow.com/q/48296726
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83339550
score: 0
comment on: http://stackoverflow.com/a/48179480
type: Comment
has text: @Oakley Would I have to create_window for Frame in the Canvas config? If not then do i attach the scrollbar to frame3 and just configure the Canvas (yscrollcommand=scrollbar.set) ?
type: AnswerComment

http://stackoverflow.com/q/48192535
has comment: http://stackoverflow.com/comment/83389536
score: 0
has comment: http://stackoverflow.com/comment/83388927
has comment: http://stackoverflow.com/comment/83366416
has comment: http://stackoverflow.com/comment/83366596
has comment: http://stackoverflow.com/comment/83366748
has comment: http://stackoverflow.com/comment/83365668
has comment: http://stackoverflow.com/comment/83366102
type: Question
linked to: http://stackoverflow.com/q/22450927
answer count: 0
tagged with: django
tagged with: javascript
type: UnansweredQuestion
has title: Google maps javascripts api with more than 100000 markes
tagged with: python
has comment: http://stackoverflow.com/comment/83376805
tagged with: google-maps-api-3
has body: I have a google maps app in django a try to draw a map with near 200.000 markers, the time to load is around 45 seconds, I want to less it. I use MarkerClusterer for agregattion this markers, but the process spend more time es create the markers. In a static .js, I have: function addMarkers() { add_marker(features) ... (others 200.000 lines)... }(+- 40 MB) It is posible compress it with (django-webpacker)? And in the html file: function add_marker(array){ var marker = new google.maps.Marker({ position: new google.maps.LatLng(lt,lg), map: map, (with others features) }); gmarkers.push(marker); google.maps.event.addListener(marker, 'click', function(){ window.open(...); }); google.maps.event.addListener(marker, 'rightclick', function(){ this.info.open(map, this); }); } Clusterer = new MarkerClusterer(map, gmarkers, options);

http://stackoverflow.com/q/48270395
tagged with: keras
type: Question
tagged with: deep-learning
has title: Solving FizzBuzz with Keras
score: 1
favorite count: 0
has body: I am trying to solve FizzBuzz using Keras and it works quite well for numbers between 1 and 10.000 (90-100% win rate and close to 0 loss). However, if I try even higher numbers, that is numbers between 1 and 100.000 it doesn't seem to perform well (~50% win rate, loss ~0.3). In fact, it performs quite poorly and I have no clue what I can do to solve this task. So far I am using a very simple neural net architecture with 3 hidden layers: model = Sequential() model.add(Dense(2000, input_dim=state_size, activation="relu")) model.add(Dense(1000, activation="relu")) model.add(Dense(500, activation="relu")) model.add(Dense(num_actions, activation="softmax")) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=["accuracy"]) I found that the more neurons I have the better it performs, at least for numbers below 10.000. I am training my neural net in a step-wise fashion, meaning that I am not computing the inputs and targets beforehand, but instead train the network step by step. Again, this works quite well and it shouldn't make a difference right? Here's the main loop: for epoch in range(np_epochs): action = random_number() x_raw = to_binary(action) x = np.expand_dims(x_raw, 0) prediction = model.predict(x) y, victory, _, _ = check_prediction(action, prediction) memory.append((x_raw, y)) curr_batch_size = min(batch_size, len(memory)) batch = random.sample(memory, curr_batch_size) inputs = [] targets = [] for i, t in batch: inputs.append(i) targets.append(t) if victory: wins += 1 loss, accuracy = model.train_on_batch(np.array(inputs), np.array(targets)) As you can see, I am training my network not on decimal numbers but convert them into binary first before feeding it into the net. Another thing to mention here is that I am using a memory, to make it more like a supervised problem. I thought it may perform better if train on numbers that the neural net has already been trained on. It doesn't seem to make any difference at all. Is there anything I can do…
answer count: 0
downvote count: 0
tagged with: fizzbuzz
tagged with: machine-learning
upvote count: 1
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/48253529
has comment: http://stackoverflow.com/comment/83528835
has comment: http://stackoverflow.com/comment/83597535
has comment: http://stackoverflow.com/comment/83556149
answers question: http://stackoverflow.com/q/48251068
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83557081
type: Answer
has comment: http://stackoverflow.com/comment/83538245
has comment: http://stackoverflow.com/comment/83544735
has comment: http://stackoverflow.com/comment/83556214
has body: Even though you have an if statement to ensure that stats from other divisions don't get shown, the for loop counter still increments even when stat.division == division returns False. Consider working out the places in Python, and use that in the template instead of trying to work it out in the template. Here's a possible solution. Python (assuming you have sorted the stats set previously): context = { # ... 'divisions_and_stats': [[division, [stat for stat in stats if stat['division'] == division]] for division in divisions] # ... } Depending on your preference/need, you could use stat.get('division', None) so you don't run into any KeyError exceptions. Template: {% for division, stats in divisions_and_stats %} {{ division }} Place Team Points {% for stat in stats %} {{ forloop.counter }} {{ stat.team }} {{ stat.points }} {% endfor %} {% endfor %}
has comment: http://stackoverflow.com/comment/83545046
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83589094
accepted answer of: http://stackoverflow.com/q/48251068

http://stackoverflow.com/comment/83393492
type: Comment
type: QuestionComment
has text: Possible duplicate of [Keep a application window always on current desktop on linux and mac](https://stackoverflow.com/questions/16775352/keep-a-application-window-always-on-current-desktop-on-linux-and-mac)
score: 0
comment on: http://stackoverflow.com/q/48204226

http://stackoverflow.com/q/48232204
accepted answer: http://stackoverflow.com/a/48232269
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48232254
has comment: http://stackoverflow.com/comment/83446705
score: 0
has answer: http://stackoverflow.com/a/48232269
upvote count: 2
possible better answer: http://stackoverflow.com/a/48232236
has answer: http://stackoverflow.com/a/48232257
downvote count: 2
has answer: http://stackoverflow.com/a/48232236
has title: Match a number that is preceded by 's' and succeeded by '/'
favorite count: 0
type: Question
answer count: 5
has body: I have a list of filenames which are all like so: orl_faces/s22/3.pgm I am trying to extract the number which is preceded by the letter s like so: re.findall(r'\[s][0-9]*','orl_faces/s22/3.pgm') but it is not working, any suggestions?
has answer: http://stackoverflow.com/a/48232280
tagged with: python
tagged with: regex

http://stackoverflow.com/comment/83476604
type: QuestionComment
comment on: http://stackoverflow.com/q/48246810
score: 0
has text: @Balaji.J.B Try checking my [answer](https://stackoverflow.com/a/48246983/1116098). It might solve your problem.
type: Comment

http://stackoverflow.com/comment/83370222
type: AnswerComment
has text: A typo? Shame on me. Apparently, it's all working fine now.
type: Comment
comment on: http://stackoverflow.com/a/48191503
score: 0

http://stackoverflow.com/q/48226041
has comment: http://stackoverflow.com/comment/83447154
score: 5
has answer: http://stackoverflow.com/a/48226309
has answer: http://stackoverflow.com/a/48226509
tagged with: arrays
possible better answer: http://stackoverflow.com/a/48226141
has comment: http://stackoverflow.com/comment/83434823
tagged with: string
downvote count: 1
has answer: http://stackoverflow.com/a/48226141
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48226515
tagged with: python-3.x
has body: Tiddlywiki uses internally a space-separated tags for making a list of tags. But it uses and to limit multi-word tags. That is, a list of foo, ram doo, bar and very cool becomes in tiddlywiki a string like that: "foo ram doo bar very cool" How can I transform that into python list that look like: ['foo', 'ram doo', 'bar', 'very cool'] "foo ram doo bar".split() does not work for me..
has answer: http://stackoverflow.com/a/48226515
tagged with: python
upvote count: 6
answer count: 4
type: AnsweredQuestion
has title: Pass from tiddlywiki list to python list

http://stackoverflow.com/comment/83601862
type: Comment
type: QuestionComment
score: 0
has text: Did you mean `https://pypi.anaconda.org/pypi/simple/flickr-api/`?
comment on: http://stackoverflow.com/q/48308077

http://stackoverflow.com/comment/83417184
type: QuestionComment
comment on: http://stackoverflow.com/q/48217036
score: 0
has text: And what about `pip install pygame` or, if you need 1.9.3 specifically, `pip install pygame==1.9.3`?
type: Comment

http://stackoverflow.com/q/48187790
has answer: http://stackoverflow.com/a/48188089
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has body: I am trying to get a certain value in a string of json but I can't figure out how exactly to do it. I don't want to convert it into a string and strip / replace the unwanted pieces because then I won't be able to get the other values. My current code is: username = "Dextication" url = f"https://minecraft-statistic.net/api/player/info/{username}/" response = requests.get(url) json_data = json.loads(response.text) print(json_data) Edit: when I run this, json.data = "{"status":"ok","data":{"online":0,"total_time_play":46990,"last_play":1513960562,"license":1,"name":"Dextication","uuid":"74d57a754855410c90b3d51bc99b8beb"}}" I would like to only print the value: 46990
has comment: http://stackoverflow.com/comment/83355237
tagged with: http://stackoverflow.com/tag/json
tagged with: python
score: -1
has title: How to get a specific value in a json string in python 3.6
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48188089
upvote count: 0
answer count: 1

http://stackoverflow.com/a/48325537
has comment: http://stackoverflow.com/comment/83636794
score: 3
upvote count: 3
type: Answer
has body: list(Counter(dict(a)).elements()) Demo: &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; a = [(-3.0, 4), (-2.0, 1), (-1.0, 1), (0.0, 1), (1.0, 1), (2.0, 1), (3.0, 4)] &gt;&gt;&gt; list(Counter(dict(a)).elements()) [-3.0, -3.0, -3.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0, 3.0] So if you actually do have a Counter, just ask it for its elements directly.
has comment: http://stackoverflow.com/comment/83636719
answers question: http://stackoverflow.com/q/48325475
has comment: http://stackoverflow.com/comment/83636963
has comment: http://stackoverflow.com/comment/83637058
has comment: http://stackoverflow.com/comment/83636961
has comment: http://stackoverflow.com/comment/83636983
accepted answer of: http://stackoverflow.com/q/48325475
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83636943
has comment: http://stackoverflow.com/comment/83636782
has comment: http://stackoverflow.com/comment/83637164

http://stackoverflow.com/comment/83561311
score: 0
comment on: http://stackoverflow.com/q/48287841
type: QuestionComment
has text: @KyrSt yes, you are right. I commented too soon.
type: Comment

http://stackoverflow.com/comment/113364685
type: AnswerComment
has text: It might be good to include that `format_html` canbe imported with `from django.utils.html import format_html`
score: 0
comment on: http://stackoverflow.com/a/48273675
type: Comment

http://stackoverflow.com/a/48289778
score: 3
upvote count: 3
downvote count: 0
has body: Change the function: def __mul__ (self, other): self.__zaehler *= other self.__nenner *= other to: def __mul__ (self, other): return Bruch(self.__zaehler * other.__zeahler, self.__nenner * other.__nenner) You want to return a new Bruch and not change the current one.
has comment: http://stackoverflow.com/comment/83564643
answers question: http://stackoverflow.com/q/48289565
type: Answer
has comment: http://stackoverflow.com/comment/83564789

http://stackoverflow.com/a/48191073
downvote count: 0
has body: The correct operator to extend a pathlib object is / from pathlib import Path Desktop = Path('Desktop') print(Desktop) # WindowsPath('Desktop') # extend the path to include subdir SubDeskTop = Desktop / "subdir" print(SubDeskTop) # WindowsPath('Desktop/subdir') # passing an absolute path has different behavior SubDeskTop = Path('Desktop') / '/subdir' print(SubDeskTop) # WindowsPath('/subdir') When several absolute paths are given, the last is taken as an anchor (mimicking os.path.join()’s behavior): >>> PurePath('/etc', '/usr', 'lib64') PurePosixPath('/usr/lib64') >>> PureWindowsPath('c:/Windows', 'd:bar') PureWindowsPath('d:bar') In a Windows path, changing the local root doesn’t discard the previous drive setting: >>> PureWindowsPath('c:/Windows', '/Program Files') PureWindowsPath('c:/Program Files') Refer to the documentation for addition details pertaining to giving an absolute path, such as Path('/subdir'). Resources: pathlib Basic use Python 3's pathlib Module: Taming the File System
answers question: http://stackoverflow.com/q/48190959
upvote count: 150
has comment: http://stackoverflow.com/comment/133757740
score: 150
type: Answer
accepted answer of: http://stackoverflow.com/q/48190959
type: AcceptedAnswer

http://stackoverflow.com/comment/83360885
score: 0
comment on: http://stackoverflow.com/q/48190255
has text: Without chaining it will give empty queryset.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48289610
type: AnsweredQuestion
tagged with: pandas-groupby
answer count: 3
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/48289715
possible better answer: http://stackoverflow.com/a/48289715
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83564399
has comment: http://stackoverflow.com/comment/83568412
has answer: http://stackoverflow.com/a/48289714
accepted answer: http://stackoverflow.com/a/48289714
has comment: http://stackoverflow.com/comment/83568294
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48289761
has title: Pandas group to others
tagged with: python
has body: I have a question about the syntax for grouping "other". For example, df Type Start End Count Total A x a 1 3 A x b 1 3 A x c 1 3 A y A 2 4 A y b 1 4 A y c 1 4 B x A 1 6 B x b 2 6 B x c 3 6 B y a 3 6 B y b 2 6 B y c 1 6 Group by Type/Start/End columns, if End doesn't contain "a" or "A" then label them as "other" Type Start End Count Total A x a 1 3 A x other 2 3 A y A 2 4 A y other 2 4 B x A 1 6 B x other 5 6 B y a 3 6 B y other 3 6

http://stackoverflow.com/comment/83462000
type: AnswerComment
score: 1
has text: @Max You must reset w to 0 after leaving internal `while`
type: Comment
comment on: http://stackoverflow.com/a/48239768

http://stackoverflow.com/q/48269471
has answer: http://stackoverflow.com/a/48269557
tagged with: python
accepted answer: http://stackoverflow.com/a/51109051
possible better answer: http://stackoverflow.com/a/51053108
has answer: http://stackoverflow.com/a/51109051
has comment: http://stackoverflow.com/comment/83525120
tagged with: optimization
has comment: http://stackoverflow.com/comment/83523595
has comment: http://stackoverflow.com/comment/83522569
has comment: http://stackoverflow.com/comment/83523293
upvote count: 2
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/83523920
answer count: 3
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83522988
tagged with: computer-science
has answer: http://stackoverflow.com/a/51053108
has body: Problem: You are given a list(1-D array) of scores(some numbers). You are given two more lists: lowerLimits : A list that contains lower limit value(s) upperLimits : A list that contains upper limit value(s) Your task is to find out how many counts of scores fall within the inclusive range of each (lowerLimit[i], upperLimit[i]) pair. Example 1: Inputs: scores = [1,3,5,6,8] lowerLimits = [2] upperLimits = [6] Output:[3] Explanation: Three elements(3,5 and 6) in scores array, fall inside the inclusive range [2,6] Example 2: Inputs: scores = [4,8,7] lowerLimits = [2,4] upperLimits = [8,4] Output: [3,1] Explanation: All three elements(4,8 and 7) in scores array, fall inside the first inclusive range [2,8] and only one element (4) falls within the inclusive range of [4,4]. So the answer to be returned is the counts array [3,1]. What algorithm have I attempted so far? 1. Iterate through each lowerLimit - upperLimit pair 2. For this pair check all scores values 3. Repeat step 1 to 2 for all lowerLimit - upperLimit pairs Python 3 Implementation # utility function def jobOffers(scores, lowerLimits, upperLimits): answer = [] for index, item in enumerate(lowerLimits): dummy = [] for score in scores: if score &gt;= lowerLimits[index] and score &lt;= upperLimits[index]: dummy.append(score) if dummy: answer.append(len(dummy)) return answer # dummy inputs scores = [4,8,7] lowerLimits = [2,4] upperLimits = [8,4] print(jobOffers(scores,lowerLimits,upperLimits)) Problem: I can only pass 3 out of 15 test cases with this brute-force algorithm. In fact, the code times out for about 7 test cases and returns incorrect result for the remaining failed test cases. Unfortunately, the server doesn't provide the list of failed test cases, so I can't accommodate logic for such cases. At present, I'm unable to think of any alternate strategy to tackle this problem. Could
type: Question
tagged with: algorithm
has title: Optimize algorithm for determining qualifying score from a predefined range

http://stackoverflow.com/q/48258994
tagged with: pandas
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: matplotlib
has body: apple is a dataframe whose data structure is as the below: apple Date Open High Low Close Adj Close 0 2017-01-03 115.800003 116.330002 114.760002 116.150002 114.311760 1 2017-01-04 115.849998 116.510002 115.750000 116.019997 114.183815 2 2017-01-05 115.919998 116.860001 115.809998 116.610001 114.764473 3 2017-01-06 116.779999 118.160004 116.470001 117.910004 116.043915 4 2017-01-09 117.949997 119.430000 117.940002 118.989998 117.106812 5 2017-01-10 118.769997 119.379997 118.300003 119.110001 117.224907 6 2017-01-11 118.739998 119.930000 118.599998 119.750000 117.854782 7 2017-01-12 118.900002 119.300003 118.209999 119.250000 117.362694 8 2017-01-13 119.110001 119.620003 118.809998 119.040001 117.156021 9 2017-01-17 118.339996 120.239998 118.220001 120.000000 118.100822 Now i want to select two columns Date and Close ,to set Date as x axis and Close as y axis,how to plot it? import pandas as pd import matplotlib.pyplot as plt x=pd.DataFrame({'key':apple['Date'],'data':apple['Close']}) x.plot() plt.show() I got the graph such as below. The x axis is not Date column !
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48259004
downvote count: 0
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/48259004
has title: How to select two columns to plot with dataframe?
answer count: 1
tagged with: plot

http://stackoverflow.com/comment/83410085
comment on: http://stackoverflow.com/q/48190726
type: QuestionComment
has text: The reason is twofold: The software ingesting those CSV is buggy and ingest empty lines as new lines, also it's simply because even in some theoretical way, there's more lines than there should be (when we count the extra empty line)
score: 0
type: Comment

http://stackoverflow.com/comment/101853664
type: AnswerComment
has text: num_classes=0 is not applicable for v1.3.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50535359

http://stackoverflow.com/comment/84462264
score: 0
has text: @ Daniel Möller One more question, what if I do not have "y_org" and just want to maximize "output = Subtract()([output1,output2])"? which will fail to use "pairWiseModel.fit([x1,x2],y,...)" since I do not have "y" now...then how should I train the model?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48225470

http://stackoverflow.com/comment/83642787
comment on: http://stackoverflow.com/a/48328072
type: Comment
score: 0
type: AnswerComment
has text: Hm, note that it's the first time you mention the shape `[2, 50, 50, 50, 100]`. Finally, I understand your question. The solution is absolutely the same - call the `transconv3d_layer` 2 or more times with `out_shape`s you want.

http://stackoverflow.com/a/48305218
accepted answer of: http://stackoverflow.com/q/48304723
score: 2
type: Answer
has body: If I've understood what you're asking, you could use while loops. Have it periodically check the current time with the times for the shift beginning and end. Below is a guide of what I mean, but I'm not sure the comparisons will work. from time import sleep def start(): time_periods = working_periods_table.find_all() today = datetime.datetime.now().isoweekday() for day in time_periods: if day["day"] == today: start_time = day["work_start_at"] end_time = day["work_end_at"] while True: if datetime.datetime.now() &gt;= start_time: while True: schedule.every().week.at(start_time).do(record_activity(idle_time=300)) if datetime.datetime.now() &gt;= end_time: break break else: sleep(100)
upvote count: 2
answers question: http://stackoverflow.com/q/48304723
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83414781
score: 4
type: Comment
has text: Pandas is smart: `pd.to_datetime(df['A'])`
type: QuestionComment
comment on: http://stackoverflow.com/q/48216417

http://stackoverflow.com/comment/83563706
type: QuestionComment
comment on: http://stackoverflow.com/q/48288366
score: 1
has text: Do you mean inverse transform sampling? https://stackoverflow.com/questions/21100716/fast-arbitrary-distribution-random-sampling
type: Comment

http://stackoverflow.com/comment/83587086
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48300303
score: 0
has text: this for the loop, I paste code with some of loop recognition, whole code is for parsing data from websites

http://stackoverflow.com/a/48329818
downvote count: 0
answers question: http://stackoverflow.com/q/48329219
has body: You should use post generation hook: @factory.post_generation def items(self, create, extracted, **kwargs): if not create: return if extracted: for item in extracted: self.items.add(item)
score: 1
type: Answer
upvote count: 1

http://stackoverflow.com/comment/83634156
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48324228
has text: So for each iteration of the inner loop you want give a result to the outer loop?
score: 0

http://stackoverflow.com/a/48287489
has comment: http://stackoverflow.com/comment/83820673
answers question: http://stackoverflow.com/q/48272799
has comment: http://stackoverflow.com/comment/83580470
score: 1
has comment: http://stackoverflow.com/comment/83571707
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83820676
upvote count: 1
has comment: http://stackoverflow.com/comment/83614447
has comment: http://stackoverflow.com/comment/83567294
has comment: http://stackoverflow.com/comment/83567774
has comment: http://stackoverflow.com/comment/83614482
type: Answer
has body: I don't have access to the TomTom API, so I can't run all your code as posted, but I did have a look at the XML string you posted. Below is some code I used to extract the individual "leg" elements and process them. I've just printed them as text (could save them to file instead), and also extracted specific children and printed them. It's not clear from your question exactly what you wanted to do with the data, but maybe this gives you a starting point to work from. from lxml import etree import urllib.request xml = '<calculateRouteResponse xmlns="http://api.tomtom.com/routing" formatVersion="0.0.12">\ ... \ ... \ \ \ 5144 \ 687 \ 0 \ 2018-01-16T11:16:06+11:00 \ 2018-01-16T11:27:33+11:00 \ <noTrafficTravelTimeInSeconds>478</noTrafficTravelTimeInSeconds>\ <historicTrafficTravelTimeInSeconds>687</historicTrafficTravelTimeInSeconds>\ <liveTrafficIncidentsTravelTimeInSeconds>687</liveTrafficIncidentsTravelTimeInSeconds>\ \ \ \ 806 \ 68 \ 0 \ 2018-01-16T11:16:06+11:00 \ 2018-01-16T11:17:14+11:00 \ <noTrafficTravelTimeInSeconds>59</noTrafficTravelTimeInSeconds>\ <historicTrafficTravelTimeInSeconds>68</historicTrafficTravelTimeInSeconds>\ <liveTrafficIncidentsTravelTimeInSeconds>68</liveTrafficIncidentsTravelTimeInSeconds>\ \ ... \ \ \ \ 958 \ 114 \ 0 \ 2018-01-16T11:17:14+11:00 \ 2018-01-16T11:19:08+11:00 \ <noTrafficTravelTimeInSeconds>77</noTrafficTravelTimeInSeconds>\ <historicTrafficTravelTimeInSeconds>114</historicTrafficTravelTimeInSeconds>\ <liveTrafficIncidentsTravelTimeInSeconds>114</liveTrafficIncidentsTravelTimeInSeconds>\ \ ... \ \ \ \ 1798 \ 224 \ 0 \ 2018-01-16T11:19:08+11:00 \ 2018-01-16T11:22:53+11:00 \ <noTrafficTravelTimeInSeconds>181</noTrafficTravelTimeInSeconds>\ <historicTrafficTravelTimeInSeconds>224</historicTrafficTravelTimeInSeconds>\ <liveTrafficIncidentsTravelTimeInSeconds>224</liveTrafficIncidentsTravelTimeInSeconds>\ \ ... \ \ \ \ 1582 \ 280 \ 0 \ 2018-01-16T11:22:53+11:00 \ 2018-01-16T11:27:33+11:00 \ <noTrafficTravelTimeInSeconds>160</noTr…
accepted answer of: http://stackoverflow.com/q/48272799

http://stackoverflow.com/q/48325302
tagged with: redux-saga
type: Question
accepted answer: http://stackoverflow.com/a/48325847
has comment: http://stackoverflow.com/comment/83636598
has answer: http://stackoverflow.com/a/48325847
tagged with: python
linked to: http://stackoverflow.com/q/41340027
has title: Uncaught TypeError: Super expression must either be null or a function
has body: So I'm new to React and even though I've found multiple others having the same issue, I still haven't found the error in my code. Therefore I turn to you stackoverflow, you're my only hope! I am learning, so I wanted to create a simple ReactJS application that handles a HTTP-request. After finishing the code I encountered the error: Uncaught TypeError: Super expression must either be null or a function, not object at exports.default (inherits.js?0578:21) at eval (app.js?71f7:22) The error persists even though I've tried a lot of different changes and I am fairly certain that it's related to imports/exports as this is what a lot of other sources tell me, although double-checking imports etc. hasn't yielded any results. The code: app.js ( handles the rendering of a simple button and should execute a simple GET request on click ) import React, { Component } from 'react' import { connect } from 'react-redux' import { createServerSagaRequest } from '../saga/serverSaga' import { incrRequestAmount, requestSelector } from '../reducer/requestReducer' const mapStateToProps = (state) =&gt; { return { getRequestAmount: requestSelector.requests(state), } } const mapDispatchToProps = (dispatch) =&gt; { return { open: (url, data, action, method) =&gt; dispatch(createServerSagaRequest((url, data, action, method))), requests: () =&gt; dispatch(incrRequestAmount()), } } class App extends React { constructor(props){ super(props) } _buttonClick() { this.props.requests() this.props.open("http://mvctestproject.local/GetData", "TestDataFraGet", action, "GET") } render(){ return ( &lt;button className="btn btn-default" onClick={this._buttonClick()}&gt;{this.props.getRequestAmount()} &lt;/button&gt; ) } } export default connect(mapStateToProps, mapDispatchToProps)(App) serverSaga.js (my saga which can access the reducer and service) import React, { Component } from 'react' import { put, call, take, fork, select } from 'redux-saga/effects' import { callServer } from '../service/serverService…
type: AnsweredQuestion
tagged with: ecmascript-6
tagged with: react-redux
tagged with: reactjs
score: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/41340027
has comment: http://stackoverflow.com/comment/83636130

http://stackoverflow.com/comment/83599723
has text: Have you tried anything that didn't work?
comment on: http://stackoverflow.com/q/48307163
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/83646945
type: Comment
type: QuestionComment
has text: @hoefling Ah, pytest-runner seems to do what I need. If you can write your reply as a short formal answer I'll accept it.
comment on: http://stackoverflow.com/q/48330471
score: 0

http://stackoverflow.com/comment/83416638
type: Comment
score: 0
type: AnswerComment
has text: @sadAndClueless72 my fault, the bar plot doesn't return `axe`, I edited.
comment on: http://stackoverflow.com/a/48216957

http://stackoverflow.com/comment/83585774
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48300157
has text: A filter will not "override the field render method", but it can process the string returned by the field's rendering. Also note that you can do most of the rendering manually cf https://simpleisbetterthancomplex.com/article/2017/08/19/how-to-render-django-form-manually.html#expanding-the-form-fields
score: 0

http://stackoverflow.com/a/48241255
type: Answer
answers question: http://stackoverflow.com/q/48241196
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83464935
has comment: http://stackoverflow.com/comment/83465835
has body: It's pretty much impossible to answer this question without documentation on the endpoint that you're calling. A 400 normally means there is something wrong with the format of the request. One possibility would be that you're trying to send a Python dictionary when it should probably be stringified JSON, or you should use the json parameter instead. Using json parameter: r = requests.post("http://tupodomen.info/api/login", json={'username': '&lt;login&gt;', 'password': '&lt;password&gt;'}, headers={'content-type': 'application/x-www-form-urlencoded'}) Stringified data: r = requests.post("http://tupodomen.info/api/login", data=json.dumps({'username': '&lt;login&gt;', 'password': '&lt;password&gt;'}), headers={'content-type': 'application/x-www-form-urlencoded'})
has comment: http://stackoverflow.com/comment/83466200
score: 1
accepted answer of: http://stackoverflow.com/q/48241196
has comment: http://stackoverflow.com/comment/83464889

http://stackoverflow.com/q/48288140
answer count: 0
has body: In the algorithm I have a main loop in the form: for i in itertools.product(range(2), repeat=4): # do something on"i" The results from the whole loop arise recursively. This means that the result from the first step affects the result of the second step, the result from the second step affects the result of the third step, and so on. Can multiprocessing be used with such an algorithm construction?
tagged with: python-itertools
type: UnansweredQuestion
upvote count: 1
has title: How to combine itertools.product and multiprocessing?
has comment: http://stackoverflow.com/comment/83562954
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83562733
tagged with: parallel-processing
score: 0
tagged with: python
tagged with: multiprocessing
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/83565070
comment on: http://stackoverflow.com/a/48288529
score: 0
type: AnswerComment
has text: Original min and max are 0 and 255 but are scaled to 0-1 in preprocessing.
type: Comment

http://stackoverflow.com/comment/83573017
has text: Could not create resource url and bytes like object is required not 'None-type'. Error 400 has disappeared though :S
comment on: http://stackoverflow.com/a/48293568
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83618205
type: QuestionComment
comment on: http://stackoverflow.com/q/48289385
has text: thank you for your suggestion
score: 0
type: Comment

http://stackoverflow.com/comment/83456973
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48237162
has text: Remove the line `from random import *` or use only `randint`.
type: QuestionComment

time
tags question: http://stackoverflow.com/q/48176949
tags question: http://stackoverflow.com/q/48264056
tags question: http://stackoverflow.com/q/48328382
tags question: http://stackoverflow.com/q/48268130
tags question: http://stackoverflow.com/q/48202117
type: Tag
tags question: http://stackoverflow.com/q/48230473
tag name: time
tags question: http://stackoverflow.com/q/48313021
tags question: http://stackoverflow.com/q/48242145
tags question: http://stackoverflow.com/q/48196000
tags question: http://stackoverflow.com/q/48269859
tags question: http://stackoverflow.com/q/48253740

http://stackoverflow.com/comment/83449580
type: Comment
type: AnswerComment
has text: No, I was just giving you a little alternative to your code, which uses a temp variable to swap :) (since in python, you can swap without a temp variable).
comment on: http://stackoverflow.com/a/48233479
score: 1

http://stackoverflow.com/a/48261426
has comment: http://stackoverflow.com/comment/83507796
has comment: http://stackoverflow.com/comment/83507081
type: Answer
has body: If you have to handle a computation heavy process in your Gui while allowing the rest to run you can just multi-process: import multiprocess as mp def OnButtonClick(bid): mp.Process(target=Power_On_Off,args=('1',('Off','On')[bid-1])).start() Answers to comments mp.Process defines a Process object. Once I .start() it the process will call the function in target, with arguments args. You can see the use here for example. You can of course separate, and pass each id on with different on off choices. I implemented what you wrote. No need for a queue here if I just want it to run and do something while I continue clicking my buttons. Your problem was that the button is not released until action ends. By delegating the action to a different process you can return immediately, thus allowing the button to raise. Your problem isn't really "button isn't rising fast enough". Rather it's the Gui is stuck until Power_On_Off completes. If I run that function in a different process, then my Gui won't be stuck for any noticeable time. If you want something in the main process to happen when the other process ends, you may need to keep the Process in some sort of list for future pinging. Otherwise, this is fine.
has comment: http://stackoverflow.com/comment/83506481
accepted answer of: http://stackoverflow.com/q/48259089
score: 0
has comment: http://stackoverflow.com/comment/83506234
has comment: http://stackoverflow.com/comment/83507118
answers question: http://stackoverflow.com/q/48259089
type: AcceptedAnswer
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/83633993
type: AnswerComment
comment on: http://stackoverflow.com/a/48291167
has text: Thanks, I accepted, but my karma's currently too low for upvotes to appear. Cheers!
score: 0
type: Comment

http://stackoverflow.com/comment/83570890
comment on: http://stackoverflow.com/a/48292495
type: Comment
score: 0
type: AnswerComment
has text: Are you trying to iterate through an EmployeeProfile object? You shouldn't need to do that if there is only one object.

http://stackoverflow.com/a/71413711
type: Answer
has body: I use this function to auto white balance images. Unlike Gimp function, it does not normalize image contrast. So it is useful with low contrast images too. import numpy as np from imageio import imread import matplotlib.pyplot as plt def auto_white_balance(im, p=.6): '''Stretch each channel histogram to same percentile as mean.''' # get mean values p0, p1 = np.percentile(im, p), np.percentile(im, 100-p) for i in range(3): ch = im[:,:,i] # get channel values pc0, pc1 = np.percentile(ch, p), np.percentile(ch, 100-p) # stretch channel to same range as mean ch = (p1 - p0) * (ch - pc0) / (pc1 - pc0) + p0 im[:,:,i] = ch return im def test(): im = imread('imageio:astronaut.png') # distort white balance im[:,:,0] = im[:,:,0] *.6 im[:,:,1] = im[:,:,1] *.8 plt.imshow(im) plt.show() im2 = auto_white_balance(im) im2 = np.clip(im2, 0, 255) # or 0, 1 for float images plt.imshow(im2) plt.show() if __name__ == &quot;__main__&quot;: test() If you want equivalent of Gimp function, use fixed values instead: p0, p1 = 0, 255
answers question: http://stackoverflow.com/q/48268068
score: 0

http://stackoverflow.com/comment/83464774
has text: it shows 2.1.0.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48240792
score: 0

http://stackoverflow.com/comment/83489131
type: Comment
score: 0
has text: @at14 Thank you! I've deleted the init files and now i got this ugly error :(
type: QuestionComment
comment on: http://stackoverflow.com/q/48253070

http://stackoverflow.com/a/48316638
score: -1
answers question: http://stackoverflow.com/q/48316370
downvote count: 1
type: Answer
has body: with pandas &gt;&gt;&gt; (pd.Series([5, 8, 2, 7, 8, 8, 2, 4]) == 8).nonzero() (array([1, 4, 5], dtype=int64),)
upvote count: 0
has comment: http://stackoverflow.com/comment/83619118

http://stackoverflow.com/comment/83487884
type: Comment
has text: Ok sure but why does adding 8.7 and 4.1 results in a repeating number and the others don't ? what's so special about them
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48252663

http://stackoverflow.com/comment/83442805
has text: Fixed. Was another view class. With old variable. Unfortunately, none of the variables are being saved with the test GET parameters. Example: http://127.0.0.1:8000/payment/webhook/?clientAccnum=900&clientSubacc=123 I used print (hook.client_acc_num, hook.client_sub_acc, hook.time_stamp_local) to debug in the console and it clearly shows the variables are pulled from the URL.
comment on: http://stackoverflow.com/a/48229937
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48250051
answers question: http://stackoverflow.com/q/48250037
score: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48250037
has body: This is fine. Modules are just objects, just like everything else in Python. It's not by accident that this works, it is by design, Python does try to be consistent in naming, so functions that deserialise data are generally called load. See marshal.load() for another example. Or yaml.load(). If you want to make it more generic still, you can store the load function references: def read_data(filename, deserialize) with open(filename, 'r') as infile: data = deserialize(infile) return data data1 = read_data('file.pickle', pickle.load) data2 = read_data('file.json', json.load) Functions are just objects too, after all, and now you made your function independent of the name of the callable.
upvote count: 5
type: Answer

http://stackoverflow.com/q/48272497
answer count: 0
has title: How to restore tensorflow model once but use multiple times?
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/83572885
type: Question
has comment: http://stackoverflow.com/comment/83530993
type: UnansweredQuestion
tagged with: python
has body: I would like to be able to restore a tensorflow model once in my program, but use it for multiple inputs. Currently I have for i in range(100): with tf.Session() as sess: saver.restore(sess, 'C:/model.ckpt') y_pred = sess.run(tf.argmax(y, 1), feed_dict={X: test_current} However, I would like to be able to do something like with tf.Session() as sess: saver.restore(sess, 'C:/model.ckpt') for i in range(100): y_pred = sess.run(tf.argmax(y, 1), feed_dict={X: test_current} But I get an error, if I type that so could I get some help?
score: 0

http://stackoverflow.com/q/48329685
answer count: 2
has title: How can I force django to restart a database connection from the shell?
tagged with: django
upvote count: 32
tagged with: python
score: 31
has answer: http://stackoverflow.com/a/50694172
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/62632743
accepted answer: http://stackoverflow.com/a/50694172
downvote count: 1
has answer: http://stackoverflow.com/a/62632743
favorite count: 0
has body: I have a django project on a remote server. From my local machine, I connect to the database through ssh: ssh -L 63333:localhost:5432 me@my.server And change my local settings.py as: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': 63333 } } And on a Jupyter QtConsole on my local machine, I follow these steps for setup: import os import django os.chdir('/path/to/my/project') os.environ['DJANGO_SETTINGS_MODULE'] = 'my_project.settings' django.setup() It all works fine until my ssh connection is broken by some reason. First I get this error (on a line that queries the database, say, my_model.objects.first()): DatabaseErrorTraceback (most recent call last) /home/ayhan/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args) 84 else: ---&gt; 85 return self.cursor.execute(sql, params) 86 DatabaseError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. When I reconnect through ssh, I keep getting the following error: InterfaceErrorTraceback (most recent call last) /home/ayhan/anaconda3/lib/python3.6/site-packages/django/db/backends/base/base.py in _cursor(self, name) 233 with self.wrap_database_errors: --&gt; 234 return self._prepare_cursor(self.create_cursor(name)) 235 /home/ayhan/anaconda3/lib/python3.6/site-packages/django/db/backends/postgresql/base.py in create_cursor(self, name) 211 else: --&gt; 212 cursor = self.connection.cursor() 213 cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None InterfaceError: connection already closed The error only goes away if I restart the IPython kernel. I tried executing the same steps for the setup. I also tried from importlib import reload; reload(django) and then doing the setup again but it gives the same error no matter what. Sometimes this happens while I have varia…
type: Question

http://stackoverflow.com/a/48191658
has body: This should do the trick # code for fries fries_polygons = [ (150, 100, 160, 250, 170, 250, 160, 80), (160, 100, 170, 250, 180, 250, 170, 80), (170, 100, 180, 250, 190, 250, 180, 80), (180, 100, 190, 250, 200, 250, 190, 80), (190, 100, 200, 250, 210, 250, 200, 80), (200, 100, 210, 250, 220, 250, 210, 80), (210, 100, 220, 250, 230, 250, 220, 80), (220, 100, 230, 250, 240, 250, 230, 80), (230, 100, 240, 250, 250, 250, 240, 80), (240, 100, 250, 250, 260, 250, 250, 80), (250, 100, 260, 250, 270, 250, 260, 80), (260, 100, 270, 250, 280, 250, 270, 80), ] for fry in fries_polygons: canvas.create_polygon(*fry, fill='yellow', outline='black') You can read here about the *-operator that is used to unpack arbitrary list arguments.
type: Answer
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/48191375
downvote count: 0
has comment: http://stackoverflow.com/comment/83363693

http://stackoverflow.com/q/48239310
has comment: http://stackoverflow.com/comment/83461206
tagged with: python-2.7
has title: Need to copy files into subfolder
has comment: http://stackoverflow.com/comment/83460921
has answer: http://stackoverflow.com/a/48239664
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/83461143
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
score: -3
has body: I want to copy a particular number of files from one folders subdirectory to another folders subdirectory, I have tried with below code but it is not working properly. import os import shutil def copy_files_to(src, dest): dirList = os.listdir(src) for folder in dirList: files_in_folder = os.listdir(src + folder) for f in files_in_folder: source_files = src + folder + '\\' + f if not os.path.exists(dest): os.mkdir(dest) shutil.copy(source_files, dest) copy_files_to("\\src", "\\dest") please help on this. I want to only copy only 30 files to the destination folder, not all files.
tagged with: python

http://stackoverflow.com/q/48214293
tagged with: rdd
has title: is there a way to convert an rdd to df ignoring lines that don't fit the schema?
has comment: http://stackoverflow.com/comment/83416725
type: Question
accepted answer: http://stackoverflow.com/a/48224507
has comment: http://stackoverflow.com/comment/83413373
has body: I have a large file of jsons (can't post any, sorry for that) varying in number of keys and datatype of values of identical keys as well - is there a way to put all the lines that follow a schema (hard-coded or inferred) into a dataframe and leave all the lines that don't fit the schema in an rdd? Eventually, I would like to iterate through such a process and get a couple of df's each one with its own schema at the end. here is a close to reality example: a = 'aaa', 'bbb', 'ccc'*22 b ='aaa', 'bbb', 'ccc', 'ddd'*22 rdd_1 = sc.parallelize(a+b) rdd_1.toDF().show(30) this fails with: Caused by: java.lang.IllegalStateException: Input row doesn't have expected number of values required by the schema. 3 fields are required while 4 values are provided. In this specific case I could form a function that adds null in case of less than max fields, but I'm after a more generic try and except method that could tackle nested data with unpredictable schema changes. any ideas would be very much appreciated.
tagged with: apache-spark
has answer: http://stackoverflow.com/a/48224507
score: 0
answer count: 1
type: AnsweredQuestion
tagged with: apache-spark-sql
tagged with: pyspark
tagged with: python

http://stackoverflow.com/a/48229015
score: 0
accepted answer of: http://stackoverflow.com/q/48228924
has comment: http://stackoverflow.com/comment/83443211
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83443633
has comment: http://stackoverflow.com/comment/83441410
has comment: http://stackoverflow.com/comment/83440225
has body: A very crude and dirty way of doing...since the length of your list is fixed this code will work without issue... report_dict = {} for root, dirs, reports in os.walk(assembly_report_dir): for report in reports: accession = '_'.join(report.strip().split('/')[-1].replace('_assembly_report.txt', '').split('_')[0:2]) path = os.path.join(assembly_report_dir, report) # path = the name of the genbank with the complete path to it with open(path, 'r') as inputfile: lines = inputfile.readlines() MAX_LENGTH = 3 description = ['null' for x in range(MAX_LENGTH)] for line in lines: if line.startswith('Organism name: '): organism = line.strip().split(': ')[-1].split(' (', 1)[0] species = ' '.join(organism.split(' ')[0:2]) description[0] = str(species) elif line.startswith('Infraspecific name: strain='): strain = line.strip().replace(' ','').split('strain=')[-1] description[1] = str(strain) elif line.startswith('Assembly name: '): assembly = line.strip().split(': ')[-1] description[2] = str(assembly) report_dict[accession] = description print report_dict
has comment: http://stackoverflow.com/comment/83440048
has comment: http://stackoverflow.com/comment/83441527
type: Answer
answers question: http://stackoverflow.com/q/48228924
has comment: http://stackoverflow.com/comment/83443806

http://stackoverflow.com/q/48261358
has body: I have following dataframe : p p_loc s s0 s0_loc s1 s1_loc s2 s2_loc s3 s3_loc 0 ABCD M AB,AC,AD AB A AC M AD Q NaN U 1 PQRS N PQ,PR,PS,QR PQ B PR N PS R QR V I'm splitting column s into columns s0,s1,s2,s3 using , as delimeter. I want to pass values from s0,s1,s2,s3,s4,s5,s0_loc,s1_loc,s2_loc,s3_loc to following function which accepts following arguments: def func(p,p_loc,**args): print(p) print(p_loc) print(kwargs) I'm passing arguments as follows: df['new'] = df.apply(lambda x: func(df['p'],df['p_loc'],df['s0'],df['s1'],df['s2'],df['s3'],df['s0_loc'],df['s1_loc'],df['s2_loc'],df['s3_loc'])) I want to know is there any simpler way to pass these arguments(Say, suppose my split of column s results in more than 15-20 columns.. How can I pass these many arguments in a simpler way)...??? Thanks in advance...
has answer: http://stackoverflow.com/a/48261961
accepted answer: http://stackoverflow.com/a/48261961
tagged with: dataframe
tagged with: python
has title: How to pass large number arguments to **kwargs
score: 2
has answer: http://stackoverflow.com/a/48261483
upvote count: 2
possible better answer: http://stackoverflow.com/a/48261483
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83505458
answer count: 3
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/83506152
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48261522

http://stackoverflow.com/a/48263858
type: Answer
answers question: http://stackoverflow.com/q/48263314
has comment: http://stackoverflow.com/comment/83575499
has comment: http://stackoverflow.com/comment/83536964
has body: This should work using diff, Timedelta and indexing: data.Timestamp = pd.to_datetime(data.Timestamp) timediff = pd.Timedelta(minutes=10) #Specify the ammount of time you want to add #diff() here returns a series where the value for #each row is the difference between this row and the previous row mask = data.Timestamp.diff() &gt; timediff #if there are more than 1 consecutive +10 mins different #the latter value will update on the updated previous values while mask.any(): #The following is just one way for assigning the values which has #+10 min difference to the previous value + 10 mins data.loc[mask,'Timestamp'] = (data.iloc[data.loc[mask].index-1].Timestamp + timediff).values #update the mask mask = data.Timestamp.diff() &gt; timediff
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83536307
score: 0
accepted answer of: http://stackoverflow.com/q/48263314
has comment: http://stackoverflow.com/comment/83582018

http://stackoverflow.com/comment/83527841
score: 0
has text: You can try streaming the results instead of generating a response in memory *then* serving it
type: QuestionComment
comment on: http://stackoverflow.com/q/48271573
type: Comment

http://stackoverflow.com/q/48315921
has comment: http://stackoverflow.com/comment/83617436
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48316172
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/83617974
downvote count: 2
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48316172
has answer: http://stackoverflow.com/a/48315995
possible better answer: http://stackoverflow.com/a/48315995
upvote count: 1
has title: Two dicts One Val
score: -1
has body: I am using python 3.5, please explain result of code: dict1={} dict1['a']= 'one %s two' dict2=dict1 print(dict1) dict2['a']=dict1['a'] % 'less than' # changing one of dict2 values, print(dict1) # but also changes dict 1 value # with same key why after this code dict1['a'] value becomes 'one less than two'?

http://stackoverflow.com/q/48258463
tagged with: python
has comment: http://stackoverflow.com/comment/83501125
score: 0
has comment: http://stackoverflow.com/comment/83519063
has body: Hey im using eclipse and i have the pydev plugin and am currently using python to write programs but for some reason there is no syntax highlighting. I just installed all this as of january 7th 2018. so everything is the new version but i have tried so many things from changing colors to installing themes but there is no syntax highlighting. all the text is just the same color which makes it a lot more difficult for me so any solutions?
answer count: 1
tagged with: eclipse
type: Question
tagged with: pydev
has title: Why isnt there syntax highlighting when i code
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48260980

http://stackoverflow.com/a/48217900
type: AcceptedAnswer
downvote count: 0
has body: If your blue curves show your initial output y and your orange ones the output of your model (you have not cared to clarify this...), then there is nothing strange here... There is problem with maximum values prediction Looking more carefully at your code, you will realize that you don't actually feed your initial y into your network, but its scaled version, i.e. the result of sc.transform(); hence, your output is also scaled, and you should use the inverse_transform method to get it back to the initial scale: y_final = sc.inverse_transform(y_pred) BTW, this will happen to work now, but in general it is not a good idea to use the same scaler (sc here) for two different datasets (i.e. your X's and y's) - you should define two different scalers instead, say sc_X and sc_y. There are no negative values That is because the sigmoid function you have used as activation in your output layer takes only positive values in [0, 1], so you may want to change it to something else that will be able to give the required value range (linear is a candidate), and possibly also change your other sigmoids to tanh.
accepted answer of: http://stackoverflow.com/q/48216574
score: 3
type: Answer
answers question: http://stackoverflow.com/q/48216574
upvote count: 3

http://stackoverflow.com/comment/99217397
type: AnswerComment
comment on: http://stackoverflow.com/a/48251455
has text: I am using get_ticklabels() fxn on the x-axis list but it is saying AttribueError as list doesn't support any fxn. So what to do now ?
type: Comment
score: 0

http://stackoverflow.com/comment/132321033
score: 0
has text: @AzharKhan I edited my response specifying more about the process. Hope it helps in some way!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/74981391

http://stackoverflow.com/comment/83455336
comment on: http://stackoverflow.com/q/48236181
has text: @sytech He did, see the traceback. Flag for dupe?
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83507551
has text: You don't want to pass column `s` at all?
comment on: http://stackoverflow.com/a/48261961
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48197363
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48181275
has body: Ensure you are instantiating a Web3 object as mentioned in the quickstart docs before calling into web3.eth.getBlock to setup the eth module functions. from web3 import Web3, TestRPCProvider w3 = Web3(TestRPCProvider()) A look at the code for web3.eth shows us that class Eth(Module): contains def getBlock. If you also look at the definition of Module, you see see that the attach function is used to actually redefine web3.eth with the behavior you want. The attach function is normally called in the web3/main.py: for module_name, module_class in modules.items(): module_class.attach(self, module_name) Note in one of the loops above the module_class is Eth and module_name is "eth". You are likely missing this logic, so ensure you are instantiating a Web3 object before calling into web3.eth.getBlock.
downvote count: 0
type: Answer

http://stackoverflow.com/q/48242213
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83466794
has title: Python with turtle, move turtle from one spot to another
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83466937
has comment: http://stackoverflow.com/comment/83468482
has answer: http://stackoverflow.com/a/48246958
tagged with: turtle-graphics
upvote count: 0
has body: It's a really simple question, though I didn't find a solution. I want that when the turtle reaches a certain position, I use a command to move it to another position. The command I use is: while turtle.xcor() and turtle.ycor() == **: turtle.goto() But it seems it doesn't work...
type: UnansweredQuestion

http://stackoverflow.com/q/48202923
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47015578
tagged with: python
tagged with: numpy
score: 0
answer count: 0
tagged with: arrays
type: Question
has comment: http://stackoverflow.com/comment/83386885
duplicate of: http://stackoverflow.com/q/47015578
has body: I have a n-dimensional array arr in which I need to modify k entries, which are specified in an separate array pos with shape (k, n). If the dimension n is fixed, this can be easily achieved using arr[pos[:, 0], pos[:, 1]] = 1. How could this be generalized to n dimensions? A working example for the specific case n=3 is k = 6 a = np.zeros((4, 4, 4)) pos = np.random.randint(0, 4, size=(k, a.ndim)) a[pos[:, 0], pos[:, 1], pos[:, 2]] = 1
has comment: http://stackoverflow.com/comment/83386798
has title: Numpy indexing in $n$ dimensions

http://stackoverflow.com/comment/83635091
comment on: http://stackoverflow.com/q/48304612
score: 0
has text: Python:fio speeds 4:1. also your suggestion is noted. I updated the software to do that because you have no gaurentee that the write will return blocksize. it could fail and return 0. having added it, though the results looks the same
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48213328
tagged with: python-requests
favorite count: 0
type: Question
has title: Why does Python Request's JSON decoder return the concatenation of top-level keys
has answer: http://stackoverflow.com/a/48213437
upvote count: 0
possible better answer: http://stackoverflow.com/a/48213437
score: -2
has answer: http://stackoverflow.com/a/48213445
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83408512
has comment: http://stackoverflow.com/comment/83408363
type: AnsweredQuestion
answer count: 2
has body: I am using the Requests library to decode a JSON response as follows: Payload Being Decoded: { "objectOne": { "desc": "one" }, "objectTwo": { "desc": "two" } } Code: from django.http import HttpResponse import requests class ApiService: @staticmethod def say_something(self): resp = requests.get('http://127.0.0.1:9501/polls/test/') return HttpResponse(resp.json()) Output: objectOneobjectTwo I followed the simple example from the official documentation: JSON Response Content In addition I wrapped the response in [] brackets to see if the response must be in a JSON array but it just returns an array with 'objectOneobjectTwo' as the 1st and only element.
tagged with: http://stackoverflow.com/tag/json
downvote count: 2
accepted answer: http://stackoverflow.com/a/48213445

http://stackoverflow.com/comment/83384551
type: Comment
score: 0
type: QuestionComment
has text: No i installed the correct version of Python3.6. https://cntk.ai/PythonWheel/CPU-Only/cntk-2.3.1-cp36-cp36m-win_amd64.whl 64bit, Python3.6 wheel
comment on: http://stackoverflow.com/q/48201821

http://stackoverflow.com/a/48300305
upvote count: 30
type: Answer
answers question: http://stackoverflow.com/q/48288076
accepted answer of: http://stackoverflow.com/q/48288076
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83585883
has body: You can use a RawSQL expression: ModelB.objects.filter(id__in=RawSQL( 'SELECT unnest(a.pk_values) FROM app_modela a WHERE a.id = %s', [index_id] )) Alternatively you can reproduce the exact query you have in your question with extra(): ModelB.objects.extra( tables=['foo_modela'], where=[ '"app_modelb"."id" = ANY("app_modela"."pk_values")', '"app_modela"."id" = %s', ], params=[index_id], )
score: 30

http://stackoverflow.com/q/48199512
has answer: http://stackoverflow.com/a/48200473
score: 1
has body: I have been trying to execute a python file from gitbash. It seems my gitbash is not able to locate my file. I thought python is not installed properly or maybe the environment variables are not set. However, I have set everything and when I execute $ python --version in gitbash, it comes up with Python 3.6.4, which I guess means python and path variables are set properly. Now, when I write $python filename.py then it comes up with an error: No such file and directly found, but I do have a file with the name challenge1.py installed in the same folder.
has comment: http://stackoverflow.com/comment/83380199
favorite count: 0
type: Question
has title: No such file found while executing python file in gitbash
has comment: http://stackoverflow.com/comment/83381315
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
tagged with: git-bash

http://stackoverflow.com/q/48192290
has comment: http://stackoverflow.com/comment/83365122
linked to: http://stackoverflow.com/q/20125172
has comment: http://stackoverflow.com/comment/83365879
downvote count: 1
has comment: http://stackoverflow.com/comment/83365590
score: 8
favorite count: 0
type: Question
upvote count: 9
has body: I have been trying to understand why python behaves this way, in the block of code below. I have done my research but couldn't find a good answer so I came here to see if anyone can point me in the right direction or provide a good clarification. I understand that it has to do with some old ALGOL principle, but I don't fully understand it. var = 5 def func1(): print(var) func1() def func2(): var = 8 print(var) func2() def func3(): print(var) var = 8 func3() The output of this code is as follows: 5 8 UnboundLocalError: local variable 'var' referenced before assignment I understand why we get the outputs '5' and '8'. But with 'func3()', I was expecting an output of '5'. As it seems, the interpreter thinks that I want to print the local 'var' in the function instead of the global 'var'. So it throws this error. Or maybe if a variable is defined somewhere inside of the function, then the function will default to the local variable, instead of a global one with the same name. But why exactly does python behave this way ? I am not complaining, I am just trying to understand something... How could I use a predefined global variable in a function, then define a local variable with the same name inside of the same function, without changing the value of the global variable ? ( in python of course ) Thanks in advance to everyone here. You are amazing people ! :) Edit_1: Thanks every one for the great answers. I totally understand that it is a bad and unpractical idea to use a predefined global variable in a function, then define a local variable with the same name inside of the same function. I was just thinking about it from a theoretical perspective, because I saw it in a college lecture. XD I can't find a single use case, in which it would be optimal to do that either ! Edit_2: I already read the PEP8 and I know that being explicit is better than being implicit. :) It's true. Otherwise the code will be confusing and lead to bugs. That question was just about some useless a…
answer count: 2
linked to: http://stackoverflow.com/q/4693120
linked to: http://stackoverflow.com/q/370357
has title: Why does python behave this way with variables?
tagged with: python
duplicate of: http://stackoverflow.com/q/370357
possible better answer: http://stackoverflow.com/a/48192698
linked to: http://stackoverflow.com/q/291978
has comment: http://stackoverflow.com/comment/83365068
has answer: http://stackoverflow.com/a/48192698
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48192457
linked to: http://stackoverflow.com/q/1261875
accepted answer: http://stackoverflow.com/a/48192457

http://stackoverflow.com/comment/83485421
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48251068
has text: None of these suggestions work. I did search the docs and stack first to make sure it wasn't duplicating (from what i found). However, this just made me think a little bit more. I think its my IF Statement causing this as it would technically be skipping 3 from the list in each division. Any thoughts on getting it to count in order with the IF statement skipping some of them?
type: Comment

http://stackoverflow.com/q/48254096
tagged with: comparison
accepted answer: http://stackoverflow.com/a/48254127
has title: Compare list of tuples - Equals no matter position
favorite count: 0
tagged with: tuples
has answer: http://stackoverflow.com/a/48254127
type: AnsweredQuestion
tagged with: list
linked to: http://stackoverflow.com/q/7828867
answer count: 3
possible better answer: http://stackoverflow.com/a/48254106
score: 1
has answer: http://stackoverflow.com/a/48254106
duplicate of: http://stackoverflow.com/q/7828867
type: Question
has comment: http://stackoverflow.com/comment/83490888
has comment: http://stackoverflow.com/comment/83490762
has body: Assuming: a = [(1,2,3),(4,5,6)] b = [(4,5,6),(1,2,3)] I want the following comparison to be True. Meaning position of tuple inside list doesn't matter. a == b
has answer: http://stackoverflow.com/a/48254121
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/a/48231106
upvote count: 82
answers question: http://stackoverflow.com/q/48230230
has body: It's a little difficult to duplicate this without some example data, but here is what I came up with. arr = np.array([np.array([1,2,3]), np.array([1,2,3,4])]) arr array([array([1, 2, 3]), array([1, 2, 3, 4])], dtype=object) np.savetxt('x.txt', arr) TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e') As pointed out by @Artier there is a little snippet at the end of the accepted answer in Write object array to .txt file that points out you can just save the array as a string with fmt='%s'. Using this format seems to solve the problem for me (again I can't recreate your issue exactly without a sample of data). np.savetxt('x.txt', arr, fmt='%s') I would point out that if you are looking to save disparate arrays and want a single location to keep them savez is very useful.
type: Answer
has comment: http://stackoverflow.com/comment/128656709
score: 82
downvote count: 0

http://stackoverflow.com/a/48253516
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48253360
has comment: http://stackoverflow.com/comment/83489608
has comment: http://stackoverflow.com/comment/83489598
accepted answer of: http://stackoverflow.com/q/48253360
has body: Demo: In [280]: A Out[280]: time 2017-09-01 01:00:00 0.5 2017-09-01 02:00:00 0.4 Name: val, dtype: float64 In [281]: B Out[281]: time 2017-09-01 00:00:00 NaN 2017-09-01 00:03:00 -0.000350 2017-09-01 00:06:00 0.000401 Name: val, dtype: float64 In [282]: B.to_frame('B').join(A.to_frame('A').set_index(A.index.shift(-1, freq='H')).resample('3T').ffill()) Out[282]: B A time 2017-09-01 00:00:00 NaN 0.5 2017-09-01 00:03:00 -0.000350 0.5 2017-09-01 00:06:00 0.000401 0.5
has comment: http://stackoverflow.com/comment/83489589
type: Answer

http://stackoverflow.com/a/48196470
has body: Here's a terrible pandas answer using nested for loops. This was faster to write than figuring out how to compare index values between dataframes. for df1_row in df1.index.tolist(): for df2_row in df2.index.tolist(): if df1_row == df2_row: row = df1.index.get_loc(df1_row) print(df1.iloc[row]['High'] / df1.iloc[row - 1]['Close']) print(df1.iloc[row]['Close'] / df1.iloc[row - 1]['Close']) Output: 1.00078600904 1.00078600904 Every time I use a for loop with pandas, I imagine there's some better solution out there. Edit: df3 = df1'High', 'Close'.iloc[ \ (df1.index.get_loc(df1.index.intersection(df2.index)[0]) - 2):\ df1.index.get_loc(df1.index.intersection(df2.index)[0])] df3['Close_Div_Prev_Close'] = df3.Close/df3.shift().Close df3['High_Div_Prev_Close'] = df3.High/df3.shift().Close Output: High Close Close_Div_Prev_Close High_Div_Prev_Close date_time 2012-08-30 09:40:00 1271.25 1271.25 NaN NaN 2012-08-30 09:50:00 1272.25 1272.25 1.000787 1.000787
score: 0
answers question: http://stackoverflow.com/q/48195007
type: Answer

http://stackoverflow.com/comment/83386885
type: Comment
type: QuestionComment
has text: Great! If you formulate it as an answer, Ill accept it
score: 0
comment on: http://stackoverflow.com/q/48202923

http://stackoverflow.com/comment/83429291
comment on: http://stackoverflow.com/a/48223885
score: 0
type: Comment
has text: @MaxU - Thanks, the hardest was replace NaNs in columns.
type: AnswerComment

http://stackoverflow.com/comment/83481232
comment on: http://stackoverflow.com/q/48249317
type: Comment
type: QuestionComment
score: 0
has text: The `label` variable is still alive after `make` returns, as long as there is a function around that still refers to it (such as `echo` (bound to `F`)).

http://stackoverflow.com/a/48572623
has body: Is there a faster algorithm? Looking at these two trees, (i've represented the numbers in binary to make the paths easier to see). Now to reduce this from 14 nodes to 7 nodes, can you layer the required paths from one tree onto the other? You can add any edge you like to one of the trees as long as it doesn't connect a node with its ancestors. _ 000 _ 00 _/ / \_ 001 0 _ 010 \_ 01 _/ \_ 011 _ 100 _ 10 _/ / \_ 101 1 _ 110 \_ 11 _/ \_ 111 can you see for example connecting 01 to 00, would be similar to replacing the head of the tree's 0 with 01, and thus with one edge you have added 100, 101 and 110..
has comment: http://stackoverflow.com/comment/84209047
has comment: http://stackoverflow.com/comment/84187359
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/84207752
type: Answer
has comment: http://stackoverflow.com/comment/84205946
has comment: http://stackoverflow.com/comment/84187336
answers question: http://stackoverflow.com/q/48250410
downvote count: 0

http://stackoverflow.com/q/48204194
type: Question
has title: Check if a (2d domain) function has root in specific (small) region
tagged with: performance
tagged with: python
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/83406747
has body: I am a little confused that I couldn't find anything regarding this topic, sorry in case I was just too dumb for searching. My Problem: I have an array of 2d points/tuples path that describe a curve in the plane. I want to get an array, same shape as path, that has boolean values for if a certain function has a root in proximity of the corresponding path point. By in proximity I mean somewhere in a disk with fixed radius around the point. What I did: Basically nothing. I'm stuck at step one, directly after import numpy as np def func(x,y): res = 0 ...some magic with res,x and y return res has_roots = np.zeros_like(path, dtype = bool) I thought I might use scipys fsolve to find all roots and then check if any roots are in proximity of my path points. My path is however very large (in total I will be considering several million points) so performance is crucial, and the comparison between path points and all roots would surely be a bottleneck. Any suggestions welcome!
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83438819
has comment: http://stackoverflow.com/comment/83429819
has comment: http://stackoverflow.com/comment/83419721

http://stackoverflow.com/comment/83600831
has text: `c = str(year)[:2]` will make `c` a string. What do you expect `some_string % 4` to do? I'll give you a hint - it isn't the `mod` operation. Also note, in Python, `(...)` is the *function call operator*. so `5(...)` is **not** "5 multiply whatever is in parentheses", it's "5 call whatever is in parentheses", which will give you another error, telling you that `int` objects (like `5`) are not callable. If you want multiplication, you need to use the multiplication operator, `5*(...)`
type: QuestionComment
comment on: http://stackoverflow.com/q/48307584
type: Comment
score: 1

http://stackoverflow.com/q/48320056
tagged with: python-2.7
answer count: 2
downvote count: 0
tagged with: django
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48320247
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48363417
has title: ChineseWords python format UnicodeEncodeError , but in django OK
tagged with: python
type: UnansweredQuestion
has body: demo code like this： #_*_ coding: utf-8 _*_ a = u'北京' b = u'地图' c = '{0} {1}'.format(a, b) when i write this in python file(test.py), and then run 'python test.py'. it will raise Exception like: UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) but, when i run a Django， django methon run demo code， it will be ok。 django run demo code python version and python path is totally same. python version: 2.7.9

http://stackoverflow.com/q/48225473
tagged with: django
tagged with: python
has body: I want to run a function in background. so I use Threading in my code. but return error ValueError: signal only works in main thread and don't know about two things: what is the main thread how to solve this problem :) views.py def callback(update): print('I received', update) def message_poll_start(): try: client = TelegramClient('phone', api_id, api_hash, update_workers=1, spawn_read_thread=False) client.connect() client.add_update_handler(callback) client.idle() except TypeNotFoundError: pass def message_poll_start_thread(request): t = threading.Thread(target=message_poll_start, args=(), kwargs={}) t.setDaemon(True) t.start() return HttpResponse("message polling started") urls.py urlpatterns = [ path('message_poll_start', messagemanager_views.message_poll_start_thread, name="message_poll_start"), ] trace [12/Jan/2018 11:24:38] "GET /messages/message_poll_start HTTP/1.1" 200 23 Exception in thread Thread-3: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/home/teletogram/telethogram/messagemanager/views.py", line 123, in message_poll_start client0.idle() File "/home/teletogram/.env/lib/python3.5/site-packages/telethon/telegram_bare_client.py", line 825, in idle signal(sig, self._signal_handler) File "/usr/lib/python3.5/signal.py", line 47, in signal handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler)) ValueError: signal only works in main thread
has answer: http://stackoverflow.com/a/56331399
answer count: 1
downvote count: 0
favorite count: 0
score: 9
type: Question
tagged with: telethon
has comment: http://stackoverflow.com/comment/83432818
has title: How to use telethon in a thread
upvote count: 9
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83432702

http://stackoverflow.com/q/48183073
has comment: http://stackoverflow.com/comment/83346049
downvote count: 1
favorite count: 0
type: Question
has title: python help me to access json nested and make it looks better
tagged with: python-3.x
linked to: http://stackoverflow.com/q/48181747
answer count: 1
has comment: http://stackoverflow.com/comment/83346127
has body: I need help to display a result like result number 2, Below is the full code for result number 1 import json json_obj = { "STATUS": "SUCCESS", "DATA": { "data": [ { "destinationId": "216", "name": "Bandung", "destinationCode": "24417", "tourList": [] }, { "destinationId": "54", "name": "Batam", "destinationCode": "BTH", "tourList": [ { "tourId": "20586", "tourCode": "IDBTH00585", "tourName": "BATAM SPECIAL SPA PACKAGE", "tourTime": [ { "tourStartTime": "09:00:00", "tourEndTime": "16:00:00", } ], "pricing": [ { "adultPrice": "193.00", "tourId": "20586" } ] } ] } ] } } wanted = ['tourId', 'tourCode', 'tourName', 'tourTime','pricing'] for item in json_obj["DATA"]["data"]: details = item['tourList'] if not details: pass else: #print(details['tourId']) for d in details: for key in wanted: print(key, ':', json.dumps(d[key], indent=4)) #Put a blank line at the end of the details for each item print() Result Number 1 Result how can i edit the code so the result is like result number 2, just make it become nice to read like result number 2 Result Number 2 tourId : "20586" tourCode : "IDBTH00585" tourName : "BATAM SPECIAL SPA PACKAGE" tourStartTime: "09:00:00" tourEndTime: "16:00:00" adultPrice: "193.00" tourId: "20586" also 1 more question, can i edit the name of json value into our own string example(tourId : "20586") to (Tour ID : 20586)
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83345852
has comment: http://stackoverflow.com/comment/83346115
type: AnsweredQuestion
score: 0
tagged with: list
accepted answer: http://stackoverflow.com/a/48183658
has answer: http://stackoverflow.com/a/48183658
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/83346811
has comment: http://stackoverflow.com/comment/83345906
tagged with: nested

http://stackoverflow.com/q/48308384
score: 0
tagged with: 3ds
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48750578
answer count: 1
type: Question
has title: Using 3DS Max's Python API, How to Select All Objects in Scene?
tagged with: 3dsmax
has body: I'm struggling to understand how to select objects using the MaxPlus class approach. For example, the following script will print the material used for every INode objects in the NodeTree (assuming I manually select them in the 3DS Max Viewport) nodes = MaxPlus.SelectionManager.GetNodes() for n in nodes: print(n.Material) The trouble is, I don't know how to get those objects from a script-only perspective as opposed to manually selecting them. I've found the MaxPlus.SelectionManager class but it seems it requires an existing selection to be made. Basically, I'm just trying to issue a command equivalent of pressing CTRL + A in the 3DS Max viewport to select all scene objects. Using 3DS Max 2016 + PyCharm

http://stackoverflow.com/comment/83532134
type: AnswerComment
comment on: http://stackoverflow.com/a/48274302
has text: Any reason this is faster than the above for-loop?
type: Comment
score: 0

http://stackoverflow.com/a/48182400
score: 3
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48182268
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48182268
has body: The error in your code is in the line: s = s[i:(i+len(s)+1)] You leave a leading space in the string s that leads to an infinite loop and (i+len(s)+1) part is wrong. It could be replaced with: s = s[i+1:] In general, this pascal function simply splits the string and gets Post-th element (1-based). The equivalent is something like this: def ldExtractFromLine (ldline, post): a = ldline.split() if post &lt;= len(a): return a[post-1] return ''
has comment: http://stackoverflow.com/comment/83345110

http://stackoverflow.com/comment/83459338
has text: Can you add request body?
comment on: http://stackoverflow.com/q/48238427
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48234473
has answer: http://stackoverflow.com/a/58447245
tagged with: tuples
has comment: http://stackoverflow.com/comment/83451735
score: 35
has answer: http://stackoverflow.com/a/70220976
has comment: http://stackoverflow.com/comment/83451653
has title: Python AttributeError: 'dict' object has no attribute 'append'
has comment: http://stackoverflow.com/comment/83451711
answer count: 4
linked to: http://stackoverflow.com/q/5900578
favorite count: 0
type: Question
has body: I am creating a loop in order to append continuously values from user input to a dictionary but i am getting this error: AttributeError: 'dict' object has no attribute 'append' This is my code so far: for index, elem in enumerate(main_feeds): print(index,":",elem) temp_list = index,":",elem li = {} print_user_areas(li) while True: n = (input('\nGive number: ')) if n == "": break else: if n.isdigit(): n=int(n) print('\n') print (main_feeds[n]) temp = main_feeds[n] for item in user: user['areas'].append[temp] Any ideas?
tagged with: for-loop
has answer: http://stackoverflow.com/a/75598610
upvote count: 37
has answer: http://stackoverflow.com/a/48234717
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/83490391
score: 0
has text: @Dodilila You save the normalization factors and then you can easily invert the normalization (its a linear operation). Yes you can do the same with ReLU but then the ranges do not match.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48252184

nested
tags question: http://stackoverflow.com/q/48236890
tags question: http://stackoverflow.com/q/48211738
tag name: nested
type: Tag
tags question: http://stackoverflow.com/q/48252297
tags question: http://stackoverflow.com/q/48183271
tags question: http://stackoverflow.com/q/48276165
tags question: http://stackoverflow.com/q/48243541
tags question: http://stackoverflow.com/q/48324228
tags question: http://stackoverflow.com/q/48214483
tags question: http://stackoverflow.com/q/48183073
tags question: http://stackoverflow.com/q/48234889
tags question: http://stackoverflow.com/q/48181747
tags question: http://stackoverflow.com/q/48258642
tags question: http://stackoverflow.com/q/48177934
tags question: http://stackoverflow.com/q/48205371
tags question: http://stackoverflow.com/q/48203795

http://stackoverflow.com/a/48338001
has body: This is a link to a blog I recently read about responsible web scraping with Scrapy. Hopefully it's helpful
type: Answer
answers question: http://stackoverflow.com/q/48329534
score: 0
has comment: http://stackoverflow.com/comment/83761414

http://stackoverflow.com/comment/83501954
comment on: http://stackoverflow.com/q/48258374
has text: change 'rb'(read binary) to 'r' (read) and try..
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83327960
comment on: http://stackoverflow.com/a/48174183
type: Comment
score: 0
type: AnswerComment
has text: How does setting `self.state` to the same method that was called make it undo the action?

http://stackoverflow.com/q/48262698
has comment: http://stackoverflow.com/comment/83541562
type: Question
has comment: http://stackoverflow.com/comment/83517023
linked to: http://stackoverflow.com/q/32361173
tagged with: amazon-s3
has title: Not able to access AWS S3 buckets
tagged with: python
type: UnansweredQuestion
tagged with: boto3
has comment: http://stackoverflow.com/comment/83515827
has body: All, I am getting following error, accessing s3 using boto3 EndpointConnectionError: Could not connect to the endpoint URL: "https://s3.amazonaws.com/" I followed following steps. Created AWS account with billing. Created a user with group policy: AmazonS3FullAccess Generated a access key for that user, and using in code below: from boto3 import client from pandas import read_csv acc_key = read_csv("accessKeys.csv") # access key file ACCESS_KEY = acc_key.loc[0,"Access key ID"] SECRET_KEY = acc_key.loc[0,"Secret access key"] client_access = client( 's3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY,) client_access.list_buckets() # giving the error here Tried adding region_name in client method, but of no use. Am i missing anything?
has comment: http://stackoverflow.com/comment/83512070
has comment: http://stackoverflow.com/comment/83515440
score: 0
has comment: http://stackoverflow.com/comment/83516306
answer count: 0
tagged with: amazon-web-services

http://stackoverflow.com/q/48289803
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83564689
tagged with: python
score: -1
has body: I am a bit of a newcomer and am pouring through some tutorials like water from a firehose when I encountered an acquaintance post something on social media that looks like this: print( [format(x, "c") for x in range(32,127)] ) Now, I went and ran the code and was perplexed to see it print out a large set of varying characters. I tried to skip ahead to some tutorials talking about format and also perused the site: https://pyformat.info/ to no avail. Any pointers would be greatly appreciated. Cheers!
has comment: http://stackoverflow.com/comment/83564861
has comment: http://stackoverflow.com/comment/83564771
has title: What does this piece of code actaully do?
downvote count: 3
has answer: http://stackoverflow.com/a/48289886
has answer: http://stackoverflow.com/a/48289956
has comment: http://stackoverflow.com/comment/83565001
favorite count: 0
type: Question
upvote count: 2
tagged with: format
answer count: 2
has comment: http://stackoverflow.com/comment/83564888

http://stackoverflow.com/q/48298077
type: Question
has comment: http://stackoverflow.com/comment/83580690
tagged with: python-import
linked to: http://stackoverflow.com/q/16780014
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/714063
tagged with: path
tagged with: python
has title: Importing python module from parent folder
has body: My folder structure is: /mfolder/A/parent.py /mfolder/A/test/child.py I want to import parent.py file into child.py file. But I'm getting this error ImportError: No module named test (Note: I've set the PYTHONPATH up to /mfolder and have __init__.py in test) How to solve it?? Thanks in advance
has comment: http://stackoverflow.com/comment/117618929
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/83580814
tagged with: python-module
tagged with: directory
has comment: http://stackoverflow.com/comment/83580641

django-queryset
tags question: http://stackoverflow.com/q/48300504
tags question: http://stackoverflow.com/q/48301339
tags question: http://stackoverflow.com/q/48292070
tags question: http://stackoverflow.com/q/48271727
type: Tag
tag name: django-queryset
tags question: http://stackoverflow.com/q/48256433
tags question: http://stackoverflow.com/q/48252698

http://stackoverflow.com/q/48239371
tagged with: python
has body: I have installed the pyrouge by following the instruction given in the official site itself. https://pypi.python.org/pypi/pyrouge But i'm getting the below error when i try to run "python -m pyrouge.test" Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/bin/pyrouge_convert_plain_text_to_rouge_format", line 4, in &lt;module&gt; __import__('pkg_resources').run_script('pyrouge==0.1.3', 'pyrouge_convert_plain_text_to_rouge_format') File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pkg_resources/__init__.py", line 743, in run_script self.require(requires)[0].run_script(script_name, ns) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1490, in run_script raise ResolutionError("No script named %r" % script_name) pkg_resources.ResolutionError: No script named 'pyrouge_convert_plain_text_to_rouge_format' EEEETraceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/bin/pyrouge_evaluate_plain_text_files", line 4, in &lt;module&gt; __import__('pkg_resources').run_script('pyrouge==0.1.3', 'pyrouge_evaluate_plain_text_files') File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pkg_resources/__init__.py", line 743, in run_script self.require(requires)[0].run_script(script_name, ns) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1490, in run_script raise ResolutionError("No script named %r" % script_name) pkg_resources.ResolutionError: No script named 'pyrouge_evaluate_plain_text_files' EEEEE ====================================================================== ERROR: test_config_file (pyrouge.tests.Rouge155_test.PyrougeTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pyrouge/tests/Rouge155_test.py", line…
has title: Error when trying to run pyrouge
has comment: http://stackoverflow.com/comment/83461439
tagged with: python-2.7
answer count: 0
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83461094
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83461045
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83461607

http://stackoverflow.com/q/48289643
tagged with: statistics
tagged with: http://stackoverflow.com/tag/r
score: 0
answer count: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83565247
favorite count: 0
has comment: http://stackoverflow.com/comment/83565329
type: Question
has title: Data retrieval such that distribution is positive skewed
has body: I have a pool of users called: u1, u2, u3 upto u1100 I wish to retrieve users from this pool such that resulting user distribution has a positive skew. (ie: a few users get retrieved many times and the vast majority of users get retrieved few times) The desired shape should be as seen below. If I use a function as below where "user" is a list of users (u1, u2, u3 etc) the distribtion is normal: myUser = random.choice(user) I think providing a probability distribution to the random.choice() would work. Eg: myUser = random.choice(user, positiveSkewDistribution) If this is the way to go, how do I get this positiveSkewDistribution file for the 1000 users ? I believe the file should have as many entries as the user file.
type: UnansweredQuestion
tagged with: math
tagged with: python

http://stackoverflow.com/a/48318074
type: AcceptedAnswer
downvote count: 0
has body: Build a dictionary and then you can get it's values as you want s = {} for i in x: s.setdefault((i+9)//10*10, []).append(i), # {40: [34, 35, 36], 20: [11, 12], 30: [21]}
answers question: http://stackoverflow.com/q/48317882
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48317882

http://stackoverflow.com/a/48283847
answers question: http://stackoverflow.com/q/48283808
score: 1
type: AcceptedAnswer
has body: I think you can add mask by boolean column to both sides: my_dataframe.loc[my_dataframe['is_true'], [new_col_one, new_col_two]] = my_dataframe.loc[my_dataframe['is_true'], 'col_with_values'].str.extract(some_regex,expand=True)
accepted answer of: http://stackoverflow.com/q/48283808
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/83512033
comment on: http://stackoverflow.com/q/48264580
type: Comment
type: QuestionComment
has text: Don't even match & negate & replace, instead match & join (the set of `@words`)
score: 0

http://stackoverflow.com/a/48271121
type: Answer
has body: Am I right? No. The OpenCV function moments() uses Green's theorem as mentioned in the OpenCV moments() docs. Green's theorem is indeed a correct way to find the center of mass of a shape. Green's theorem specifically relates integrals about some shape to integrals about the shape's border. As such, it doesn't at all matter how many points define the border or not. I say center of mass specifically, because you can pass in a single-channel image array into moments() as well to compute the moments and not just a point array. However for an image array, if the array is just binary, then the center of mass is the centroid. And with an array of points (from your contours), there is no array to tell the pixel values inside, so the result is similarly still the centroid.
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83543133
has comment: http://stackoverflow.com/comment/83555796
has comment: http://stackoverflow.com/comment/83556304
answers question: http://stackoverflow.com/q/48266277

http://stackoverflow.com/comment/83469575
type: QuestionComment
has text: Welcom to SO. Great first post - clear and concise. You should have googled/SO-Searched for QApplication before asking, you would have seen lots of results (f.e. https://stackoverflow.com/questions/17601896/how-qapplication-and-qwidget-objects-are-connected-in-pyside-pyqt ) with running code - and compared it to yours which would have made the error obvious. :)
type: Comment
comment on: http://stackoverflow.com/q/48243522
score: 1

http://stackoverflow.com/comment/83365615
has text: Thanks for your response, but I'm still a little confused. My datafiles variable is an input to ``tf.train.string_input_producer`` so I'm not sure if iterating over that is the right move. The number of epochs was an input to the filename_queue. Are you suggesting that I don't need the ``tf.train.string_input_producer``?
comment on: http://stackoverflow.com/a/48190907
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48246869
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/83476442
downvote count: 0
possible better answer: http://stackoverflow.com/a/48246911
favorite count: 0
has title: loading csv file using pandas in python
type: Question
has body: Here is my sample data: 2017-11-27T00:29:37.698-06:00,,"42,00,00,00,3E,51,1B,D7,42,1C,00,00,40" 2017-11-27T00:29:37.698-06:00,,"42,00,00,00,3E,51,1B,D7,42,1C,00,00,40" 2017-11-27T00:29:37.698-06:00,,"42,00,00,00,3E,51,1B,D7,42,1C,00,00,40" I tried to load the data using pandas using : data = pd.read_csv("sample.csv",header = None) My output is: 0 1 2 0 2017-11-27T00:29:37.698-06:00 NaN 42,00,00,00,3E,51,1B,D7,42,1C,00,00,40 1 2017-11-27T00:29:37.698-06:00 NaN 42,00,00,00,3E,51,1B,D7,42,1C,00,00,40 2 2017-11-27T00:29:37.698-06:00 NaN 42,00,00,00,3E,51,1B,D7,42,1C,00,00,40 I wanted to separate each data in second column with first column as time stamp. My expected output would be: 0 1 2 3 4.... 0 2017-11-27T00:29:37.698-06:00 42 00 00 00 1 2017-11-27T00:29:37.698-06:00 42 00 00 00 2 2017-11-27T00:29:37.698-06:00 42 00 00 00
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48246941
tagged with: python
has answer: http://stackoverflow.com/a/48246941
has comment: http://stackoverflow.com/comment/83476409
has answer: http://stackoverflow.com/a/48246911
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48246915
answer count: 3

http://stackoverflow.com/comment/83971691
comment on: http://stackoverflow.com/q/48250410
has text: I have removed only the part responsible for drawing the graph.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48440466
has comment: http://stackoverflow.com/comment/85784001
type: Answer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/85784032
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48226362
has comment: http://stackoverflow.com/comment/94079332
has body: Actual solution was to type chcp 65001 before the install command. This changes the default character encoding of the console to UTF-8, then it worked.
answers question: http://stackoverflow.com/q/48226362

http://stackoverflow.com/a/48270803
answers question: http://stackoverflow.com/q/48270469
type: Answer
score: 2
upvote count: 2
has body: It looks as if your forms.py is in your templates/blog directory. It should be in the main blog directory alongside models.py.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48270469

apache-spark-sql
tags question: http://stackoverflow.com/q/48318515
tags question: http://stackoverflow.com/q/48214293
tags question: http://stackoverflow.com/q/48252181
tag name: apache-spark-sql
tags question: http://stackoverflow.com/q/48174484
tags question: http://stackoverflow.com/q/48206622
tags question: http://stackoverflow.com/q/48179837
tags question: http://stackoverflow.com/q/48228909
tags question: http://stackoverflow.com/q/48208193
tags question: http://stackoverflow.com/q/48196203
tags question: http://stackoverflow.com/q/48178039
tags question: http://stackoverflow.com/q/48176862
tags question: http://stackoverflow.com/q/48232314
tags question: http://stackoverflow.com/q/48270789
type: Tag
tags question: http://stackoverflow.com/q/48302090
tags question: http://stackoverflow.com/q/48278489

http://stackoverflow.com/a/48208427
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48189689
accepted answer of: http://stackoverflow.com/q/48189689
type: Answer
has body: I was able to solve the problem. I was so stupid to insert a wrong version number of the freezed app in my setup.py-file for cxfreeze build. In there, i thought like 2 months ago to have a version number with some other characters in it and did not test it back then. In the end the version number contained an underline, which is not allowed! Only X.X-something is.

http://stackoverflow.com/comment/83412326
type: Comment
type: QuestionComment
has text: You need to find the form, and see what URL it submits to as its `action`, then send your request to that URL.
comment on: http://stackoverflow.com/q/48215222
score: 0

http://stackoverflow.com/comment/83495596
comment on: http://stackoverflow.com/q/48256408
score: 0
type: Comment
has text: also you're constantly opening and closing the file in every loop, highly inefficient
type: QuestionComment

http://stackoverflow.com/comment/83624365
comment on: http://stackoverflow.com/q/48318968
has text: @anuragal I added info more.If you know something, please help me.
type: Comment
type: QuestionComment
score: 0

gdal
tags question: http://stackoverflow.com/q/48180140
tag name: gdal
type: Tag

http://stackoverflow.com/comment/83533043
type: QuestionComment
has text: http://pyserial.readthedocs.io/en/latest/shortintro.html I'm following these examples.
score: 0
comment on: http://stackoverflow.com/q/48274695
type: Comment

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/48261561
tags question: http://stackoverflow.com/q/48243522
tags question: http://stackoverflow.com/q/48246575
tags question: http://stackoverflow.com/q/48213190
tags question: http://stackoverflow.com/q/48257321
tags question: http://stackoverflow.com/q/48181361
type: Tag
tags question: http://stackoverflow.com/q/48304675

http://stackoverflow.com/q/48197871
score: 0
has title: In Tensorflow, calculatin Spearman instead of accuracy
tagged with: deep-learning
has answer: http://stackoverflow.com/a/48258302
answer count: 1
tagged with: tensorflow
type: Question
type: UnansweredQuestion
has body: How to calculate Spearman and also Pearson correlations instead of the accuracy, for example in the below code chunk? (For a complete code example, you can also answer over this tutotrial: http://adventuresinmachinelearning.com/convolutional-neural-networks-tutorial-tensorflow/) Currently for accuracy, in summary, I use : prediction = tf.nn.sigmoid(logits) preds = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1)) accuracy = tf.reduce_mean(tf.cast(preds, tf.float32)) with tf.Session() as sess: t_acc= accuracy.eval(feed_dict={X: X_test, y: Y_test}) Along with t_acc, how to calculate Spearman and Pearson correlations. Specifically something like this would be fine: rho, _ = scipy.stats.spearmanr(preds, actuals)
tagged with: python

http://stackoverflow.com/q/48176265
linked to: http://stackoverflow.com/q/46675670
downvote count: 1
tagged with: macos
has comment: http://stackoverflow.com/comment/83334167
has comment: http://stackoverflow.com/comment/83332880
favorite count: 0
type: Question
answer count: 2
has title: pip install tweepy error
has answer: http://stackoverflow.com/a/48176622
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83332663
tagged with: pip
tagged with: python
score: -1
tagged with: tweepy
has comment: http://stackoverflow.com/comment/83332409
has body: When I try to install tweepy using pip (pip install tweepy) I get the below error on my mac (10.12.3). Please help. OSError: [Errno 1] Operation not permitted: '/var/folders/s0/0j_bp8b96bl2mzltwxnc56300000gn/T/pip-9zf_EM-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info
has answer: http://stackoverflow.com/a/48176333
upvote count: 0

http://stackoverflow.com/comment/83400213
score: 0
type: Comment
type: AnswerComment
has text: Actually, I've noticed that the problem stems from another list embedded within the list. Maybe `json` does not deepcopy the embedded lists
comment on: http://stackoverflow.com/a/48208596

qcalendarwidget
tags question: http://stackoverflow.com/q/48183151
tag name: qcalendarwidget
type: Tag

http://stackoverflow.com/a/48187840
type: Answer
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
has body: If we look at the source code of pandas Series we can see the following, def __init__(self, data=None, index=None, dtype=None, name=None, copy=False, fastpath=False): if not isinstance(data, SingleBlockManager): data = SingleBlockManager(data, index, fastpath=True) if copy: data = data.copy() So you have passed x for the data argument, therefore, the line data = data.copy() makes a copy of x. This should be equivalent to doing, g = pd.Series(x.copy()) This is subtly different to pd.Series.copy(x) which now makes a copy of the Series object itself, not the underlying x. Therefore, the underlying x might still be referenced by the new Series. The idea of making a copy is that you be confident that any operations you perform on the Series do not change the original object x.
accepted answer of: http://stackoverflow.com/q/48185809
answers question: http://stackoverflow.com/q/48185809

http://stackoverflow.com/q/48207063
has title: save error compile message in txt file in python3
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83395186
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83402521
has body: Could you help me that when I compile my program and if I have an error how can I redirect this error message in text file, before compilation terminate? I wrote this code, But my problem is i want when i have an error after that my COMP_ERR.txt file create and write error inside this file. but in my code this create before import urllib.request import os import tempfile import sys import fileinput original_stderr = sys.stderr f_error = open("COMP_ERR.txt", "w") sys.stderr = f_error try: url = sys.argv[1] path_snip_file = sys.argv[2] #url = 'http://pages.di.unipi.it/corradini/Didattica/AP-17/PROG-ASS/03/ClassWithTest.java' #path_snip_file = "C:/Users/user/AppData/Local/Programs/Python/Python36/snip1.java" path_remote_file_inOurComp = "C:/Users/user/AppData/Local/Programs/Python/Python36/ClassWithTest.java" path_remote_file_inOurCom = "C:/Users/user/AppData/Local/Programs/Python/Python36/ClassWithTest1.java" gt_url = urllib.request.urlretrieve(url) print("the URL is: ") print(gt_url) link = input("input the path of file: ") """ f = open(link, "r") for line in f: print(line, end='') f.close() """ #--------------------] #copy snipper java file inside remote file #[-------------------- with open(path_remote_file_inOurComp, 'w') as modify_file: with open (link, 'r') as r_file: for line in r_file: if " public static void main(" not in line: modify_file.write(line) else: with open(path_snip_file, 'r') as snip_file: for lines in snip_file: modify_file.write(lines) modify_file.write('\n'+line) #------------------------------------------------------------- #refactor #------------------------------------------------------------- with open(path_remote_file_inOurCom, 'w') as ft: with open(path_remote_file_inOurComp, 'r') as file_n: for line in file_n: line = line.replace("System.out.println(", "System.out.println(insertLength(") line = line.replace(";", ");") ft.write(line) except IndexError: print("Not enough input! ! !") sys.stderr = original_stderr f_error.close()
has answer: http://stackoverflow.com/a/48207105
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83395054
linked to: http://stackoverflow.com/q/641420
answer count: 3
has answer: http://stackoverflow.com/a/58548735
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48207912

http://stackoverflow.com/q/48319325
has comment: http://stackoverflow.com/comment/83624747
has comment: http://stackoverflow.com/comment/83624698
tagged with: hex
has comment: http://stackoverflow.com/comment/83627339
accepted answer: http://stackoverflow.com/a/48319783
score: 0
has body: I'm working on a IPv6 header compressor called SCHC, and in my code I have to read a value that sometimes it's decimal, and others is hexadecimal. I'll show you an example: # fID pos dir tv mo cda rule = {"ruleid" : 0, "content" : [["IPv6.version", 1, "bi", 6, "equal", "not-sent"], ["IPv6.trafficClass", 1, "bi", 0x00, "equal", "not-sent"], ["IPv6.flowLabel", 1, "bi", 0x000000, "ignore", "not-sent"], ["IPv6.payloadLength",1, "bi", None, "ignore", "compute-length"], ["IPv6.nextHeader", 1, "bi", 17, "equal", "not-sent"], ["IPv6.hopLimit", 1, "bi", 30, "equal", "not-sent"], ["IPv6.prefixES", 1, "bi", 0x200104701f1209f2, "equal", "not-sent"], ["IPv6.iidES", 1, "bi", 0x000000000000000b, "equal", "not-sent"], ["IPv6.prefixLA", 1, "bi", [0xFE80000000000000, 0x2001123456789012, 0x200104701f1209f2, 0x200141d004013100],"match-mapping", "mapping-sent"], ["IPv6.iidLA", 1, "bi", 0x0000000000003682, "equal", "not-sent"], ["UDP.PortES", 1, "bi", 5684, "equal", "not-sent"], ["UDP.PortLA", 1, "bi", 5684, "equal", "not-sent"], ["UDP.length", 1, "bi", None, "ignore", "compute-length"], ["UDP.checksum", 1, "bi", None, "ignore", "compute-checksum"], ["CoAP.version", 1, "bi", 1, "equal", "not-sent"], ["CoAP.type", 1, "up", 0, "equal", "not-sent"], ["CoAP.type", 1, "dw", 2, "equal", "not-sent"], ["CoAP.tokenLength", 1, "bi", 1, "equal", "not-sent"], ["CoAP.code", 1, "up", 2, "equal", "not-sent"], ["CoAP.code", 1, "dw", [69, 132], "match-mapping", "mapping-sent"], ["CoAP.messageID", 1, "bi", 0, "MSB(12)", "LSB"], ["CoAP.token", 1, "bi", 0x80, "MSB(4)", "LSB"], ["CoAP.Uri-Path", 1, "up", "foo", "equal", "not-sent"], ["CoAP.Uri-Path", 2, "up", "bar", "equal", "not-sent"], ["CoAP.Uri-Path", 3, "up", None, "ignore", "value-sent"], ["CoAP.Content-Format",1, "dw", None, "ignore", "value-sent"], ["CoAP.Uri-Query", 1, "up", "k=", "MSB(16)", "LSB"], ["CoAP.Option-End", 1, "up", 0xFF, "equal", "not-sent"] ]} This is an example of a rule compression for SCHC. As you can see, the tv (target value) fiel…
tagged with: ipv6
has answer: http://stackoverflow.com/a/48319783
has comment: http://stackoverflow.com/comment/83624441
answer count: 1
has title: Check if a read value is hex or decimal in python?
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83624381
has comment: http://stackoverflow.com/comment/83624912
linked to: http://stackoverflow.com/q/11592261
tagged with: python

http://stackoverflow.com/a/48326438
has comment: http://stackoverflow.com/comment/83638530
score: 7
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/118305471
answers question: http://stackoverflow.com/q/48326151
accepted answer of: http://stackoverflow.com/q/48326151
type: Answer
upvote count: 7
has body: In order to move the ticklabels by a few pixels you may add a translation to their transformation chain. E.g. to move by 20 pixels to the right, use import matplotlib.transforms as mtrans # ... trans = mtrans.Affine2D().translate(20, 0) for t in ax.get_xticklabels(): t.set_transform(t.get_transform()+trans) If course the number of pixels that you need to shift in order for the #-sign to be under the tickmark is not a priori clear - that needs to be found out via trial and error. Or maybe you have a different hint on by how much you want to shift in what other units. Here is the complete example, import matplotlib.pyplot as plt import pandas as pd import numpy as np import matplotlib.transforms as mtrans categories = ['This is class #{}'.format(n) for n in range(10)] data = { 'Value': [categories[np.random.randint(10)] for _ in range(100)], 'id': [1000+i for i in range(100)] } df = pd.DataFrame(data) ax = df.Value.value_counts().sort_index().plot(kind='bar', rot=45) plt.xticks(ha='right') trans = mtrans.Affine2D().translate(20, 0) for t in ax.get_xticklabels(): t.set_transform(t.get_transform()+trans) plt.tight_layout() plt.show() producing

point
type: Tag
tag name: point
tags question: http://stackoverflow.com/q/48228018

http://stackoverflow.com/a/48232609
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48232511
has body: As Coldspeed pointed out the modulo operator is the right tool for that, it gives you the rest of the integer division - if you use number % len(list) it will only give you indexes that are valid. 0 if it divides w/o rest or up to len(list)-1 - exactly matching the indexes available on your list. For data = ['a','b','c'] for n in range(-5,6): print(n, '--&gt;', data[n % len(data)]) Output: -4 --&gt; c -3 --&gt; a -2 --&gt; b -1 --&gt; c 0 --&gt; a 1 --&gt; b 2 --&gt; c 3 --&gt; a 4 --&gt; b 5 --&gt; c and so on.
downvote count: 0
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48232511
upvote count: 1

http://stackoverflow.com/comment/83434579
type: AnswerComment
has text: thanks, please see my revised *apps* above. How would I get the revised *apps* to be like: [{'category': 'two'}, {'category': 'three}, {'category': 'one'}] NOT: [{'category': 'two', 'item': 'blah'}, {'category': 'three', 'item': 'blah'}, {'category': 'one', 'item': 'blah'}]
comment on: http://stackoverflow.com/a/48219989
type: Comment
score: 0

http://stackoverflow.com/a/48223941
has comment: http://stackoverflow.com/comment/83463556
type: Answer
has body: Assert: hist_t = tk.Text(...) You can always call hist_t.delete('end-1c', 'end') whenever you want to remove the last char, which is newline in this case. You can also remove the last char only if it is newline: while hist_t.get('end-1c', 'end') == '\n': hist_t.delete('end-1c', 'end')
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48220788

aes
tag name: aes
tags question: http://stackoverflow.com/q/48292315
type: Tag

http://stackoverflow.com/comment/83627813
has text: I made a clean update of my post for you, I hope it gives you more insight about your original problem. It might be a bit long, but I invite you to read it and give me your opinion. :)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48291663
type: Comment

http://stackoverflow.com/a/48253597
has comment: http://stackoverflow.com/comment/83763666
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48252297
has body: You are making your life harder than necessary by looping over the index. I heard quite often here on SO "If you use numpy with loops you are probably doing it wrong". And it is true. You can instead use numpy broadcasting: F_all = (EL + E0)[:, None] + (ET - TS) Et voila. P.S.: I am not going to do your debugging, but shouldn't it be -TS[x, y] in your inner loop?
type: Answer
answers question: http://stackoverflow.com/q/48252297
has comment: http://stackoverflow.com/comment/83761691
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/48263203
upvote count: 1
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83509779
answers question: http://stackoverflow.com/q/48261354
has comment: http://stackoverflow.com/comment/83509449
has body: Instead of having the full path in the zipfile can you just zip the CSV files only? EX: import os import zipfile zipped_file = zipfile.ZipFile("csvOutput.zip", 'w') os.chdir("/path/to/ CSV file path ") zipped_file.write('mail_maga_file.csv') zipped_file.write('sms_file.csv') zipped_file.close()
has comment: http://stackoverflow.com/comment/83509849
score: 1

http://stackoverflow.com/comment/83571037
has text: I know what the code does but I'm not sure where to insert the new code.
comment on: http://stackoverflow.com/q/48292916
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/83555408
score: 0
has text: is `filename = random.choice(filenames)` equivalent?
comment on: http://stackoverflow.com/q/48285315
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49285888
answers question: http://stackoverflow.com/q/48325729
has body: There is no compatibility at the moment for that, you can check it out in their wiki in github https://github.com/opendatagroup/hadrian/wiki
type: Answer
score: 0

http://stackoverflow.com/q/48175437
type: Question
answer count: 2
has title: Python Library Reference/Usage
accepted answer: http://stackoverflow.com/a/48175530
tagged with: python
tagged with: biopython
has answer: http://stackoverflow.com/a/48175512
type: AnsweredQuestion
has body: I'm trying to use a method from the BioPython package to calculate an isoelectric point for a list of given peptides. The class breakdown can be seen here: http://biopython.org/DIST/docs/api/Bio.SeqUtils.ProtParam.ProteinAnalysis-class.html#isoelectric_point In order to import this class to my environment, I'm using the following code (did I do this right?): from Bio.SeqUtils.ProtParam import ProteinAnalysis Then, to call the method, I do the following: window_aas = "ditkdteneveadveveadveveadvseql"; ProteinAnalysis.isoelectric_point(window_aas); However I'm getting the following error, and I'm not sure how to interpret it, despite several searches for similar errors: File "C:\Users\----\AppData\Local\Programs\Python\Python36-32\lib\site-packages\Bio\SeqUtils\ProtParam.py", line 68, in count_amino_acids if self.amino_acids_content is None: AttributeError: 'str' object has no attribute 'amino_acids_content' Is anyone able to guide me in the right direction here? This other class is also called IsoElectricpoint but I don't see a method in it to use: http://biopython.org/DIST/docs/api/Bio.SeqUtils.IsoelectricPoint-module.html
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/48175530
possible better answer: http://stackoverflow.com/a/48175512
tagged with: libraries
favorite count: 0

http://stackoverflow.com/a/48291786
has comment: http://stackoverflow.com/comment/83569776
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48291719
has body: The request is set at a fundamental level in Django's generic view base, here, which every other kind of view derives from. You should be perfectly safe accessing the request attribute provided you're inheriting a Django class-based view of some sort. If you have some AttributeError, it's probably because you forgot to inherit from a Django view (as in the example code posted in the question).
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48291719
score: 1

http://stackoverflow.com/q/48244919
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48249714
tagged with: keras
tagged with: tensorflow
has answer: http://stackoverflow.com/a/48249714
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/47532162
tagged with: python
has title: How to flatten the varying-sized data in Keras and use it in the next layers
tagged with: flatten
score: 2
type: AnsweredQuestion
has body: I'd like to build a CNN that can be feed matrices with the constant number of rows but the varying number of columns. I started from this blog but it uses Flatten layer at some point. According to this GitHub issue, the Flatten layer cannot be used with not fully-shape-defined data. I used this answer to build a CNN like this: from keras import Input, Model from keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Lambda, Activation from keras.optimizers import SGD import keras.backend as K input = Input(shape=(None, 60, 1)) x = Conv2D(list_of_neurons[0], (3, 3), padding='same', activation='relu')(input) x = MaxPooling2D(pool_size=(2, 2))(x) # None x 30 x = Conv2D(list_of_neurons[1], (3, 3), padding='same', activation='relu')(x) x = MaxPooling2D(pool_size=(2, 2))(x) # None x 15 x = Conv2D(list_of_neurons[2], (3, 3), padding='same', activation='relu')(x) x = MaxPooling2D(pool_size=(3, 3))(x) # None x 5 x = Lambda(lambda k: K.batch_flatten(k))(x) x = Dense(list_of_neurons[3])(x) x = Activation("relu")(x) x = Dropout(dropout)(x) output = Dense(1, activation='sigmoid')(x) self._model = Model(inputs=input, outputs=output) self._model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) self._model.summary() However, when I try to run a script an error occurs: Traceback (most recent call last): File "/home/kuba/Dropbox/MGR Jakub Kustra/implementacja/first_cnn.py", line 66, in &lt;module&gt; mlp = MLP([60, 60, 120, 120], 0.3) File "/home/kuba/Dropbox/MGR Jakub Kustra/implementacja/models.py", line 22, in __init__ x = Dense(list_of_neurons[3])(x) File "/home/kuba/anaconda3/lib/python3.6/site-packages/keras/engine/topology.py", line 576, in __call__ self.build(input_shapes[0]) File "/home/kuba/anaconda3/lib/python3.6/site-packages/keras/layers/core.py", line 830, in build constraint=self.kernel_constraint) File "/home/kuba/anaconda3/lib/python3.6/site-packages/keras/legacy/interfaces.py", line 87, in wrapper return func(*args, **kwargs) File "/…
tagged with: conv-neural-network
upvote count: 2

http://stackoverflow.com/a/48289343
upvote count: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/48289171
downvote count: 0
has body: There are two windows getting displayed because when a tkinter widget is created, it forces a Tk instance to be created as well, and every widget, unless a parent is explicitly passed, is a child to that automatically created Tk instance. So your code essentially mimics the following code: from tkinter import * root = Tk() top = Toplevel(root, bg='red') root.mainloop() Now there are some ways to work around that for the behavior you want, one is to hide the actual Tk instance: import tkinter as tk root = tk.Tk() root.withdraw() top = tk.Toplevel(root, bg='red') #to display root window again #root.iconify() #root.deiconify() root.mainloop() Another way would be to overrule the deletion of the root itself, but I doubt that's actually what you want: import tkinter as tk def callback(): print("Won't close") root = tk.Tk() root.protocol("WM_DELETE_WINDOW", callback) root.mainloop()
type: AcceptedAnswer
score: 6
answers question: http://stackoverflow.com/q/48289171
has comment: http://stackoverflow.com/comment/83563996

http://stackoverflow.com/q/48210858
accepted answer: http://stackoverflow.com/a/48211285
has comment: http://stackoverflow.com/comment/83403234
has answer: http://stackoverflow.com/a/48211285
has title: How to add business days to date in python?
type: AnsweredQuestion
upvote count: 3
score: 0
has comment: http://stackoverflow.com/comment/83403052
downvote count: 3
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83402916
linked to: http://stackoverflow.com/q/44822697
type: Question
has comment: http://stackoverflow.com/comment/83402927
has comment: http://stackoverflow.com/comment/83402959
tagged with: python
has body: How can I calculate the resulting date of adding a given number of business days to a date in python? For example: I have a start date of Jan 11, 2018 and I want to know the date that is 115 business days later (so excluding weekends and holidays).
tagged with: date

http://stackoverflow.com/q/48250655
has body: Using Python 3. I have a very large CSV file that I need to split and save to_csv. I use chunksize parameter to determine how many rows I need in both files. Expectation is the first code should read required rows so I can save it into first CSV file and the second should take care of remaining rows so I can save them in second CSV file: As an example, let's say file is 3000 rows and using below code : file = pd.read_csv(r'file.csv',index_col=None, header='infer', encoding='ISO-8859-1',skiprows=None, chunksize=500) I've used skiprows=None as I want it to start from the beginning and chunk the first 500. Then, second code should skip previous 500 and chunk remaining: file = pd.read_csv(r'file.csv',index_col=None, header='infer', encoding='ISO-8859-1',skiprows=500, chunksize=2500) However, the result I get from first code is that it always goes directly and chunk the last 500 and not starting from beginning as expected. It doesn't sound that skiprows is working as expected if chunksize will always skip to the last given number. Would appreciate any kind of suggestion on what might be going on here.
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: dataframe
tagged with: python
has title: chunksize isn't starting from first row in csv file
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
answer count: 2
possible better answer: http://stackoverflow.com/a/48250968
accepted answer: http://stackoverflow.com/a/48250990
has answer: http://stackoverflow.com/a/48250968
downvote count: 0
has answer: http://stackoverflow.com/a/48250990
score: 4
type: AnsweredQuestion

http://stackoverflow.com/a/48267073
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83520217
upvote count: 1
has comment: http://stackoverflow.com/comment/83517833
has comment: http://stackoverflow.com/comment/83517792
has body: Going by the text of the question, it seems you are shrinking the image by 50% and by the code it seems, you are doing it in blocks. We can reshape to split each of the two axes of the 2D input by lengths as the required block sizes to get a 4D array and then compute mean along the axes corresponding to the block sizes, like so - def block_mean(im, BSZ): m,n = im.shape[:2] return im.reshape(m//BSZ[0],BSZ[0],n//BSZ[1],BSZ[1],-1).mean((1,3)) Sample run - In [44]: np.random.seed(0) ...: im = np.random.randint(0,9,(6,8,3)) In [45]: im[:2,:2,:].mean((0,1)) # average of first block across all 3 channels Out[45]: array([3.25, 3.75, 3.5 ]) In [46]: block_mean(im, BSZ=(2,2)) Out[46]: array([[[3.25, 3.75, 3.5 ], [4. , 4.5 , 3.75], [5.75, 2.75, 5. ], [3. , 3.5 , 3.25]], [[4. , 5.5 , 5.25], [6.25, 1.75, 2. ], [4.25, 2.75, 1.75], [2. , 4.75, 3.75]], [[3.25, 3.5 , 5.25], [4.25, 1.5 , 5.25], [3.5 , 3.5 , 4.25], [0.75, 5. , 5.5 ]]])
has comment: http://stackoverflow.com/comment/83517309
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48266869
has comment: http://stackoverflow.com/comment/83517745
answers question: http://stackoverflow.com/q/48266869
score: 1

http://stackoverflow.com/q/48222837
has comment: http://stackoverflow.com/comment/83428216
has answer: http://stackoverflow.com/a/76782607
accepted answer: http://stackoverflow.com/a/48223348
tagged with: python
has answer: http://stackoverflow.com/a/48223348
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/76782607
has comment: http://stackoverflow.com/comment/83428027
tagged with: django-middleware
has body: I'm running my Django code, but get this error AttributeError: 'WSGIRequest' object has no attribute 'user' My Django version is 1.8.2, and here is my middleware class of setting.py MIDDLEWARE_CLASSES = ( 'khxia.middlewares.PeeweeConnectionMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'subdomains.middleware.SubdomainURLRoutingMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'referral.middlewares.ReferralRecordMiddleware', 'common.middlewares.ExceptionMiddleware', ) Here is my full traceback Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/Users/motion/kuaixiao_env/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 189, in __call__ response = self.get_response(request) File "/Users/motion/kuaixiao_env/lib/python2.7/site-packages/django/core/handlers/base.py", line 218, in get_response response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) File "/Users/motion/kuaixiao_env/lib/python2.7/site-packages/django/core/handlers/base.py", line 268, in handle_uncaught_exception return callback(request, **param_dict) File "/Users/motion/Documents/GitHub/khx2/khxia/home/views.py", line 68, in server_error res = render(request, 'home/500.html') File "/Users/motion/Documents/GitHub/khx2/khxia/common/shortcuts.py", line 40, in render if request.user.is_authenticated(): AttributeError: 'WSGIRequest' object has no attribute 'user' The line 68 of views.py is: def server_error(request): res = render(request, 'home/500.html') res…
answer count: 2
downvote count: 0
tagged with: django
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83427041
has title: AttributeError: 'WSGIRequest' object has no attribute 'user'
favorite count: 0
has comment: http://stackoverflow.com/comment/83427926
tagged with: attributeerror
type: Question

http://stackoverflow.com/q/48324949
type: Question
has title: grabbing variables from the tf session
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48325769
score: 0
has comment: http://stackoverflow.com/comment/83635438
has answer: http://stackoverflow.com/a/48325769
answer count: 1
has comment: http://stackoverflow.com/comment/83635495
has body: I have introduced to this code snippet , this is a very simple linear regression model using gradient descent. What confuses me is the last line final_slope , final_intercept = sess.run([m,b]), is this the best way to grab the variables from the session, instead to run the session again? I hope to understand how this statement operate under hood My code: import tensorflow as tf import numpy as np x_data = np.linspace(0,10,10) + np.random.uniform(-1.5,1.5,10) y_label = np.linspace(0,10,10) + np.random.uniform(-1.5,1.5,10) m = tf.Variable(0.29220241) b = tf.Variable(0.84038402) error = 0 for x,y in zip(x_data,y_label): y_hat = m*x + b error += (y-y_hat)**2 optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001) train = optimizer.minimize(error) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) epochs = 1 for i in range(epochs): sess.run(train) # Fetch Back Results final_slope , final_intercept = sess.run([m,b]) as per documentation a = tf.constant([10, 20]) b = tf.constant([1.0, 2.0]) # 'fetches' can be a singleton v = session.run(a) # v is the numpy array [10, 20] # 'fetches' can be a list. v = session.run([a, b]) # v a Python list with 2 numpy arrays: the numpy array [10, 20] and the # 1-D array [1.0, 2.0] # 'fetches' can be arbitrary lists, tuples, namedtuple, dicts: MyData = collections.namedtuple('MyData', ['a', 'b']) v = session.run({'k1': MyData(a, b), 'k2': [b, a]}) # v is a dict with # v['k1'] is a MyData namedtuple with 'a' the numpy array [10, 20] and # 'b' the numpy array [1.0, 2.0] # v['k2'] is a list with the numpy array [1.0, 2.0] and the numpy array # [10, 20]. still don't get the meaningful information of running the session again to extract the variable . i am would like to understand if running session every time is the best case to grabbing the variables or there is another way much better and faster
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/q/48202174
has title: Create a list from two lists based on values in another list
has comment: http://stackoverflow.com/comment/83385429
type: AnsweredQuestion
tagged with: list
score: -5
has comment: http://stackoverflow.com/comment/83385227
answer count: 2
upvote count: 0
possible better answer: http://stackoverflow.com/a/48202416
has comment: http://stackoverflow.com/comment/83385237
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48202266
has comment: http://stackoverflow.com/comment/83385229
has answer: http://stackoverflow.com/a/48202266
tagged with: python
downvote count: 5
has answer: http://stackoverflow.com/a/48202416
tagged with: merge
has comment: http://stackoverflow.com/comment/83385273
has body: list1=['String-1', 'String-2', 'String-1', 'String-1', 'String-2', 'String-2', 'String-1', 'String-2', 'String-1', 'String-2'] list2=['TEXT-1', 'TEXT-1', 'TEXT-1', 'TEXT-1', 'TEXT-1'] list3=['TEXT-2', 'TEXT-2', 'TEXT-2', 'TEXT-2'] i want to construct list 4 from list2 and list3 based on the values in list1 if value in list1=String-1 then pick from list2 else pick from list3 finallist=['TEXT-1', 'TEXT-2', 'TEXT-1', 'TEXT-1', 'TEXT-2', 'TEXT-2', 'TEXT-1', 'TEXT-2', 'TEXT-1', 'TEXT-2'] Any help?

http://stackoverflow.com/a/48210108
has comment: http://stackoverflow.com/comment/83645313
has body: The error says it all : selenium.common.exceptions.WebDriverException: Message: Unknown error It's pretty clear that the webdriver instance is not getting invoked. So you have to pass the edge_path along with the argument executable_path as follows : driver = webdriver.Chrome(executable_path=edge_path)
has comment: http://stackoverflow.com/comment/83401563
type: Answer
answers question: http://stackoverflow.com/q/48209959
score: 0

http://stackoverflow.com/q/48316439
answer count: 0
linked to: http://stackoverflow.com/q/37897766
has title: Loop User Input Python
tagged with: loops
has comment: http://stackoverflow.com/comment/83618936
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83622062
has body: I want to loop the input so I get 3 guesses, or 2 guesses and 1 clue: if chosen == 1: print ("Your anagram is:", anagrameasy) time.sleep(1) easyguess = input ("Please input the answer in lower case, type clue for a clue") if easyguess == answereasy: print ("correct") if easyguess == "clue": print (clueeasy) easyguess = input ("Please input the answer in lower case, type clue for a clue") elif easyguess != answereasy: print("try again")
tagged with: python
tagged with: user-input
score: 0

http://stackoverflow.com/comment/83456008
type: QuestionComment
has text: Does it help if you set the "unwanted" values to NAN and plot them like this? https://stackoverflow.com/questions/31345489/pyplot-change-color-of-line-if-data-is-less-than-zero
comment on: http://stackoverflow.com/q/48236622
score: 0
type: Comment

http://stackoverflow.com/comment/83442880
score: 0
comment on: http://stackoverflow.com/q/48230210
type: QuestionComment
has text: It doent show me my screenshot. Just open the winsows photos and does not show it.
type: Comment

http://stackoverflow.com/comment/83428837
comment on: http://stackoverflow.com/q/48223588
score: 0
has text: You can use `request.user.is_anonymous`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83428102
type: QuestionComment
has text: In your second example, what is your input and what's your output?
score: 0
comment on: http://stackoverflow.com/q/48223231
type: Comment

qpython
tags question: http://stackoverflow.com/q/48248939
type: Tag
tag name: qpython

http://stackoverflow.com/comment/83361998
score: 0
has text: I am running Python 3.6.3. It is potentially an issue with my Jupyter Notebook? I have tried restarting the notebook several times and it does not remedy the issue. I initially had an issue with creating a new notebook, but once i moved into the anaconda projects file i had no issue creating a new notebook.
comment on: http://stackoverflow.com/q/48190843
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83482368
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48244857
has text: @Sleepy-Z Could you please elaborate on what role Excel might play in this? How are you trying to use Excel with your Python script?
score: 1

http://stackoverflow.com/comment/83366596
has text: @devlincarnate It is OpenstreetMap
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48192535
type: Comment

http://stackoverflow.com/comment/83489666
has text: `Hals-iMac:epubcheck-4.0.2 Hal$ zip -l IdealogicalEcho.epubzip error: Nothing to do! (IdealogicalEcho.epub)` I messed up and hardcoded the `EBOOK` folder name, but everything else zips exactly including the `mimetype` and `META-INF`.
comment on: http://stackoverflow.com/q/48252192
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83603861
type: Comment
type: QuestionComment
has text: A date plus a timedelta is a date, but a timedelta by itself is not a date. I think that may be your problem.
comment on: http://stackoverflow.com/q/48308933
score: 0

http://stackoverflow.com/comment/83523113
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48269684
has text: Thanks for the code smac! When I tried to run this, I get an error on the A1ext line because X is not defined?

http://stackoverflow.com/q/48330727
score: 4
has title: How to solve a sqlalchemy.exc.AmbiguousForeignKeysError in SQLalchemy?
linked to: http://stackoverflow.com/q/22355890
favorite count: 0
tagged with: foreign-keys
tagged with: relationship
duplicate of: http://stackoverflow.com/q/22355890
tagged with: python
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/83648323
type: Question
upvote count: 4
linked to: http://stackoverflow.com/q/18807322
has comment: http://stackoverflow.com/comment/83648402
has body: I am learning SQLalchemy, so I decided to make a small database with a few tables in order to understand the way it works. In the docs and tutorials it all seems so clear, but when I start coding, I get long error messages, and right now I am stuck with this one. I am trying to create 3 related tables in a store application that manages repairs: repairs, contacts and products. A repair will always have a single product (the one being repaired), a costumer (the person who owns the product) and a supplier (the external company responsible for the warranty exchange or the repair). I had decided to have a single 'contacts' table to store both the suppliers and the costumers. But now I am getting a sqlalchemy.exc.AmbiguousForeignKeysError. I have been reading the "relationships" section in the docs, but no idea about this message. Here is my sample code: #!/usr/bin/env python3.6 # encoding: utf-8 from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey, MetaData from sqlalchemy.orm import relationship, backref from random import choice Base = declarative_base() class Contact(Base): __tablename__ = 'contact' id = Column(Integer, primary_key=True) name = Column(String, nullable=False) class Product(Base): __tablename__ = 'product' id = Column(Integer, primary_key=True) product_descr = Column(String, nullable=False) class Repair(Base): __tablename__ = 'repair' id = Column(Integer, primary_key=True) costumer_id = Column(Integer, ForeignKey('contact.id')) costumer = relationship("Contact", backref=backref('repair', uselist=True)) product_id = Column(Integer, ForeignKey('product.id')) product = relationship("Product", backref=backref("repair", uselist=True)) supplier_id = Column(Integer, ForeignKey('contact.id')) supplier = relationship("Contact", backref=backref("repair", uselist=True)) def init_database(): engine = create_engine('sqlite+pysql…
has comment: http://stackoverflow.com/comment/83648262
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83648170
downvote count: 0
duplicate of: http://stackoverflow.com/q/18807322

http://stackoverflow.com/q/48275290
has body: I'm new to Javascript and trying to parse through it using Python but i've been giving it a go using BeautifulSoup along with Requests to extract the 'file' line out of the 'RT.currentVideo' section of this script, but i can't seem to. I'm completly lost as to how i'd even be able to store this section of the webpage as it doesn't have an identifier like most other questions related to this i've found online. Any help would really be appreciated, thanks for taking the time to check in! This is what i've been using to read the page: url = "http://roosterteeth.com/episode/rt-docs-connected-connected-official-trailer" req = Request(url, headers={'User-Agent': 'Mozilla/5.0', 'Accept-Encoding': 'utf-8'}) response = urlopen(req) webpage = BeautifulSoup(response.read().decode('utf-8', 'ignore'), "html.parser") And this is the Javascript block on the page i want to extract info from. Again, what i'm looking to get is the string in the 'file' variable. &lt;script&gt; RT.currentVideo = { authUser: 0, autoPlay: 1, csrfToken: 'H240Yw8x9oYasUw2Tzt3qpwzA14Z1ajRjuXo6RV1', endPoint: 89, desktopAgent: 1, file: 'https://rtv2-video.roosterteeth.com/uploads/videos/0e840b4f-a188-440d-adc0-b78093c1009f/index.m3u8',
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/48276856
downvote count: 0
has answer: http://stackoverflow.com/a/48276856
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48277174
answer count: 2
has answer: http://stackoverflow.com/a/48277174
has comment: http://stackoverflow.com/comment/83534446
has title: Extracting variable from Javascript script block
tagged with: javascript
tagged with: python

http://stackoverflow.com/a/48260805
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83507897
accepted answer of: http://stackoverflow.com/q/48259782
type: Answer
answers question: http://stackoverflow.com/q/48259782
has body: In your first case , locator(//*[@id="selTeamSeason"]) is pointing to season dropdown of Teams tab and page has only one matching node at the time ,so its working for you. But in the second case , for the same locator there are 2 matching nodes are available and in this case selenium automatically pick the first one(Its an hidden element in your case). So try to build a unique xpath with can work in both the tabs. You can try //div[@id='stats-player-stats']//select[@id='selTeamSeason'] locator for season dropdown in Players tab and //div[@id='stats-team-stats']//select[@id='selTeamSeason'] for season dropdown in Teams tab Hope this will work for you
score: 1

http://stackoverflow.com/comment/83328812
type: AnswerComment
comment on: http://stackoverflow.com/a/48174131
type: Comment
has text: You are totally correct. PyQt was messing with my locale. Because of that I wasn't getting that error when testing with the REPL alone.
score: 0

http://stackoverflow.com/q/48254555
score: 2
type: AnsweredQuestion
tagged with: pandas
has body: I have a DataFrame which looks like this: Col1 Col2 Col3 Col4 Datetime 2016-11-01 1 Male 01/11/2016 Durham 2016-11-01 2 Female 01/11/2016 Durham 2016-11-02 3 Female 02/11/2016 New 2016-11-02 4 Male 02/11/2016 Ips 2016-11-03 5 Male 03/11/2016 Durham What I am trying to do, is return the count of Col4 entries per day and hence return information like: ColA ColB Datetime 2016-11-01 Durham 2 2016-11-02 New 1 2016-11-02 Ips 1 2016-11-03 Durham 1 I.E. Durham occurred twice on the 1st, so it has a count of 2. New and Ips both occurred once on the 2nd, so they both have a count of 1. Finally Durham occurred once on the 3rd, so it will be given a count of 1. Ultimately I am trying to define a "frequency" so that I can define a "hotspot" by region. If something occurs at least once every day, then I'll call it a "hotspot".
tagged with: datetime
tagged with: dataframe
favorite count: 0
has title: Return the count of unique column entries per day in a datetime DataFrame
type: Question
has answer: http://stackoverflow.com/a/48254579
upvote count: 2
downvote count: 0
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48254579

http://stackoverflow.com/a/48290463
answers question: http://stackoverflow.com/q/48286251
has comment: http://stackoverflow.com/comment/83566240
score: 2
accepted answer of: http://stackoverflow.com/q/48286251
downvote count: 0
has body: I've found the problem. You're checking if event.type == pygame.quit(): in the event loop whereas you should check if event.type == pygame.QUIT:. That means the first time the event loop is executed, you call pygame.quit() in this line and uninitialize all modules whereupon you cannot use many pygame functions anymore and the pygame.error is raised. I think you actually want your program to look more like this version: import pygame pygame.mixer.init(44100, -16,2,2048) class Player(pygame.sprite.Sprite): def __init__(self, *groups): super(Player, self.__init__(*groups)) self.image = pygame.image.load('Sprite-01.png') self.rect = pygame.rect.Rect((320, 240), self.image.get_size()) class Game(object): def main(self, screen): # pygame.mixer.music.load('The Tonight Show Star Wars The Bee Gees Stayin Alive Shortened.mp3') # pygame.mixer.music.play(-1, 0.0) # image = pygame.image.load('Sprite-01.png') image = pygame.Surface((30, 50)) image.fill((0, 90, 240)) clock = pygame.time.Clock() # initialize variables image_x = 0 image_y = 0 done = False while not done: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: done = True key = pygame.key.get_pressed() if key[pygame.K_LEFT]: image_x -= 10 if key[pygame.K_RIGHT]: image_x += 10 if key[pygame.K_UP]: image_y -= 10 if key[pygame.K_DOWN]: image_y += 10 screen.fill((200, 200, 200)) screen.blit(image, (image_x, image_y)) pygame.display.flip() # pygame.mixer.music.stop(52) if __name__ == '__main__': pygame.init() screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption('St.Patrick game') Game().main(screen) pygame.quit()
upvote count: 2
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/48309877
tagged with: rest
has comment: http://stackoverflow.com/comment/83607369
type: Question
score: 0
has answer: http://stackoverflow.com/a/48330851
has title: Is there an alternative way to request JSON REST API in django?
has body: I currently have a fully working Serializers using the Django REST Framework. I want to be able to parse data or request data that can be used in my django app. I have been using import requests r = requests.get('django_api_url') data = json.loads(r.text) I have no problem using this, but I'm trying to see if there's a better/faster way. EDIT: Basically looking for something to replace requests.get()
has answer: http://stackoverflow.com/a/48309955
answer count: 2
has comment: http://stackoverflow.com/comment/83609235
tagged with: django
tagged with: python
type: UnansweredQuestion
tagged with: django-rest-framework

http://stackoverflow.com/q/48230149
downvote count: 0
has comment: http://stackoverflow.com/comment/83442959
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/48230282
has title: Template form does not render in Django
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83442369
has comment: http://stackoverflow.com/comment/83442669
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83442879
tagged with: django
tagged with: python
has body: I have a form that I want to display. It looks like this: # The template to be filled with the form: # base.html {% load staticfiles %} {% block title %}{% endblock %} {% block content %}{% endblock %} The concrete template # home.html {% extends 'base.html' %} {% block title %}Main{% endblock %} {% block content %} Home page {% csrf_token %} {{ form.as_p }} Login {% endblock %} views.py def home(request): context = locals() template = 'home.html' return render(request, template, context) urls.py from django.conf.urls import url from .views import home as home_view urlpatterns = [ url(r'^home/$', home_view, name='home'), ] This does not draw the {{ form.as_p }}. It only draws the submit button. Any ideas why?

http://stackoverflow.com/q/48283886
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/65820809
has answer: http://stackoverflow.com/a/48302646
has comment: http://stackoverflow.com/comment/83587757
has comment: http://stackoverflow.com/comment/83559762
has comment: http://stackoverflow.com/comment/138934992
has body: My function needs to accept an object, from which data can be extracted by index, viz. a List or an instance with defined __getitem__ method. Which type can I use for type hinting this argument? Update: As I understand there are presently no such type, I tried to make one myself: class IndexableContainer(Generic[int, ReturnType]): def __getitem__(self, key: int) -> ReturnType: ... But I get the following error: File "indexable_container.py", line 22, in IndexableContainer class IndexableContainer(Generic[int, ReturnType]): File ".../lib/python3.6/typing.py", line 682, in inner return func(*args, **kwds) File ".../lib/python3.6/typing.py", line 1112, in __getitem__ "Parameters to Generic[...] must all be type variables") TypeError: Parameters to Generic[...] must all be type variables How should I do it?
linked to: http://stackoverflow.com/q/42486006
has comment: http://stackoverflow.com/comment/83552175
linked to: http://stackoverflow.com/q/55127855
has comment: http://stackoverflow.com/comment/83588424
tagged with: python
has answer: http://stackoverflow.com/a/48314895
accepted answer: http://stackoverflow.com/a/48314895
has comment: http://stackoverflow.com/comment/83587860
type: AnsweredQuestion
has title: Python type-hinting, indexable object
answer count: 3
has comment: http://stackoverflow.com/comment/83588200
downvote count: 0
has answer: http://stackoverflow.com/a/65820809
upvote count: 21
score: 21
has comment: http://stackoverflow.com/comment/83555221
has comment: http://stackoverflow.com/comment/138938879
has comment: http://stackoverflow.com/comment/138946961
has comment: http://stackoverflow.com/comment/83588915
has comment: http://stackoverflow.com/comment/138938616
tagged with: python-typing

http://stackoverflow.com/a/48213484
has comment: http://stackoverflow.com/comment/83408796
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48213412
accepted answer of: http://stackoverflow.com/q/48213412
has body: Try the following - sudo apt-get install python3-tk tkinter cannot be installed via pip (as far as I know).
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/48223921
type: Answer
has comment: http://stackoverflow.com/comment/83440333
has body: The problem is that you are using the 'sparse_categorical_crossentropy' loss with class_mode='binary' in your ImageDataGenerator. You have two possibilities here: Change the loss to 'categorical_crossentropy' and set class_mode='categorical'. Leave the loss as is but set class_mode='sparse'. Either will work. Refer to this answer for the difference between the two losses (in Tensorflow, but it holds for Keras too). The short version is that the sparse loss expects labels to be integer classes (e.g. 1, 2, 3...), whereas the normal one wants one-hot encoded vectors (e.g. [0, 1, 0, 0]). Cheers EDIT: as @Simeon Kredatus pointed out, it was a normalization issue. This can be easily solved by setting the appropriate flags in the ImageDataGenerator constructors for both training and test sets, namely samplewise_center=True and samplewise_std_normalization=True. Updating the answer so people can see the solution. In general, remember the trash-in-trash-out principle.
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83432335
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83798218
has comment: http://stackoverflow.com/comment/83438067
answers question: http://stackoverflow.com/q/48217119
has comment: http://stackoverflow.com/comment/83764857
has comment: http://stackoverflow.com/comment/83469509
accepted answer of: http://stackoverflow.com/q/48217119

http://stackoverflow.com/q/48291861
has title: Python: Using Tuples get filtered list
has answer: http://stackoverflow.com/a/48292067
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
score: -3
tagged with: python
tagged with: tuples
has comment: http://stackoverflow.com/comment/83569091
has body: Input Format : The first line of input is an integer that corresponds to the number of records, 'n'. The next 'n' line corresponds to the records. The last line of input consists of the date to be filtered. Output format : The first line of the output is a set of comma seperated strings containing the cargo name and date. The next lines consists of the names of the cargos printed one next to the other seperated by new line. Refer to sample input and output for formatting specifications and more details. Sample Input 1: 5 Allegan,11-12-2013 Douglas,29-12-2016 Junkers,27-03-2017 Biruinta,10-04-2014 ABC,27-03-2017 27-03-2016 Expected Sample Output 1: [('Allegan', '11-12-2013'), ('Douglas', '29-12-2016'), ('Junkers', '27-03-2017'), ('Biruinta', '10-04-2014'), ('ABC', '27-03-2017')] Douglas Junkers ABC Code that was written: n=int(input()) list1=[] i=0 for i in range(0,n): string1=raw_input() i+=1 string1=string1.split() for item in string1: list1.append(item) dateformat=raw_input() mutuple = tuple(list1) I am unable to split input from my list and get desired output by comparing as per the question. Can you please help
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/83610513

http://stackoverflow.com/comment/83696082
score: 1
type: Comment
type: QuestionComment
has text: So you **are** using some spline. In that case we need to see the code you have the problem with, because the code you currently have produces the desired output, right?!
comment on: http://stackoverflow.com/q/48323164

http://stackoverflow.com/comment/83415517
score: 0
type: Comment
type: QuestionComment
has text: @DanielRoseman When I search the full repository the only hit for `dj-database-url` is in the `Pipfile.lock` and there is no hits for `DATABASE_URL` anywhere. I appreciate you trying to help me!
comment on: http://stackoverflow.com/q/48214884

http://stackoverflow.com/comment/83615452
comment on: http://stackoverflow.com/q/48314694
type: QuestionComment
type: Comment
has text: Either you can use https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html To get all information or you can build custom library for each OAuth for google oauth https://github.com/anupy/google-oauth For other service providers you can use your own (custom)
score: 0

http://stackoverflow.com/a/48246182
downvote count: 0
upvote count: 5
score: 5
type: Answer
answers question: http://stackoverflow.com/q/48246092
has comment: http://stackoverflow.com/comment/83475044
has body: Here is a version of the intersect function, that intersects the keys and uses the values of the first dictionary, that means in case of different values, this function is biased towards the value in the first dictionary: def intersect(a, b): return {k: a[k] for k in a.keys() &amp; b.keys()} This works because, the dict_keys view objects returned by dict.keys() (since Python 3) are sets (i.e. implement collections.abc.Set). If you want to customize, which value will be used, we can use a function, that takes both values: def intersect(a, b, select=lambda a, b: a): return {k: select(a[k], b[k]) for k in a.keys() &amp; b.keys()} Instead of returning one of the values, we could then also e.g. add the values: &gt;&gt;&gt; intersect({'a': 4, 'b': 3}, {'a': 5}, lambda a, b: a + b) {'a': 9}
has comment: http://stackoverflow.com/comment/83484748

http://stackoverflow.com/comment/83612611
has text: Still getting the element not visible error when it ran button.click() "selenium.common.exceptions.ElementNotVisibleException: Message: element not visible"
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48313304

http://stackoverflow.com/comment/83398972
comment on: http://stackoverflow.com/q/48208839
score: 0
type: Comment
type: QuestionComment
has text: Also whats the difference between a class and a class method? Not sure who attached the `class method` answer.. but it doesnt seem to be related to what I asked here?

http://stackoverflow.com/a/48305418
answers question: http://stackoverflow.com/q/48293590
score: 0
has body: There's an easier way to do this. You can use an XPath that will specify the category name you want to click. That way you don't have to loop, it will find the desired element in one search. //span[@name='topCategory'][.='Beauty'] I'm assuming you will be reusing this code. In cases like this, I would create a function that takes a string parameter which would be the category name that you want to click. You feed that parameter into the XPath above and you can then click any category on the page. I tested this and it's working.
type: Answer

http://stackoverflow.com/a/48208721
upvote count: 1
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48208507
has body: you are using packb() which returns packed bytes, so to unpack , should use unpackb() unpacmsgpack.unpackb(msgpack.packb(item1))
score: 0

http://stackoverflow.com/q/48189252
type: Question
has comment: http://stackoverflow.com/comment/83359276
has comment: http://stackoverflow.com/comment/86534561
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83383751
tagged with: pygame
tagged with: module
has comment: http://stackoverflow.com/comment/83374872
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/23319059
upvote count: 0
has title: Pygame input window (think like the input textboxes from stackoverflow)
has comment: http://stackoverflow.com/comment/83382763
has comment: http://stackoverflow.com/comment/83404936
has answer: http://stackoverflow.com/a/67159042
accepted answer: http://stackoverflow.com/a/67159042
answer count: 1
downvote count: 1
has body: I'm creating a game with pygame. Then and again I want to let the player type something - multiple lines, with the option to click anywhere into the text and edit from there. You can think of it pretty much like the post/comment input window here on stackoverflow. So far the only thing I have found are other modules, and most of the modules dont have the functionality, that I can click with my mouse between any two letters and edit/type from there. The only thing I have found, that is able to do that is Tkinter widgets, but I cannot get them working inside my pygame window. I found something where pygame was blitting onto a Tkinter frame, but since my entire game is based on pygame, I would not like to change everything in order to implement the textbox. Does anyone know of a input textbox tool/module with the described functionalities, which works with pygame?
tagged with: textbox
has comment: http://stackoverflow.com/comment/86534593
favorite count: 0

http://stackoverflow.com/q/48235701
has comment: http://stackoverflow.com/comment/83454077
has body: I have an Linux instance running on Google Compute Engine. I installed pip and django on it and cloned a Django project that I worked on locally. Like I would on localhost I ran my app like so: python3 manage.py runserver 0.0.0.0:8080, and my server was up and running with no problems. I read online on how WSGI servers are required for python apps to run well on servers however I don't see why I would need something like gunicorn to run my app
accepted answer: http://stackoverflow.com/a/48235754
tagged with: django
tagged with: google-compute-engine
tagged with: python
has answer: http://stackoverflow.com/a/48235754
score: -1
type: AnsweredQuestion
has title: What is the point of using Gunicorn when hosting a Django project on Linux VM
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83454089
downvote count: 1
favorite count: 0
type: Question
tagged with: gunicorn
tagged with: linux

http://stackoverflow.com/q/48212964
has comment: http://stackoverflow.com/comment/83408971
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/48213774
has comment: http://stackoverflow.com/comment/83408495
possible better answer: http://stackoverflow.com/a/48218546
has comment: http://stackoverflow.com/comment/83408624
has answer: http://stackoverflow.com/a/48213774
type: Question
has comment: http://stackoverflow.com/comment/83408779
tagged with: systemd
tagged with: linux
has body: I'm trying to create an install script with Python to create a daemon using systemd. Exctract of install script: .... # Copy ProcessManager directory into /usr/local/bin/ print('Copy sources into /usr/local/bin') os.system('cp -r ' + processManagerPath + ' /usr/local/bin') fileContent = '[Unit] \n' \ 'Description=ProcessManager \n' \ 'After=tlp-init.service \n\n' \ '[Service] \n' \ 'Type=oneshot \n' \ 'RemainAfterExit=no \n' \ 'ExecStart=/usr/bin/python /usr/local/bin/ProcessManager/gobatch.py \n\n' \ '[Install] \n' \ 'WantedBy=multi-user.target' file = open('/etc/systemd/system/processManager.service', 'w') file.write(fileContent) file.close() .... However, when I start my daemon with: sudo systemctl status processManager.service I get this error: stringToSend = convertFileToString() File "/usr/local/bin/ProcessManager/gobatch.py", line 23, in convertFileToString fbatchContent = readFile() File "/usr/local/bin/ProcessManager/gobatch.py", line 13, in readFile with open("FBatch", "r") as f: IOError: [Errno 2] No such file or directory: 'FBatch' And when I list /usr/local/bin/ProcessManager the content is: FBatch findCommand.py gobatch.py install.py Programs.md UpdateFBatchFile.py It exists something that I don't know about cp -r? or about privileges? Thank's for help!
has title: File not found after a directory copy
has comment: http://stackoverflow.com/comment/83408898
has comment: http://stackoverflow.com/comment/83408573
tagged with: python
has answer: http://stackoverflow.com/a/48218546

http://stackoverflow.com/comment/83561908
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/48288526
has text: Not directly related to your question, but general advice: take the time to get familiar with all of the methods available in the `random` module, not just `randint`. In particular I think `shuffle`, `choice`, and `sample` are useful for card games. And if you're thinking "but methods that take elements from a single sequence aren't useful to me because I need to take elements from the two sequences `deck_of_cards` and `value` in parallel", think about how you might condense those two lists into a single list.

http://stackoverflow.com/comment/83614583
type: QuestionComment
comment on: http://stackoverflow.com/q/48314387
score: 0
has text: have you tried `setattr(TempUser,'print_name',property(print_name))`
type: Comment

http://stackoverflow.com/comment/83368164
type: QuestionComment
comment on: http://stackoverflow.com/q/48193767
has text: um, that looks like JSON. What are you talking about with regards to "columns" and "type Object"??? What is a "cell?" Please provide a [mcve]
score: 0
type: Comment

http://stackoverflow.com/comment/83330949
type: AnswerComment
has text: Your event may not be a valid JSON.
comment on: http://stackoverflow.com/a/48175337
score: 0
type: Comment

http://stackoverflow.com/comment/83528554
has text: Possible duplicate of [Displaying inline images on iPhone, iPad](https://stackoverflow.com/questions/10103210/displaying-inline-images-on-iphone-ipad)
type: Comment
comment on: http://stackoverflow.com/q/48272100
type: QuestionComment
score: 0

http://stackoverflow.com/a/48304253
accepted answer of: http://stackoverflow.com/q/48302987
answers question: http://stackoverflow.com/q/48302987
has body: Try this... from nltk.corpus import wordnet as wn ss = wn.synset('car.n.01') print min([len(path) for path in ss.hypernym_paths()]) hypernym_paths() gives you a list of the possible paths back to the root, which for a noun is entity.n.01.
type: Answer
type: AcceptedAnswer
score: 6
downvote count: 0
upvote count: 6

http://stackoverflow.com/comment/83444684
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48231135
type: AnswerComment
has text: So what if it’s an “anti pattern”... it’s a useful debugging “pattern” that saves me time... that’s interesting I didn’t think of using the import to lookup the module object. Thanks. That’s why I had to get strange with the exec statements.

http://stackoverflow.com/q/48291449
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83568026
has body: I understand that the dot operator is accessing the method specific to an object that is an instance of the class containing that method/function. However, in which cases do you instead call the function directly on an object, in the form func(obj) as opposed to obj.func()? Can both techniques always be implemented (at least in custom code) or are there certain cases in which the former should be used over the latter, and vice versa? I had previously read that the form func(obj) is for processing data that the object holds, but why would this not be possible with doing obj.dataMember.func(), is there an advantage to passing just the object, such as some change in mutability?
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/83569937
has answer: http://stackoverflow.com/a/48291494
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83568040
has comment: http://stackoverflow.com/comment/83568023
favorite count: 0
has title: In Python, when should an object be passed as an argument as opposed to calling the method on object with the dot operator?
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/83585226

http://stackoverflow.com/q/48231758
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/83445759
score: 6
upvote count: 6
has title: Merge Pandas Dataframes based on date
type: AnsweredQuestion
tagged with: pandas
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83445961
favorite count: 0
accepted answer: http://stackoverflow.com/a/48231959
type: Question
has answer: http://stackoverflow.com/a/48231959
has comment: http://stackoverflow.com/comment/83446194
has body: I'm looking to merge two pandas DataFrames based on date. The issue is the 2nd dataframe does not include every date from the 1st dataframe. I need to use every date from df1 with the latest value from df2. +-------------+---------------+-------------+ | DataFrame 1 | | | +-------------+---------------+-------------+ | Date | Sales loc1 | Sales loc2 | | 1/1/17 | 100 | 95 | | 1/2/17 | 125 | 124 | | 1/3/17 | 115 | 152 | | ... | | | | 2/1/17 | 110 | 111 | +-------------+---------------+-------------+ +-------------+---------+------+ | DataFrame 2 | | | +-------------+---------+------+ | Date | exp | loc | | 1/1/17 | 100 | 1 | | 1/1/17 | 125 | 2 | | 2/1/17 | 115 | 1 | | 2/1/17 | 110 | 2 | +-------------+---------+------+ +---------------+---------------+--------------+------------+-------------+ | New Dataframe | | | | | +---------------+---------------+--------------+------------+-------------+ | Date | Sales loc1 | Sales loc2 | exp loc1 | exp loc2 | | 1/1/17 | 100 | 95 | 100 | 125 | | 1/2/17 | 125 | 124 | 100 | 125 | | 1/3/17 | 115 | 152 | 100 | 125 | | ... | | | | | | 2/1/17 | 110 | 111 | 115 | 110 | +---------------+---------------+--------------+------------+-------------+ The values from df2 will be used for multiple cells till there is a new value in df2. Thanks a lot for your time.
has comment: http://stackoverflow.com/comment/83445974

http://stackoverflow.com/q/48320167
has answer: http://stackoverflow.com/a/48320350
type: Question
tagged with: jenkins
has title: Running a python script from jenkins - but can't see the python prints in the output of jenkins
type: UnansweredQuestion
tagged with: python
has body: I am running Python script from Jenkins but the prints of Python doesn't shows in the jenkins output Jenkins output example: "Started by user anonymous Building in workspace C:\Program Files (x86)\Jenkins\workspace\Testing Sanity [Testing Sanity] $ cmd.exe /c call C:\windows\TEMP\shiningpanda6085220944592659293.bat C:\Program Files (x86)\Jenkins\workspace\Testing Sanity&gt;nosetests C:\Users\asafb\PycharmProjects\Sanity_HB_RR_from_Saved_Pos\Check_Newly_Created_Cluster_Monitor.py C:\Program Files (x86)\Jenkins\workspace\Testing Sanity&gt;exit 0 Finished: SUCCESS"
downvote count: 0
upvote count: 1
score: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/a/48276271
score: 0
has comment: http://stackoverflow.com/comment/83573821
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83587417
accepted answer of: http://stackoverflow.com/q/48274696
has comment: http://stackoverflow.com/comment/83536105
type: Answer
answers question: http://stackoverflow.com/q/48274696
has body: I found your error. You have referenced the input data to be strings (%s). But you are putting in integers (numbers). If you want to put the numbers as strings, in the first chunk of code (yours), you need to put in str(variable) instead of just variable. In the second chunk of code (copied from MySQL), you can declare the variables as variable = "0000" with the quotes. If you want to work with numbers in your code, change the table structure to be INTEGER or DOUBLE instead of VARCHAR or CHAR. I would assume that the table is present and all fields are present as there is no error connecting to the database and finding the table.
has comment: http://stackoverflow.com/comment/83536401

http://stackoverflow.com/a/48186294
has body: After successful echo operation of user message, you can integrate Wit API to your Flask application. This will add NLP functionalities to your bot. Here is a good short tutorial series of how to integrate Wit API to provide NLP services in messenger bot: Facebook Messenger Bot Tutorial (using Python) | Wit.ai Integration (Part-1) Finish the 8th, 9th and 10th tutorials and you will get some head start on this. Good luck!
answers question: http://stackoverflow.com/q/48184712
type: Answer
score: 0

http://stackoverflow.com/a/48235935
type: Answer
answers question: http://stackoverflow.com/q/48235813
score: 1
downvote count: 0
upvote count: 1
has body: I'd suggest using python's built-in lexical analysis tool, shlex. It is very useful as it contains functionality that makes it easy to write a (simple) lexical analyzer. So in your case you can do something like this: import shlex user_input = 'My day was good' li = shlex.split(user_input) print 'Your day was good' if 'good' in li else 'Your day was bad' The prints here are for demonstrating purposes only. You have to substitute them with your code that will choose the correct response for "good".

http://stackoverflow.com/comment/83496148
score: 0
comment on: http://stackoverflow.com/a/48236977
type: Comment
type: AnswerComment
has text: This is super helpful explanation, @andrew_reece! Thank you! Now I understand how and when to use the '.' and '*' notations :)

http://stackoverflow.com/comment/83652101
type: AnswerComment
has text: Thanks, your solution might be the better one, but what I found is the ID of SVG element(parents of SVG element) might be generated by js or something else which will be different every time. That's the reason my scrapy spider cannot crawl anything. I can easily solve this by locate the parents of that element which the ID won't change, then follow index path to get the data I want. (Might only work for my case)
score: 0
comment on: http://stackoverflow.com/a/48317862
type: Comment

http://stackoverflow.com/comment/83603914
comment on: http://stackoverflow.com/a/48308811
has text: sorry but some of methods i want to use in flickr not flickrapi !!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83631489
type: AnswerComment
comment on: http://stackoverflow.com/a/48321959
score: 0
has text: Hi Nico Albers,thank you very much, your method works! I would further know how np.array works here? It seems that it converts list containing of multiple characters back again to a array, right?
type: Comment

http://stackoverflow.com/a/74978022
has body: Similar to @Aditi , I also like to use glob for this. Just adding a slight variation to help teach our future GPT Transformer based code assist tools . In my case, I needed this to iterate over ".jpg" and ".JPG", so I did this, from glob import glob from functools import reduce from collections import Counter from pathlib import Path workdir = "my/blah/dir" extensions = ["jpg", "JPG", "jpeg", "JPEG"] files = reduce( lambda x, y: x + y, [glob(str(Path(workdir) / f"*.{extension}")) for extension in extensions]) Counter([Path(x).suffix for x in files]) Counter({'.jpg': 267, '.JPG': 281})
answers question: http://stackoverflow.com/q/48181073
type: Answer
score: 0

http://stackoverflow.com/comment/83363781
score: 0
type: Comment
type: AnswerComment
has text: @BloodyD Both solutions as in your stack based one and this one? I think to see performance gains with this one, you would need a lot more number of windows, i.e. a large number of rows in `locations`.
comment on: http://stackoverflow.com/a/48191338

http://stackoverflow.com/q/48299491
answer count: 1
tagged with: pyqt5
has title: How to add listener in PyQT TableView's select all button?
has comment: http://stackoverflow.com/comment/83584174
downvote count: 1
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48300155
tagged with: pyqt4
tagged with: python
tagged with: qtableview
type: Question
has body: How do I attach a listener to PyQT's TableView's select all button? PyQT TableView Sample I have tried using below which only gets triggered when a cell is selected. table.clicked.connect() I have also tried adding listener to both header which only gets triggered when the columns or rows are selected table.horizontalHeader().sectionClicked.connect() table.verticalHeader().sectionClicked.connect() They are all working as what they are intended to do, however I want to add listener to the top left button, the select all button. I can't seem to find from Qt's documentation that mentions this particular part of the button. Code: # Imported from Qt Designer created dialog dialog = x.UI_Dialog() table = dialog.tableSchedule table.setModel(___) # I used my custom model that inherits from QtCore.QAbstractTableModel table.clicked.connect(lambda: print('cell')) table.horizontalHeader().sectionClicked.connect(lambda: print('col')) table.verticalHeader().sectionClicked.connect(lambda: print('row')) Answer (by @eyllanesc): Get the corner button of the QTableView and add listener to it. corner = table.findChild(QAbstractButton) corner.clicked.connect(___) Upon further inspection by getting the children of QTableView, these are the components: 3 QWidget QStyledItemDelegate 2 QHeaderView QAbstractButton QItemSelectionModel
score: 0
has comment: http://stackoverflow.com/comment/83583785
upvote count: 1
tagged with: pyqt
has answer: http://stackoverflow.com/a/48300155

http://stackoverflow.com/q/48242145
tagged with: psychopy
accepted answer: http://stackoverflow.com/a/48244856
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has title: Various duration in psychopy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48244856
tagged with: time
tagged with: python
has body: I have an experimentation of n-back. I have letter that appear for a maximum of 2.5 sec and then a fixation cross for 0.5 sec. Right now: When the participant pressed on the keyboard, it ends the routine and go directly to the fixation cross. I have 60 letters so the experimentation would take at max 3 minutes, but it can be less if the participant pressed fast. What I want : My experimentation should take 3 min at every time. So the fixation cross should stay for more than 0.5 sec if the participant answer fast Do you have an idea how to do that ? I was thinking about creating a variable that equals 3. And then if text is 2 sec then 3-2 = 1 so fixation would be 1 sec, but I was not able to write that in my code component Thanks!!

http://stackoverflow.com/comment/83489897
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48253666
type: AnswerComment
has text: @MadhavNakar There's hardly anyway to delete repeatedly from a list in-place in linear time. Your best bet is a list comp.

http://stackoverflow.com/q/48280733
duplicate of: http://stackoverflow.com/q/31736671
has answer: http://stackoverflow.com/a/48280774
downvote count: 0
answer count: 1
has title: how to group by list ranges of value in python pandas
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/31736671
has body: I have following dataframe name,value a,100 b,200 c,150 d,300 e,400 f,200 g,100 i have list of ranges like [0-100,100-200,more than 200] based on this i have to take count of records in above dataframe. i need output like category,count 0-100,2 100-200,3 mor than 200,3
upvote count: 2
accepted answer: http://stackoverflow.com/a/48280774
tagged with: python
has comment: http://stackoverflow.com/comment/83545015
score: 2
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/comment/83560911
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48287841
has text: @juanpa.arrivillaga The OP was clear about sorting the values of the dicts and not the dicts themselves. This actually makes perfect sense.

http://stackoverflow.com/comment/83424877
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48221731
score: 0
has text: What is the question in the end? *Homebrew in the PATH env* or *python3 default*?

http://stackoverflow.com/comment/83401254
type: QuestionComment
comment on: http://stackoverflow.com/q/48209497
has text: `a` is a single floating point number? Strange. I wouldn't expect printing a float to give you five lines of datetimes.
score: 1
type: Comment

http://stackoverflow.com/q/48269844
downvote count: 0
tagged with: dataframe
has answer: http://stackoverflow.com/a/48270834
has comment: http://stackoverflow.com/comment/83524026
favorite count: 0
type: Question
has body: I want to overwrite my df1.Name values based on a mapping table in (df2.Name1, df2.Name2). However, not all values in df1.Name exist in df2.Name1 df1: Name Alex Maria Marias Pandas Coala df2: Name1 Name2 Alex Alexs Marias Maria Coala Coalas Expected Result: Name Alexs Maria Maria Pandas Coalas I have tried several solutions online such as using the Map function. By turning df2 in a Dictionary I am using df1.Name = df1.Name.map(Dictionary), but this will result in nan for all values not in df2 as per below. Name Alexs Maria Maria NAN Coalas I am not sure how to use an IF statement to replace only the ones that do exist in df2 and keep the rest as per df1. I also tried to create a function with if statements, but was big time failure. How I could approach this problem?
has answer: http://stackoverflow.com/a/48270211
answer count: 5
tagged with: matching
accepted answer: http://stackoverflow.com/a/48270441
score: 6
possible better answer: http://stackoverflow.com/a/48270109
tagged with: python
has answer: http://stackoverflow.com/a/48270441
tagged with: dictionary
upvote count: 6
has answer: http://stackoverflow.com/a/48270109
type: AnsweredQuestion
has title: Replace a value in a column by vlookup another dataframe only if the value exists
tagged with: pandas
has answer: http://stackoverflow.com/a/48270410

http://stackoverflow.com/a/48279403
has comment: http://stackoverflow.com/comment/83547967
has comment: http://stackoverflow.com/comment/83543971
has comment: http://stackoverflow.com/comment/83545025
has comment: http://stackoverflow.com/comment/83547164
score: 1
has comment: http://stackoverflow.com/comment/83545871
has comment: http://stackoverflow.com/comment/83547322
has comment: http://stackoverflow.com/comment/83546950
upvote count: 1
has comment: http://stackoverflow.com/comment/83554718
has comment: http://stackoverflow.com/comment/83544642
answers question: http://stackoverflow.com/q/48276631
has body: Here is a sorting based solution. One could try and be a bit smarter and use bincount and argpartition to avoid the sorting, but at N &lt;= 500 it's not worth the trouble. import numpy as np def flexibin(a): idx0 = np.argsort(a) as_ = a[idx0] A = np.r_[as_, as_+2] idx = np.argsort(A) uinv = np.flatnonzero(idx &gt;= len(a)) linv = np.empty_like(idx) linv[np.flatnonzero(idx &lt; len(a))] = np.arange(len(a)) bins = [0] curr = 0 while True: for j in range(uinv[idx[curr]], len(idx)): if idx[j] &lt; len(a) and A[idx[j]] &gt; A[idx[curr]] + 2: bins.append(j) curr = j break else: return np.split(idx0, linv[bins[1:]]) a = 180 * np.random.random((500,)) bins = flexibin(a) mn, mx = zip(*((np.min(a[b]), np.max(a[b])) for b in bins)) assert np.all(np.diff(mn) &gt; 2) assert np.all(np.subtract(mx, mn) &lt;= 2) print('all ok')
has comment: http://stackoverflow.com/comment/83547282
has comment: http://stackoverflow.com/comment/83547255
has comment: http://stackoverflow.com/comment/83545672
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83546115
has comment: http://stackoverflow.com/comment/83546346
has comment: http://stackoverflow.com/comment/83544243

http://stackoverflow.com/a/48314393
type: Answer
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48314010
has body: pip is available with Python by default in most cases. It is the most common tool used for installing python packages. When authors publish Python packages, they include project metadata (like a setup.py, setup.cfg, or pypoject.toml file) that, in part, declares dependencies of a package so packaging tools like pip can resolve the dependencies when you install packages. Some projects may also include one or more requirements.txt files in their source which you can direct pip to gather the required packages IE pip install -r /path/to/requirements.txt Typically speaking, almost all packages you might use are published in the PyPI repository and you merely need to do pip install &lt;package name&gt; and pip will resolve all the required dependencies. There are other tools available as well, which feature things like lockfiles that more closely resemble nodejs lockfiles. pipenv is one tool recommended by PyPA for installing packages and managing dependencies. It bundles features similar to those found in related tools like virtualenv, pipfile, and more. It also gives you similar features to tools in the JavaScript world, such as npm, yarn, etc.
score: 3

http://stackoverflow.com/a/48260589
upvote count: 9
type: Answer
answers question: http://stackoverflow.com/q/48260352
accepted answer of: http://stackoverflow.com/q/48260352
type: AcceptedAnswer
downvote count: 0
score: 9
has body: Maybe I'm missing something, but I think it can be done relatively simply: def mirror(data): if not isinstance(data, tuple): return data return tuple(map(mirror, reversed(data))) &gt;&gt;&gt; mirror(((1, (2, 3)), (4, 5))) ((5, 4), ((3, 2), 1)) This applies the mirror function to every element in the tuple, combining them into one new tuple in reverse order.

http://stackoverflow.com/q/48235938
has answer: http://stackoverflow.com/a/48238822
tagged with: permutation
favorite count: 0
tagged with: recursion
has title: Python permutations of a list, storing value, without mutating
score: 0
has comment: http://stackoverflow.com/comment/83454965
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48236207
has comment: http://stackoverflow.com/comment/83459774
type: Question
answer count: 2
upvote count: 1
type: UnansweredQuestion
has body: I have a hard time writing permutations. Once I find a new algorithm, I bump into mutability. Is there a way to append into newArray, but keep old values untouched? Or how should I modify it? newArray = [] def permutations(array): if array in newArray: return for i in range(len(array)): array[0], array[i] = array[i], array[0] newArray.append(array) permutations(array) return newArray

http://stackoverflow.com/q/48215353
has body: I'm trying to write a program that takes in a person's name and stores it in a .json file. If that person has already run the program on their computer then the program will check the .json file and read that the user has already entered their name, and greet them. If not, the program will prompt them for their name. I think I have it mostly correct. Here's the code: import json def get_stored_username(): """retrieve username of old user""" filename = 'text_files\filenameu.json' try: with open(filename) as usernames: username = json.load(usernames) except FileNotFoundError: return None else: return username def greet_user(): """greet the user by name""" username = get_stored_username() if username: print("Welcome back, " + username + "!") else: username = input("What is your name? ") filename = 'text_files/filenameu.json' with open(filename, 'w') as usernames: json.dump(username, usernames) print("we'll remember you next time you come back, " + username + "!") greet_user() and the error: Traceback (most recent call last): File "jasoncont.py", line 27, in &lt;module&gt; greet_user() File "jasoncont.py", line 16, in greet_user username = get_stored_username() File "jasoncont.py", line 7, in get_stored_username with open(filename) as usernames: OSError: [Errno 22] Invalid argument: 'text_files\x0cilenameu.json' Any help would be greatly appreciated. Thanks!
linked to: http://stackoverflow.com/q/13955176
type: Question
duplicate of: http://stackoverflow.com/q/13955176
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83412574
has comment: http://stackoverflow.com/comment/83412624
has title: basic .json storage and retrieval
score: 0
has comment: http://stackoverflow.com/comment/83413327
answer count: 0

http://stackoverflow.com/comment/83406322
score: 0
type: Comment
has text: Thanks, yeah that's what I'm going to do. Decompose the JSON and use cursor.executemany().
type: QuestionComment
comment on: http://stackoverflow.com/q/48191218

http://stackoverflow.com/comment/83620507
type: Comment
score: 0
has text: Please see [the `readlines` docs](https://docs.python.org/3/library/io.html#io.IOBase.readlines). The arg to `readlines` is a size hint, with the size measured in bytes or characters (depending on which mode the file was opened in). It is **not** the number of lines you want to read.
type: QuestionComment
comment on: http://stackoverflow.com/q/48317329

http://stackoverflow.com/comment/83603130
comment on: http://stackoverflow.com/q/48308350
score: 0
type: Comment
has text: Okay, now you removed the first image (it doesn't look like it was corrected).
type: QuestionComment

http://stackoverflow.com/q/48267620
score: 1
answer count: 1
tagged with: caching
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48270709
has answer: http://stackoverflow.com/a/48270709
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
tagged with: axios
tagged with: django-rest-framework
has body: I'm trying to understand how Etag works in Django. I added middleware in settings ('django.middleware.http.ConditionalGetMiddleware') and this seems to work as it generates the Etag: HTTP/1.0 200 OK Date: Mon, 15 Jan 2018 16:58:30 GMT Server: WSGIServer/0.2 CPython/3.6.0 Content-Type: application/json Vary: Accept Allow: GET, HEAD, OPTIONS X-Frame-Options: SAMEORIGIN Content-Length: 1210 ETag: "060e28ac5f08d82ba0cd876a8af64e6d" Access-Control-Allow-Origin: * However, when I put If-None-Match: '*' in the request header, I get the following error: Request header field If-None-Match is not allowed by Access-Control-Allow-Headers in preflight response. And I notice the request method sent back in the response is OPTIONS and the rest of the headers look like this: HTTP/1.0 200 OK Date: Mon, 15 Jan 2018 17:00:26 GMT Server: WSGIServer/0.2 CPython/3.6.0 Content-Type: text/html; charset=utf-8 Access-Control-Allow-Origin: * Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT Access-Control-Max-Age: 86400 So the question is how do I get If-None-Match to be an allowed header? I'm not sure if this is a server or client issue. I'm using Django/DRF/Vue for my stack and Axios for making http requests.
type: AnsweredQuestion
has title: If-None-Match header not accepted request header

http://stackoverflow.com/comment/83340531
type: AnswerComment
comment on: http://stackoverflow.com/a/48178915
has text: You should be able to use numpy.correlate or numpy.convolve, but it has different bounds handling IIRC.
type: Comment
score: 0

http://stackoverflow.com/comment/83626093
type: Comment
has text: That array has more than 27 elements. What do you mean by "tied together"? It would help if you showed us a small input array and the exact output you want from that input.
type: QuestionComment
comment on: http://stackoverflow.com/q/48320367
score: 1

http://stackoverflow.com/q/48232924
has comment: http://stackoverflow.com/comment/83448266
favorite count: 0
has comment: http://stackoverflow.com/comment/83448314
tagged with: python
has answer: http://stackoverflow.com/a/48232961
linked to: http://stackoverflow.com/q/2104080
has body: I'm not sure how to use the getsize method. What I'd want to do with it is to quit the program if the file size is greater that the specified size.
type: Question
answer count: 2
downvote count: 4
has answer: http://stackoverflow.com/a/48232990
type: UnansweredQuestion
has title: Python quit function if a file size is greater than 5kb
has comment: http://stackoverflow.com/comment/83448231
score: -3
upvote count: 1

http://stackoverflow.com/q/48176175
type: Question
has body: I have python reading long lines and then wrapping them if they exceed x characters and writing them to a new file. I figured out how to ensure words are not split apart, but I have a more specific problem. I don't want specific words to ever appear a the start of a line. After hours of research, I have realized I have been running down the wrong path to fix this and need help. Here's the code I have now: with txtfile as infile, testfile as outfile: for line in infile: if len(line) &gt; 80 and any(word in line[77:] for word in connectives): outfile.write(textwrap.fill(line,96,replace_whitespace=False)) elif len(line) &gt; 80 and not any(word in line[77:] for word in connectives): outfile.write(textwrap.fill(line,80,replace_whitespace=False)) else: outfile.write(line) A little explanation for what I tried to do: Right now it reads a line of a couple hundred characters and if it's more than 80 characters, it wraps it to 80. I had thought that I would see if the last few characters of the line contained any of the words I am targeting and if so, I would lengthen the wrap for those lines, so that the target word wouldn't get dropped to the next line. But I have realized that was faulty thinking (maybe moronic is better) on my part because the if statement checks that first line of several hundred characters. It doesn't then check the subsequent lines as it wraps. In the end, I can avoid breaking at the wrong word on the first line, but not subsequent lines. Since textwrap won't breakup whole words if you don't want it too, I'm hoping there is then a way to also tell it to not allow certain words or characters to be dropped to the next line. Alternatively, perhaps there is a way to read what was wrapped and anytime a specific word appears as the first word on the line, then move it up to the end of the previous line.
has comment: http://stackoverflow.com/comment/83338161
has answer: http://stackoverflow.com/a/48181233
accepted answer: http://stackoverflow.com/a/48181233
has title: How to textwrap.fill text, but prevent specific words from being at the start of the lines?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83333967
answer count: 1
tagged with: python
tagged with: word-wrap

http://stackoverflow.com/comment/83547908
type: QuestionComment
has text: I did not get you question... Do you have dataframe or list ??? What data structure are you using
comment on: http://stackoverflow.com/q/48281925
score: 0
type: Comment

http://stackoverflow.com/comment/83541842
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48278281
has text: What about `df.groupby(['group', pd.Grouper(freq='5Min')]).count()`?
type: Comment

http://stackoverflow.com/q/48293787
has body: I am trying to display a Tree of objects in PyGTK such that when you click on one object, it will move to the previous space and then render its children where it was. For example, if we start with object 1 selected, its children will be displayed. | Level 1 | Level 2 | | -&gt;Object 1&lt;- | Object 1 Child 1 | | Object 2 | Object 1 Child 2 | | Object 3 | Object 1 Child 3 | If we then select one of its children, its children will get displayed. | Level 1 | Level 2 | | -&gt;Object 1 Child 1&lt;- | Object 1 Child 1 Child 1 | | Object 1 Child 2 | Object 1 Child 1 Child 2 | | Object 1 Child 3 | Object 1 Child 1 Child 3 | So we are just traversing through the tree of data. I have implemented this with PyGTK.TreeView's connected to PyGTK.ListStore's that hold the display value of the object, and then another list of the actual objects themselves. I have methods to listen for the PyGTK.TreeViewSelection changed event to do the re-rendering of the data. The problem is, when I am rebuilding the ListStore's, for the new object, the event is getting hit twice, and I can't figure out why. Simply eating the first or second event doesn't seem to work because occasionally only one event is fired. Below is some working sample code illustrating what is happening and kind of what I am trying to do: #!/usr/bin/python3 import gi gi.require_version('Gtk','3.0') gi.require_version('WebKit2','4.0') from gi.repository import Gtk, WebKit2, Gdk class TmpWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self) self.set_position(Gtk.WindowPosition.CENTER) self.connect('delete-event', Gtk.main_quit) self.outerBox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,spacing=6) self.add(self.outerBox) self.urlGrid = Gtk.Grid() self.urlGrid.set_column_homogeneous(True) self.urlGrid.set_row_homogeneous(True) self.outerBox.pack_start(self.urlGrid,False,False,10) # Set the starting lists self.node0List = ['Object'] self.node0GridList = Gtk.ListStore(str) self.node0GridList.append(['ObjectString'…
score: 0
tagged with: pygtk
has title: TreeView Selection Handler triggering twice
tagged with: python
has answer: http://stackoverflow.com/a/48491847
tagged with: python-3.x
type: UnansweredQuestion
answer count: 1
type: Question

http://stackoverflow.com/comment/83622857
comment on: http://stackoverflow.com/q/48318113
type: Comment
has text: So each of your arrays is 32GiB? Then 128GB is not enough to store all of your data
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83604437
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48290132
has text: Can't help. Have never used that website, can't understand enough of the detail.

http://stackoverflow.com/q/48219522
type: Question
has body: I was trying using tensorboard along with tensorflow, and I did this as a set up: rand = tf.placeholder(dtype=tf.float32) # this will be visualised in tensorboard later on tf.summary.image('random_noise_visualisation', rand,max_outputs=5) merged_summary_op = tf.summary.merge_all() # to me this seems like a helper to # merge all tensorboard related operations Then I evaluate my merged_summary_op and feed it a very large array, about 1 GB in size. It does not seem to use any extra GPU memory from the memory that was already being used. I also just tried to evaluate my rand placeholder, thinking maybe summary ops have special handling to prevent data from going to the GPU. I did: random_value = np.random.randn(3000,224,224,1) sess.run(rand,feed_dict={rand:random_value}) There was again, no extra GPU utilisation. However, when I do sess.run(rand + 2 ,feed_dict={rand:random_value}) # forced to do some calculation There is an additional GPU utilisation, with an increase of about 1 GB. for all the above experiments, I used my session as: sess = tf.InteractiveSession(graph=tf.Graph()) My questions are: Does Tensorflow know when to not bother to send a Tensor to the GPU ? Will changing from Interactive session to a normal session affect this behaviour ? Is there any particular documentation for this ?
upvote count: 3
score: 3
answer count: 1
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48227390
has title: Does Tensorflow "know" when not to put data in GPU?
has answer: http://stackoverflow.com/a/48227390
tagged with: gpu
tagged with: tensorboard
tagged with: python
tagged with: optimization

http://stackoverflow.com/q/48308074
has title: Why are my images flickering? (Pygame)
has comment: http://stackoverflow.com/comment/83630631
downvote count: 0
has comment: http://stackoverflow.com/comment/83601562
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48308325
has comment: http://stackoverflow.com/comment/83630703
tagged with: python
tagged with: pygame
has body: I'm trying to "animate" a sprite by simply loading a set of 4 images over and over while the assigned left/right buttons are held down. It mostly works, except the images keep flickering and aren't "switching" as I intended. It also slows down considerably. Being a beginner in Pygame/Python my brain is absolutely fried. import pygame import os from test_menu import drawmenu from game_over import player1wins from game_over import player2wins from game_over import tie pygame.init() while True: screen_size = (1080, 400) screen = pygame.display.set_mode(screen_size) background = (255,255,255) image = pygame.image.load("background(1).png") imagerect = image.get_rect() wall_left = pygame.Rect(0,0,1,950) wall_right = pygame.Rect(1080,0,1,950) square1 = pygame.Rect(750, 350, 20, 20) square2 = pygame.Rect(330, 350, 20, 20) IMAGE = pygame.image.load("player1standright.png").convert_alpha() rect = IMAGE.get_rect() rect.x = 100 rect.y = 225 x_movement = 0 y_movement = 0 x2_movement = 0 y2_movement = 0 accelx1 = 0 accely1 = 0 accelx2 = 0 accely2 = 0 jumping = False jumping2 = False #This is the function that does it def player1runright(images1right, IMAGE, image, imagerect): i = -1 while i &lt;= 2: pygame.time.delay(0) i += 1 print (i) IMAGE = pygame.image.load(images1right[i]) print (images1right[i]) screen.blit(IMAGE, rect) images1right = ["player1runright-1.png","player1runright-2.png","player1runright-3.png","player1runright-4.png"] def health_bars(player1_health, player2_health): if player1_health &gt; 75: player1_health_color = (62, 219, 41) elif player1_health &gt; 50: player1_health_color = (239, 212, 9) else: player1_health_color = (239, 9, 9) if player2_health &gt; 75: player2_health_color = (62, 219, 41) elif player2_health &gt; 50: player2_health_color = (239, 212, 9) else: player2_health_color = (239, 9, 9) pygame.draw.rect(screen, player1_health_color, (70, 50, player1_health, 25)) pygame.draw.rect(screen, player2_health_color, (900, 50, player2_health, 25)) player…
has answer: http://stackoverflow.com/a/48322805
score: 2
linked to: http://stackoverflow.com/q/14044147
answer count: 2

http://stackoverflow.com/a/48241749
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48206687
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48206687
has body: Here is a solution: import pandas as pd # Prepare a list of ranges ranges = [('CIN','LAN'), ('DET','LAN')] # Declare an empty list of data frames and a list with the existing data frames df_ranges = [] df_list = [df1, df2] # Loop over multi-indices for i, idx_range in enumerate(ranges): df = df_list[i] row1, row2 = idx_range df_ranges.append(df.loc[(slice(None), slice(row1, row2)),:]) # Print the extracted data print('Extracted data:\n') print(df_ranges) Output: [ stint g ab r h X2b X3b hr rbi sb cs bb year team 2007 CIN 6 379 745 101 203 35 2 36 125 10 1 105 DET 5 301 1062 162 283 54 4 37 144 24 7 97 HOU 4 311 926 109 218 47 6 14 77 10 4 60 LAN 11 413 1021 153 293 61 3 36 154 7 5 114 so ibb hbp sh sf gidp year team 2008 DET 176 3 10 4 8 28 HOU 212 3 9 16 6 17 LAN 141 8 9 3 8 29]

http://stackoverflow.com/comment/83429862
score: 0
comment on: http://stackoverflow.com/q/48224019
type: Comment
type: QuestionComment
has text: Or use tuples as keys. (`my_dict[(a, b, c)]`)

http://stackoverflow.com/comment/83844528
comment on: http://stackoverflow.com/q/48308776
type: QuestionComment
has text: Sorry for the late reply. I got sidetracked. I ended up going with clearing the cache and re-reading the image. I will try this today and let you know.
score: 1
type: Comment

http://stackoverflow.com/q/48236507
tagged with: machine-learning
tagged with: keras
score: 4
type: AnsweredQuestion
tagged with: audio
has comment: http://stackoverflow.com/comment/83457108
tagged with: python
has title: Expected dense_3_input to have shape (None, 40) but got array with shape (40, 1)
has answer: http://stackoverflow.com/a/48239160
favorite count: 0
has comment: http://stackoverflow.com/comment/83463249
type: Question
upvote count: 4
has body: I am a beginner at Deep Learning and am attempting to practice the implementation of Neural Networks in Python by performing audio analysis on a dataset. I have been following the Urban Sound Challenge tutorial and have completed the code for training the model, but I keep running into errors when trying to run the model on the test set. Here is my code for creation of the model and training: import numpy as np from sklearn.preprocessing import LabelEncoder from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten num_labels = y.shape[1] filter_size = 2 model = Sequential() model.add(Dense(256, input_shape = (40,))) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(num_labels)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam') model.fit(X, y, batch_size=32, epochs=40, validation_data=(val_X, val_Y)) Running model.summary() before fitting the model gives me: _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_3 (Dense) (None, 256) 10496 _________________________________________________________________ activation_3 (Activation) (None, 256) 0 _________________________________________________________________ dropout_2 (Dropout) (None, 256) 0 _________________________________________________________________ dense_4 (Dense) (None, 10) 2570 _________________________________________________________________ activation_4 (Activation) (None, 10) 0 ================================================================= Total params: 13,066 Trainable params: 13,066 Non-trainable params: 0 _________________________________________________________________ After fitting the model, I attempt to run it on one file so that it can classify the sound. file_name = ".../UrbanSoundClassifier/test/Test/5.wav" test_X, sa…
has comment: http://stackoverflow.com/comment/83460257
accepted answer: http://stackoverflow.com/a/48239160
answer count: 1
downvote count: 0
tagged with: neural-network

http://stackoverflow.com/a/48263201
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48263087
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48263087
has body: Use: filter by query or boolean indexing groupby and aggregate size and mean rename columns names by dictionary convert index to column by reset_index My_list = ['apple', 'orange', 'grapes'] df1 = (df.query("Fruits in @My_list") .groupby('Fruits', sort=False)['value'] .agg(['size','mean']) .rename(columns={'mean':'average', 'size':'count'}) .reset_index()) df1 = (df[df['Fruits'].isin(My_list)] .groupby('Fruits', sort=False)['value'] .agg(['size','mean']) .rename(columns={'mean':'average', 'size':'count'}) .reset_index()) print (df1) Fruits count average 0 apple 2 15 1 orange 1 2 2 grapes 3 6 If want use loop, it should be slowier: L = [] for x in My_list: s = df.loc[df['Fruits'] == x, 'value'] #print (s) L.append({'Fruits': x, 'average':s.mean(), 'count':len(s)}) df = pd.DataFrame(L, columns=['Fruits','count','average']) print (df) Fruits count average 0 apple 2 15.0 1 orange 1 2.0 2 grapes 3 6.0
score: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83572325
has comment: http://stackoverflow.com/comment/83509831

http://stackoverflow.com/comment/83495798
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ, are you saying I have to write it like EXAMPLE = {0:'low', 1:'low'... etc} ?
comment on: http://stackoverflow.com/q/48256557
score: 0
type: Comment

http://stackoverflow.com/comment/83576716
type: QuestionComment
comment on: http://stackoverflow.com/q/48296033
type: Comment
has text: Actually there are multiple possible questions. Even [this one](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference). The problem is the list modified is being passed by reference, so I linked to a similar question
score: 0

http://stackoverflow.com/q/48214475
upvote count: 4
possible better answer: http://stackoverflow.com/a/48220082
type: AnsweredQuestion
has body: I'm trying to get SymPy to solve a system of equations but it gives me an error saying: NotImplementedError: could not solve 3*sin(3*t0/2)*tan(t0) + 2*cos(3*t0/2) - 4 Is there another way for me to be able to solve the system of equations: sin(x)+(y-x)cos(x) = 0 -1.5(y-x)sin(1.5x)+cos(1.5x) = 2 I used : from sympy import * solve([sin(x)+(y-x)cos(x), -1.5(y-x)sin(1.5x)+cos(1.5x)-2], x, y)
answer count: 2
tagged with: sympy
has answer: http://stackoverflow.com/a/48220082
downvote count: 0
has title: SymPy unable to solve a system of trigonometric equations
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48216793
has answer: http://stackoverflow.com/a/48216793
tagged with: python
score: 4

http://stackoverflow.com/q/48287252
has comment: http://stackoverflow.com/comment/83559399
type: Question
has comment: http://stackoverflow.com/comment/83560357
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83560147
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/48287354
has title: Pandas looking up values
has body: I have the following df: Id Date Value 111 1/1/18 a 111 1/3/18 a 111 1/5/18 x 222 1/1/18 x 222 1/2/18 y 333 1/2/18 a 333 1/3/18 x 333 1/4/18 a 333 1/5/18 a 444 1/5/18 y 555 1/2/18 a I want to add 2 new columns according to the date where the Value field contains the letter "a". result: Id Value StartDate EndDate 111 a 1/1/18 1/3/18 222 (this id does not contain a) 333 a 1/4/18 1/5/18 (take the latest date contain a) 444 (this id does not contain a) 555 a 1/2/18 (there's no ending date) Thank you :)
tagged with: pandas
has comment: http://stackoverflow.com/comment/83560260
has answer: http://stackoverflow.com/a/48287874
tagged with: python
has answer: http://stackoverflow.com/a/48287765
has comment: http://stackoverflow.com/comment/83559486
accepted answer: http://stackoverflow.com/a/48287765
tagged with: lookup
has answer: http://stackoverflow.com/a/48287354

http://stackoverflow.com/comment/83460549
score: 0
has text: do you need `G=df2.loc[0, 'a']` and `H=df2.loc[0, 'b']`?
type: Comment
comment on: http://stackoverflow.com/q/48239021
type: QuestionComment

http://stackoverflow.com/comment/83487160
comment on: http://stackoverflow.com/q/48252357
has text: Could you give a less abstract example, with some context about the problem you're solving? If you want the child to have a different default, why not simply `x1='sub value'` then `super().__init__(x1)`? What's the point of `'inaccessible value'`? Using the fixed argument to the parent just prevents the user from actually setting `x1`, breaking the inheritance.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/48286807
upvote count: 1
has comment: http://stackoverflow.com/comment/83578805
has title: python gif size on disk bigger after saving
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/41718892
tagged with: python-imaging-library
tagged with: http://stackoverflow.com/tag/gif
score: 1
tagged with: io
tagged with: python
has body: I am using the bird animated gif from this stackoverflow question about resizing gifs. The image size on disk is about 2.1MB. Now if I do (using python3.5) import PIL.Image PIL.Image.open('bird.gif').save('output.gif', save_all=True, optimize=True) I obtain an image of size 7.5MB. Using imageio, I am not getting any luckier: import imageio im = imageio.mimread('bird.gif') imageio.mimsave('output.gif', im) I obtain the exact same size of gif. Does anyone know how to save an animated gif so that it remains as small as possible, which means at least as small as the input gif ? Thanks!
type: Question
has comment: http://stackoverflow.com/comment/83558572
answer count: 0
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/83361762
comment on: http://stackoverflow.com/q/48190801
type: Comment
type: QuestionComment
score: 0
has text: yes sorted by ID

http://stackoverflow.com/q/48214088
linked to: http://stackoverflow.com/q/36287720
has title: AWS Authorization In Code - {"message": "The security token included in the request is invalid." }
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has body: I am trying to invoke an API call in my Lambda function in the form of requests.get(url, auth=auth). I have the url of the API endpoint but I am having issues with the authorization part of it. I imported an equivalent package of Requests-aws4auth and am getting my access key and secret key from Boto3 by following these instructions. session = boto3.Session() credentials = session.get_credentials() credentials = credentials.get_frozen_credentials() access_key = credentials.access_key secret_key = credentials.secret_key auth = AWS4AuthHandler(access_key=access_key, secret_key=secret_key, service_name='execute-api', region_name='us-west-2') brand_info = requests.get(url, auth=auth).json() However, brand_info returns: {"message": "The security token included in the request is invalid." } I'm assuming this is an issue with my access and secret keys, and if that's the case, am I missing any steps to get the correct access / secret key?
tagged with: amazon-web-services
tagged with: authorization
tagged with: aws-lambda
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83409865
has answer: http://stackoverflow.com/a/48214177
accepted answer: http://stackoverflow.com/a/48214177
tagged with: python

http://stackoverflow.com/comment/83561884
type: Comment
comment on: http://stackoverflow.com/a/48284117
type: AnswerComment
has text: my code doesn't use OOP - I don't create any `class`
score: 0

http://stackoverflow.com/q/48258185
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48258414
tagged with: python
score: -1
tagged with: regex
has answer: http://stackoverflow.com/a/48258226
has body: Just started working with python and got stuck with a find and match. Code is as below for line in f: if c in line: catch = line.split(' ', 1)[1] return catch f.close() so if my line has "TRA trace" and when I input TR, it returns the vale for TRA and not TR. Is there anything that can be done in the if condition to mach the exact input string. Thank you.
has title: Regex in Python to find the exact string
answer count: 3
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48258276
has comment: http://stackoverflow.com/comment/83498877

http://stackoverflow.com/a/48221963
has body: If for some strange reason(maybe a homework) you really need to use split and join you could write it as this def replace_chars(tmpStr, tmpChar) : for c in tmpChar: if c not in tmpStr: continue tmp = " ".join(tmpStr.split(c)) if tmpStr[-1] == c: tmpStr += " " # I'm not really sure if the "if" above is necessary # responding from my phone, can't test it tmpStr = tmp return tmpStr This is purely academic, the answer @Rakesh provided is the best way to do it.
answers question: http://stackoverflow.com/q/48221500
type: Answer
score: 0

http://stackoverflow.com/a/48196025
type: Answer
upvote count: 2
score: 2
has body: First, I would turn the while loop to a for loop, since i is now incremented faster. for i in range(1,condition): Now, since y doesn't change within your inner loop, you can optimize your computation from: x = ((float(array[y-(numberOfEntries-i)])-array[y-numberOfEntries])/abs(close[y-numberOfEntries]))*100.00 to: x = (float(array[y-(numberOfEntries-i)])-array[y-numberOfEntries]) * z where z is precomputed before the while/for loop as: z = 100.00 / abs(close[y-numberOfEntries]) why? first, z is pre-computed so no computation of abs and access to close array second, z is the inverse of the value to divide, so you can multiply by it. Multiplication is way faster than division. third: no more division by zero is possible since you're no longer dividing. The zerodiv can occur on z outside the loop, and has to be handled accordingly (wrap the whole z + loop thing in try/except and set result to x= 0.00000001 when it occurs, it should be equivalent) so your inner loop could be: try: z = 100.00 / abs(close[y-numberOfEntries]) for i in range(1,condition): x = (float(array[y-(numberOfEntries-i)])-array[y-numberOfEntries]) * z except ZeroDivisionError: x = 0.00000001 pattern.append(x)
downvote count: 0
answers question: http://stackoverflow.com/q/48195845

http://stackoverflow.com/comment/83550156
comment on: http://stackoverflow.com/a/48282624
has text: Maybe better yet like `keyorder.get(x.split(':', 1)[0], 99999999)`? There might be contents in the string for which order is not important or so..
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48238949
downvote count: 5
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/83461001
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48239394
answer count: 2
has answer: http://stackoverflow.com/a/48239394
upvote count: 1
tagged with: string
score: -4
favorite count: 0
has title: Python string concatenation of n coordinate grids
possible better answer: http://stackoverflow.com/a/48239013
has body: I have N strings containing pixel values for X and Y coordinates, for example: { #010101 #010101 #010101 #010101 #010101 } { #010101 #010101 #010101 #010101 #010101 } { #020202 #020202 #030303 #020202 #010101 } { #020202 #030303 #050505 #030303 #010101 } { #020202 #030303 #0f0f0f #040404 #020202 } { #030303 #0c0c0c #0f0f0f #0f0f0f #030303 } { #040404 #0b0b0b #ffffff #ffffff #040404 } { #0a0a0a #ffffff #ffffff #ffffff #050505 } { #ffffff #ffffff #ffffff #ffffff #040404 } { #ffffff #ffffff #ffffff #ffffff #040404 } And the second string { #040404 #020202 #010101 #010101 #010101 } { #040404 #020202 #010101 #010101 #000000 } { #050505 #020202 #010101 #010101 #000000 } { #040404 #020202 #010101 #010101 #000000 } { #030303 #010101 #010101 #010101 #000000 } { #020202 #010101 #010101 #010101 #000000 } { #010101 #010101 #010101 #010101 #000000 } { #010101 #010101 #010101 #000000 #000000 } { #010101 #010101 #010101 #000000 #000000 } { #010101 #010101 #010101 #000000 #000000 } This represent a 10x10 RGB grid. My problem is that i need to concatenate these two string to look like this for every row { #010101 #010101 #010101 #010101 #010101 040404 #020202 #010101 #010101 #010101 } ... This 10x10 grid was for split in two equal parts but there can be n-splits and therefore the string concatenation needs to be able to handle that. Grateful for any help.
has comment: http://stackoverflow.com/comment/83460983
has answer: http://stackoverflow.com/a/48239013
type: Question

http://stackoverflow.com/comment/83431135
type: Comment
type: QuestionComment
has text: ```a ="\U00000041" for _c in a: b= 'U+%04x' % ord(_c) print(b) >> U+0041```
score: 0
comment on: http://stackoverflow.com/q/48224320

http://stackoverflow.com/q/48184854
tagged with: django
tagged with: django-models
tagged with: python
possible better answer: http://stackoverflow.com/a/48185028
has answer: http://stackoverflow.com/a/48185048
has body: Designing a a system which needs state transitions of a model which are based on transitions of other models. I'm using Django FSM Example: class Foo(models.Model): baz = models.Charfield() state = FSMField(default='new') class Bar(models.Model): x = models.CharField() state = FSMField(default='draft') foo = models.ForeignKey(Foo) Use Case: Foo can have the following states - new, draft, complete, pending_approval, approved Foo can have multiple Bars Bar can have the following states - draft, complete Foo should move to complete automatically when all Bar's are complete, how can this be achieved
has answer: http://stackoverflow.com/a/48185028
type: AnsweredQuestion
answer count: 2
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83349955
has title: Django managing state of a parent model, based on "child models" (models that have a fk to the parent model)
tagged with: django-fsm
accepted answer: http://stackoverflow.com/a/48185048

http://stackoverflow.com/a/48307626
has comment: http://stackoverflow.com/comment/92951598
has body: I can't find documentation for it, but pip supports .netrc files in ~ and .: machine artifactory.hostname login username password password These credentials should not show up in logs.
has comment: http://stackoverflow.com/comment/83763527
answers question: http://stackoverflow.com/q/48304300
score: 5
upvote count: 5
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83758964

http://stackoverflow.com/comment/83378730
has text: 'Belo Horizonte', 'Belo Horizonte', 'Belo Horizonte', 'Belo Horizonte',
comment on: http://stackoverflow.com/q/48198646
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/48289917
type: Answer
answers question: http://stackoverflow.com/q/48289834
score: 0
has body: You should give an admin panel to all users. However, limit what certain users see. Example: Students shouldn't be able to create courses in the panel but Admins could.

http://stackoverflow.com/comment/83374872
type: QuestionComment
comment on: http://stackoverflow.com/q/48189252
has text: none of those GUIs supported input textboxes with asci character and clicking inbetween letters to edit them... or they didn't work with pygame. In the end I just programmed a TextEditor in pygame myself from scratch - including all the functionality I needed :) [however, i don't know how to "close" my question here. ]
score: 0
type: Comment

http://stackoverflow.com/a/48270629
has body: This simple case can probably best be handled by plt.imsave. import matplotlib.pyplot as plt import numpy as np rows, cols = 200, 200 r,c = np.meshgrid(np.arange(rows), np.arange(cols)) mat = r*c # saving as image plt.imsave("output.png", mat) # or in some other format # plt.imsave("output.jpg", mat, format="jpg")
has comment: http://stackoverflow.com/comment/100496911
score: 6
has comment: http://stackoverflow.com/comment/100497019
upvote count: 6
type: Answer
answers question: http://stackoverflow.com/q/48270534
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48270534

http://stackoverflow.com/a/48286827
accepted answer of: http://stackoverflow.com/q/48286543
has body: The essence here is that as you call methods on various objects, you may change the type of object. In Python, all objects have methods and attributes associated with them, but each type of object has different methods/attributes. The .toordinal() method on a datetime object returns integers (int) so your StartDateOrdinal object is no longer a datetime object. int does not have a .fromordinal() method. That method is found in the datetime library. This should solve your problem: import datetime # I am gonna use two sample dates: Jan 1, 2018 and Mar 1, 2018 StartDateOrdinal = datetime.datetime(2018, 1, 1).toordinal() # produced the int: 736695 EndDateOrdinal = datetime.datetime(2018, 3, 1).toordinal() # produced the int: 736754 DateRange = range(StartDateOrdinal, EndDateOrdinal, 3) for a in DateRange: # convert the integer (int) called a back into a datetime object date = datetime.datetime.fromordinal(a) year = date.year month = date.month day = date.day # Let's print the results to ensure we got what we expected... print(year, month, day) # outputs... 2018 1 1 2018 1 4 2018 1 7 2018 1 10 ... etc
answers question: http://stackoverflow.com/q/48286543
type: Answer
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/48196784
accepted answer: http://stackoverflow.com/a/48197923
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48197923
has comment: http://stackoverflow.com/comment/98817665
tagged with: python
upvote count: 6
has title: Get url of public accessible s3 object using boto3 without expiration or security info
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/48608570
answer count: 1
downvote count: 0
has body: Running a line like: s3_obj = boto3.resource('s3').Object(bucket, key) s3_obj.meta.client.generate_presigned_url('get_object', ExpiresIn=0, Params={'Bucket':bucket,'Key':key}) Yields a result like: https://my-bucket.s3.amazonaws.com/my-key/my-object-name?AWSAccessKeyId=SOMEKEY&amp;Expires=SOMENUMBER&amp;x-amz-security-token=SOMETOKEN For an s3 object with public-read ACL, all the GET params are unnecessary. I could cheat and use rewrite the URL without the GET params but that feels unclean and hacky. How do I use boto3 to provide me with just the public link, e.g. https://my-bucket.s3.amazonaws.com/my-key/my-object-name? In other words, how do I skip the signing step in generate_presigned_url? I don't see anything like a generated_unsigned_url function.
tagged with: boto3
score: 6

http://stackoverflow.com/q/48219143
upvote count: 3
tagged with: sqlalchemy
type: Question
accepted answer: http://stackoverflow.com/a/48221188
has body: I have the following SQL request that is giving me the result I want, but I can't succeed to make it work in SQLAlchemy. DB Models from flask_sqlalchemy import SQLAlchemy from sqlalchemy.orm import relationship db = SQLAlchemy() class Article(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255), nullable=False) description = db.Column(db.Text) image = db.Column(db.String(255)) brand = db.Column(db.String(255), nullable=False) category_id = db.Column(db.Integer, db.ForeignKey("category.id"), nullable=False) prices = relationship("ArticlePrice", cascade="all, delete-orphan") class ArticlePrice(db.Model): article_id = db.Column(db.Integer, db.ForeignKey("article.id"), primary_key=True) location_id = db.Column(db.Integer, db.ForeignKey("location.id"), primary_key=True) price = db.Column(db.Float, nullable=False) active = db.Column(db.Boolean, nullable=False) location = relationship('Location') SQL request (working) I want to return all articles information that are located in the given location and active in this location. Plus its price, and only the price of this location. SELECT a.*, ap.price FROM article a INNER JOIN article_prices ap ON a.id = ap.article_id WHERE ap.location_id = 1 AND ap.active = true SQLAlchemy, using Flask (not working) @namespace.route('/location/&lt;location_id&gt;') class ArticleLocatedAPI(): @namespace.marshal_list_with(article, envelope='articles') def get(self, location_id): return Article.query.filter(Article.prices.any(active=True, location_id=location_id)).all() Output model As you can see, I want the price of the located articles not the relationship that would return the array of prices. article = namespace.model('Article', { 'id': fields.Integer, 'title': fields.String, 'description': fields.String, 'image': fields.String, 'brand': fields.String, 'price': fields.Float, 'category_id': fields.Integer }) Problem The code above is giving me the right articles. The problem is that it is returning me the…
has answer: http://stackoverflow.com/a/48221188
answer count: 1
downvote count: 0
tagged with: python
has title: How to translate SQL into SQLAlchemy? (Shaping output model differently from the DB model)
favorite count: 0
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/48242928
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83490937
has comment: http://stackoverflow.com/comment/83503399
has comment: http://stackoverflow.com/comment/83487552
has comment: http://stackoverflow.com/comment/83489544
tagged with: python
has title: Unable to create different sheets in an excel file for different links
accepted answer: http://stackoverflow.com/a/48243476
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83505311
has answer: http://stackoverflow.com/a/48243476
has comment: http://stackoverflow.com/comment/83490911
tagged with: openpyxl
answer count: 1
tagged with: web-scraping
upvote count: 1
downvote count: 1
has body: I've written a script in python to parse some tiles and links of different tutorials from a webpage and finally write those in an excel file. I've used openpyxl. My script is doing fine If I consider to get all of the documents in a single sheet. However, I've used three links in my scraper to scrape data from. My goal is to write those scraped documents in three different sheets in an excel file. How can I achieve that? Thanks in advance. Here is what I've written so far: import requests from urllib.parse import urljoin from lxml.html import fromstring from openpyxl import Workbook wb = Workbook() wb.active ws = wb.worksheets[0] storage ={ 'http://www.wiseowl.co.uk/videos/year/2011.htm', 'http://www.wiseowl.co.uk/videos/year/2012.htm', 'http://www.wiseowl.co.uk/videos/year/2013.htm' } def get_docs(link): response = requests.get(link) root = fromstring(response.text) for item in root.cssselect(".woVideoListDefaultSeriesTitle"): title = item.cssselect("a")[0].text title_link = item.cssselect("a")[0].attrib['href'] print(title,title_link) ws.append([title,title_link]) wb.save("tuts.xlsx") if __name__ == '__main__': for tut_link in storage: get_docs(tut_link) Once again, my script is able to scrape the documents and write those in a single sheet in an excel file but I wish to get the documents written in three different sheets (each sheet is for each link) in an excel file.
favorite count: 0

http://stackoverflow.com/a/48268413
score: 0
has body: The more_itertools third-party library has a tool for run length encoding/compression problems. See an example from the docs: &gt;&gt;&gt; compressed = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] &gt;&gt;&gt; list(run_length.decode(compressed)) ['a', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'd'] This tool is simple to use. Ideally, you would want to passing in an input of a list of tuples each comprising a string and multiplying integer. Code Here we will implement a parse helper function to convert your input into the appropriate format. import itertools as it import more_itertools as mit def parse(iterable): """Return a list of string, multiplier pairs.""" iterable = iterable.replace("(", "").replace(")", "") pred = lambda x: x.isalpha() non_numbers = ("".join(g) for k, g in it.groupby(iterable, pred) if k) numbers = (int(list(g)[0]) for k, g in it.groupby(iterable, pred) if not k) zipped = list(it.zip_longest(non_numbers, numbers, fillvalue=1)) return zipped Demo &gt;&gt;&gt; iterable = "(BA)4B5A" &gt;&gt;&gt; # Application &gt;&gt;&gt; "".join(mit.run_length.decode(parse(iterable))) 'BABABABABBBBBA' &gt;&gt;&gt; # Tests &gt;&gt;&gt; assert parse(iterable) == [("BA", 4), ("B", 5), ("A", 1)] &gt;&gt;&gt; assert list(mit.run_length.decode(parse(iterable))) == ["BA", "BA", "BA", "BA", "B", "B", "B", "B", "B", "A"] Details The parse function removes parentheses from the input iterable. It then builds two generators with itertools.groupby: one for groups of strings and one for groups of multipliers. These groups are zipped together. itertools.zip_longest accepts a fillvalue parameter, so that if the input iterable ends with a string (as in the sample input), the default multiplier is 1. The run_length.decode method is implemented here: class run_length(object): ... def decode(iterable): return list(it.chain.from_iterable(it.repeat(k, n) for k, n in iterable)) Note: use &gt; pip install more_itertools in a command line prompt to install this library. Additional References …
answers question: http://stackoverflow.com/q/48244923
type: Answer

http://stackoverflow.com/comment/83441661
has text: @Jaxi: `asyncio.sleep()` does **not block execution**, it is specifically designed to just put a coroutine on the inactive queue until the time has passed. You seem to be confusing this with `time.sleep()`.
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48229592

http://stackoverflow.com/comment/83491149
comment on: http://stackoverflow.com/q/48254281
score: 1
type: QuestionComment
has text: Welcome to SO. `Python` has ***a lot*** of decent libraries to accomplish exactly this. Please have some gooling before and come back with a specific code question afterwards.
type: Comment

http://stackoverflow.com/q/48273657
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83531210
tagged with: http://stackoverflow.com/tag/html
has title: Dropdown Menu Not Working When Implementing with Django
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83531064
tagged with: css
score: 0
answer count: 0
has body: I'm new to working with Django and am running into a problem implementing it into the static site that I've made. Could you please advise as to why the dropdown menu is not working (not dropping down)? It was working fine when it was just the html/css files before django implementation. Attached image shows the file/folder layout - please let me know if you need to see any of the additional files and I can post them. Am thinking I have some css in the wrong directory (?) Image: IMAGE {% load staticfiles %} Test Site person Profile {% if user.is_authenticated %} Logout {% else %} Login {% endif %} search Search... Test Site/a> {% block content %} {% endblock %} TestSite . Contact Us
tagged with: drop-down-menu

http://stackoverflow.com/q/48264656
possible better answer: http://stackoverflow.com/a/50244897
has answer: http://stackoverflow.com/a/48278872
has answer: http://stackoverflow.com/a/56405135
tagged with: machine-learning
has answer: http://stackoverflow.com/a/74645922
has answer: http://stackoverflow.com/a/50244897
score: 72
upvote count: 72
tagged with: amazon-web-services
has body: I've just started to experiment with AWS SageMaker and would like to load data from an S3 bucket into a pandas dataframe in my SageMaker python jupyter notebook for analysis. I could use boto to grab the data from S3, but I'm wondering whether there is a more elegant method as part of the SageMaker framework to do this in my python code?
tagged with: amazon-sagemaker
type: Question
has answer: http://stackoverflow.com/a/65032927
type: AnsweredQuestion
tagged with: amazon-s3
has title: Load S3 Data into AWS SageMaker Notebook
tagged with: python
has answer: http://stackoverflow.com/a/48267804
accepted answer: http://stackoverflow.com/a/48267804
has answer: http://stackoverflow.com/a/56060184
favorite count: 0
has answer: http://stackoverflow.com/a/59735614
has answer: http://stackoverflow.com/a/68009976
answer count: 9
downvote count: 0

http://stackoverflow.com/comment/83546543
type: QuestionComment
comment on: http://stackoverflow.com/q/48281538
has text: Could you elaborate, what kind of keys values you want? What does instance.items() contain?
score: 0
type: Comment

http://stackoverflow.com/q/48247043
has comment: http://stackoverflow.com/comment/83526433
has comment: http://stackoverflow.com/comment/83477082
linked to: http://stackoverflow.com/q/6662536
has comment: http://stackoverflow.com/comment/83478133
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83477610
has title: pywin32 RuntimeError: Can't find the Windows SDK
tagged with: python
has body: Execute "python setup3.py install" reported this error I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this. D:\Software Package\pywin32-master\pywin32-master&gt;python setup3.py install Converting... Executing... Building pywin32 3.6.221.0 Traceback (most recent call last): File "setup3.py", line 16, in &lt;module&gt; exec(str(got)) File "&lt;string&gt;", line 305, in &lt;module&gt; RuntimeError: Can't find the Windows SDK D:\Software Package\pywin32-master\pywin32-master&gt;python setup.py install File "setup.py", line 127 print "Building pywin32", pywin32_version ^ SyntaxError: Missing parentheses in call to 'print'
upvote count: 2
score: 2
answer count: 0
downvote count: 0
tagged with: pywin32
favorite count: 0
type: Question

macos
tags question: http://stackoverflow.com/q/48270385
tags question: http://stackoverflow.com/q/48269046
tags question: http://stackoverflow.com/q/48253400
tags question: http://stackoverflow.com/q/48198453
tags question: http://stackoverflow.com/q/48253800
tags question: http://stackoverflow.com/q/48329995
tags question: http://stackoverflow.com/q/48243877
tags question: http://stackoverflow.com/q/48289273
tags question: http://stackoverflow.com/q/48187228
tags question: http://stackoverflow.com/q/48235589
type: Tag
tags question: http://stackoverflow.com/q/48321513
tags question: http://stackoverflow.com/q/48267740
tags question: http://stackoverflow.com/q/48243510
tags question: http://stackoverflow.com/q/48199784
tags question: http://stackoverflow.com/q/48266063
tags question: http://stackoverflow.com/q/48174935
tags question: http://stackoverflow.com/q/48277572
tags question: http://stackoverflow.com/q/48213210
tags question: http://stackoverflow.com/q/48302857
tags question: http://stackoverflow.com/q/48249425
tags question: http://stackoverflow.com/q/48221731
tags question: http://stackoverflow.com/q/48288839
tags question: http://stackoverflow.com/q/48298170
tags question: http://stackoverflow.com/q/48191350
tag name: macos
tags question: http://stackoverflow.com/q/48199960
tags question: http://stackoverflow.com/q/48176265

http://stackoverflow.com/comment/83510671
type: QuestionComment
comment on: http://stackoverflow.com/q/48255660
type: Comment
has text: @Sraw I did what you said and used one season to crawle the content and now I've run into ServerDisconnectedError. Reading the docs and it seems that the servers closes the season itself after sometime.
score: 1

http://stackoverflow.com/a/74998556
score: 1
upvote count: 1
has body: Very loosely, you can expect to get memory savings when using a Categorical on Series/arrays that contain strings with a low cardinality. If you want to go a bit deeper, your intuition is correct - a Categorical is essentially a mapping of integral keys to the unique string values. So if your input was something like: ["abc", "abc", "def"] A categorical would behind the scenes replace that with an array of [0, 0, 1] along with a mapping of {0: "abc", 1: "def"} In the majority of use cases, [0, 0, 1] would be represented as a numpy array with dtype=np.int8. In cases where you have more than 255 unique values (2**8-1) the dtype of that array would be sized appropriately, of course at the expense of more memory usage. Numpy works with contiguous arrays in memory, so ignoring the overhead of the Python numpy object itself your int8 array is condensed to occupy 3 * 8 = 24 bytes of memory. Alongside the array you now have a mapping of codes. You can inspect these two elements using the cat accessor of >>> ser = pd.Series(["abc", "abc", "def"], dtype="category") >>> ser.cat.codes 0 0 1 0 2 1 dtype: int8 >>> ser.cat.categories Index(['abc', 'def'], dtype='object') In a simplistic world, we could compare the size of our now internally managed numpy array + mapping to the original input data and see if we've gotten any savings. However, things still aren't quite that simple... Python itself employs a similar concept to creating categoricals which is often referred to as string interning. You can see this in action below: >>> text1 = "abc" >>> text2 = "abc" >>> id(text1) 93971347966496 >>> id(text2) 93971347966496 >>> sys.getsizeof(text1) 52 >>> sys.getsizeof(text2) 52 These strings have effectively been interned, meaning they both share the same memory address. This behavior is dependent on both your Python version (examples shown are 3.11) as well as the length of the string. Note that the next example isn't interned for me: >>> text1 = "Hello, World!" >>> text2 = "Hello, Wo…
answers question: http://stackoverflow.com/q/48256395
type: Answer
downvote count: 0

http://stackoverflow.com/comment/83593635
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48294140
type: Comment
has text: thanks ! ill try to make that. will be updating if i solved it in several days.

http://stackoverflow.com/comment/83487991
score: 0
has text: My `permutations` code acts like the `choice` with `replace=False`. Neither produces duplicates like [3,1,0,0].
type: Comment
comment on: http://stackoverflow.com/a/48247633
type: AnswerComment

http://stackoverflow.com/comment/84010972
has text: would you share more about how did you find out?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48506063
type: Comment

http://stackoverflow.com/comment/83350549
type: QuestionComment
score: 0
has text: @rnso I've tried using the -F to create it as a standalone, and then read that you can add commands like the --icon thing, (Never used a python compiler to create executables before and am only learning python while at university). However, I couldn't find much information on python 3.6 and most things suggest backdating versions which I can't do as I'm required to use 3.6
type: Comment
comment on: http://stackoverflow.com/q/48180551

http://stackoverflow.com/q/48197199
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83375472
has title: networkx minimum_node_cut and node_connectivity
score: 2
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
tagged with: networkx
type: Question
tagged with: graph
has body: I am using networkx and here is my network. import networkx as nx G = nx.from_edgelist([['a','b'], ['b','c'], ['c','a']]) nx.draw_networkx(G) Can you please tell me why minimum_node_cut returns b, whereas node_connectivity returns 2? nx.minimum_node_cut(G, 'a', 'c') {'b'} nx.node_connectivity(G, 'a', 'c') 2 I was expecting length of minimum_node_cut would equal to node_connectivity.
has answer: http://stackoverflow.com/a/48197318

http://stackoverflow.com/q/48224711
has answer: http://stackoverflow.com/a/48224769
has comment: http://stackoverflow.com/comment/83430942
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: Python: the return of the function is just returning only the first line of the opened file
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83430931
type: AnsweredQuestion
tagged with: function-call
upvote count: 0
accepted answer: http://stackoverflow.com/a/48224769
answer count: 1
has body: VERSION "3" NS_ : NS_DESC_ CM_ BA_DEF_ BA_ VAL_ CAT_DEF_ CAT_ FILTER BA_DEF_DEF_ EV_DATA_ ENVVAR_DATA_ SGTYPE_ SGTYPE_VAL_ BA_DEF_SGTYPE_ BA_SGTYPE_ SIG_TYPE_REF_ VAL_TABLE_ SIG_GROUP_ above is some text in a file, but after running it is just reading the first line even after using for loop what could be the reason as am new to this programming language please help me to get this? def function(f): lines = [] for Nrow,row in enumerate(f): lines = row.split(' ') return lines with open('car.dbc', 'r') as f: #open the file contents = function(f)#put the lines to a variable (list). print(contents)

http://stackoverflow.com/comment/83379851
has text: in the if statement, break has to be after the print statement
comment on: http://stackoverflow.com/a/48199276
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48282588
score: 2
downvote count: 0
has body: You can used sorted with key. It allows you to specify an arbitrary lambda expression to sort your data: key_order = ['ID', 'GE','FN','LN','MN','EM', 'ST'] data = ['ID:12,3', 'GE:m', 'FN:Amir', 'LN:Maleki', 'EM:a@b.c', 'MN:0400101010', 'ST:VIC'] print(sorted(data, key=lambda x: key_order.index(x.split(':')[0]))) This gives as output: ['ID:12,3', 'GE:m', 'FN:Amir', 'LN:Maleki', 'MN:0400101010', 'EM:a@b.c', 'ST:VIC']
answers question: http://stackoverflow.com/q/48282388
has comment: http://stackoverflow.com/comment/83551804
type: Answer
upvote count: 2

http://stackoverflow.com/comment/83530220
type: Comment
type: QuestionComment
score: 0
has text: Sometimes the dev appserver has issues loading `google.*` modules from the local `lib/` directory. If the modules are indeed installed correctly, try something like the solution described [here](https://github.com/GoogleCloudPlatform/google-auth-library-python/issues/169#issuecomment-315417916).
comment on: http://stackoverflow.com/q/48264536

http://stackoverflow.com/a/48257564
score: -1
upvote count: 0
downvote count: 1
has body: import pandas as pd file = '/Users/JDMacBook/.spyder-py3/US Mass Shootings.csv' data = pd.read_csv(file, encoding='utf-8') Try this. This is because the encoding the file is utf-8. The default encoding is ascii.
has comment: http://stackoverflow.com/comment/83497762
answers question: http://stackoverflow.com/q/48257321
type: Answer

http://stackoverflow.com/comment/83468657
has text: In future, when you paste code, select the pasted text and use the `{}` button on the toolbar to indent the whole block. Don't try to 'repair' indentation by only indenting selected lines.
type: Comment
comment on: http://stackoverflow.com/q/48242912
score: 0
type: QuestionComment

http://stackoverflow.com/q/48244172
downvote count: 0
tagged with: http://stackoverflow.com/tag/json
has title: Python - AWS Lambda extract a key from JSON input
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48244447
accepted answer: http://stackoverflow.com/a/48244447
has answer: http://stackoverflow.com/a/48244188
possible better answer: http://stackoverflow.com/a/48244188
tagged with: python
tagged with: lambda
tagged with: amazon-web-services
upvote count: 2
type: AnsweredQuestion
score: 2
has body: Im trying to implement a function that will get the event from cloudwatch and print the results. I am able to get the event but I want to extract one particular key from that JSON. Here is my function: import json def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2)) message = event['Records'][0]['Sns']['Message'] print(message) The event got from Cloudwatch: "Records": [ { "EventVersion": "1.0", "EventSubscriptionArn": "arn:aws:sns:us-east-1:xxxxxxxxxxxxx:bhuvi:XXXXXXXXXXXXXXXXXXXXXXXXXX", "EventSource": "aws:sns", "Sns": { "SignatureVersion": "1", "Timestamp": "2018-01-13T19:18:44.369Z", "Signature": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "SigningCertUrl": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.pem", "MessageId": "4b76b0ea-5e0f-502f-81ec-e23e03dbaf01", "Message": "{\"AlarmName\":\"test\",\"AlarmDescription\":\"test\",\"AWSAccountId\":\"xxxxxxxxxxxxx\",\"NewStateValue\":\"ALARM\",\"NewStateReason\":\"Threshold Crossed: 1 out of the last 1 datapoints [2.6260535333900545 (13/01/18 19:13:00)] was greater than or equal to the threshold (1.0) (minimum 1 datapoint for OK -&gt; ALARM transition).\",\"StateChangeTime\":\"2018-01-13T19:18:44.312+0000\",\"Region\":\"US East (N. Virginia)\",\"OldStateValue\":\"OK\",\"Trigger\":{\"MetricName\":\"CPUUtilization\",\"Namespace\":\"AWS/RDS\",\"StatisticType\":\"Statistic\",\"Statistic\":\"AVERAGE\",\"Unit\":null,\"Dimensions\":[{\"name\":\"DBInstanceIdentifier\",\"value\":\"myrds\"}],\"Period\":300,\"EvaluationPeriods\":1,\"ComparisonOperator\":\"GreaterThanOrEqualToThreshold\",\"Threshold\":1.0,\"TreatMissingData\":\"\",\"EvaluateLowSampleCountPercentile\":\"\"}}", "MessageAttributes": {} , "Type": "Notification", "UnsubscribeUrl": "https://sns.us-east-1.amazonaws.com/?xcsgagrgrwgwrg", "TopicArn": "arn:aws:sns:us-east-1:xxxxxxxxxxxxx:bhuvi", "Subject": "ALARM: \"test\" in US East (N. Vi…
answer count: 2

http://stackoverflow.com/comment/83373777
score: 0
has text: BTW, what's the goal of this loop? Is there a reason you want to run `curl` four times, rather than just running it once and reading the results into four elements of a shell array?
comment on: http://stackoverflow.com/q/48196080
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48257161
tagged with: django-rest-auth
has answer: http://stackoverflow.com/a/48257953
accepted answer: http://stackoverflow.com/a/48257953
answer count: 1
tagged with: django
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47284393
has title: How to add the last_login_ip, when the user login if using `rest-auth`?
upvote count: 1
score: 1
has body: How to add the last_login_ip, when the user login if using rest-auth? Befor ask the post I searched one post bellow: How can I do my logic in `http://127.0.0.1:8000/rest-auth/login/` of `django-rest-auth`? The answer is perfect for custom verify the login params. But, how about after login, then add attribute to the User? I mean, the answer is just for verify the data, I want to after user login success, I want to add the last_login_ip to the user instance. EDIT Please be attention, I know how to get the remote IP who visit my site. I mean I use the rest-auth to login, and customized LoginSerializer like the link. The link is for verify the login data, I can not to change the last_login_ip data in the LoginSerializer, I want when the user login success, then change the user's last_login_ip. but where to write my change last_login_ip code? EDIT-2 I follow the @at14's advice, in the init.py (as the same level as apps.py): default_app_config = '管理员后台.用户管理.qiyun_admin_usermanage.apps.QiyunAdminUsermanageConfig' and in the apps.py: from django.apps import AppConfig class QiyunAdminUsermanageConfig(AppConfig): name = 'qiyun_admin_usermanage' def ready(self): import 管理员后台.用户管理.qiyun_admin_usermanage.api.signals There will get bellow error: django.core.exceptions.ImproperlyConfigured: Cannot import 'qiyun_admin_usermanage'. Check that '管理员后台.用户管理.qiyun_admin_usermanage.apps.QiyunAdminUsermanageConfig.name' is correct. and I also tried to comment the default_app_config = '管理员后台.用户管理.qiyun_admin_usermanage.apps.QiyunAdminUsermanageConfig' in the init.py, but still not work.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83497396
downvote count: 0
has comment: http://stackoverflow.com/comment/83497486
linked to: http://stackoverflow.com/q/4581789

http://stackoverflow.com/q/48268624
has comment: http://stackoverflow.com/comment/83523381
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/83520924
has comment: http://stackoverflow.com/comment/83520498
tagged with: python
tagged with: mysql
has title: Escaping MySQL LOAD DATA INFILE command
has answer: http://stackoverflow.com/a/48280277
type: Question
score: 0
has comment: http://stackoverflow.com/comment/83520827
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83521184
answer count: 1
has body: I want to escape this command in Python 3.6, as I want to use it to run it through a bulk of csv files. for filename in glob.glob(CSV_FOLDER_LOCATION + "/*.csv"): # Adds quotes to filename because of the problem caused by spaces in path names quoted_filename = '"' + filename + '"' os.system(MYSQL_LOCATION + r" -u root LOAD DATA INFILE " + quoted_filename + " INTO TABLE " + TABLE_NAME + r" CHARACTER SET ascii FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '/n' IGNORE 1 LINES") The comma shows up as whitespace. This is the output: C:/Program Files/MySQL/MySQL Server 5.7/bin/mysql.exe -u root LOAD DATA INFILE "C:/prog/csv/CSVFiles\CC19711977ZWEIG-ZZ.csv" INTO TABLE vcc2.tmp_cards CHARACTER SET ascii FIELDS TERMINATED BY ENCLOSED BY '"' LINES TERMINATED BY '/n' IGNORE 1 LINES What is the correct way to escape that string? Edit: Added image for clarification: Maybe I'm really thick and missing something obvious, but how can I "raw string" it C-style?
has comment: http://stackoverflow.com/comment/83541847

http://stackoverflow.com/comment/83371743
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48195361
has text: Why not just index the column based on username? Faster lookups and prevents duplication? http://www.sqlitetutorial.net/sqlite-index/
type: Comment

http://stackoverflow.com/a/48180303
upvote count: 31
score: 31
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/122185267
downvote count: 0
has body: The error isn't with the print statement. It's with the keys = next(c) line. Consider a simpler example which reproduces your issue. a = (i ** 2 for i in range(5)) a # `a` is a generator object &lt;generator object &lt;genexpr&gt; at 0x150e286c0&gt; list(a) # calling `list` on `a` will exhaust the generator [0, 1, 4, 9, 16] next(a) # calling `next` on an exhausted generator object raises `StopIteration` --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) &lt;ipython-input-2076-3f6e2eea332d&gt; in &lt;module&gt;() ----&gt; 1 next(a) StopIteration: What happens is that c is an iterator object (very similar to the generator a above), and is meant to be iterated over once until it is exhausted. Calling list on this object will exhaust it, so that the elements can be collected into a list. Once the object has been exhausted, it will not produce any more elements. At this point, the generator mechanism is designed to raise a StopIteration if you attempt to iterate over it even after it has been exhausted. Constructs such as for loops listen for this error, silently swallowing it, however, next returns the raw exception as soon as it has been raised.
accepted answer of: http://stackoverflow.com/q/48180209
answers question: http://stackoverflow.com/q/48180209
type: Answer

http://stackoverflow.com/a/48354820
type: Answer
answers question: http://stackoverflow.com/q/48224881
score: 0
has body: What other options do you have, than going for web based UI ? But looks like, you are creating a whole new system, so a lot of the decisions depend on your specific requirements...

http://stackoverflow.com/q/48232129
score: -1
has comment: http://stackoverflow.com/comment/83446658
tagged with: pandas
tagged with: matrix
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48232506
downvote count: 2
has answer: http://stackoverflow.com/a/48232506
upvote count: 1
tagged with: scikit-learn
tagged with: sparse-matrix
has title: Pandas: Dataframe to Matrix
favorite count: 0
linked to: http://stackoverflow.com/q/48133358
possible better answer: http://stackoverflow.com/a/48232210
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48232210
tagged with: python
has comment: http://stackoverflow.com/comment/83447238
has body: I'm quite new at this topics. I'm currently developing a latent factor matrix factorization that will be training data for a Neural Network. I have a csv table like this: user_id song_id playcount frank SOBYHAJ12A6701BF1D 23 john SODACBL12A8C13C273 1 john SODXRTY12AB0180F3B 3 mary SOFRQTD12A81C233C0 1 You could think this table as a description of a matrix. I want to build a matrix as: rows=song_id, columns=user_id, value=playcount I've loaded the data into a pandas dataframe: triplets_training_set = pd.read_csv(filepath) Now I want to build a sparse matrix with that data. Another question: Do I need to vectorize the values? i.e. translate 'b80344d063b5ccb3212f76538f3d9e43d87dca9e' to a integer user_id? (same with song_id) I've read questions like this but I don't know how to approach the last question The only solution I came up with, was to first make 2 dicts like: { frank: 1, john: 2, mary:3, ..} { SOBYHAJ12A6701BF1D:1 , SODACBL12A8C13C273:2. ..} and then iterate over the dataframe triplets_training_set row by row, constructing the matrix. But this is a naive solution. There must be a better one. Thanks in advance!

http://stackoverflow.com/comment/83514504
comment on: http://stackoverflow.com/a/48265653
type: AnswerComment
has text: It's a coincidence. I have a lot of elements in my array. Ist here a way to make it less "expensive"?
score: 0
type: Comment

http://stackoverflow.com/comment/83613633
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48300550
has text: Thanks @Tomáš for your help.
type: Comment

http://stackoverflow.com/a/48275266
answers question: http://stackoverflow.com/q/48270073
score: 1
type: Answer
has body: As @sascha pointed out, you need to persist the KMeans object to predict future data dat = dat1.reshape(nw,nx*ny) clusterer = KMeans(n_clusters=ncl).fit(np.transpose(dat) dat2 = dat2.reshape(nw,nx*ny) dat2_labels = clusterer.predict(np.transpose(dat2))
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48225334
has comment: http://stackoverflow.com/comment/83432288
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/83433195
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91206426
has body: I'm trying to extract pinterest data such as title of a pin, image description such as alt, src, comments/description, creator. Since my api hasn't yet been approved, I'm trying to do web scraping using BeautifulSoup, Python. The limitation I could see is, it retrieves only 16 alt, src no matter which query keyword that I use. How to overcome this limitation and extract at least 100 data to begin with? Below is a sample snippet. I look forward to hear from you. Thanks much in advance! import requests from bs4 import BeautifulSoup import pandas as pd var = "analytics" URL = "https://in.pinterest.com/search/pins/?q=" + var r = requests.get(URL) soup = BeautifulSoup(r.content, 'html5lib') alt = [] src = [] for link in soup.find_all('img'): alt.append(link.get('alt')) src.append(link.get('src'))
score: 0
tagged with: pinterest
has title: Extracting Data from Pinterest using BeautifulSoup, Python
has comment: http://stackoverflow.com/comment/83432394
answer count: 1
has answer: http://stackoverflow.com/a/66616256

http://stackoverflow.com/a/48301096
has comment: http://stackoverflow.com/comment/83594717
has comment: http://stackoverflow.com/comment/83588128
has comment: http://stackoverflow.com/comment/83587354
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/83586802
has comment: http://stackoverflow.com/comment/83587367
has comment: http://stackoverflow.com/comment/83594506
answers question: http://stackoverflow.com/q/48300822
has comment: http://stackoverflow.com/comment/83594633
has body: OneHotEncoder expects 2D array and you passed 1D (Series - resilt of labelencoder.fit_transform) - this can be fixed easily - use df'info.venue' instead of df['info.venue'] (pay attention at square brackets) in the following way: df['info.venue']=labelencoder.fit_transform(df['info.venue']) R = onehotencoder.fit_transform(df'info.venue') where R is a sparse 2D matrix: In [155]: R Out[155]: &lt;13x11 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 13 stored elements in Compressed Sparse Row format&gt; In [156]: R.A Out[156]: array([[ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]]) alternatively you can use LabelBinarizer in order to get One Hot Encoded values directly from strings: Source DF: In [121]: df Out[121]: info.venue 0 Adelaide Oval 1 Brabourne Stadium 2 Kensington Oval, Bridgetown 3 Kingsmead 4 Melbourne Cricket Ground .. ... 8 R Premadasa Stadium 9 Saurashtra Cricket Association Stadium 10 Shere Bangla National Stadium 11 Stadium Australia 12 Sydney Cricket Ground [13 rows x 1 columns] Solution: In [122]: from sklearn.preprocessing import LabelBinarizer In [123]: lb = LabelBinarizer() In [124]: r = pd.SparseDataFrame(lb.fit_transform(df['info.venue']), ...: df.index, ...: lb.classes_, ...: default_fill_value=0) ...: In [125]: r Out[125]: Adelaide Oval Brabourne Stadium Kensington Oval, Bridgetown Kingsmead Melbourne Cricket Ground \ 0 1 0 0 0 0 1 0 1 0 0 0 2 0 0 1 0 0 3 0 0 0 1 0 4 0 0 …
has comment: http://stackoverflow.com/comment/83587585
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83588173
has comment: http://stackoverflow.com/comment/83586964
has comment: http://stackoverflow.com/comment/83588234
has comment: http://stackoverflow.com/comment/83587881

http://stackoverflow.com/comment/83455882
type: Comment
type: QuestionComment
has text: Check your environment variables and filetype/program associations. You can also try creating a shortcut for the executable, then right-click the shortcut and select "properties" it then alter the "start in" property to the directory you want it to start in.
comment on: http://stackoverflow.com/q/48236584
score: 0

http://stackoverflow.com/comment/135865147
type: Comment
type: AnswerComment
has text: beware the "silent fail" when using `engine.connect()` for the `to_sql` `con` param! So much time wasted debugging, would like for this to be addressed
comment on: http://stackoverflow.com/a/57005991
score: 0

http://stackoverflow.com/comment/83525515
score: 0
comment on: http://stackoverflow.com/a/48270730
type: AnswerComment
has text: Good question. Probably worth opening as a new one.
type: Comment

http://stackoverflow.com/comment/99217518
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48251455
type: Comment
has text: @babygame0ver - Hmmm, not idea. Maybe the best is create new question.

http://stackoverflow.com/a/48241461
type: Answer
accepted answer of: http://stackoverflow.com/q/48241269
type: AcceptedAnswer
has body: In Python reverse method of list does the operation in-place e.g. it modifies the list you apply this operation to. This method has no return value. l = [1, 2, 3, 4] l.reverse() print(l) Output: [4, 3, 2, 1] If you try to get value returned by reverse you will get None: print([1, 2, 3, 4].reverse()) Output: None If you need a reversed copy of your list you should use reversed function: l = [1, 2, 3, 4] r = reversed(l) print(r) print(list(r)) Output: &lt;list_reverseiterator object at 0x7ff37e288ef0&gt; [4, 3, 2, 1] Notice that it returns iterator, not the list itself. You can pass that iterator to join function or you can build a list from it using list constructor. The same is true for method sort and function sorted.
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/48241269
upvote count: 3

http://stackoverflow.com/q/48282073
upvote count: 0
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/83548614
tagged with: button
has comment: http://stackoverflow.com/comment/83549095
has comment: http://stackoverflow.com/comment/83558994
has title: Event binding with buttons
favorite count: 0
type: Question
has body: So i am creating a Sudoku game, and have generated a 9x9 grid of buttons. There are two difficulty levels - easy and hard. When a difficulty level is selected, numbers randomly generate on some of the buttons. The user then clicks on the empty buttons to change/set a number (each click increased the number by 1). However, the user can also change the generated numbers. Is there any way in which i can stop this. I managed to stop this by adding an if statement in my button generator, however when i added difficulty levels and separated the code into functions, i am no longer able to stop this. Here is my button generator code: def ButtonGenerator(): for row_index in range(9): for col_index in range(9): if (row_index in {0, 1, 2, 6, 7, 8} and col_index in {3, 4, 5}) or \ (row_index in {3, 4, 5} and col_index in {0, 1, 2, 6, 7, 8}): #Colours a group of 3x3 buttons together to differentiate the board better. colour = 'gray85' else: colour = 'snow' btn = Button(frame, width = 10, height = 5, bg=colour, font=font1) #create a button inside frame btn.grid(row=row_index, column=col_index, sticky=N+S+E+W) global buttons buttons.append(btn) Here is my leftclick event function: def LeftClick(event): next_value = " 123456789 " try: current_value = next_value[next_value.index(str(int(event.widget['text']))) + 1] except ValueError: current_value = "1" event.widget.config(text=current_value, font=font1) I have also attempted at creating a function which stops the numbers with pre-generated values from being changed by the user, however it does not work. Any ideas why?? def Checker(): for row in range(9): for col in range(9): for btn in buttons: if btn.cget("text") != "": btn.bind("&lt;Button-1&gt;", LeftClick) else: btn.config(font=font2) break
has comment: http://stackoverflow.com/comment/83556784
type: UnansweredQuestion
score: -3
has answer: http://stackoverflow.com/a/48284117
tagged with: python
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83548803

http://stackoverflow.com/q/48295949
score: 1
has comment: http://stackoverflow.com/comment/83576741
has comment: http://stackoverflow.com/comment/83576504
has answer: http://stackoverflow.com/a/48296179
downvote count: 1
has comment: http://stackoverflow.com/comment/83610698
favorite count: 0
type: Question
has title: Django ImportError: Couldn't import Django
upvote count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83576486
has body: I have a project about django web, this project has no problem on other computers, but pycharm on my own laptop prompts for the following information ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I use PyCharm Professional and PyCharm3 My system is Windows 10. Can someone help?
has answer: http://stackoverflow.com/a/60914386
answer count: 2

http://stackoverflow.com/comment/83503734
type: Comment
comment on: http://stackoverflow.com/q/48258374
score: 0
type: QuestionComment
has text: i tried in read mode ..but again i am getting error arff.BadNominalValue: Data value not found in nominal declaration, at line 67.

http://stackoverflow.com/q/48230210
type: Question
tagged with: python-imaging-library
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83442621
has comment: http://stackoverflow.com/comment/83442587
has answer: http://stackoverflow.com/a/48230432
tagged with: python
has comment: http://stackoverflow.com/comment/83442799
score: -1
has title: Open picture in Python using PIL
has body: I am trying to take a screenshot of my PC and display it to me. I have tried: import PIL from PIL import ImageGrab im = ImageGrab.grab() im.save(r'D:\photo.jpg') im.show() However, it does not work, Why?
upvote count: 0
has comment: http://stackoverflow.com/comment/83442880
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/48281521
tagged with: python
has comment: http://stackoverflow.com/comment/111521381
has title: python, mongoengine ReferenceField duplicate key error
has comment: http://stackoverflow.com/comment/83546529
score: 0
answer count: 0
has body: So I have these models: class Podcast(Document): name = StringField(max_length=200, required=True) category_id = ReferenceField(Category) and: class Category(Document): name = StringField(max_length=120, required=True, unique=True) When I try to insert a new podcast that has a category that another podcast already has, I get this error: mongoengine.errors.NotUniqueError: Tried to save duplicate unique keys (E11000 duplicate key error collection:myapp.podcast index: category_id.name_1 dup key: { : null }) How I am inserting a podcast: category = 'Comedy' if not CategoryFacade.categoryExists(category): cat = CategoryFacade.createCategory(category) else: cat = CategoryFacade.get(category) podcast = { 'name': pod['name'] if 'name' in pod else None, 'category_id': cat.to_dbref() } PodcastFacade.createPodcast(podcast) the createPodcast method in PodcastFacade: @staticmethod def createPodcast(kwargs): c = Podcast(**kwargs) c.save() return c The categoryExists method: @staticmethod def categoryExists(name): try: return Category.objects.get(name=name) is not None except DoesNotExist: return False
has comment: http://stackoverflow.com/comment/83546631
tagged with: mongoengine
type: Question
tagged with: mongodb
type: UnansweredQuestion

http://stackoverflow.com/comment/83559407
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48287289
has text: Just use the for-loop...

http://stackoverflow.com/comment/83596436
type: AnswerComment
comment on: http://stackoverflow.com/a/48296981
type: Comment
has text: Thanks for this solution.
score: 0

http://stackoverflow.com/q/48270466
has comment: http://stackoverflow.com/comment/83524934
type: AnsweredQuestion
answer count: 1
downvote count: 3
has body: I am trying to extract information like price,owner,name etc from below string. str='invokeUrl("viewphonenumber","trackCode=Property_for_Rent_View_Phone_BVersion&amp;isPhoto=N&amp;pid=29563627&amp;code=&amp;price=Rs. 29,000&amp;bedroom=2&amp;area=2000 sqft&amp;verified=&amp;possession_status=Immediately&amp;prop_number=1&amp;offer=&amp;owner=Agent&amp;locality=Kadubeesanahalli&amp;city=Bangalore&amp;propertyType=Flat&amp;categoryDesc=Rent&amp;name=Manjunath&amp;brEx=Y&amp;js=true&amp;page=result&amp;from=search&amp;call=N&amp;pageOption=B&amp;isSimilarProperty=N&amp;moisd=50&amp;cardType=card_Rent_O&amp;isNight=true&amp;isNri=false&amp;isVisibleProperty=N&lt;Id=86581&amp;propertyTypeId=10002&amp;cityId=3327&amp;priceNumeric=29000&amp;vph=Y","29563627");createCookie("contactTrackCookieData","Y","10");_gaq.push([ "_trackEvent", "propertySRP", "contactopen","view_card_Rent_O" ]);' #print(str.split('&amp;')) I want to extract different value from string like price value as Rs. 29,000,owner value as Agent etc. Could you please help me?
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48271213
upvote count: 0
has title: Search string from another string in python
score: -3
has answer: http://stackoverflow.com/a/48271213
tagged with: web-scraping
tagged with: python

http://stackoverflow.com/comment/83564584
has text: are we ignoring employee number in the aggregation? the last two have the same employee number, and `marg.prent` has multiple employee numbers?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48288164

http://stackoverflow.com/q/48235012
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83452835
linked to: http://stackoverflow.com/q/11403932
tagged with: python
score: 0
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/48238160
tagged with: arduino
answer count: 1
has body: I'm aware of this being the same question as in this thread. However, I tried the named solutions (yes, all of them [I think]) and it still gives the same error message. I tried to establish a serial connection between my Raspberry and Arduino (Mega 2560). After installing the serial package (pip install serial, sudo apt-get install python-serial), my script file being called "arduino.py", the code being: import serial MySer = serial.Serial('/dev/ttyUSB0', 9600) I still get the same error message (AttributeError: 'module' object has no attribute 'Serial'). Now did I do something inherently wrong? Do I have to set some permissions or... I'm a little lost here. ^^ Thanks in advance, Tim
type: Question
has title: Raspberry Pi Arduino Serial with Python

http://stackoverflow.com/comment/83545173
type: QuestionComment
score: 0
has text: @Psytho Done with editing. Reduced the code but I can't reduce the code further because No one will get the error.
comment on: http://stackoverflow.com/q/48264157
type: Comment

http://stackoverflow.com/a/48291757
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48291699
has comment: http://stackoverflow.com/comment/83568699
has body: You can use zip like this: for i, (a1, a2, b1) in enumerate(zip(a, a[1:], b)): if b1 &gt; a1 and b1 &lt; a2: print(i)
type: Answer
has comment: http://stackoverflow.com/comment/83569022
has comment: http://stackoverflow.com/comment/83569073

http://stackoverflow.com/comment/83626272
score: 2
comment on: http://stackoverflow.com/q/48315412
has text: Do you know how to pass a value to a function? You need to add a parameter to the function definition, for example `def snowman(x):`, then you'll have the `k*40` value from the while loop (btw `k` is not defined anywhere) available inside the function and can add it to the x-positions.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48186012
has body: I create a cartesian product using the itertools.product function: from itertools import product a = list(map(list, itertools.product(list(range(2)), repeat=3))) Output: [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]] Then I get rid of mirrors reflections in the following way: b = [] for k, v in enumerate(a): if v[::-1] not in a[:k]: b.append(v[::-1]) Output: [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 1], [1, 1, 1]] But can I get the same effect step by step without saving all the results of itertools.product in the list? For example, with the usual approach on the for loop: for i in list(map(list, itertools.product(list(range(2)), repeat=3))): # blah blah blah Because ultimately I will use large cartesian products, at least repeat = 18. And that is why I have to give up the approach on the lists. Unless there is another way to do it? I will be grateful for any tips.
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/83352061
has comment: http://stackoverflow.com/comment/83352112
score: 5
downvote count: 0
has answer: http://stackoverflow.com/a/48186679
has comment: http://stackoverflow.com/comment/83352010
has comment: http://stackoverflow.com/comment/83352418
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48189435
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83351852
has comment: http://stackoverflow.com/comment/83352086
accepted answer: http://stackoverflow.com/a/48186679
tagged with: python-itertools
has answer: http://stackoverflow.com/a/48189435
linked to: http://stackoverflow.com/q/19744542
upvote count: 5
tagged with: python
has title: How to remove mirrors reflections values of itertools.product function?

http://stackoverflow.com/comment/83593517
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48303791
has text: Please note that there are different client libraries for accessing the cloud storage depending on where you're running your app: GAE standard/flex, GCE, outside Google's cloud, etc. See https://cloud.google.com/apis/docs/client-libraries-explained

syntactic-sugar
type: Tag
tag name: syntactic-sugar
tags question: http://stackoverflow.com/q/48205442

http://stackoverflow.com/comment/83533852
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48275038
type: Comment
has text: I have this code works fine, without falling. (Ubuntu)

http://stackoverflow.com/comment/83477057
comment on: http://stackoverflow.com/a/48246880
has text: Nothing happened. All the answers here are recursive?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83388590
type: Comment
comment on: http://stackoverflow.com/a/48203570
score: 0
type: AnswerComment
has text: When I tried your dense to sparse, I got this error: `File "...", line 11, in grid_rnn_fn labels = tf.SparseTensor(indices, values, dense_shape=labels.shape) ValueError: Cannot convert a partially known TensorShape to a Tensor: (?, 33)`

http://stackoverflow.com/comment/83453365
comment on: http://stackoverflow.com/q/48235277
has text: Move the `print` outside of the loop and it should work.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48241888
has comment: http://stackoverflow.com/comment/83466317
has comment: http://stackoverflow.com/comment/83466139
favorite count: 0
type: Question
has body: I'm trying to deploy my Django site on Heroku, and thus, I need a requirements.txt file with the necessary packages that Heroku needs to install for me. I understand Django is a necessary package to be installed. Unfortunately, Django isn't included in the file when I run pip freeze &gt; requirements.txt. Why is this? I'm not sure what to show you so you can tell me what's going wrong. Let me know and I'll add it. FYI the site hosts just fine on my local computer, so Django is definitely installed.
accepted answer: http://stackoverflow.com/a/48242094
has comment: http://stackoverflow.com/comment/83466257
tagged with: pip
tagged with: django
upvote count: 1
tagged with: python
tagged with: requirements.txt
has comment: http://stackoverflow.com/comment/83466147
has comment: http://stackoverflow.com/comment/83466277
has answer: http://stackoverflow.com/a/48242094
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83466204
has title: why doesn't pip freeze > requirements.txt output Django?
has comment: http://stackoverflow.com/comment/83466293
score: 1
has comment: http://stackoverflow.com/comment/83466212
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/94826900
type: QuestionComment
comment on: http://stackoverflow.com/q/48245368
has text: I noticed that Jupyter is RTL by default only on Chrome. Direction is LTR on Safari and firefox. Tried to remove any Hebrew regional settings from both Chrome and Mac O/S but that didn't solve it, so for now I am using another browser with Jupyter (too annoying to switch to RTL with ctrl-shift-F every time). Any help for fixing that for Chrome would be appreciated.
score: 1
type: Comment

http://stackoverflow.com/q/48266862
answer count: 1
tagged with: tensorflow
type: Question
has body: I have some code which is meant to simply draw a bounding box on an image, and save it out as a new image. However, when I run it I get a TypeError: Cannot handle this data type from pillow. The code is # Tests that the processed data file can be read correctly and has correct bounding boxes import tensorflow as tf import numpy as np from PIL import Image def read_processed_data(filename, num_show): """ Reads in the processed data file and displays the given number of images, along with the bounding boxes. """ with open(filename, 'r') as f: i = 0 while i &lt; num_show: for line in f: filename = line.rstrip() next_line = f.readline() num_faces = int(next_line.rstrip()) face_num = 0 #while face_num &lt; num_faces: bb_line = f.readline().rstrip() y1, x1, y2, x2 = bb_line.split(',') box = [y1, x1, y2, x2] box = tf.cast(box, tf.float32) return box, filename with tf.Session() as sess: bb, fn = read_processed_data("processed.txt", 1) image = tf.image.decode_image(tf.read_file(fn)) img = image.eval() print(img.shape) img_show = np.asarray(img) Image.fromarray(img_show).save("test_no_bb.jpg") # Works bb_image = tf.image.draw_bounding_boxes(img, bb) print(bb_image.shape) bb_image = tf.cast(bb_image, tf.uint8) bb_img_jpeg = tf.image.encode_jpeg(bb_image) bb_image_np = np.asarray(bb_img_jpeg) Image.fromarray(bb_image_np).save("test.jpg") # Does not work test_no_bb.jpg gets created fine, but when I reach Image.fromarray(bb_image_np).save("test.jpg"), I get the aforementioned type error. I have searched the web all over to no avail, and TensorFlow's documentation on this is lacking. The shape of the bb_image is correct, and the output of bb (the coordinates of the bounding box) is also correct so I am at a loss. Any help is greatly appreciated.
has title: Trouble Displaying an Image with Bounding Boxes
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48267559
tagged with: python
score: 0
tagged with: python-imaging-library

http://stackoverflow.com/a/68915079
answers question: http://stackoverflow.com/q/48304875
type: Answer
has body: It looks like that this feature was deprecated for proxied repositories. It is supposed to still work with hosted PyPI repos. "pip search" command is deprecated and doesn't work with a proxy repository, but you can still search for packages in hosted repositories.
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/48308255
type: Question
has title: Python - importing a class within the same folder
has answer: http://stackoverflow.com/a/48308399
score: 0
has comment: http://stackoverflow.com/comment/83602746
tagged with: python
has comment: http://stackoverflow.com/comment/83602648
has body: I use python 3.5 with Anaconda (python 3.6) and I have a problem with importing a class within the same folder, even though I did exactly as explained in other places. In 04-Convolutional Neural Network Folder I have 04-Convolutional Neural Network.ipynb and logger.ipynb files. I want to import Logger class in logger.ipynbto 04-Convolutional Neural Network.ipynb First, I created a blank __init__.ipynb file in the same folder, I used: from .user import User from .dir import Dir But I get the following error No module named '__main__.user'; '__main__' is not a package Any idea why do I have this problem? maybe because of the ipynb file system? Edit: The files are in Desktop/NN/.... if it's important
type: UnansweredQuestion
answer count: 1
linked to: http://stackoverflow.com/q/20186344

http://stackoverflow.com/q/48217681
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: Pipelining commands doesnt work in python fabric
type: UnansweredQuestion
tagged with: pipe
tagged with: pipelining
tagged with: fabric
tagged with: python
has answer: http://stackoverflow.com/a/48227405
score: 3
tagged with: bash
has body: I'm trying to pipeline multiple bash commands to extract an image name from the output of a command that lists the names of images but it doesnt work - it spits a blob of text, where as doing it step by step works. Code using pipeline: @task def update(): image_name = sudo('/os-updater --list | grep X86-64_ | sed "s/XXX/UEK4/" | tail -1') print("IMAGE NAME: "+image_name) Output: user@system:host-updater$ ./hu -R host-name update [host-name] Executing task 'update' [host-name] sudo: /os-updater --list | grep X86-64_ | sed "s/XXX/UEK4/" | tail -1 [host-name] out: 2018-01-11 23:33:28,628 INFO ==&gt; os-updater 1.3.3 started [host-name] out: 2018-01-11 23:33:28,629 INFO --listsnapshots:True [host-name] out: 2018-01-11 23:33:28,705 INFO Exit 0 [host-name] out: X86-64_20171201.01_UEK4 [host-name] out: IMAGE NAME: 2018-01-11 23:33:28,628 INFO ==&gt; os-updater 1.3.3 started 2018-01-11 23:33:28,629 INFO --listsnapshots:True 2018-01-11 23:33:28,705 INFO Exit 0 X86-64_20171201.01_UEK4 Done. Code without pipleine: @task def update(): image_list = sudo("/os-updater --list") out = image_list.stdout for line in out.splitlines(): if 'X86-64_' in line: image_name = line.replace("XXX", "UEK4").strip() print("IMAGE NAME: " + image_name) Output: user@system:host-updater$ ./hu -R host-name update [host-name] Executing task 'update' [host-name] sudo: /os-updater --list [host-name] out: 2018-01-11 23:36:11,752 INFO ==&gt; os-updater 1.3.3 started [host-name] out: 2018-01-11 23:36:11,753 INFO --listsnapshots:True [host-name] out: 2018-01-11 23:36:11,847 INFO Exit 0 [host-name] out: Snapshots: [host-name] out: X86-64_20171101.01_XXX [host-name] out: X86-64_20171201.01_XXX [host-name] out: Kernel trains: (XXX above) [host-name] out: UEK4 [host-name] out: STOCK [host-name] out: IMAGE NAME: X86-64_20171201.01_UEK4 Done. I dont understand why the second way (literally doing the same step by step without pipeline) works but not the first returns a lot of text with the image name. I have tried a…
upvote count: 3

http://stackoverflow.com/comment/83414590
has text: Any attempt from your side?
type: QuestionComment
comment on: http://stackoverflow.com/q/48216315
score: 3
type: Comment

http://stackoverflow.com/comment/83641962
score: 0
type: AnswerComment
has text: That's odd. Is there a new line character between each set of 'variable1=string1'?
comment on: http://stackoverflow.com/a/48327103
type: Comment

http://stackoverflow.com/a/48242072
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48241601
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: UPDATE: I found using a format that crams 3 matrix elements into one byte is actually quite fast. In the example below the speed penalty is less than 2x compared to direct multiplication using @ while the space saving is more than 20x. &gt;&gt;&gt; Y = np.random.randint(0, 5, (3000, 3000), dtype = np.int8) &gt;&gt;&gt; i, j = np.triu_indices(3000, 1) &gt;&gt;&gt; Y[i, j] = Y[j, i] &gt;&gt;&gt; values = np.array([0.3, 0.5, 0.6, 0.9, 2.0]) &gt;&gt;&gt; Ycmp = (np.reshape(Y, (1000, 3, 3000)) * np.array([25, 5, 1], dtype=np.int8)[None, :, None]).sum(axis=1, dtype=np.int8) &gt;&gt;&gt; &gt;&gt;&gt; full = values[Y] &gt;&gt;&gt; x @ full @ x 1972379.8153972814 &gt;&gt;&gt; &gt;&gt;&gt; vtable = values[np.transpose(np.unravel_index(np.arange(125), (5,5,5)))] &gt;&gt;&gt; np.dot(np.concatenate([(vtable * np.bincount(row, x, minlength=125)[:, None]).sum(axis=0) for row in Ycmp]), x) 1972379.8153972814 &gt;&gt;&gt; &gt;&gt;&gt; timeit('x @ full @ x', globals=globals(), number=100) 0.7130507210385986 &gt;&gt;&gt; timeit('np.dot(np.concatenate([(vtable * np.bincount(row, x, minlength=125)[:, None]).sum(axis=0) for row in Ycmp]), x)', globals=globals(), number=100) 1.3755558349657804 The solutions below are slower and less memory efficient. I'll leave them merely for reference. If you can afford half a byte per matrix element, then you can use np.bincount like so: &gt;&gt;&gt; Y = np.random.randint(0, 5, (1000, 1000), dtype = np.int8) &gt;&gt;&gt; i, j = np.triu_indices(1000, 1) &gt;&gt;&gt; Y[i, j] = Y[j, i] &gt;&gt;&gt; values = np.array([0.3, 0.5, 0.6, 0.9, 2.0]) &gt;&gt;&gt; full = values[Y] &gt;&gt;&gt; # full would correspond to your original matrix, &gt;&gt;&gt; # Y is the 'compressed' version &gt;&gt;&gt; &gt;&gt;&gt; x = np.random.random((1000,)) &gt;&gt;&gt; &gt;&gt;&gt; # direct method for reference &gt;&gt;&gt; x @ full @ x 217515.13954751115 &gt;&gt;&gt; &gt;&gt;&gt; # memory saving version &gt;&gt;&gt; np.dot([(values * np.bincount(row, x)).sum() for row in Y], x) …
answers question: http://stackoverflow.com/q/48241601

http://stackoverflow.com/comment/83356942
has text: @SantiPeñate-Vera sorry but the professor does not allow 3.6.2 although I do not know why...
comment on: http://stackoverflow.com/q/48188307
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83371518
has text: Actually that is answered [here](https://stackoverflow.com/questions/2960864/how-can-i-save-all-the-variables-in-the-current-python-session).
comment on: http://stackoverflow.com/a/48192813
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/83478239
has text: @cᴏʟᴅsᴘᴇᴇᴅ - I answer only because 2 dataFrames and I think it is not pivot dupe, so why you answer? I dont understand, because your answer is clear dupe.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48247739
score: 0

http://stackoverflow.com/comment/83352495
type: Comment
has text: No... please don't butcher strings in the name of parsing... this looks like JSON, so just load it using a JSON parser. `import json; json.loads(html.text)`
comment on: http://stackoverflow.com/q/48186448
type: QuestionComment
score: 3

http://stackoverflow.com/comment/83468690
has text: Also I think cv2.imread() returns the channels in the last column. So it should rather be float_img.reshape([32,32,3])
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48243098
type: AnswerComment

http://stackoverflow.com/comment/83377561
type: AnswerComment
score: 0
has text: @JCena Indeed, there is. See my last edit. Happy coding!
comment on: http://stackoverflow.com/a/48198034
type: Comment

http://stackoverflow.com/q/48225315
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: tensorflow-slim
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I need to read in many 'images' from .txt files and want to generate a tensorflow dataset with them. Currently, I read in every single matrix with numpy.loadtxt and create an array of shape [N_matrices, height, width, N_channels], and a similar array with the label for every matrix. I create a tensorflow dataset from these two arrays by using inputs = tf.convert_to_tensor(x_train, dtype=tf.float32) labels = tf.convert_to_tensor(y_train, dtype=tf.float32) dataset = tf.data.Dataset.from_tensor_slices( {"image": inputs,"label": labels}) I now want to make use of the following function to create batches from this dataset (as done here): def load_batch(dataset, batch_size=BATCH_SIZE, height=LENGTH_INPUT, width=LENGTH_INPUT): data_provider = slim.dataset_data_provider.DatasetDataProvider(dataset) image, label = data_provider.get(['image', 'label']) images, labels = tf.train.batch( [image, label], batch_size=batch_size, allow_smaller_final_batch=True) return images, labels However, this gives me the following error: data_provider = slim.dataset_data_provider.DatasetDataProvider(dataset) File "/home/.local/lib/python3.5/site-packages/tensorflow/contrib/slim/python/slim/data/dataset_data_provider.py", line 85, in init dataset.data_sources, AttributeError: 'TensorSliceDataset' object has no attribute 'data_sources' Why am I getting this error, and how can I fix it? I also suppose there are much better ways for handling input from txt files to tensorflow (or tensorflow-slim) but I've found very little information on this. How could I generate my Datasets in a better way?
score: 2
has title: Reading data into tensorflow and creating Dataset with TF-slim
answer count: 0
downvote count: 0

http://stackoverflow.com/a/48271944
has comment: http://stackoverflow.com/comment/83527748
has comment: http://stackoverflow.com/comment/83527790
has comment: http://stackoverflow.com/comment/83527713
score: 0
has comment: http://stackoverflow.com/comment/83528130
has body: matplotlib has a built in function called plot_date that will help you out here. Note that your time series has to be in the date-time format (though you can add the year, month and day arbitrarily as they do not affect plotting if all times are on the same day). Here is the code: import matplotlib.pyplot as plt import csv import datetime x = [] y = [] with open('calibrated.csv','r') as csvfile: plots = csv.reader(csvfile, delimiter=' ') year = 2017 month = 1 day = 16 for row in plots: hours,minutes,seconds,milliseconds = [int(s) for s in row[0].split(",")] x.append(datetime.datetime(year,month,day,hours,minutes,seconds,milliseconds)) y.append(float(row[1])) plt.plot_date(x,y, marker='o', label='brightness') plt.gca().invert_yaxis() plt.xlabel('time [UT]') plt.ylabel('brightness [mag, CR]') plt.legend() plt.grid() plt.show() As coldspeed pointed out you would likely benefit greatly from using pandas. Note that now if the time series was much longer the plot still works correctly. Thanks to @ImportanceOfBeingErnest for pointing out the original misunderstanding.
answers question: http://stackoverflow.com/q/48271838
type: Answer

http://stackoverflow.com/comment/83535739
has text: i tried your link (https://repl.it/repls/VillainousRemorsefulSulphurbutterfly). but there is backslashes in out put. like when i try my own terminal using pdb.
type: AnswerComment
comment on: http://stackoverflow.com/a/48276076
score: 0
type: Comment

http://stackoverflow.com/q/48325729
has body: I have read through some of the PFA documentation and understand that PFA model can be imported and used in Production deployments (I have followed along a few examples on GitHub). However, it is not clear to me how the PFA model is exported/generated. Is it possible to export Python scikit-learn model as a PFA model? Is it possible to export Tensorflow model built in Python as a PFA model? Would you please be able to provide guidelines on the export process?
has title: PFA model export from Python scikit-learn
answer count: 2
downvote count: 0
tagged with: scikit-learn
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49285888
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/54058372
tagged with: python
upvote count: 4
score: 4

http://stackoverflow.com/comment/83567453
type: Comment
type: QuestionComment
has text: The `print` statements that are run _after_ `root.mainloop()` do yield whatever I entered in the entry for me.
comment on: http://stackoverflow.com/q/48291140
score: 1

http://stackoverflow.com/comment/83371933
type: Comment
comment on: http://stackoverflow.com/a/48195266
has text: If you'd share more of the stack trace (not only the message, but the function where this message appears and the file), it might be easier to find the issue.
score: 0
type: AnswerComment

http://stackoverflow.com/a/48220907
has body: Replace '==' with 'in' "hello" in "123hello123" # RETURNS True "hello" in "aasdasdasd123hello123" # RETURNS True "hello" in "123123hello" # RETURNS True "hello" in "hello" # RETURNS True
has comment: http://stackoverflow.com/comment/83423488
score: 6
has comment: http://stackoverflow.com/comment/83423794
upvote count: 6
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/83423517
answers question: http://stackoverflow.com/q/48220840

http://stackoverflow.com/q/48327787
has comment: http://stackoverflow.com/comment/83641301
type: Question
has answer: http://stackoverflow.com/a/48332734
score: 0
has comment: http://stackoverflow.com/comment/83641249
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83641121
answer count: 1
tagged with: email
has body: I have developed a code to iterate over outlook folder and download attachment from emails that have a predefined subject line and delete the message and delete messages that have a different subject than the predefined one.the code is as below folder = inbox.Folders("folder") for msg in folder.Items: if msg.Subject == "Predefined msg Subject": for att in msg.Attachments: msg_date = msg.SentOn.srftime(%Y-%m-%d) att.SaveAsFile(os.path.join(dest_folder, msg_date + "_" + att.Filename) else: pass msg.Delete() continue I have about 150 messages in the folder, there are about 8 messages with required attachments and others are just to bedeleted. but the loop above breaks at 73 exactly (i used a counter and msg.Subject to where it breaks and why). The sencond run then breaks after ~24 and so forth. I had to run the code 3 more times to go over all the emails from folder. Any idea why the code exits loop
tagged with: loops
has comment: http://stackoverflow.com/comment/83641413
has title: For loop exits while downloading outlook email attachments python
has comment: http://stackoverflow.com/comment/83641196
has comment: http://stackoverflow.com/comment/83641592
has comment: http://stackoverflow.com/comment/83641665
tagged with: outlook
has comment: http://stackoverflow.com/comment/83641099
has comment: http://stackoverflow.com/comment/83641461
tagged with: python
has comment: http://stackoverflow.com/comment/83641262

http://stackoverflow.com/a/48184421
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83349833
type: Answer
answers question: http://stackoverflow.com/q/48184200
score: 2
has comment: http://stackoverflow.com/comment/83389470
has body: lat[i, j] is a scalar right? You can't do lat[i, j][x, y]

http://stackoverflow.com/a/48245528
has comment: http://stackoverflow.com/comment/83487795
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48245453
has comment: http://stackoverflow.com/comment/83488656
has comment: http://stackoverflow.com/comment/83493112
has comment: http://stackoverflow.com/comment/83488026
has comment: http://stackoverflow.com/comment/83568592
answers question: http://stackoverflow.com/q/48245453
score: 1
has comment: http://stackoverflow.com/comment/83489010
has comment: http://stackoverflow.com/comment/83474099
has comment: http://stackoverflow.com/comment/83500837
has comment: http://stackoverflow.com/comment/83495914
has comment: http://stackoverflow.com/comment/83494597
has body: Note, that this is not the usual way to build an URL for accessing a specific object. Below I present first the approach that integrates pk in the URI and second the one passing pk as a parameter. 1. Approach Here you put the pk in the URI and request something like http://localhost:8000/homesite/viewstatus/1/. If you do so, you need to adapt your urls.py by specifying what part of the URI is the pk you want: # urls.py url(r'^viewstatus/(?P&lt;pk&gt;\d+)/$', views.view_status, name='ViewStatus'), The way you wrote the view is fine: def view_status(request, pk=None): if pk is not None: device = Devices.objects.get(pk=pk) else: device = None return render(request, 'homesite/device_status.html', {'device' : device}) Now, views.view_status will be called with both the request object and the pk as arguments and objects.get will behave as you expected, if the pk you put in the URI exists in you database. Note that this is the preferred way to get an object. 2. Approach In this case you pass the pk as a parameter, so call http://localhost:8000/homesite/viewstatus/?pk=1, for example. Now pk is a parameter of a GET request. In this case: # urls.py url(r'^viewstatus/$', views.view_status, name='ViewStatus'), And the view only takes the request object as argument. Within the view you can get the pk as follows: def view_status(request): pk = request.GET.get('pk', None) if pk is not None: device = Devices.objects.get(pk=int(pk)) else: device = None return render(request, 'homesite/device_status.html', {'device' : device}) So in this case your view does not take any arguments other than the request object. Another issue is in your view function: Django's shortcut render takes a dict object for the optional argument context. Currently you directly pass a Devices object. You need to update your return statement in view_status: return render(request, 'homesite/device_status.html', {'device' : device}) Hope that helps!
has comment: http://stackoverflow.com/comment/83568650
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83492163
has text: Thank you for the help. But it seems that the unstack method automatically sorts the month names as they are now string instead of categorical type. Is there any way to fix this since I still want the month names in the original order. Also, is there a way to cast the type of the month column right before the unstack method so that I won't change anything about the original dataset "flights". Thank you.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48253912

http://stackoverflow.com/comment/83383685
comment on: http://stackoverflow.com/q/48201291
type: Comment
type: QuestionComment
score: 0
has text: @peur - so need `df.unstack(-1)` only? No necessary `rename` ?

http://stackoverflow.com/q/48270813
has body: I am trying to get the try except block to work with django 2.0. def find_recurrence_i18n_js_catalog(): # used cached version global _recurrence_javascript_catalog_url if _recurrence_javascript_catalog_url: return _recurrence_javascript_catalog_url # first try to use the dynamic form of the javascript_catalog view try: return urlresolvers.reverse( i18n.javascript_catalog, kwargs={'packages': 'recurrence'}) except urlresolvers.NoReverseMatch: pass I'm assuming that if I change it to this that it won't work: # first try to use the dynamic form of the javascript_catalog view try: return reverse( i18n.javascript_catalog, kwargs={'packages': 'recurrence'}) except: pass
has comment: http://stackoverflow.com/comment/83525462
upvote count: 0
has comment: http://stackoverflow.com/comment/83525778
answer count: 1
tagged with: django-forms
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
tagged with: django-models
tagged with: python
score: -1
has title: Using Django 2.0 So django.core.urlresolvers is no longer supported, how to make this try except block work?
has answer: http://stackoverflow.com/a/48271093
has comment: http://stackoverflow.com/comment/83525512

http://stackoverflow.com/q/48289959
has title: NoSuchElementException using Selenium
type: Question
has body: I'm trying to learn python/webscraping and want to scrape my bank statements, but am having trouble logging into my by account through selenium. Here is my code: from selenium import webdriver username = 'XXXXXXXX' password = 'XXXXXXXX' base_url = 'https://www.onlinebanking.pnc.com/alservlet/PNCOnlineBankingServlet' driver = webdriver.Chrome() driver.get(base_url) uname = driver.find_element_by_name('userId') uname.send_keys(username) passw = driver.find_element_by_name('password') passw.send_keys(password) submit_button = driver.find_element_by_class_name('formButton').click() driver.quit() I'm getting a NoSuchElementException when I call the find_element_by_name() method: NoSuchElementException Traceback (most recent call last) &lt;ipython-input-5-e5d0b6d323ff&gt; in &lt;module&gt;() 11 driver = webdriver.Chrome() 12 driver.get(base_url) ---&gt; 13 uname = driver.find_element_by_name('userId') 14 uname.send_keys(user) 15 NoSuchElementException: Message: no such element: Unable to locate element: {"method":"name","selector":"userId"} I don't exactly understand why I'm getting this error since the login elements clearly exist when I inspect the webpage. Any help/pointers are greatly appreciated, thanks!
tagged with: python
accepted answer: http://stackoverflow.com/a/48290428
has answer: http://stackoverflow.com/a/48290428
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: selenium
tagged with: web-scraping

http://stackoverflow.com/comment/83473967
type: Comment
type: QuestionComment
score: 0
has text: thanks for your response. but I did not want user to know there has to be "". Anyway without it?
comment on: http://stackoverflow.com/q/48245595

http://stackoverflow.com/comment/83648021
type: QuestionComment
score: 0
has text: Seem's like your algorithm is naturally sequential (i.e. any type of parallel execution will invalidate the answer). Your problem might have a different solution. Can you formulate the problem itself?
type: Comment
comment on: http://stackoverflow.com/q/48327672

http://stackoverflow.com/comment/92264554
score: 0
type: AnswerComment
has text: found a related thread and can use this : df2 = pd.DataFrame(df['column'].values.tolist()) ... but wonder if there is a way to assign the column names such that one can set it as 'state_xx'
type: Comment
comment on: http://stackoverflow.com/a/48207144

http://stackoverflow.com/q/48239116
has answer: http://stackoverflow.com/a/48249026
has comment: http://stackoverflow.com/comment/83464251
tagged with: typeahead
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83463566
upvote count: 0
type: UnansweredQuestion
has body: Edit typeahead assumes results retrieved from your source: dataset are arrays (and parses them as such) passing in a single JSONified dict{} raises an error by Typeahead. (see below) I am trying to parse a single dictionary (python) in a Typeahead's templates option (js): Imagine the dict looks like {"id": 1, "name": "us", "place": "idaho"} // trying to parse a dict obj here templates: { suggestion: Handlebars.compile("&lt;div&gt;+{{ key }}+&lt;/div&gt;") } 1. dict passed as flask.jsonify([dict]) -- {{ key }} works. dict passed as flask.jsonify(dict) -- {{ this.key }} works, {{ key }} doesn't, how is jQuery accessing this dict? 2. is this how the script runs? (when a query ("#q") is typed) code (.js) (.js) asyncResults(data) passed to (.js) typeahead {source: func1(*kwargs)} ----&gt; func1(query, syncResults, asyncResults): ------------------------------------------------&gt; typeahead {suggestion: Handlebars.compile()} ＾calls function1 $.getJSON("/url", params, func2(data,textStatus,jqXHR)) (.py) ＾uses asyncResults(data) as associated Suggestion object ＾sends GET request to "/url" -----------------&gt; function at ("/url") (i.e suggestion.data = whatever was returned from asyncResults()?) ＾calls func2 on success &lt;------------- ＾return jsonify(result) as data ＾return asyncResults(data) [AsyncFunction object] Code: script.js function configure() { $("#q").typeahead( // options { highlight: false, minLength: 1 }, // *dataset { display: function(suggestion) {return null;}, limit: 10, source: search, templates: { suggestion: Handlebars.compile("&lt;div&gt;" + "{{ id }}" + "&lt;/div&gt;");} } ); } function search(query, syncResults, asyncResults) { let params = { q: query }; $.getJSON("/search", params, function(data, textStatus, jqXHR){ asyncResults(data); } ); } app.py from flask import Flask, jsonify, json, render_template, request from sqlalchemy import * @app.route("/search") def search(): if request.method == "GET": query = request.args.get("q") stmt = table.sel…
answer count: 1
tagged with: handlebars.js
tagged with: jquery
tagged with: flask
downvote count: 1
has title: jsonify() and jsonify([]) returning different results in jQuery
favorite count: 0
type: Question

http://stackoverflow.com/a/48260915
has comment: http://stackoverflow.com/comment/83539454
score: 2
accepted answer of: http://stackoverflow.com/q/48260014
upvote count: 2
has comment: http://stackoverflow.com/comment/83540828
has comment: http://stackoverflow.com/comment/83541131
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48260014
has body: I would use numpy functionality to cut your line into segments and then plot all solid and dashed lines separately. In the example below I added two additional -1s to your data to see that this works universally. import numpy as np import matplotlib.pyplot as plt Y = np.array([5,6,-1,-1, 8,3,5,7,3,6,-1,3,8,5]) X = np.arange(len(Y)) idxs = np.where(Y==-1)[0] sub_y = np.split(Y,idxs) sub_x = np.split(X,idxs) fig, ax = plt.subplots() ##replacing -1 values and plotting dotted lines for i in range(1,len(sub_y)): val = sub_y[i-1][-1] sub_y[i][0] = val ax.plot([sub_x[i-1][-1], sub_x[i][0]], [val, val], 'r--') ##plotting rest for x,y in zip(sub_x, sub_y): ax.plot(x, y, 'r-o') plt.show() The result looks like this: Note, however, that this will fail if the first value is -1, as then your problem is not well defined (no previous value to copy from). Hope this helps.
type: Answer

http://stackoverflow.com/q/48257598
type: AnsweredQuestion
tagged with: python
type: Question
has body: I'm writing a tool for live coding in Python, and I want to monkeypatch matplotlib if the user imports it. It's kind of slow to import though, so I don't want to import it and monkeypatch it when the user doesn't import it. I read through the import hooks documentation, and I got this working in Python 3. # scratch.py from importlib import import_module import sys class PatchedModuleFinder(object): def find_module(self, fullname, path=None): if fullname not in ('matplotlib', 'matplotlib.pyplot'): return None is_after = False for finder in sys.meta_path: if not is_after: is_after = finder is self continue loader = finder.find_module(fullname, path) if loader is not None: return PatchedMatplotlibLoader(fullname, loader) class PatchedMatplotlibLoader(object): def __init__(self, fullname, main_loader): self.fullname = fullname self.main_loader = main_loader def load_module(self, fullname): if self.main_loader is not None: module = self.main_loader.load_module(fullname) else: module = import_module(fullname) PatchedModuleFinder.is_desperate = False if fullname == 'matplotlib': module.use('Agg') elif fullname == 'matplotlib.pyplot': module.show = self.mock_show return module def mock_show(self, *args, **kwargs): print('mock_show:', args, kwargs) sys.meta_path.insert(0, PatchedModuleFinder()) import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.plot([1, 2, 5]) plt.show() This works fine for Python 3, but not for Python 2.7: $ .tox/py36/bin/python scratch.py mock_show: () {} $ .tox/py27/bin/python scratch.py $ My tool runs on both Python 2.7 and Python 3.x, so how can I lazily monkeypatch a module in both versions?
tagged with: python-import
score: 1
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48257599
upvote count: 1
has answer: http://stackoverflow.com/a/48257599
favorite count: 0
has title: Lazy monkeypatch in Python

http://stackoverflow.com/comment/83341270
type: QuestionComment
has text: everything should work , what error are you getting?
comment on: http://stackoverflow.com/q/48180676
score: 0
type: Comment

http://stackoverflow.com/comment/83334988
score: 0
has text: @Tai you can assume that multiple matches won't occur. However, the code I included wouldn't break or raise exception even if there are multiple matches. It would simply list all the matches, unique as well as duplicate. Then I can later filter out the indices array in post-processing.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48176651

http://stackoverflow.com/comment/83341256
has text: Thanks a lot Idlehands for your time. By combining your two comments, my problem is solved. Have provided the details in Answer. Thanks again
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48179542
score: 0

http://stackoverflow.com/a/48289546
has comment: http://stackoverflow.com/comment/83564818
accepted answer of: http://stackoverflow.com/q/48289528
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/48289528
has body: X[:, None, :] and Y[None, :, :] are already views. Both operations are NumPy basic slicing, which always generates a view. X[:, None, :] == Y[None, :, :] is going to be a much bigger memory problem, as it creates a very large boolean array. You can avoid this by rewriting your computation in terms of scipy.spatial.distance.cdist in 'hamming' mode: In [10]: x Out[10]: array([[3, 0, 2, 2, 3], [3, 2, 1, 3, 2], [2, 2, 1, 1, 1]]) In [11]: y Out[11]: array([[0, 0, 1, 2, 3], [2, 0, 0, 1, 1], [2, 0, 2, 3, 3], [2, 1, 1, 2, 1]]) In [12]: numpy.sum(x[:, None, :] == y[None, :, :], axis=2) Out[12]: array([[3, 1, 3, 1], [1, 0, 1, 1], [1, 3, 1, 3]]) In [13]: 5 - 5*cdist(x, y, 'hamming') # 5 for the row length of x and y Out[13]: array([[ 3., 1., 3., 1.], [ 1., 0., 1., 1.], [ 1., 3., 1., 3.]]) There's no option to compute non-normalized hamming distances in scipy.spatial.distance, so we have to undo the normalization.
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83564541
has comment: http://stackoverflow.com/comment/83564369
type: Answer
has comment: http://stackoverflow.com/comment/83564269

http://stackoverflow.com/q/48293421
has title: pandas to_datetime formats date from same column in different formats
tagged with: datetime
tagged with: python
tagged with: date
has body: I am using pandas to extract two columns(out of many) from a csv file and store it in a new csv file. The issue is, pd.to_datetime formats the date into two different formats. It formats the date as YYYY-MM-DD and YYYY-DD-MM. The date in the original file is in the format DD-MM-YYYY. Original Data: **DATE_TIME** 01/1/2016 21:11:19 01/1/2016 21:29:58 01/1/2016 22:49:19 01/1/2016 22:50:41 02/1/2016 00:11:41 02/1/2016 00:19:47 02/1/2016 00:19:48 02/1/2016 00:19:50 02/1/2016 00:19:50 The weird formatted data: **DATE_TIME** 2016-01-01 21:11:19 2016-01-01 21:29:58 2016-01-01 22:49:19 2016-01-01 22:50:41 2016-02-01 00:11:41 2016-02-01 00:19:47 2016-02-01 00:19:48 2016-02-01 00:19:50 2016-02-01 00:19:50 Note how the date goes from 1st Jan to 1st Feb. series = read_csv("original_sample.csv") series = series"DATE_TIME", "REPLY_SIZE" series["DATE_TIME"] = pd.to_datetime(series["DATE_TIME"]) series.to_csv("clean_sample.csv") Why is this happening? Note: I've edited out the REPLY_SIZE for clarity.
has answer: http://stackoverflow.com/a/48293470
accepted answer: http://stackoverflow.com/a/48293470
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/83571889

http://stackoverflow.com/comment/83349939
type: QuestionComment
comment on: http://stackoverflow.com/q/48185043
type: Comment
has text: just use post instead of get?
score: 7

http://stackoverflow.com/q/48248816
has answer: http://stackoverflow.com/a/48272401
tagged with: pycharm
answer count: 1
tagged with: tensorflow
type: Question
type: UnansweredQuestion
has title: how to create and save a pycharm project from an existing python program?
tagged with: python
has body: I recently installed TensorFlow on a Ubunu 14.04 machine using virtual environment and installed PyCharm to analyze TensoFlow Python programs. I downloaded mnist_softmax.py, the first tutorial program under ~/TF. I opened it with PyCharm and set the Python interpreter to the one in the virtual environment. I can run it, set breakpoint, and do single stepping. Ok, then, I exit PyCharm . When I start PyCharm again, the recent project list is shown, but the location is /tmp/mnist_softmax.py, not ~/TF/mnist_softmax.py and of course if I try to open it (/tmp/mnist_softmax.py), it complains that the file is not there. How can I save the mnist_softmax.py as a PyCharm project? I couldn't find the submenu in the File menu. I tried Save All before exiting but it was the same and no *.idea file is under ~/TF. How can I do it?
score: 0

http://stackoverflow.com/a/48295544
score: 0
type: Answer
has body: Does the string always end with :? Then use this str.split(":", 1)[0]
answers question: http://stackoverflow.com/q/48295470

http://stackoverflow.com/comment/83390104
type: Comment
type: QuestionComment
score: 0
has text: That does not look like Python 2.7
comment on: http://stackoverflow.com/q/48204501

http://stackoverflow.com/comment/83469672
type: QuestionComment
has text: Your list has type `ARRAY(db.String)`. Why do you expect it to accept objects of type `Post`?
type: Comment
comment on: http://stackoverflow.com/q/48243602
score: 1

http://stackoverflow.com/a/48269737
has comment: http://stackoverflow.com/comment/83618170
has comment: http://stackoverflow.com/comment/138085937
has comment: http://stackoverflow.com/comment/83806129
has comment: http://stackoverflow.com/comment/83559957
answers question: http://stackoverflow.com/q/48262966
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83617579
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83601115
has comment: http://stackoverflow.com/comment/138086268
has comment: http://stackoverflow.com/comment/83784729
has comment: http://stackoverflow.com/comment/83593081
has comment: http://stackoverflow.com/comment/83536965
has body: The simplest way to do this is to use multiprocessing. This will allow you to run a task (or group of tasks) concurrently and terminate processing at any time. However, make sure you read the programming guidelines to understand how to use the module effectively. In particular, although the terminate method works fine for self-contained tasks, it should not be used with multiple tasks that use shared resources. Here is a simple demo based on your example: import sys import time from PyQt5.QtWidgets import (QApplication, QMainWindow, QLabel, QDialog, QVBoxLayout, QPushButton, QDialogButtonBox) from multiprocessing import Pool def long_task(): for x in range(10): print('long task:', x) time.sleep(1) return 'finished' class MainWindow(QMainWindow): def __init__(self): super().__init__() button = QPushButton("Start", self) button.clicked.connect(self.long_task) self.setGeometry(300, 300, 300, 200) self.show() def long_task(self): dialog = QDialog(self) vbox = QVBoxLayout(dialog) label = QLabel("Running...") button = QDialogButtonBox(QDialogButtonBox.Cancel) button.rejected.connect(dialog.close) vbox.addWidget(label) vbox.addWidget(button) pool = Pool() def callback(msg): print(msg) dialog.accept() pool.apply_async(long_task, callback=callback) if dialog.exec_() == QDialog.Rejected: pool.terminate() print('terminated') app = QApplication(sys.argv) main = MainWindow() app.exec_()
has comment: http://stackoverflow.com/comment/83665678
accepted answer of: http://stackoverflow.com/q/48262966
has comment: http://stackoverflow.com/comment/83617640
type: Answer

http://stackoverflow.com/a/48196705
has body: You can't redefine a function that way. It would be like saying sqrt(x) = 2*sqrt(x) What you can do is reassign the value of a (not imag(a)). if imag(a) &lt; 0 a = a - 2*imag(a)*j For example, if a = 3 - 5j, then it would give you 3 - 5j - 2(-5)j = 3 + 5j
score: 0
answers question: http://stackoverflow.com/q/48196567
has comment: http://stackoverflow.com/comment/83379136
type: Answer

http://stackoverflow.com/comment/83465832
type: Comment
type: QuestionComment
has text: It's very broad and treating the general problem, all comments are depressing (NP-hardness; no-free-lunch-theorem and co). Without a-priori knowledge about your optimization-surface there is not much you can do. Some people use global-optimization methods based on bayesian-methods (try to infer the surface by observing and using some smoothness assumptions) but we won't know if that's something for you. E.g. [rbfopt](https://github.com/coin-or/rbfopt). Your best bet is probably looking for keywords Global-/ derivative-free / black-box optimization. But it's hard to tackle!
comment on: http://stackoverflow.com/q/48240927
score: 0

http://stackoverflow.com/q/48192924
type: Question
type: UnansweredQuestion
tagged with: citations
tagged with: python
score: 4
has body: I'm using the habanero library to retrieve citation information given a DOI. I've hit a road block when trying to retrieve information about the works citing a given DOI. For instance, from habanero import counts c = counts.citation_count(doi = {DOI}) will give me the number of works that cited a DOI. Unfortunately, the DOI's I'm interested in are associated with data sets, so these counts are almost always going to be 1. What I really need is to count the citations of the work that references the DOI. For example, something like this: from habanero import CrossRef cr = CrossRef() work = cr.works(ids = {DOI}) work['message']['references_count'] # what I'm really looking for is something like the following line work['message']['references_dois'] I've been digging through the CrossRef documentation and I haven't been able to find anything that can help me achieve this. Has anyone solved a similar problem?
tagged with: habanero
upvote count: 4
has title: CrossRef API Tracing DOI Citations
answer count: 2
tagged with: doi
has answer: http://stackoverflow.com/a/51661388
downvote count: 0
has answer: http://stackoverflow.com/a/52592541
favorite count: 0

http://stackoverflow.com/comment/83656419
comment on: http://stackoverflow.com/a/48331625
score: 0
type: Comment
has text: cool and legible. can you now parallel `doit (a)` and `doit (b)`? and so that it would break the calculation if one of them returns non-empty value. because in this way I will not gain time. I would be grateful.
type: AnswerComment

http://stackoverflow.com/q/48305006
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48305407
has comment: http://stackoverflow.com/comment/83595228
upvote count: 2
has comment: http://stackoverflow.com/comment/83595146
downvote count: 0
has title: Conditional expressions in Python's documentation
tagged with: python
accepted answer: http://stackoverflow.com/a/48305407
type: AnsweredQuestion
score: 2
answer count: 1
has body: If I understand correctly, in Python3, a conditional expression is something of the form "x if C else y". For instance, if I understand correctly, the following block is a conditional expression which return the string 'a' 'a' if 0&lt;1 else 'b' while the following block is a conditional expression that returns 'b' 'a' if 0&gt;1 else 'b' In the Python language reference the grammar rule for conditional expressions is given by those lines: conditional_expression ::= or_test ["if" or_test "else" expression] I don't understand this rule because for instance it would say with my above example that 'a' and 0&gt;1 were derived from or_test and that 'b' was derived from expression, whereas for me 'a' and 'b' should both be derived by the same rule (expr here). The only thing that make sense to me would be replace the first grammar rule by conditional_expression ::= expression \["if" or_test "else" expression\] What am I missing here?
has comment: http://stackoverflow.com/comment/83595570

http://stackoverflow.com/a/48296319
has comment: http://stackoverflow.com/comment/83578699
has comment: http://stackoverflow.com/comment/83577908
accepted answer of: http://stackoverflow.com/q/48296262
has body: You need to return an HttpResponse on every condition.In last if else statement you can see you are not returning anything from the view so you have to return an appropriate http response for every case in your view. See updated code below. @csrf_exempt def get_recieve_update(request): if request.method=="POST": man= json.loads(request.body) txId = man['hash'] uri = bgo_main_base_url + '/wallet/{}/tx/{}'.format(WALLETID, txId) rexa = requests.get(uri, headers=headers) vd = rexa.json() isMine = vd['outputs'][0]['isMine'] confirmations = vd['confirmations'] if isMine == True and confirmations &gt; 1: address = vd['outputs'][0]['account'] value = vd['outputs'][0]['value'] try: get_adr = CPro.objects.get(address = address) except CPro.DoesNotExist: get_adr = None if not get_adr.is_used==True and get_adr.is_active==False: update_cw = CW.objects.filter(user = get_adr.user).update(current_btc_balance=F('current_btc_balance') + value , modified_date=datetime.datetime.now()) return HttpResponse('done') elif get_adr.is_used==True and get_adr.is_active==False: address = vd['outputs'][0]['account'] value = vd['outputs'][0]['value'] send_mail('Recieved on Used Address','failed to credit for {} with {} and id {}'.format(address, value, txId), DEFAULT_FROM_EMAIL,[DE_MAIL,]) return HttpResponse("Some appropriate response") else: # return something. If both condition from does not get true then there will be no return from view else: address = vd['outputs'][0]['account'] value = vd['outputs'][0]['value'] send_mail('Recieved Callback Error','failed to credit for {} with {}'.format(address, value), DEFAULT_FROM_EMAIL,[DE_MAIL,]) return HttpResponse("Some appropriate response") # &lt;-- here you were not returning a response Another Helpful answer
type: Answer
has comment: http://stackoverflow.com/comment/83578540
has comment: http://stackoverflow.com/comment/83577756
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83578670
answers question: http://stackoverflow.com/q/48296262

http://stackoverflow.com/a/48281912
type: Answer
answers question: http://stackoverflow.com/q/48281593
has body: You can simply use a groupby: df1.groupby('code').max().reset_index(drop=True,inplace=True) Be careful, if there are many values for an item with the same code, here you will keep the biggest one. The reset_index is only used to get Output DataFrame in the same format.
score: 0

http://stackoverflow.com/comment/83587300
type: AnswerComment
has text: I guess, i do it wrong (( Is there tutorial of some kind? Thx
type: Comment
comment on: http://stackoverflow.com/a/48300707
score: 0

http://stackoverflow.com/comment/83454436
comment on: http://stackoverflow.com/q/48235825
has text: @magreenberg Can AJAX requests be sent with the requests library, or do i need to use something like selenium with the chrome webdriver or the firefox geckodriver?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83626430
type: Comment
has text: Check this https://stackoverflow.com/questions/16870663 or this https://stackoverflow.com/questions/25341945
comment on: http://stackoverflow.com/q/48320590
score: 1
type: QuestionComment

http://stackoverflow.com/comment/83571316
type: AnswerComment
comment on: http://stackoverflow.com/a/48293128
has text: What about the 'and' in the OP's output? Your going to have to end up doing something similar to what @Julian did in her answer.
type: Comment
score: 0

http://stackoverflow.com/q/48181698
accepted answer: http://stackoverflow.com/a/48185587
has comment: http://stackoverflow.com/comment/83350951
answer count: 1
has answer: http://stackoverflow.com/a/48185587
has comment: http://stackoverflow.com/comment/83362882
downvote count: 1
has title: twinx and sns.barplot seaborn are overlapping bars
type: AnsweredQuestion
has body: I would like to use sns.seaborn to display the np.sum and the np.mean on 2 different axes (with ax2 = ax1.twinx() I assume). The probem I have is that the graphs are overlapped and not readable. Am I approaching the problem correctly? What can I do to get those bars next to each other? import seaborn as sns tips = sns.load_dataset("tips") f, ax1 = plt.subplots() ax2 = ax1.twinx() sns.barplot(x="day", y="total_bill", data=tips, estimator=np.mean, ax=ax1) sns.barplot(x="day", y="total_bill", data=tips, estimator=np.sum, ax=ax2, ci=None) Thanks for your help Larry
tagged with: matplotlib
tagged with: python
score: -1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/20109391
upvote count: 0
tagged with: seaborn

http://stackoverflow.com/q/48308109
upvote count: 1
has answer: http://stackoverflow.com/a/48308147
favorite count: 0
has title: break down a long string to integers
score: 1
has comment: http://stackoverflow.com/comment/83601595
tagged with: python
has body: thank you for going over my question. I am green on Python so I would like to ask for your help here. I am using Python 2 on Win7. I would like to break down a string to integers so that I can compare the int values afterwards. I googled some solutions but does not work, please see my code in below. angle = " 0 1 2 3 4 5 6 7 8 9 10 11" int_lst = [int(x) for x in angle] print int_lst I got an error that "Traceback (most recent call last): ***File "C:/Users/Desktop/pythonwifi/LDS Patern - Copy.py", line 2, in &lt;module&gt; int_lst = [int(x) for x in angle] ValueError: invalid literal for int() with base 10: ''"*** Any advice please? Thank you very much.
type: Question
tagged with: python-2.7
type: UnansweredQuestion
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48289552
type: Question
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/83564114
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83564275
has body: I made function for registration of clients, firstly they have to register then they are written in txt file. Now, they have to log in, and when they are logged in, is it possible for my program to know which client is logged in? I need to know his username,name and lastname which is in my file by index[0],[2],[3], they are written in like this (john10|john123456|John|Frusciante|buyer). Here is my log in function: client_list = [] def clients(): with open("svi.txt","r") as f: all_h = ["username","password","name","lastname","role"] for r in f.readlines(): dicct = {} bla = r.strip().split("|") count = 0 for i in bla: dicct[all_h[count]] = i count += 1 client_list.append(dicct) clients() def log(username,password): for r in client_list: while r["username"] == username and r["password"] == password: if r["role"] == "buyer": return buyer_menu() elif r["role"] == "manager": return manager_menu() elif r["role"] == "seller": return seller_menu() return False def login(): x = False while x == False: username = input("Input username: ") password = input("Input password: ") x = log(username,password) if x == False: print() print("Wrong username or password, try again: ") print() print() login() So, do I have to modify something here or? Btw, my register function required 4 inputs (username,password,name and lastname), the role part I added automatically.
tagged with: python
has comment: http://stackoverflow.com/comment/83564391
score: 0
has title: recognizing of logged in client - python
has comment: http://stackoverflow.com/comment/83564963

http://stackoverflow.com/a/48252615
has body: In order to achieve that, you need to replace raw_input with a function that returns different things when called multiple times, e.g. one like this: answers = [1, 2, 4] fake_input = answers.pop # 4 print(fake_input()) # 2 print(fake_input()) # 1 print(fake_input()) # raise IndexError print(fake_input()) You install this similar to the existing function: # replace raw_input original_raw_input = __builtins__.raw_input __builtins__.raw_input = ['input', 'fake', 'my'].pop # ... code that uses raw_input print raw_input() print raw_input() print raw_input() # restore raw_input __builtins__.raw_input = original_raw_input Some notes: I don't know why the original author used __builtins__.raw_input instead of just assigning to raw_input (which requires declaring it as global raw_input when in a function, of course). I haven't tried if it makes any difference. In your test, if the output is not as expected, the original raw_input is not restored! While this may be acceptable in a test, it is still a bug. The easy way out is to use try ... finally, restoring raw_input in the finally code. There's a better way though: Use a so-called context manager. captured_out is one example, it redirects the output for some code and guarantees that the original output target is restored. Take this as exercise, it's very useful to understand this technique. The order is reversed, since pop removes elements from the back. You could first feed the sequence to reversed, but that would make the code even less readable and understandable. Wrapping it into a context manager would hide these details. Don't forget to upgrade to Python 3!
accepted answer of: http://stackoverflow.com/q/48252473
has comment: http://stackoverflow.com/comment/83531957
type: Answer
has comment: http://stackoverflow.com/comment/83489199
answers question: http://stackoverflow.com/q/48252473
has comment: http://stackoverflow.com/comment/83499709
has comment: http://stackoverflow.com/comment/83488488
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83488682
has comment: http://stackoverflow.com/comment/83502333
upvote count: 1

http://stackoverflow.com/comment/83531957
has text: Almost! :) your `lambda` creates a function which just calls another function with the exact same arguments (no arguments, to be precise). Just use that function directly. I have added an according example to the answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48252615
type: Comment

http://stackoverflow.com/a/48206198
has comment: http://stackoverflow.com/comment/83394021
type: Answer
has comment: http://stackoverflow.com/comment/128716996
upvote count: 11
has comment: http://stackoverflow.com/comment/83393922
has comment: http://stackoverflow.com/comment/83394352
downvote count: 0
score: 11
answers question: http://stackoverflow.com/q/48205956
has body: You simply do the following: func1_time = %timeit -o func1(10) You can access the timing for each iteration by func1_time.timings and total time taken for each loop by func1_time.all_runs Note that your loops are unneccessary, since %timeit executes your code N times in a loop and iterates this loop r times. Update If you need the timings for different argumets x, you may try the following: func1_time = [] for i in [10, 100, 1000]: foo = %timeit -o func1(x) func1_time.append(foo) Then func1_time[0].timings holds the timings for func1(10). If you do so, I recommend specifying the r and N options, since %timeit adapts the number of loops to the complexity of the problem. The means, the longer it takes to execute a function on time, the fewer loops are run.

http://stackoverflow.com/comment/83516722
score: 0
comment on: http://stackoverflow.com/q/48266247
has text: I think it complains about division by x inside `Poly` function. I just don't know how to construct a rational function without `Poly`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83487245
has text: Frankly, I used `GlobalMaxPooling2D` instead of Flatten before but don't I lose lots of information then?
score: 0
comment on: http://stackoverflow.com/a/48249714
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83461045
score: 0
type: Comment
type: QuestionComment
has text: `/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pyrouge/data does not exist.`. Are you sure that you installed `pyrouge` into right python interpreter?
comment on: http://stackoverflow.com/q/48239371

web-crawler
tags question: http://stackoverflow.com/q/48216663
tags question: http://stackoverflow.com/q/48326983
tags question: http://stackoverflow.com/q/48329749
tag name: web-crawler
tags question: http://stackoverflow.com/q/48317302
tags question: http://stackoverflow.com/q/48264917
type: Tag
tags question: http://stackoverflow.com/q/48232176

http://stackoverflow.com/comment/85977659
score: 0
has text: Possible duplicate of [Key <variable\_name> not found in checkpoint Tensorflow](https://stackoverflow.com/questions/45179556/key-variable-name-not-found-in-checkpoint-tensorflow)
comment on: http://stackoverflow.com/q/48233684
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83529252
comment on: http://stackoverflow.com/q/48272061
type: QuestionComment
score: 0
has text: Perhaps Anaconda is doing something funky with paths still. The error you're getting is usually an exe loading problem involving 64-vs-32bit. Have you tried installing cxOracle via `conda` instead of `pip` (make sure to pip uninstall first)?
type: Comment

http://stackoverflow.com/comment/83582528
has text: you need to read [their docs](https://virtualenvwrapper.readthedocs.io/en/latest/) to understand that
comment on: http://stackoverflow.com/q/48298170
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48243303
has comment: http://stackoverflow.com/comment/83469169
has comment: http://stackoverflow.com/comment/83469568
has comment: http://stackoverflow.com/comment/83469254
has comment: http://stackoverflow.com/comment/83469272
has body: I'm trying to get a random distribution of N integers with total sum equal to K. numbers = np.array(range(N)) for n in range(N): prob[n] = rd.randrange(10000) sum = numpy.sum(prob) prob = (prob / sum * K).astype(int) The problem is that the result is not exactly equal to N because of float number approximation. For example N = 100 will yield a a total of about 95. What is a pythonic solution to this problem?
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83469605
has comment: http://stackoverflow.com/comment/83469591
duplicate of: http://stackoverflow.com/q/3589214
tagged with: random
linked to: http://stackoverflow.com/q/36824129
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83469097
has comment: http://stackoverflow.com/comment/83469148
has comment: http://stackoverflow.com/comment/83469521
downvote count: 0
answer count: 0
tagged with: floating-accuracy
has comment: http://stackoverflow.com/comment/83469529
favorite count: 0
has comment: http://stackoverflow.com/comment/83472548
has comment: http://stackoverflow.com/comment/83469355
type: Question
has comment: http://stackoverflow.com/comment/83469689
has title: Random distribution of integers with fixed total

http://stackoverflow.com/a/48312137
answers question: http://stackoverflow.com/q/48311807
has comment: http://stackoverflow.com/comment/83610618
has comment: http://stackoverflow.com/comment/83611128
score: 0
accepted answer of: http://stackoverflow.com/q/48311807
has comment: http://stackoverflow.com/comment/83644299
has body: Why not learn the numerical representations for each base? This is a common problem in Neural Machine Translation, where we seek to encode "words" with a meaning as (naively) numbers. The core idea is that different words should not be represented with simple numbers, but with a learned dense vector. The process of finding this vector representation is called embedding. In this, bases that are more closely related to one other might have vector representations closer to one another in n-dimensional space (where n is the size of the vector). This is a simple concept that can be difficult to visualize the first time. Your choice of embedding size (a hyperparameter) should likely be small, since you are only embedding one of four parameters (try a size of 2-5). As an example of some embedding mappings with size 4 (numerical values are not relevant to this example): G -&gt; [1.0, 0.2, 0.1, 0.2] A -&gt; [0.2, 0.5, 0.7, 0.1] T -&gt; [0.1, 0.2, 1.0, 0.5] C -&gt; [0.4, 0.4, 0.5, 0.8] The exact technique of generating and optimizing embedding is a topic in itself; hopefully the concept is useful to you. Alternative If you want to avoid embeddings (since your "vocabulary" is limited to 4), you can assign scalar values to each base. If you do this, you should normalize your mappings between -1 and 1.
has comment: http://stackoverflow.com/comment/83610307
has comment: http://stackoverflow.com/comment/83610503
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/48182268
linked to: http://stackoverflow.com/q/16749121
tagged with: python
has comment: http://stackoverflow.com/comment/83344157
score: 2
type: AnsweredQuestion
has body: I have the following Pascal routine: function TForm1.ldExtractFromLine (ldline: String; Post: Integer): String; var s: String; t: array[1..15] of String; i, iT: Integer; begin s := Trim(ldline); iT := 1; while s &lt;&gt; '' do begin s := Trim(s) + ' '; i := 1; while s[i] &lt;&gt; ' ' do Inc(i); t[iT] := Copy(s, 1, i-1); Inc(iT); s := Copy(s, i, Length(s)); end; ldExtractFromLine := ''; if Post &lt; iT then ldExtractFromLine := t[Post]; end; I am trying to convert to Python. Here is what I have so far: def ldExtractFromLine (ldline, post): post -= 1 # mjh t = [] s = ldline.strip() iT = 0; # mjh while s &lt;&gt; '': s = s.strip() + ' ' i = 0 # mjh while s[i] &lt;&gt; ' ': i += 1 # t[iT] = Copy(s, 1, i-1) # function Copy(const S: string; From: integer = 1; Count: integer = MaxInt): string; t.insert(iT, s[0:i-1+1]) # mjh iT += 1 s = s[i:(i+len(s)+1)] print "lala" result = '' if post &lt; iT: result = t[post] # mjh return result However, executing the routine results in endless "lala" printed to stdout. The problem is that Pascal lists start with index 1 and Python lists start with index 0. This is really confusing me. Can anyone find my error? The variable post is an integer generally less than 20. The variable ldline is a string that looks somewhat like "1 0 60 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat". [edit] The entire script can be viewed here: https://github.com/Jeremy1980/LDBoxer Here is some example input data: 0 Safe House 0 Name: building_013_safehouse.ldr 0 Author: Kevin Loch 0 ROTATION CENTER 0 0 0 1 "Custom" 0 ROTATION CONFIG 0 0 1 0 60 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat 1 0 60 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat 1 0 -20 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat 1 0 -20 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat 1 0 -100 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat 1 0 -100 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat 1 0 -180 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat 1 0 -180 -24 -160 1 0 0 0 1 0 0 0 1 3001.dat More examples of input data can be found here: https://github.com/Jeremy1980/LDBoxer/is…
upvote count: 2
answer count: 1
downvote count: 0
has title: Convert pascal to python
accepted answer: http://stackoverflow.com/a/48182400
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48182400
has comment: http://stackoverflow.com/comment/83344190
has comment: http://stackoverflow.com/comment/83344093

http://stackoverflow.com/q/48198173
has comment: http://stackoverflow.com/comment/83377761
has comment: http://stackoverflow.com/comment/83377510
accepted answer: http://stackoverflow.com/a/48198422
answer count: 1
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48198422
downvote count: 1
favorite count: 0
type: AnsweredQuestion
score: 0
has title: str to int issue 'int' object not callable when var set for multiplication
has body: Some of the code can be ignored, I am trying to turn a str into int, while doing so I seem to be getting this error. 'int' object is not callable llb and lw are not mentioned anywhere else in the code only in this section. and it's the first and only time they are set. I have been fiddling with this for hrs now and can't seem to figure it out. Nothing else with this error seems to match the same scenario with my error. llb is normally set to something simple like 2 from a post @app.route('/printlab', methods=['POST']) def printlab(): if request.method == 'POST': lfname = request.form['first_name'] llname = request.form['last_name'] lstate = request.form['state'] lcity = request.form['city'] laddress = request.form['shipping_address'] lzip = request.form['zip'] llb = request.form['lbs'] loz = request.form['ozs'] lw = (int(llb)*16) return lw edit: added error below Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1615, in full_dispatch_request return self.finalize_request(rv) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1630, in finalize_request response = self.make_response(rv) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1740, in make_response rv = self.response_class.force_type(rv, request.environ) File "/usr/local/lib/python2.7/site-packages/werkzeug/wrappers.py", line 921, in force_type response = BaseResponse(*_run_wsgi_app(response, environ)) File "/usr/local/lib/python2.7/site-packages…
has comment: http://stackoverflow.com/comment/83377565
type: Question

http://stackoverflow.com/comment/134833203
comment on: http://stackoverflow.com/a/48216491
type: Comment
has text: @Ed_: that's not what the question is asking about, however. The answer addresses the stated question, not *when should I use `assertTrue`* without further context.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83561527
has text: @OdatNurd I can't add a clear in the loop as I would need to maintain the list of multiple selections, not just the last one. That is why I thought subtract would be a good idea. Subtract might not have been doing what I thought it was. I had assumed that the initial cursor was removed but it looked like it was there in addition to other `sel()`s. I still ended up doing a clear after I collected all the regions I wanted in the same way it would have been done for the paste. Likely I could combine the two as one loop but I dont do this enough to know for sure.
type: Comment
comment on: http://stackoverflow.com/q/48285766
type: QuestionComment
score: 0

http://stackoverflow.com/a/48193430
has comment: http://stackoverflow.com/comment/83367456
has body: The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming.--Donald Knuth I started learning to program in...1982 or 83 on a time sharing mini computer. Stuff ran SLOWLY. Memory was tight. As a consequence I worry way too much about how much memory/ops/etc. my code uses. Letting go of this is hard. You say: My concern with the simpler code was that I was opening and closing the csv file 25K times and it was slowing down my run time. Of course it was. But noticeably? How time sensitive is the application? If it takes an extra 60 seconds to run, what is the impact? On the other hand: My current concern is the problem with memory corruption on an exception with leaving f open. What do you mean by this? If you hit an exception and the program shuts down Python will clean up after itself. It might not scrub every bit of memory on the way out if you're worried about someone doing something nefarious, but the whole point of exception handling is to handle exceptions in a safe and consistent way. I could be very wrong about this, but the way I read this code: elif link == url[1]: # Opening the file in append mode and keeping it open for the majority of the loop # and writing with no headers f = open(file_Name, mode = 'a') stats_df.to_csv(f, header=False) record_Counter = record_Counter + 1 print ('Two entries for one game recorded. Counter = ' + str(record_Counter)) You're attempting to open file_name every time through the loop and call the file handle f. I don't know what happens inside the VM with this, but either (a) you're closing and reopening the file every time, or (ii) you're finding the file already open and just reusing f. I don't know how much more efficient this is than just opening the file in append and blasting data to it. IMO I don't think the difference in speed is worth it at that scale. On the…
type: Answer
answers question: http://stackoverflow.com/q/48193090
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/48214346
has answer: http://stackoverflow.com/a/51624786
tagged with: keras-layer
answer count: 3
has body: I am new to python and am working on an image processing project and built the below model. I get the error posted below the model. In my research, I found some answers regarding this error: Merge 2 sequential models in Keras the issue above is of Concatenate 2 models not Concatenate 2 layers https://keras.io/getting-started/functional-api-guide/#multi-input-and-multi-output-models In the keras example, Concatenate 2 layers but 1 layer is an input layer. I would like to understand how to Concatenate 2 regular layers and use the concatenated layer as a layer in a sequence of layers. similar concept to the Inception Model. input / | \ a1 b1 c1 | | | a2 b2 c2 \ | / concatenate / | \ d1 e1 f1 | | | d2 e2 f2 \ | / output above is my attempt to draw what my final goal :) def fet_Model(): bnd_input = Input(shape=input_shape) k31 = Conv2D(128, kernel_size=(3, 3), activation='relu', padding='same')(bnd_input) k31 = Conv2D(128, kernel_size=(3, 3), activation='relu', padding='same')(k31) k31 = MaxPooling2D(pool_size=(3, 3), strides=(2, 2))(k31) in_ly1_cv_1n1 = Conv2D(32, kernel_size=(1, 1), activation='relu', padding='same')(k31) in_ly1_cv_3n3 = Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same')(in_ly1_cv_1n1) in_ly1_cv_5n5 = Conv2D(64, kernel_size=(5, 5), activation='relu', padding='same')(in_ly1_cv_1n1) in_ly1_mx_pl = MaxPooling2D(pool_size=(3, 3), strides=(1, 1), padding='same')(k31) in_ly1_mxcv_1n1 = Conv2D(32, kernel_size=(1, 1), activation='relu', padding='same')(in_ly1_mx_pl) filt_concat1 = Concatenate([in_ly1_mxcv_1n1, in_ly1_cv_5n5, in_ly1_cv_3n3, k31]) # when running the below line I receive the error in_ly2_cv_1n1 = Conv2D(32, kernel_size=(1, 1), activation='relu', padding='same')(filt_concat1) in_ly2_cv_3n3 = Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same')(in_ly2_cv_1n1) in_ly2_cv_5n5 = Conv2D(64, kernel_size=(5, 5), activation='relu', padding='same')(in_ly2_cv_1n1) in_ly2_mx_pl = MaxPooling2D(pool_size=(3, 3), strides=(1, 1))(filt_…
downvote count: 0
has answer: http://stackoverflow.com/a/49477549
favorite count: 0
type: Question
has title: ValueError: input that isn't a symbolic tensor
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51821269
tagged with: python
upvote count: 4
score: 4
linked to: http://stackoverflow.com/q/45979848

http://stackoverflow.com/a/48180596
accepted answer of: http://stackoverflow.com/q/48180041
type: Answer
score: 3
answers question: http://stackoverflow.com/q/48180041
upvote count: 3
has comment: http://stackoverflow.com/comment/83341160
type: AcceptedAnswer
has body: It doesn't look like polyfit supports fitting multivariate polynomials, but you can do it by hand, with linalg.lstsq. The steps are as follows: Gather the degrees of monomials x**i * y**j you wish to use in the model. Think carefully about it: your current model already has 9 parameters, if you are going to push to 5 variables then with the current approach you'll end up with 3**5 = 243 parameters, a sure road to overfitting. Maybe limit to the monomials of __total_ degree at most 2 or three... Plug the x-points into each monomial; this gives a 1D array. Stack all such arrays as columns of a matrix. Solve a linear system with aforementioned matrix and with the right-hand side being the target values (I call them z because y is confusing when you also use x, y for two variables). Here it is: import numpy as np x = np.random.random((100, 2)) z = np.sin(5 * x[:,0]) + .4 * np.sin(x[:,1]) degrees = [(i, j) for i in range(3) for j in range(3)] # list of monomials x**i * y**j to use matrix = np.stack([np.prod(x**d, axis=1) for d in degrees], axis=-1) # stack monomials like columns coeff = np.linalg.lstsq(matrix, z)[0] # lstsq returns some additional info we ignore print("Coefficients", coeff) # in the same order as the monomials listed in "degrees" fit = np.dot(matrix, coeff) print("Fitted values", fit) print("Original values", y)
downvote count: 0
has comment: http://stackoverflow.com/comment/83341124
has comment: http://stackoverflow.com/comment/83342761
has comment: http://stackoverflow.com/comment/83341214
has comment: http://stackoverflow.com/comment/83341334

http://stackoverflow.com/q/48306968
upvote count: 2
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48328197
has title: Why two get requests are not updating fields in thingspeak?
has answer: http://stackoverflow.com/a/48328197
favorite count: 0
type: Question
tagged with: get-request
tagged with: python
has body: A single run cannot update two or more get request to my thingspeak fields. My code has a part which requires two fields to get updated in one python program. Like.., urlopen("https://api.thingspeak.com/update?api_key=D------MQV&amp;field1=5") urlopen("https://api.thingspeak.com/update?api_key=D------MQV&amp;field2=10") Only field1 gets updated with the above example. Thanks!
tagged with: iot
has comment: http://stackoverflow.com/comment/83599246
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83770827

http://stackoverflow.com/comment/83514241
score: 0
has text: Would you mind demonstrating the solution you propose with the code example I give? Is ti doable using just the `linprog` function I give?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48264544

http://stackoverflow.com/a/48359502
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48292298
type: Answer
accepted answer of: http://stackoverflow.com/q/48292298
downvote count: 0
score: 1
upvote count: 1
has body: Define the names inside here, not the screen classes: sm = ScreenManager() sm.add_widget(firstScreen()) sm.add_widget(secondScreen()) above should be: sm = ScreenManager() sm.add_widget(firstScreen(name="first")) sm.add_widget(secondScreen(name="second"))

http://stackoverflow.com/comment/83538367
comment on: http://stackoverflow.com/q/48276429
type: Comment
score: 1
type: QuestionComment
has text: what's the problem? maybe, are you trying to normalize each block *in-place* and realized that this won't work with overlapping blocks ? just store the result in a *different* vector per block ... otherwise, can you better explain what you didn't understand ?

http://stackoverflow.com/a/48209935
answers question: http://stackoverflow.com/q/48209706
score: 0
type: Answer
has body: You can also use \w+: import re s = "PROGRAM S51_Mix_Station" new_data = re.findall('^PROGRAM\s\w+\_\w+_\w+', s) final_data = new_data[0] if new_data else new_data Output: 'PROGRAM S51_Mix_Station'

http://stackoverflow.com/a/48250808
type: Answer
has comment: http://stackoverflow.com/comment/140173736
accepted answer of: http://stackoverflow.com/q/48248567
type: AcceptedAnswer
downvote count: 0
score: 17
has body: You could use loop.add_reader to wait for the read availability of your socket: async def watch(fd): future = asyncio.Future() loop.add_reader(fd, future.set_result, None) future.add_done_callback(lambda f: loop.remove_reader(fd)) await future async def run(self): while True: await watch(self._q._connection) msg = self._q.receive() print(msg) However, it'll be very tricky to avoid all the blocking IO calls of the library you mentioned without rewriting it completely. Instead, I'd recommend to use the loop.run_in_executor method to schedule the blocking IO calls in a thread pool: async def run(self): loop = asyncio.get_event_loop() while True: msg = await loop.run_in_executor(None, self._q.receive) print(msg)
upvote count: 17
answers question: http://stackoverflow.com/q/48248567

http://stackoverflow.com/comment/83488006
score: 0
comment on: http://stackoverflow.com/q/48252649
type: Comment
type: QuestionComment
has text: Welcome to SO. Unfortunately you picked a question thats kinda offtopic , namely asking for a offsite lib/tut/... - Please go over [how to ask](https://stackoverflow.com/help/how-to-ask) and [on-topic](https://stackoverflow.com/help/on-topic) again and if you have questions provide your code as [mvce](https://stackoverflow.com/help/mcve). If you encounter errors, copy and paste the error message verbatim ( word for word) into your question. Avoid using screenshots unless you need to convey layout errors.

http://stackoverflow.com/comment/83600485
type: Comment
comment on: http://stackoverflow.com/q/48307584
type: QuestionComment
has text: `str(year)[:2]` is not a number. It's a *string*.
score: 4

http://stackoverflow.com/comment/83374581
has text: I'm launching `launcher.py` from a different directory and it looks fine, or did I get you wrong?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48196631

http://stackoverflow.com/q/48235169
tagged with: numpy
type: AnsweredQuestion
downvote count: 0
tagged with: keras
answer count: 1
score: 24
upvote count: 24
accepted answer: http://stackoverflow.com/a/48364708
favorite count: 0
has title: How to fix AttributeError: module 'numpy' has no attribute 'square'
tagged with: python-3.x
has body: I have updated numpy to 1.14.0. I use Windows 10. I tried to run my code and I got this error: AttributeError: module 'numpy' has no attribute 'square' Here are my imports: %matplotlib inline import matplotlib.pyplot as plt import tensorflow as tf import numpy as np from sklearn.metrics import confusion_matrix import math
has answer: http://stackoverflow.com/a/48364708
has comment: http://stackoverflow.com/comment/83452935
tagged with: attributeerror
type: Question
has comment: http://stackoverflow.com/comment/106424425
has comment: http://stackoverflow.com/comment/83452915
tagged with: python
has comment: http://stackoverflow.com/comment/83453325

http://stackoverflow.com/comment/83477518
has text: Are you calculating the date from today (2018) or necessarily from the max value in the data?
comment on: http://stackoverflow.com/q/48247401
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83408553
type: Comment
type: QuestionComment
has text: Hey, @JonathonMcMurray, thanks (!); how can I post the Data.xlsx? Tried looking up how to insert it into this post, but haven't found anything... The data is currently in xlsx format and that's what I've loaded into python. Is there a way to attach the file to posts, or to get the data formatted into code that can be pasted in the post?
comment on: http://stackoverflow.com/q/48211975
score: 0

http://stackoverflow.com/comment/83640514
type: Comment
score: 0
has text: @Niema Moshiri That is why he/she is using a `defaultdict` from `collections` rather than the built-in `dict` `type`.
type: QuestionComment
comment on: http://stackoverflow.com/q/48327371

http://stackoverflow.com/q/48272618
tagged with: cocos2d-iphone
answer count: 0
score: 2
upvote count: 2
has body: Python version: V3.6.1 cocos2d version: v0.6.5 (python.cocos2d.org) I tried to draw a circle using cocos2d, but failed. cocos2d turtorial don't mentioned about this function, and cannot find any instructions from the web, thanks for your help. code: import cocos class Ant(cocos.layer.Layer): def __init__(self): super(Ant, self).__init__() centerPoint=cocos.draw.Vector2(200,200) circle=cocos.draw.Circle(centerPoint, 30.0) self.add(circle) cocos.director.director.init(width=640, height=480) scene=cocos.scene.Scene(Ant()) cocos.director.director.run(scene) warning: 'Circle' object has no attribute 'on_enter' File: C:\Users\gshao\AppData\Local\Programs\Python\Python36\lib\site-packages\cocos\cocosnode.py, Line: 611
downvote count: 0
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has title: how to use cocos2d-python draw a circle

http://stackoverflow.com/comment/83723151
type: Comment
has text: @DanielNetzer what symbols are expected to be in words except '@'?
comment on: http://stackoverflow.com/a/48323646
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83356739
has text: Before doing anything else, try if a different backend even changes anything. To this end try `%matplotlib tk` instead of `%matplotlib` without any extention.
type: Comment
comment on: http://stackoverflow.com/q/48187228
type: QuestionComment
score: 0

http://stackoverflow.com/a/48389054
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48228110
score: 1
type: AcceptedAnswer
upvote count: 1
has body: After a good week of suffering I can shine some light on the subject Yes it is possible, but with caveats. If you want to do it then I recommend you go down the route of using the most recent version of everything, i.e. Python3 latest and PyQT5 latest, ideally > 5.6 so you get webengine rather than webkit. If you have a dated setup then expect some of the javascript stuff not to work. For example, my setup: pyqt 4.11.4 py27_1 python 2.7.11 0 qt 4.8.7 1 no good! can't even plot a simple polyline conda can be your friend in this respect as you can quickly set up sandboxed python environments with different package versions. I tried this setup and I was able to plot a simple polyline: pyqt 5.6.0 py27h4b1e83c_5 anaconda python 2.7.13 0 anaconda qt 5.6.2 5 anaconda note the switch from PyQT4 to PyQT5 but still with Python2.7. I couldn't face porting all my code from 2 to 3, but I may be able to stretch to a QT4 to QT5 port. Note I did also try the Python3.5 and PyQT4 combo: ('Qt version:', '4.8.7') ('SIP version:', '4.16.9') ('PyQt version:', '4.11.4') And this also worked. Finally, the one you should probably aim for, Python3 with PyQT5: Qt version: 5.5.1 SIP version: 4.17 PyQt version: 5.5.1 This also worked. I wouldn't recommend using PyQT4 if you are interested in doing anything javascript related with a QWebView widget. Once you have a Python and QT environment hooked up to a recent webkit, or even better, webengine build then I would concur that it is relatively easy to get python and javascript working together with a QWebView widget. For my use case of displaying and manipulating googlemaps it is a very powerful approach. The reason I say webengine is better than webkit is because QT have ditched webkit in favour of webengine as the browser engine in their most recent version releases, so using webengine will be more future-proof
accepted answer of: http://stackoverflow.com/q/48228110

http://stackoverflow.com/a/48256068
score: 1
has comment: http://stackoverflow.com/comment/83494947
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: It's not a fractional number; when using Python 2.x, the expression (x + y * self.width) / 8 will be evaluated as an integer division, resulting in an integer index - as long as x, y and self.width are also integers. Just as an example: 23 / 8 # 2.875, but the decimals get truncated =&gt; 2 By the way, to get the same result in Python 3.x, you'd have to use the // operator.
answers question: http://stackoverflow.com/q/48256058
type: Answer
accepted answer of: http://stackoverflow.com/q/48256058

http://stackoverflow.com/comment/83525013
has text: Python 2's `str` type isn't unicode, it's bytes.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48267821

http://stackoverflow.com/comment/83329488
score: 0
type: Comment
type: AnswerComment
has text: (That's not a particularly compelling example, I admit.)
comment on: http://stackoverflow.com/a/48174818

http://stackoverflow.com/q/48314209
answer count: 2
has answer: http://stackoverflow.com/a/48314465
has title: Count Identical items in csv and append the count as column
has comment: http://stackoverflow.com/comment/83614332
has comment: http://stackoverflow.com/comment/83614304
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48314448
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83614288
tagged with: python
has body: i have inputs.csv like below apple 400 banana 401 mango 430 orange 440 banana 401 orange 440 mango 430 apple 400 orange 440 banana 401 i want my output like output.csv apple 400 2 banana 401 3 mango 430 2 orange 440 3 i.e we should count the number of items of that particular type and insert the count as the 3rd column i have tried with the below code with open('new.csv','r') as csvinput: with open('update.csv', 'w') as csvoutput: writer = csv.writer(csvoutput) reader = csv.reader(csvinput) all = [] row = next(reader) row.append("No.of.Rows") all.append(row) cn = Counter(map(itemgetter(0), reader)) for k, v in cn.items(): print("k compared is::",k) with open('new.csv','r') as csvinput: reader = csv.reader(csvinput) for row in reader: print("Executing inner loop") print("row value compared is ::",row[0]) if k == row[0] : print("matched") row.append(v) all.append(row) break writer.writerows(all) with this code it worked but my worry is new.csv file will be opened and read for k number of times , so is there any better solution than this
has comment: http://stackoverflow.com/comment/83614303
linked to: http://stackoverflow.com/q/48312674
tagged with: python-2.7
score: 0

http://stackoverflow.com/a/48234502
has body: So, let's begin from locations. I've faced Eventual Consistency issues from two locations: office and home. From office they where usually bellow 5 seconds and at evening in major cases. From home such replicas distribution may last more than 20 seconds. So I would not say, that there are some really rough defined time for that. I believe that you will be able to see such crazy timings as 90 seconds as well, but for that you need really dirty index table in datastore and a lot of data in it. Even though, I would not say, that you will be able to understand guaranteed replicas distribution time. In normal cases it would be few seconds, as documentation says. Instead you can try to develop your application in the way, that will handle such inconsistency situations or will has minimal fails chance (rare operations). We added caching layer build up on redis, so such inconsistency issues for now has been solved in this way, but this is not the cleanest solution as well.
answers question: http://stackoverflow.com/q/48217687
type: Answer
has comment: http://stackoverflow.com/comment/83518479
has comment: http://stackoverflow.com/comment/83518540
score: 0

rest
tags question: http://stackoverflow.com/q/48317680
tags question: http://stackoverflow.com/q/48286609
tags question: http://stackoverflow.com/q/48278296
tags question: http://stackoverflow.com/q/48224881
type: Tag
tags question: http://stackoverflow.com/q/48248771
tags question: http://stackoverflow.com/q/48307390
tags question: http://stackoverflow.com/q/48181508
tag name: rest
tags question: http://stackoverflow.com/q/48243367
tags question: http://stackoverflow.com/q/48220104
tags question: http://stackoverflow.com/q/48309877
tags question: http://stackoverflow.com/q/48193343
tags question: http://stackoverflow.com/q/48247490
tags question: http://stackoverflow.com/q/48284569
tags question: http://stackoverflow.com/q/48296986

download
tags question: http://stackoverflow.com/q/48248013
tag name: download
tags question: http://stackoverflow.com/q/48222953
type: Tag
tags question: http://stackoverflow.com/q/48257994
tags question: http://stackoverflow.com/q/48218145
tags question: http://stackoverflow.com/q/48239112

http://stackoverflow.com/comment/83335019
type: AnswerComment
comment on: http://stackoverflow.com/a/48177422
has text: @APorter1031 negates the mask (ie: not operator)
score: 1
type: Comment

http://stackoverflow.com/q/48325475
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83636913
has title: retrieve input of collections.Counter output
tagged with: python-collections
has body: Not sure if the title is correct but. Lets say you have a list that would look like the output from a Counter object. [(-3.0, 4), (-2.0, 1), (-1.0, 1), (0.0, 1), (1.0, 1), (2.0, 1), (3.0, 4)] How could I go back and get the original list, as [-3.0, -3.0, -3.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0, 3.0]
has comment: http://stackoverflow.com/comment/83636942
accepted answer: http://stackoverflow.com/a/48325537
tagged with: python
has answer: http://stackoverflow.com/a/48325493
has answer: http://stackoverflow.com/a/48325537
possible better answer: http://stackoverflow.com/a/48325541
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/41772054
has answer: http://stackoverflow.com/a/48325541
answer count: 3
upvote count: 2

http://stackoverflow.com/comment/83363257
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48191205
has text: But there is no such folder path is created on my local system, can you please help me out, i am stucked with it
type: Comment

http://stackoverflow.com/comment/83612257
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48313112
has text: Works perfectly. Thank you.
type: Comment

http://stackoverflow.com/q/48309380
has body: If I have a dictionary where each value is a list, how can I check if there is a specific element in my list? For example: myDict = { 0 : ['a','b','c'], 1 : ['d','e','f']} How can I check if 'a' exists?
has answer: http://stackoverflow.com/a/48309472
upvote count: 1
has title: How to check a dictionary where values are lists for an element of that list?
has answer: http://stackoverflow.com/a/48309453
downvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/48309396
has answer: http://stackoverflow.com/a/48309396
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 3
accepted answer: http://stackoverflow.com/a/48309472

http://stackoverflow.com/comment/87081157
score: 0
comment on: http://stackoverflow.com/q/48218503
has text: FYI: I have switched to asyncio (p3 built-in event loop) which supports similar concepts (futures, coroutines etc.), but is a lot more user friendly.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83446572
score: 0
type: Comment
type: QuestionComment
has text: Hmm. That exact syntax caused attribute errors but I tried "Group.__table__.columns.group_id" and that did not cause attribute errors, but I still ended up with the same "..no mapped classes" error from SQL Alchemy. I wonder if there's something I could look at (beyond the traceback) that might give more clues as to what it's stumbling on..
comment on: http://stackoverflow.com/q/48230018

http://stackoverflow.com/comment/85126233
type: Comment
type: AnswerComment
has text: The difference between R-CNN and Fast R-CNN is where in the network ROIPooling is applied, otherwise they both use ROIPooling. In R-CNN, ROIPooling is applied straight on the input image (i.e. a tensor of [batch, 3, height, width], 3 for number of RGB channels) and in Fast R-CNN it is applied to the features out of a base network (like VGG or Resnet with a tensor shape of [batch, 512, height/32, width/32] for example for Resnet).
score: 0
comment on: http://stackoverflow.com/a/49041481

http://stackoverflow.com/comment/83482101
score: 2
type: AnswerComment
has text: It might be better to use [`set`](https://docs.python.org/3/tutorial/datastructures.html#sets).
comment on: http://stackoverflow.com/a/48249769
type: Comment

http://stackoverflow.com/a/48196050
upvote count: 1
type: Answer
has body: Bonjour, votre code est bon! Going back to english now, some small fixes needed: The f-=1 and d+=1 need to move indentation. The ranges need to change to (d,f,1) and (f,d,-1) Final Code: def bubbleSort_UpDown(alist,ite): up=True d=0 f=len(alist)-1 while d&lt;f : if up==True : for i in range(d,f,1): ite+=1 if alist[i]&gt;alist[i+1]: alist[i+1],alist[i]=alist[i],alist[i+1] f-=1 up=False else: for i in range(f,d,-1): ite+=1 if alist[i]&lt;alist[i-1]: alist[i-1],alist[i]=alist[i],alist[i-1] d+=1 up=True print("debut",d) print("fin",f) return ite L=[10,9,8,7,6,5,4,3,2,1,0] print("UnSorted list:", L) iterr=bubbleSort_UpDown(L,0) print("Sorted list:", L) print(iterr)
answers question: http://stackoverflow.com/q/48195828
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48195828

http://stackoverflow.com/q/48279003
type: Question
accepted answer: http://stackoverflow.com/a/48279068
duplicate of: http://stackoverflow.com/q/17778372
has comment: http://stackoverflow.com/comment/83541444
has answer: http://stackoverflow.com/a/48279068
tagged with: python
score: -1
has title: Python return None instead of value
type: AnsweredQuestion
upvote count: 0
answer count: 1
has body: I am trying to implement a very easy Binary search question here: return the index of an array that is plus/minus one from the given target. However, when I execute this code, my result is always None. Python does not seem to capture my return value. Here's my code: class Solution: def closestNumber(self, A, target): if len(A) == None: return -1 if target - 1 &gt; A[-1] or target + 1 &lt; A[0]: return -1 result = self.BinarySearch(0,len(A), A, target) return result def BinarySearch(self,startIndex, endIndex, A, target): if startIndex &gt; endIndex: return -1 mid = (startIndex + endIndex)//2 print(mid) if target == A[mid]: return mid if target + 1 == A[mid] or target - 1 == A[mid]: return mid if target + 1 &gt; A[mid]: self.BinarySearch(mid, endIndex, A, target) if target - 1 &lt; A[mid]: self.BinarySearch(startIndex, mid, A, target) print(Solution().closestNumber([1,4,6,10,20],21))
has comment: http://stackoverflow.com/comment/83541441
downvote count: 1
favorite count: 0

firefox
type: Tag
tag name: firefox
tags question: http://stackoverflow.com/q/48313388
tags question: http://stackoverflow.com/q/48203171

http://stackoverflow.com/a/48327660
score: 0
has body: Just to put my two cents in - you could use , (?P&lt;CompanyName&gt;\b(?:(?!\d{3,})[A-Z\d ])+\b)\s+ (?P&lt;Reference&gt;\b\d{1,18}\b)\s+ (?P&lt;Type&gt;[A-Z]+) See a demo on regex101.com.
answers question: http://stackoverflow.com/q/48325900
type: Answer

http://stackoverflow.com/q/48238531
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83459453
has answer: http://stackoverflow.com/a/48238573
answer count: 1
has comment: http://stackoverflow.com/comment/83459481
linked to: http://stackoverflow.com/q/15112125
type: Question
accepted answer: http://stackoverflow.com/a/48238573
has body: so I recently started out in python, and I'm looking around the internet for answers. Whenever I copy and paste the following code from a different thread, it always seems to work: import os import time #Must Access this to continue. def main(): while True: UserName = input ("Enter Username: ") PassWord = input ("Enter Password: ") if UserName == 'Bob' and PassWord == 'rainbow123': time.sleep(1) print ("Login successful!") logged() else: print ("Password did not match!") def logged(): time.sleep(1) print ("Welcome to ----") main() It works even when I rename the variables etc etc, however when retyping it myself, I have discovered that no matter what i try it never actually seems to work. This is what I tried: import os import time welcomeMessage = "Welcome to free bitcoin application." print (welcomeMessage) time.sleep(1) # userName = igoo # passWord = b def begin(): userName = input("Please enter your username...") passWord = input("Please enter your passowrd...") if userName == "igoo" or "igor" or "Igoo" or "Igor" and passWord == "b" or "B": print: ("Welcome along.") logged() else: print ("Wrong password") time.sleep(1) def logged(): time.sleep(1) print("Alright you in.") begin() So any Idea what I'm doing wrong? I've tried several things but none of them seem to work. I understand most people will just shrug it off and say that this is the most simple thing ever and that I shouldn't even bother, but I really want to get this right. I want to continue developing this into a website cloner but only after the login bit, however for now I only wish to finish the login bit. Any help is much appreciated.
duplicate of: http://stackoverflow.com/q/15112125
has comment: http://stackoverflow.com/comment/83459420
has title: What is wrong with this code? [NEWBIE]
tagged with: python

http://stackoverflow.com/comment/83353031
type: QuestionComment
comment on: http://stackoverflow.com/q/48175870
score: 0
has text: Thanks. It is more or less similar. The original question has the same issue however, data is of the same date. Do you know what if I wanted to set range over a few hours in the same date?
type: Comment

http://stackoverflow.com/comment/83760978
comment on: http://stackoverflow.com/a/48327367
type: Comment
has text: My bad, it is completely normal that I get some nans here and there, given my data. I could even use this information later on
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83507837
score: 2
has text: The second chunk of code has a print statement which will always be called.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48262517

http://stackoverflow.com/q/48317409
tagged with: sqlalchemy
type: Question
has title: Print column name and their values from SQL Alchemy
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83621029
has body: How could I print column name and their values using SQLAlchemy in python? For ex: I have a USER table, which contains 2 fields ID &amp; NAME. ID NAME 1 John 2 Stella I need something similar to this mysql query: select id as User_ID from USER where id = '1'; Currently, I am using the following query to get just the values: meta = MetaData(engine) users = Table('USER', meta, autoload=True) selectQuery = select([users.c.ID, users.c.NAME]).where(users.c.ID == '1') Executing above query I am getting: ('1', 'John') Instead I need this: ID NAME 1 John
score: 0
linked to: http://stackoverflow.com/q/1958219
tagged with: python
has comment: http://stackoverflow.com/comment/83624232
duplicate of: http://stackoverflow.com/q/1958219

http://stackoverflow.com/q/48187843
upvote count: 2
tagged with: flask-restless
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83621010
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
accepted answer: http://stackoverflow.com/a/48932798
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48932798
has comment: http://stackoverflow.com/comment/83359560
tagged with: python
has body: I have following SQLAlchemy DB models describing parts that go through several production steps: class Part(db.Model): part_number = db.Column(db.Integer, primary_key=True) production_steps = db.relationship("ProductionStep") class ProductionStep(db.Model): id = db.Column(db.Integer, primary_key=True) part_number = db.Column(db.Integer, db.ForeignKey('part.part_number')) name = db.Column(db.String) status = db.Column(db.String) Now I'd like to query all parts that have a production step with a certain name and status through a Flask-Restless search query. Is this possible with a Flask-Restless search query? If yes, how can I achieve the specified behaviour? I'm using Flask-Restless version 0.17.0. I have tried following filters: q={"filters":[{"and":[{"name":"production_steps__name","op":"==","val":"cutting"}, {"name":"production_steps__status","op":"any","val":"done"}]}]} Which leads to following error: sqlalchemy.exc.InvalidRequestError: Can't compare a collection to an object or collection; use contains() to test for membership. Which sounds reasonable, so I also tried the following: q={"filters":[{"and": [{"name":"production_steps","op":"any","val":{"name":"name","op":"eq","val":"cutting"}}, {"name":"production_steps","op":"any","val":{"name":"status","op":"eq","val":"done"}}] }]} This query does work, but it does return parts that match only one of the criterions (e.g. parts with a production step "cutting" where the status is not "done")
score: 2
type: AnsweredQuestion
has title: Searching an exact match for the attribute of a relation

http://stackoverflow.com/a/48215641
answers question: http://stackoverflow.com/q/48215592
has body: PostgreSQL supports declarative column security (as well as row security) Use this template: GRANT { { SELECT | INSERT | UPDATE | REFERENCES } ( column_name [, ...] ) [, ...] | ALL [ PRIVILEGES ] ( column_name [, ...] ) } ON [ TABLE ] table_name [, ...] TO role_specification [, ...] [ WITH GRANT OPTION ] Example: GRANT INSERT (colA, colB) ON TABLE foo TO michi;
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83413197
downvote count: 0
has comment: http://stackoverflow.com/comment/83413268
has comment: http://stackoverflow.com/comment/83413850

http://stackoverflow.com/comment/83559209
comment on: http://stackoverflow.com/q/48286217
has text: Thanks for the help. It seems silly, but that was really useful for me. I can go to cloudwatch logs and start to get an idea for what the `event` and `context` objects actually are. On a related note, is it possible to open/work with a file in an s3 bucket via lambda? For instance, could I load a csv into a pandas dataframe, manipulate the dataframe, return the manipulated dataframe, and then upload that to my destination bucket? Would it be something as simple as putting with the event handler something like `df = pd.read_excel(['Records']['bucket']['object']['key'])`?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48312870
tagged with: python
tagged with: python-decorators
type: Question
type: UnansweredQuestion
has title: Class Decorator when Inheriting from another class
answer count: 1
tagged with: decorator
tagged with: inheritance
score: 0
has body: Ive been on a tear of writing some decorators recently. One of the ones I just wrote allows you to put the decorator just before a class definition, and it will cause every method of the class to print some logigng info when its run (more for debugging/initial super basic speed tests during a build) def class_logit(cls): class NCls(object): def __init__(self, *args, **kwargs): self.instance = cls(*args, **kwargs) @staticmethod def _class_logit(original_function): def arg_catch(*args, **kwargs): start = time.time() result = original_function(*args, **kwargs) print('Called: {0} | From: {1} | Args: {2} | Kwargs: {3} | Run Time: {4}' ''.format(original_function.__name__, str(inspect.getmodule(original_function)), args, kwargs, time.time() - start)) return result return arg_catch def __getattribute__(self, s): try: x = super(NCls, self).__getattribute__(s) except AttributeError: pass else: return x x = self.instance.__getattribute__(s) if type(x) == type(self.__init__): return self._class_logit(x) else: return x return NCls This works great when applied to a very basic class i create. Where I start to encounter issues is when I apply it to a class that is inheriting another - for instance, using QT: @scld.class_logit class TestWindow(QtGui.QDialog): def __init__(self): print self super(TestWindow, self).__init__() a = TestWindow() Im getting the following error... and im not entirely sure what to do about it! self.instance = cls(*args, **kwargs) File "&lt;string&gt;", line 15, in __init__ TypeError: super(type, obj): obj must be an instance or subtype of type Any help would be appreciated! (Apologies in advance, no matter WHAT i do SO is breaking the formatting on my first bit of code... Im even manually spending 10 minutes adding spaces but its coming out incorrectly... sorry!)
has answer: http://stackoverflow.com/a/48775217

http://stackoverflow.com/comment/83479274
comment on: http://stackoverflow.com/q/48248338
has text: https://stackoverflow.com/questions/26245862/reducing-pandas-series-with-multiple-nan-values-to-a-set-gives-multiple-nan-valu
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/83433974
type: Comment
type: QuestionComment
has text: While I uderstand that I should use a random seed constant, I've run the experiments many times and the accuracy obtained by tensorflow code never better than that of sklearn. What do you mean by "follows Glorot et. al."? Is it a better way to initialize weights?
comment on: http://stackoverflow.com/q/48225494
score: 0

http://stackoverflow.com/q/48320432
has comment: http://stackoverflow.com/comment/83626224
type: Question
tagged with: string
favorite count: 0
tagged with: numpy
has title: Extract the first letter from each string in a numpy array
accepted answer: http://stackoverflow.com/a/48320451
has comment: http://stackoverflow.com/comment/83626402
has body: I got a huge numpy array where elements are strings. I like to replace the strings with the first alphabet of the string. For example if C[0] = 'A90CD' I want to replace it with C[0] = 'A' IN nutshell, I was thinking of applying regex in a loop where I have a dictionary of regex expression like '^A.+$' => 'A' '^B.+$' => 'B' etc How can I apply this regex over the numpy arrays ? Or is there any better method to achieve the same ?
has comment: http://stackoverflow.com/comment/83626443
has comment: http://stackoverflow.com/comment/83626177
tagged with: arrays
tagged with: python
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/83626239
upvote count: 3
has answer: http://stackoverflow.com/a/48320451
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48196412
tagged with: module
score: -1
has answer: http://stackoverflow.com/a/48196631
upvote count: 0
has body: I am trying to import my own files in Python3. My directory looks like this: /path/folder/__init__.py /path/folder/custom_module2.py /path/folder/custom_module.py /path/launcher.py init: import custom_module custom_module: import custom_module2 def custom_function: custom_module2.custom_function() print('world') custom_module2: def custom_function2: print('hello') launcher: import folder custom_function() it says that there is no module named custom_module
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83374120
type: Question
has title: trouble with custom imports Python3
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83345269
type: Comment
has text: I have updated my demo code, and I am a little confused, If I got wrong, please show me what the target directory structure.@Ryan
type: AnswerComment
comment on: http://stackoverflow.com/a/48180427
score: 0

http://stackoverflow.com/comment/83503586
has text: Okay cool thanks :-) will going through it ,just a question I dont need all the parts in that json only few parts so can I skip the problematic parts by directly selecting the required "key: values" ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48259515
score: 0

http://stackoverflow.com/comment/83518150
type: QuestionComment
comment on: http://stackoverflow.com/q/48261685
score: 0
has text: @IanThompson This doesn't look like working in my way. Its not writing the index values in excel. Also I just don't want to get sum of column S to AA. Only wanted to get sum of column E to R. substring "Total" can be anywhere in between on placement Id to day. Also i want all columns to write in excel.
type: Comment

http://stackoverflow.com/q/48249093
has title: Kafka-python connection lost
tagged with: exception
has answer: http://stackoverflow.com/a/51299136
tagged with: kafka-consumer-api
tagged with: python
tagged with: kafka-python
score: 0
type: UnansweredQuestion
answer count: 1
has body: I would like to know how to verify the connection to kafka: let me to explain better: I have one KafkaConsumer is waiting to consume messages, let's assume that kafka connection meantime is down. While I am trying to consume messages with my iteration on my consumer and connection is lost, it will go on Exception. Is there any way to check connection? I am using kafka-python version 1.3.3. This is a pieace of code: consumer = KafkaConsumer(....) for msg in consumer: DO.... This is the execpetion I have during my iteration: getaddrinfo failed for kafka:9092, exception was [Errno -2] Name or service not known Thank you all
type: Question

http://stackoverflow.com/comment/83484409
type: QuestionComment
has text: How should I write the 2-D array when I have only 1 equality constraint ?
score: 0
comment on: http://stackoverflow.com/q/48250644
type: Comment

http://stackoverflow.com/comment/96844002
comment on: http://stackoverflow.com/a/48178776
type: Comment
type: AnswerComment
has text: Documentation link was dead. I found [this](https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#creating-an-environment-with-commands)
score: 0

http://stackoverflow.com/q/48237302
score: 2
tagged with: mongodb
answer count: 2
upvote count: 2
tagged with: pymongo
downvote count: 0
has answer: http://stackoverflow.com/a/48237575
has title: How to run pymongo aggregation query for large(200,000+ records) collection?
has body: I need to run an aggregation query for a large collection which has 200,000+ data records. And I want to run it with pymongo. I tried out the preferred method in the docs. pipeline = [...] db.command('aggregate', 'statCollection', pipeline=pipeline_aggregate) But this returned an error saying pymongo.errors.OperationFailure: The 'cursor' option is required, except for aggregate with the explain argument.
favorite count: 0
type: Question
tagged with: data-analysis
has answer: http://stackoverflow.com/a/48237404
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48272247
tagged with: stdout
tagged with: python
has answer: http://stackoverflow.com/a/48272325
has title: Outputting data to file from for statement in python
score: 0
answer count: 1
tagged with: file
linked to: http://stackoverflow.com/q/34204523
type: Question
has body: I'm trying to achieve outputing data to a file which currently is printing the desired output to the screen from a for statement. I have the below portion which prints out data to the screen without issue. What can I use to have it write to a file instead? search = open ("algo_fg.txt") for line in search: if app in line: print (line) I figured since I was in the for statement, it was a bit trickier to have it write to a file. The original algo_fg.txt file in the code above is where the for statement is running through originally.
duplicate of: http://stackoverflow.com/q/34204523
tagged with: for-loop
type: UnansweredQuestion

http://stackoverflow.com/comment/83581172
type: QuestionComment
comment on: http://stackoverflow.com/q/48298306
score: 0
has text: See [`input`](https://docs.python.org/3/library/functions.html#input)
type: Comment

http://stackoverflow.com/a/48245264
type: Answer
has body: You can do something like this: Code1.py def hello(): print("Hello") New file import Code1 Code1.hello() # "Hello" This way you don't have to copy and paste all the code. If the file you are trying to import is not in the same directory... Here is a possible answer to your question taken from here. By default, you can't. When importing a file, Python only searches the current directory, the directory that the entry-point script is running from, and sys.path which includes locations such as the package installation directory (it's actually a little more complex than this, but this covers most cases). However, you can add to the Python path at runtime: # some_file.py import sys sys.path.insert(0, '/path/to/application/app/folder') import file
score: 1
has comment: http://stackoverflow.com/comment/83474781
has comment: http://stackoverflow.com/comment/83474755
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83473303
accepted answer of: http://stackoverflow.com/q/48245239
answers question: http://stackoverflow.com/q/48245239

http://stackoverflow.com/q/48292443
type: Question
type: UnansweredQuestion
tagged with: javascript
upvote count: 1
tagged with: python
tagged with: flask
tagged with: ajax
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48292468
has body: I'm currently developing a flask application that retrieves the teams from a football league. The teams_list method returns the following response from an ajax request. I'm getting the right output but it's leading me into an infinite loop that really slows down the entire web application. How I got the response: teams = [] @app.route('/get_team_list', methods=['POST']) def team_list(): league = request.form['team_name'] id = get_league_id(league) get_teams(id) json_str = json.dumps({'status':'OK','id': id, 'league': league, 'teams': teams}) json_obj = json.loads(json_str) temp = json_obj['teams'] #a subarray team_str = json.dumps(temp) print("STR: ",team_str) print("JSON: ", str(temp)) clear_team_array(teams) return team_str Response: ["Juventus Turin", "Cagliari Calcio", "Hellas Verona FC", "SSC Napoli", "Atalanta BC", "AS Roma", "Udinese Calcio", "AC Chievo Verona", "US Sassuolo Calcio", "Genoa CFC", "UC Sampdoria", "Benevento Calcio", "SS Lazio", "SPAL Ferrara", "FC Internazionale Milano", "ACF Fiorentina", "Bologna FC", "Torino FC", "FC Crotone", "AC Milan"] Ajax call: $('#test').click(function() { $.ajax({ url: '/get_team_list', data: $('form').serialize(), type: 'POST', success: function(response) { var json = $.parseJSON(response); for (var i = 0; json.length - 1; i++) { console.log("RESPONSE: " + json[i]); } }, error: function(error) { console.log("ERROR: "+ error) } }); }); It is working fine but the problem I'm heaving is that when I retrieve the teams through the for loop it gives me the following output: RESPONSE: Juventus Turin RESPONSE: SSC Napoli RESPONSE: Atalanta BC RESPONSE: AC Milan RESPONSE: ... (140231)REPONSE: undefined
downvote count: 1
has title: $.parseJSON returns correct items plus infinite undefined response
favorite count: 0

http://stackoverflow.com/comment/83605128
type: QuestionComment
has text: check this https://stackoverflow.com/a/17548578/8150371 or use JsonResponse instead of HttpResponse
comment on: http://stackoverflow.com/q/48309523
score: 1
type: Comment

http://stackoverflow.com/comment/83666583
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48326469
type: Comment
has text: @Equalsk Wow. So for those of us that aren't coding focused and don't know what we're looking for so come to something like this only to get told we aren't bothering. Thanks. I'll try and search elsewhere

http://stackoverflow.com/q/48327962
has body: I define a 3D transpose convolution in Tensorflow as follows: def weights(shape): return tf.Variable(tf.truncated_normal(shape, mean = 0.0, stddev=0.1)) def biases(shape): return tf.Variable(tf.constant(value = 0.1, shape = shape)) def trans_conv3d(x, W, output_shape, strides, padding): return tf.nn.conv3d_transpose(x, W, output_shape, strides, padding) def transconv3d_layer(x, shape, out_shape, strides, padding): # shape: [depth, height, width, output_channels, in_channels]. # output_shape: [batch, depth, height, width, output_channels] W = weights(shape) b = biases([shape[4]]) return tf.nn.elu(trans_conv3d(x, W, out_shape, strides, padding) + b) Suppose I have a 4D tensor x from a previous layer with shape [2, 1, 1, 1, 10] where batch = 2, depth = 1, height = 1, width = 1, and in_channels = 10 as set out here. How would I use transconv3d_layer to upsample x, over a sequence of layers, to have a final shape such as [2, 100, 100, 100, 10] or something similar? It is not clear to me how to follow the shape of my tensor through transpose layers.
tagged with: convolution
tagged with: python
tagged with: computer-vision
type: AnsweredQuestion
has title: Upsampling using 3d transpose convolutions in Tensorflow
has answer: http://stackoverflow.com/a/48328072
tagged with: deep-learning
downvote count: 0
upvote count: 1
score: 1
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48328072

http://stackoverflow.com/comment/88561492
score: 1
type: Comment
has text: You're probably on python2.x. Use super(ClassName, self)
comment on: http://stackoverflow.com/a/48344897
type: AnswerComment

http://stackoverflow.com/comment/83641272
has text: What's the question?
comment on: http://stackoverflow.com/q/48327849
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48330581
upvote count: 1
has comment: http://stackoverflow.com/comment/83647065
has comment: http://stackoverflow.com/comment/83646970
favorite count: 0
has answer: http://stackoverflow.com/a/48330722
has comment: http://stackoverflow.com/comment/83647374
has body: This code is from a beginning python book I'm studying, the chapter is discussing Dictionaries. favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } friends = ['phil','sarah'] for name in favorite_languages.keys(): print(name.title()) if name in friends: print(" hi " +name.title() + ", i see your favorite language is " + favorite_languages[name].title() + "!") The result is: Jen Ed Phil hi Phil, i see your favorite language is Python! hi Sarah, i see your favorite language is C! I'm having trouble understanding the logic of the code relative to the varible "name" and why the value changed. Meaning, the variable "name" is created by the "for" loop and all the Dictionary keys are stored in it, so that when the "if" statement begins the value of "name" is all keys. My understanding of the "if" statement is that it just returns a boolean value of true or false, in this case true. But why does the value of "name" (as a result of this "if" statement) get changed to the value of "friends" at this point? Is it just a rule that is built into Python? Because it does not logically follow, unless I'm missing something. It would make more sense to me to write it: if friends in name: print(" hi " friends.title() +
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48330991
has title: Python "if" statement changes variable value
type: Question
answer count: 2
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/a/48273737
type: Answer
accepted answer of: http://stackoverflow.com/q/48273396
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48273396
downvote count: 0
has body: TLDR; From my findings, all of the currency buy prices from this api are all sending the same results, as you said. With that being said, the currency names you are trying to use aren't in the list of supported currencies. I would advise finding an alternative to this api. You can see that the currency ids aren't valid by calling client.get_currencies(): from coinbase.wallet.client import Client api_key = "&lt;Your API Key&gt;" api_secret = "&lt;Your API Secret&gt;" client = Client(api_key, api_secret) currencies = client.get_currencies() names = [currency["id"] for currency in currencies["data"]] print("LTC" in names) print("ETH" in names) print("BCH" in names) This prints: False False False You can get a list of currency ids and their name like so: from coinbase.wallet.client import Client api_key = "&lt;Your API Key&gt;" api_secret = "&lt;Your API Secret&gt;" client = Client(api_key, api_secret) currencies = client.get_currencies() for currency in currencies["data"]: print(currency["id"], currency["name"]) This prints out: AED United Arab Emirates Dirham AFN Afghan Afghani ALL Albanian Lek AMD Armenian Dram ANG Netherlands Antillean Gulden AOA Angolan Kwanza ARS Argentine Peso AUD Australian Dollar AWG Aruban Florin AZN Azerbaijani Manat BAM Bosnia and Herzegovina Convertible Mark BBD Barbadian Dollar BDT Bangladeshi Taka BGN Bulgarian Lev BHD Bahraini Dinar BIF Burundian Franc ... ... ... Although, it does seem the same thing is happening to me with the prices being the same..: print(client.get_buy_price(currency_pair="BTC-USD")) print(client.get_buy_price(currency_pair="CAD-USD")) also gives the same result: { "amount": "13142.02", "base": "BTC", "currency": "USD" } { "amount": "13142.02", "base": "BTC", "currency": "USD" } If the api isn't being maintained, then I would recommend you look around for another api that can provide what you need.
upvote count: 1

http://stackoverflow.com/comment/83470882
comment on: http://stackoverflow.com/q/48241158
has text: Would the correlation make sense if `True = 1` and `False = 0`?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48336005
score: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83696855
has body: The similarity measures can only be accessed by the Synset objects not Lemma nor lemma_names (i.e. str type). dog = wn.synsets('dog', 'n')[0] paw = wn.synsets('paw', 'n')[0] print(type(dog), type(paw), dog.wup_similarity(paw)) [out]: &lt;class 'nltk.corpus.reader.wordnet.Synset'&gt; &lt;class 'nltk.corpus.reader.wordnet.Synset'&gt; 0.21052631578947367 When you get the .lemmas() and access the .names() attribute from the Synset object, you are getting str: dog = wn.synsets('dog', 'n')[0] print(type(dog), dog) print(type(dog.lemmas()[0]), dog.lemmas()[0]) print(type(dog.lemmas()[0].name()), dog.lemmas()[0].name()) [out]: &lt;class 'nltk.corpus.reader.wordnet.Synset'&gt; Synset('dog.n.01') &lt;class 'nltk.corpus.reader.wordnet.Lemma'&gt; Lemma('dog.n.01.dog') &lt;class 'str'&gt; dog You can use the hasattr function to check what objects/types can access a certain function or attribute: dog = wn.synsets('dog', 'n')[0] print(hasattr(dog, 'wup_similarity')) print(hasattr(dog.lemmas()[0], 'wup_similarity')) print(hasattr(dog.lemmas()[0].name(), 'wup_similarity')) [out]: True False False Most probably, you want a similar function to https://github.com/alvations/pywsd/blob/master/pywsd/similarity.py#L76 which maximizes the wup_similarity across two synsets but note that there are many caveats like pre-lemmatization that is necessary. So I think that's where you want to avoid it by using the .lemma_names(). Perhaps, you can do this: def ss_lnames(word): return set(chain(*[ss.lemma_names() for ss in wn.synsets(word, 'n')])) dog_lnames = ss_lnames('dog') paw_lnames = ss_lnames('paw') for dog_name, paw_name in product(dog_lnames, paw_lnames): for dog_ss, paw_ss in product(wn.synsets(dog_name, 'n'), wn.synsets(paw_name, 'n')): print(dog_ss, paw_ss, dog_ss.wup_similarity(paw_ss)) But most probably the results are un-interpretable and unreliable since there's no word sense disambiguation going up prior to synset look up bot in the outer and inner loop.
answers question: http://stackoverflow.com/q/48323393
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48323393

http://stackoverflow.com/comment/83631748
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48323235
has text: Can you add some data sample? - 3-4 rows
type: Comment

http://stackoverflow.com/a/48216723
has body: This is not strictly an answer to your question since its not vectorized, but hopefully its a helpful benchmark for any other potential solutions (there's bound to be something in image processing libraries?) Regardless, I've implemented the window as a loop which takes the average of the window with output into a new array. Inputs are an array and the window size +/- the current index. One version using straight Python and Numpy, the other compiled with numba. def mw_mean(in_arr,out_arr,x_win,y_win): xn,yn = in_arr.shape for x in range(xn): xmin = max([0,x - x_win]) xmax = min([xn, x + x_win + 1]) for y in range(yn): ymin = max([0,y - y_win]) ymax = min([yn, y + y_win + 1]) out_arr[x,y] = in_arr[xmin:xmax, ymin:ymax].mean() return out_arr @jit("i4[:,:](i4[:,:],i4[:,:],i4,i4)", nopython = True) def mw_mean_numba(in_arr,out_arr,x_win,y_win): xn,yn = in_arr.shape for x in range(xn): xmin = max(0,x - x_win) xmax = min(xn, x + x_win + 1) for y in range(yn): ymin = max(0,y - y_win) ymax = min(yn, y + y_win + 1) out_arr[x,y] = in_arr[xmin:xmax, ymin:ymax].mean() return out_arr This is tested against three different array sizes--your original test case and two larger ones (100x100 and 1000x1000): a = np.array([[1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]]) b = np.random.randint(1,7, size = (100,100)) c = np.random.randint(1,7, size = (1000,1000)) aout,bout,cout = np.zeros_like(a),np.zeros_like(b),np.zeros_like(c) x_win = 1 y_win = 1 Runtimes without compilation: %timeit mw_mean(a,aout,x_win,y_win) 1000 loops, best of 3: 225 µs per loop %timeit mw_mean(b,bout,x_win,y_win) 10 loops, best of 3: 137 ms per loop %timeit mw_mean(c,cout,x_win,y_win) 1 loop, best of 3: 14.1 s per loop Runtimes with compilation: %timeit mw_mean_numba(a,aout,x_win,y_win) 1000000 loops, best of 3: 1.22 µs per loop %timeit mw_mean_numba(b,bout,x_win,y_win) 1000 loops, best of 3: 550 µs per loop %timeit mw_mean_numba(c,cout,x_win,y_win) 10 loops, best of 3: 55.1 ms per loop Edit: a previous version of th…
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/48215914
type: Answer
upvote count: 6

http://stackoverflow.com/comment/83554492
has text: yep. typo fixed
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48285065
type: QuestionComment

http://stackoverflow.com/comment/83431610
type: AnswerComment
score: 0
has text: Thank you,I will try this also.
type: Comment
comment on: http://stackoverflow.com/a/48224243

http://stackoverflow.com/q/48259135
score: 1
tagged with: chatterbot
downvote count: 0
has comment: http://stackoverflow.com/comment/83501212
upvote count: 1
favorite count: 0
type: Question
has title: Django chatterbot response is not showing in chat window
has comment: http://stackoverflow.com/comment/83501240
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: i am trying Django chatterbot. when i want to interact with bot, bot's response is not showing in chat window. please check the attached image. There is no error in code when i am running it. i also tried python manage.py makemigrations python manage.py migrate python manage.py migrate django_chatterbot python manage.py train i am unable to figure out the problem. Please help. Thanks.
has comment: http://stackoverflow.com/comment/83501105
has comment: http://stackoverflow.com/comment/83501329
answer count: 0

http://stackoverflow.com/comment/83496670
type: AnswerComment
has text: Just ensure that the data is first sorted by date or by ticker and date.
score: 1
comment on: http://stackoverflow.com/a/48256948
type: Comment

http://stackoverflow.com/q/48206443
score: 6
has comment: http://stackoverflow.com/comment/83393954
has answer: http://stackoverflow.com/a/48206683
has answer: http://stackoverflow.com/a/48206760
tagged with: python
has answer: http://stackoverflow.com/a/48206571
answer count: 6
upvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48206651
possible better answer: http://stackoverflow.com/a/48206559
downvote count: 0
has title: Infinite loops using 'for' in Python
has body: Why does this not create an infinite loop? a=5 for i in range(1,a): print(i) a=a+1 or this for i in range(1,4): print(i) i=i-1 or this for i in range(1,4): print(i) i=1 Is there any way we can create infinite loops using a for loop? I know there is the while loop for that but I was just curious.
has answer: http://stackoverflow.com/a/48206559
linked to: http://stackoverflow.com/q/5737196
has answer: http://stackoverflow.com/a/48206612
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: for-loop
tagged with: infinite-loop
accepted answer: http://stackoverflow.com/a/48206571
duplicate of: http://stackoverflow.com/q/5737196

http://stackoverflow.com/q/48268789
has answer: http://stackoverflow.com/a/48268976
answer count: 2
has title: python thread with os.chdir and c/fortran Program
tagged with: fortran
tagged with: multithreading
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/48269569
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has body: I am having some troubles by understanding my python with C or FORTRAN code. I have a Python script that simply deploys two threads, each thread will go into a sub-directory and call the same Fortran Program (for the same of simplicity with os.system, but Popen is the same. I also included a C Program to show the same problem ) When each instance of a.out (F77 or C) is called, I was expecting that they know in which CWD they are, but 1 out of 10 or 20 runs, they don't. So I think I am doing something wrong with my python. When running the Python script with the F77 code I got this error: CWD_F: /home/usr/f_fail/2 CWD_F: /home/usr/f_fail/2 Fortran runtime error: Cannot open file 'dummy.txt': File exists When running with C sometimes I get CWD_C : /home/usr/f_fail/2 CWD_C : /home/usr/f_fail/2 Here is my very simple python. One thing; when I uncomment the time.sleep() it seems to work well! #!/usr/bin/python import threading, os,time def t1( newDir ): os.chdir( newDir ) os.system('../a.out') os.chdir('..') def t2( newDir ): os.chdir( newDir ) os.system('../a.out') os.chdir('..') #main starts here cwd_=os.getcwd() try : os.mkdir('1') except: pass try : os.mkdir('2') except: pass newDir1=os.path.join( cwd_ , '1') newDir2=os.path.join( cwd_ , '2') tt1 = threading.Thread( target=t1 , args=(newDir1,)) tt2 = threading.Thread( target=t2 , args=(newDir2,)) tt1.start() #time.sleep(1) tt2.start() tt1.join() tt2.join() Here the FORTRAN77 code : program test implicit none integer i,k,unt real*8 a(3,10 ), c(3) character*132 fl,cwdpath do i=1,10 c(1)=i*1.11 c(2)=i*2.22 c(3)=i*3.33 a(:,i)=c enddo unt=1 fl='dummy.txt' call getcwd(cwdpath) write(*,*) 'CWD_F: ', cwdpath write(*,*) 'unit: ', unt open(unt,file=fl,status='unknown') close(unt,status='delete') open(unt,file=fl,status='new') do k=1,10 write(unt,200) a(1,k),a(2,k),a(3,k) enddo close(unt) 200 format(' ',F10.4,F10.4,F10.4) end Alternatively, here is my C code: #include &lt;unistd.h&gt; #include &lt;stdio.h&gt; #define PATH_MAX_ …
tagged with: http://stackoverflow.com/tag/c

pca
tag name: pca
type: Tag
tags question: http://stackoverflow.com/q/48263740
tags question: http://stackoverflow.com/q/48271342
tags question: http://stackoverflow.com/q/48279647

http://stackoverflow.com/q/48210900
tagged with: dynamic
downvote count: 0
has comment: http://stackoverflow.com/comment/83402936
upvote count: 1
has comment: http://stackoverflow.com/comment/83403120
linked to: http://stackoverflow.com/q/394770
has comment: http://stackoverflow.com/comment/83403754
favorite count: 0
linked to: http://stackoverflow.com/q/10829200
type: Question
has title: Is it possible to do dynamic method overriding from a method of another class? If so, How?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83403534
has answer: http://stackoverflow.com/a/48213424
accepted answer: http://stackoverflow.com/a/48213424
score: 1
tagged with: overriding
has comment: http://stackoverflow.com/comment/83403955
has body: I looked at the following posts and blogs which explain to do this with a function. I wonder if its even legal to do the same for a class or object method? Will appreciate answers which work for Python2 (though its good to know how it works for Python3 as well). Sources from stackoverflow: Override module method where from...import is used and Override a method at instance level blogs with similar content: https://tryolabs.com/blog/2013/07/05/run-time-method-patching-python/ http://igorsobreira.com/2011/02/06/adding-methods-dynamically-in-python.html This code illustrates my intention and what I tried: class Person: def __init__(self, name): self.name = name class OtherPerson: def __init__(self, name): self.name = name def do_something(self): print self.name + '$$' p = Person('alpha') p.do_something = OtherPerson.do_something # TypeError: unbound method do_something() must be called with OtherPerson #instance as first argument (got nothing instead) p.do_something() op = OtherPerson('beta') p.do_something = op.do_something # output: 'beta$$' I would like to get 'alpha$$' p.do_something() Tried following suggestion from @khelwood: Person.do_something = OtherPerson.do_something #TypeError: unbound method do_something() must be called with OtherPerson instance as first argument (got nothing instead) # Works if OtherPerson.do_something is staticmethod p.do_something()
tagged with: python
has answer: http://stackoverflow.com/a/48212270
possible better answer: http://stackoverflow.com/a/48212270
answer count: 2

http://stackoverflow.com/comment/88262210
type: AnswerComment
score: 0
has text: @j_4321 : I do however have another question in relation to DateEntry please - can you have a look at this please? Many many thanks https://stackoverflow.com/questions/50625818/how-to-get-the-selected-date-for-dateentry-in-tkcalendar-python
type: Comment
comment on: http://stackoverflow.com/a/48309092

http://stackoverflow.com/q/48289554
linked to: http://stackoverflow.com/q/47360766
has title: Python tkinter: Getting the number of entries in an OptionMenu dropdown list
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48290107
has comment: http://stackoverflow.com/comment/83602723
tagged with: python
has comment: http://stackoverflow.com/comment/83604589
type: Question
score: 0
has comment: http://stackoverflow.com/comment/83565432
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83600694
linked to: http://stackoverflow.com/q/22973347
has body: The function below creates a nicely formatted list of all attributes of an OptionMenu widget. However a kludge is needed because OptionMenu does not having a "Menu size"' attribute (that holds the number of elements inside the dropdown list). How do I extract this value from the widget so I can eliminate the kludge (and show the attributes of EVERY entry in the drop-down menu) ? BTW, The function does not list the contents of the (non-standard) Optionmenu "command" option. For info on this option see the accepted answer to tkinter OptionMenu issue (bug?): GUI and program values not kept in lockstep (python 3.x) ) def OptionMenuConfigLister( OptionMenuWidget ) : ''' Uncomment this block to see ALL attributes of the widget # # Gets the main attributes of the widget (EXCLUDING the attributes for # the dropdown list and the values in the list) # print( " \nOptionMenuWidget.config()\n" ) for i, j in enumerate( sorted( OptionMenuWidget.config().items() ) ) : print( " {0:&lt;19} |{1}|".format( j[ 0 ], j[ 1 ][ -1 ] ), flush = True ) # # Gets the attributes of the list portion of the widget (but NOT the entries) # print( "\nOptionMenuWidget[ 'menu' ].config().items() :\n" ) for i, j in enumerate( sorted( OptionMenuWidget[ 'menu' ].config().items() ) ) : print( " {0:&lt;18} |{1}|".format( j[ 0 ], j[ 1 ][ -1 ] ), flush = True ) ''' # # Get the attributes of each/every entry in the dropdown list # # TODO: Determine how to get # of items in list # for i in range( 0, 1 ) : ''' &lt;======== KLUDGE ''' print( "\nOptionMenuWidget[ 'menu' ].entryconfig(" + str( i ) + ").items()) :\n" ) for _, j in enumerate( sorted( OptionMenuWidget[ 'menu' ].entryconfig( i ).items() ) ) : print( " {0:&lt;16} |{1}|".format( j[ 0 ], j[ 1 ][ -1 ] ), flush = True ) print() return EDIT 20180117: Here's the fix, based on the answer by @nae - replace the kludge line with: ElementCount = OptionMenuWidget[ 'menu' ].index( 'end' ) + 1 for i in range( 0, ElementCount ) : And as per comment by @furas, sample co…
answer count: 1
has comment: http://stackoverflow.com/comment/83564631
accepted answer: http://stackoverflow.com/a/48290107
has comment: http://stackoverflow.com/comment/83600128

http://stackoverflow.com/comment/83381686
comment on: http://stackoverflow.com/q/48200272
score: 1
type: QuestionComment
type: Comment
has text: Yes , in the command line

http://stackoverflow.com/comment/83647368
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48330428
has text: On a Lambda, I am unable to do ldconfig as described. Here's the full error message: DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so: cannot open shared object file: No such file or directory". See https://oracle.github.io/odpi/doc/installation.html#linux for help. I get the same error on the ec2 instance until I export the LD_LIBRARY_PATH
score: 0

http://stackoverflow.com/comment/83495144
comment on: http://stackoverflow.com/a/48256142
type: Comment
type: AnswerComment
has text: What? This 100% explains your question. IE by design
score: 3

http://stackoverflow.com/comment/83603271
type: AnswerComment
has text: Problem with this is that later in the file, a `Series` may be repeated, but the elements dont belong together.
score: 0
comment on: http://stackoverflow.com/a/48308858
type: Comment

http://stackoverflow.com/comment/83634801
has text: They could also lean on the RDBMS and its constraints, if set up correctly, in which case the bulk method you've shown is just as safe.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48323683
type: Comment

http://stackoverflow.com/comment/83473279
type: Comment
type: QuestionComment
score: 0
has text: @kmario23 I didnt mean writing the whole program in numpy. just these definitions of xs, ys, hs, etc in numpy so I can understand why they use these parameters.
comment on: http://stackoverflow.com/q/48241666

http://stackoverflow.com/q/48241885
has comment: http://stackoverflow.com/comment/83466161
type: Question
accepted answer: http://stackoverflow.com/a/48241953
duplicate of: http://stackoverflow.com/q/47152691
has answer: http://stackoverflow.com/a/48241953
has body: I have a list of (x,y,z) tuples in a dataframe A. How can I produce a dataframe B which represents the underlying matrix of A, using the existing values of x and y as index and columns values, respectively? Example: A: x y z 1 1 1 1 2 10 2 1 100 B: 1 2 1 1 10 2 100 NaN
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: pandas
has title: Get matrix from list of tuples
linked to: http://stackoverflow.com/q/47152691
answer count: 1

http://stackoverflow.com/a/54147741
score: 1
has body: Just in case somebody else needs another way of implementing "Followers" exactly like you described, but with a different modelling scheme: # project/account/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from model_utils import Choices class User(AbstractBaseUser, PermissionsMixin): class Meta: # ... username = models.CharField(...) email = models.EmailField(...) # ... ### Custom app-specific relationships (database scheme) ### # symmetrical=False is needed for this reason: https://stackoverflow.com/a/42040848/3433137 following = models.ManyToManyField('self', related_name='followers', blank=True, symmetrical=False) # project/account/forms.py from django import forms from django.contrib.auth import get_user_model from django.contrib.admin.widgets import FilteredSelectMultiple from .models import User class UserChangeForm(forms.ModelForm): # ... # new: following = forms.ModelMultipleChoiceField( queryset=User.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='Following', is_stacked=False ) ) # new: followers = forms.ModelMultipleChoiceField( queryset=User.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='Followers', is_stacked=False ) ) class Meta: model = get_user_model() # add 'following' and 'followers' to the fields: fields = ('email', 'password', ..., 'following', 'followers') # also needed to initialize properly: def __init__(self, *args, **kwargs): super(UserChangeForm, self).__init__(*args, **kwargs) # Filter out the self user in the lists and initialize followers list: if self.instance and self.instance.pk: self.fields['following'] = forms.ModelMultipleChoiceField( queryset=User.objects.all().exclude(pk=self.instance.pk), required=False, widget=FilteredSelectMultiple( verbose_name='Following', is_stacked=False ) ) self.fields['followers'] = forms.ModelMultipleChoiceField( queryset=User.objects.all().exclude(pk=self.instance.p…
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/48218081

amazon-athena
type: Tag
tag name: amazon-athena
tags question: http://stackoverflow.com/q/48314880

http://stackoverflow.com/comment/83413422
score: 0
type: AnswerComment
has text: Your advice is to switch to Python3 just because Python2.x returns integer on division of two integers?
comment on: http://stackoverflow.com/a/48215779
type: Comment

http://stackoverflow.com/a/48291580
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48291170
has comment: http://stackoverflow.com/comment/83572585
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48291170
type: Answer
has body: Assuming you have the following orginal DF (containing numpy arrays of the same shape in cells): In [320]: df Out[320]: file numpy 0 x [1, 2, 3] 1 y [4, 5, 6] Convert it to the following format: In [321]: d = pd.DataFrame(df['numpy'].values.tolist(), index=df['file']) In [322]: d Out[322]: 0 1 2 file x 1 2 3 y 4 5 6 Now you are free to use all the Pandas/Numpy/Scipy power: In [323]: d.sum(axis=1) Out[323]: file x 6 y 15 dtype: int64 In [324]: d.sum(axis=0) Out[324]: 0 5 1 7 2 9 dtype: int64 In [325]: d.mean(axis=0) Out[325]: 0 2.5 1 3.5 2 4.5 dtype: float64 In [327]: d.std(axis=0) Out[327]: 0 2.12132 1 2.12132 2 2.12132 dtype: float64

http://stackoverflow.com/q/48292632
tagged with: user-interface
downvote count: 0
score: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48295403
has comment: http://stackoverflow.com/comment/83574612
tagged with: tkinter
has answer: http://stackoverflow.com/a/48295403
has body: import tkinter as tk class MainWindow: def __init__(self, master): self.master = master self.button_height = 2 self.button_width = 8 self.list_of_tasks = [] **#Other irrelevant code** #Button for adding a new task to current tab self.new_task = tk.Button(self.buttons_frame, bg="yellow", height=self.button_height, width=self.button_width*2, text="New Task", command=self.create_new_task) self.new_task.grid(row=1, column=0, columnspan=2, sticky="N"+"W"+"S"+"E") #Frame for holding all tasks in currently selected tab self.tasks_in_tab = tk.Frame(master, height=300, width=300) self.tasks_in_tab.grid(row=2, rowspan=5, column=0, columnspan=5) def create_new_task(self): #Creates a new task new_window = tk.Toplevel(self.master) entry_window = Task_Entry(new_window) entry_window.wait_window(entry_window) task = tk.Button(self.tasks_in_tab, text=entry_window.test_entry) self.list_of_tasks.append(task) task.pack() class Task_Entry: #Window for entering data into a new window def __init__(self, master): self.master = master self.test_entry_field = tk.Entry(self.master) self.test_entry_field.pack() self.test_entry = self.test_entry_field.get() self.cancel_button = tk.Button(self.master, text="Cancel", command=self.exit_program) self.cancel_button.pack() def exit_program(self): self.master.destroy() root = tk.Tk() gui = MainWindow(root) root.mainloop() I am attempting to use Tkinter's wait_window function in my code, but I am unsure how to properly use it in the context of where I wish to implement it. What is suppose to happen is the user clicks the new_task button, the function create_new_task is called. This then prompts a new window, as stored under the class Task_Entry, which contains an Entry field for the user to enter text into. As soon as the user enters their input the Task_Entry window is terminated, the user input - under the test_entry field of the called Task_Entry window class - is supposed to be passed to the new Button named task. I am pretty sure I should be using…
has comment: http://stackoverflow.com/comment/83595034
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/72565047
has title: How to correctly implement wait_window()?
has answer: http://stackoverflow.com/a/72565047
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/48176567
tagged with: python
has comment: http://stackoverflow.com/comment/83769802
has title: Python script bypasses PostgreSQL login?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83333344
answer count: 1
accepted answer: http://stackoverflow.com/a/48176663
tagged with: psycopg2
has body: I'm trying to work with a PostgreSQL database I have locally, and for some odd reason the program is able to login and make changes to the database without any username or password. I have done this same process in JavaScript and it required the username and password. Either way, isn't it extremely strange that this simple python script can use the database without any credentials? Code below. import psycopg2 user = ""; pw = ""; conn = psycopg2.connect("dbname='log_to_db' user='" + user + "' host='localhost' password='" + pw + "'") cur = conn.cursor() cur.execute("SELECT * from logs WHERE id=132") print (cur.fetchall()) conn.close() So, this script displays a row in the table. If anyone can help me understand why it's gaining access into the database without credentials (in addition to what I need to do to fix it), I would really appreciate it!
has comment: http://stackoverflow.com/comment/83333263
has comment: http://stackoverflow.com/comment/83333153
type: Question
has answer: http://stackoverflow.com/a/48176663
tagged with: postgresql
has comment: http://stackoverflow.com/comment/83333404

http://stackoverflow.com/comment/83575838
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48286324
has text: Maybe check this [guide](https://brennan.io/2016/03/02/logging-in-with-requests/) about logging in to website. In the bottom part "Single Sign On" there is a section about logging in to websites which delegate authentication to somebody else like it might be your case.

http://stackoverflow.com/comment/83435246
comment on: http://stackoverflow.com/q/48222810
score: 0
type: Comment
type: QuestionComment
has text: Yes, sure. First thing is for difference of 2 datetiems get [timedeltas](http://pandas.pydata.org/pandas-docs/stable/timedeltas.html) and then is the best use function `dt.days` for convert timedeltas to intergrs as days. Good luck1

ipv6
tag name: ipv6
tags question: http://stackoverflow.com/q/48319325
type: Tag

http://stackoverflow.com/q/48322070
tagged with: python
has comment: http://stackoverflow.com/comment/83629220
answer count: 4
has answer: http://stackoverflow.com/a/48322381
tagged with: type-conversion
has answer: http://stackoverflow.com/a/48322410
tagged with: python-2.7
score: 0
tagged with: list
has body: I have a column in Pandas.DataFrame where every row of this column is the list of numbers. But these number is typed as string The column name is allmz, the dataframe is exp_df print exp_df.iloc[:3]['allmz'] &gt;2129 [445.120788574, 355.067465091, 355.069260997, ... &gt;2130 [445.120758057, 355.06748396, 355.069279865, 3... &gt;2131 [445.120880127, 355.067417985, 355.06921389, 3... &gt;Name: allmz, dtype: object I tried to convert each number by iteritemsbut the type is still str. Although I assign mzz = float(mzz). for ind, mzlist in exp_df['allmz'].iteritems(): for mzz in mzlist: mzz = float(mzz) print type(exp_df.iloc[0]['allmz'][0]) &gt;&lt;type 'str'&gt; Each list comes from exp_df['allmz'] = exp_df['allmz'].apply(lambda x: x.split(" ")) so I tried to do exp_df[each] = exp_df[each].apply(lambda x: float(y) for y in x.split(" ")) But I guess lambda is not applicable with for loop. How I can access and convert string in list in each row of Pandas.DataFrame?
tagged with: pandas
upvote count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48322344
type: Question
has title: Convert numerical string in lists where each list is in Pandas row to float
has answer: http://stackoverflow.com/a/48322337
type: UnansweredQuestion

http://stackoverflow.com/q/48235018
answer count: 1
tagged with: python
has title: "For y in range(1,x)" loops taking too long to run. How can one expedite this process in Python?
has body: This code takes 40 seconds to run with an order of 1000. I need to run it while order = 100,000,000. Is there a way for me to speed up this code? from fractions import Fraction x=5 order=1000 count=0 while x &lt;=order: for y in range(1,x): if str(Fraction(y/x).limit_denominator()) != "%s/%s"%(y,x): print(Fraction(y/x).limit_denominator()) count += 1 print(" ") x+=1 count= (count + 1) * 6 + (order -1)*6 print(count) The purpose of this code was to decipher problem #351 on Project Euler. I have a limited understanding of Python, so I tried to use what I know to figure it out. I initially figured each line of hidden green dots was an easy find ((n-1)* 6), but determining the center dots was a greater challenge. Finding out that the pattern of each obstructed green dots was not linear, but rather a matter of considering the rows of each of the six present triangles as fractions, and finding the fractions that simplify. This code parses each "row" of the triangle for fractions that are simplified. If it finds one the code adds 1 to the variable 'count'. Since the while loop starts at row 5, (1 row beyond the first green dot) I had to add those dots back to the final count at the end ((count + 1)* 6). I used this code to confirm the green dots found in the order of 1000. It took 40 seconds to run though. 100,000,000 will likely take a bit longer (upwards of a few days to a few weeks.) I've been running it on a computer for over a day and a half as of January 11th, 2018 11:34pm EST.
has comment: http://stackoverflow.com/comment/83453329
has answer: http://stackoverflow.com/a/48239372
has comment: http://stackoverflow.com/comment/83452717
score: 0
has comment: http://stackoverflow.com/comment/83452763
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83456403

http://stackoverflow.com/comment/83382193
comment on: http://stackoverflow.com/q/48199960
has text: Possible duplicate of [How to fix "WebDriverException: Message: connection refused"?](https://stackoverflow.com/questions/47920639/how-to-fix-webdriverexception-message-connection-refused)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83332919
type: Comment
comment on: http://stackoverflow.com/a/48176328
type: AnswerComment
has text: I'd probably use [`with mutex:`](https://docs.python.org/3/library/threading.html#using-locks-conditions-and-semaphores-in-the-with-statement), but yeah.
score: 0

http://stackoverflow.com/a/48198654
answers question: http://stackoverflow.com/q/48198573
has comment: http://stackoverflow.com/comment/83404373
upvote count: 1
has body: Your problem springs from the fact that the input em_type parameter of your BaseFilter.__init__() method has just a single value. When you call it, after running rand_type = random.choice(types) super().__init__(mail, em_type= ' ' + rand_type + '\n') the rand_type is either OK or SPAM. There is no room for variability. So, within BaseFilter.__init__() you are marking all the lines as being of type em_type, where em_type is one value. I would suggest that you not try to do all the work in the __init__ method. Instead, try writing a generator function as an iterator on your object: def classify(self, text): """Given a text, return a classification of either 'OK' or 'SPAM'.""" return random.choice(self.types) def __iter__(self): with open(self.mailfile) as f: for line in f: text = line.strip() classification = self.classify(text) yield f"{text} {classification}" # py&lt;3.6: yield "{} {}".format(text, classification)
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/a/48294246
type: Answer
score: 0
has body: Something like this could be used, Your range is quite crazy but I believe adjusting key-3 and key+4 will handle your job. def near(): key = int(my_dict[input("Enter Key:")]) return [i for i in my_dict if int(my_dict[i]) in range(key-3,key+4)] So now when you run it: &gt;&gt;&gt; near() Enter Key:apples ['pears', 'peaches', 'apples'] &gt;&gt;&gt; You can remove apples from the list easily but that's left out for you!
answers question: http://stackoverflow.com/q/48294099

http://stackoverflow.com/comment/83681070
type: Comment
has text: inside `main()` you execute `main()` so you have recursion - it is not good idea - especially that you don't need it. Use `while True` loop.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48273226

http://stackoverflow.com/comment/83556607
type: Comment
comment on: http://stackoverflow.com/q/48270433
score: 0
has text: Does the username of your logged in user appears on the page, right below the emit line?
type: QuestionComment

http://stackoverflow.com/a/48235342
type: Answer
score: 12
has body: The problem is with floating point. Result of np.dot(u,v) / (mag(u) * mag(v)) can be something like -1.000000000000002 and this is not valid number for acos (coz cos must be in range [-1, 1]) I suggest you to use np.clip: def mag(x): return np.sqrt(np.sum(i ** 2 for i in x)) u = np.array([1, 1, 1]) v = np.array([-1, -1, -1]) cos = np.dot(u, v) / (mag(u) * mag(v)) cos = np.clip(cos, -1, 1) rad = np.arccos(cos) # or m.acos(cos) print(rad) theta = m.degrees(rad) print(theta)
upvote count: 12
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48235232
answers question: http://stackoverflow.com/q/48235232

http://stackoverflow.com/q/48213646
answer count: 2
has comment: http://stackoverflow.com/comment/83408945
has title: duplicate item_01 and rename to item_02
accepted answer: http://stackoverflow.com/a/48213935
has comment: http://stackoverflow.com/comment/83409730
possible better answer: http://stackoverflow.com/a/48213832
has answer: http://stackoverflow.com/a/48213935
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83409690
has answer: http://stackoverflow.com/a/48213832
has body: I'm a complete beginner in Python, and I'm trying to use the language to make scripts in a program called Modo. I'm attempting to make a script that duplicates an item which has a suffixed number, and adds 1 to the suffix of the new duplicated item. So for example; duplicate 'item_01', which will create 'item_01 (2)', then rename 'item_01 (2)' to 'item_02'. I'm having trouble finding out how to get Python to take the '_01' part of the previous item's name, then add 1 to it and using the sum of that as the suffix for the new item name. Also, this is my first question on this great site, so if additional information is needed, please let me know.
has comment: http://stackoverflow.com/comment/83409116
tagged with: python
has comment: http://stackoverflow.com/comment/83409465
linked to: http://stackoverflow.com/q/2553354
type: Question
score: 0

http://stackoverflow.com/comment/83590629
type: AnswerComment
comment on: http://stackoverflow.com/a/48302790
type: Comment
has text: i am not familiar with ubidots however in the tutorial http://help.ubidots.com/iot-projects-tutorials/diy-raspberry-pi-temperature-system-with-ubidots the data is organized like this. this is also in https://ubidots.com/docs/api/
score: 0

http://stackoverflow.com/comment/83615492
score: 2
comment on: http://stackoverflow.com/q/48315005
type: QuestionComment
has text: Probably you have not registered them in admin.py?
type: Comment

http://stackoverflow.com/a/48286869
type: Answer
has body: List comprehension in base python works well here: outlist = [ (i, j) for i in df.colA for j in df.colB ] print(outlist) Output: [('Adam', 'Smith'), ('Adam', 'Brown'), ('Adam', 'Red'), ('Barry', 'Smith'), ('Barry', 'Brown'), ('Barry', 'Red'), ('Ben', 'Smith'), ('Ben', 'Brown'), ('Ben', 'Red')] This can be converted to dataframe: newdf = pd.DataFrame(data=outlist, columns=['first_col','second_col']) print(newdf) Output: first_col second_col 0 Adam Smith 1 Adam Brown 2 Adam Red 3 Barry Smith 4 Barry Brown 5 Barry Red 6 Ben Smith 7 Ben Brown 8 Ben Red
score: 10
has comment: http://stackoverflow.com/comment/138132137
has comment: http://stackoverflow.com/comment/138144436
answers question: http://stackoverflow.com/q/48285893
downvote count: 0
upvote count: 10

http://stackoverflow.com/q/48230875
has answer: http://stackoverflow.com/a/48231144
tagged with: transformation
linked to: http://stackoverflow.com/q/19448282
possible better answer: http://stackoverflow.com/a/48231013
tagged with: matplotlib
tagged with: python
accepted answer: http://stackoverflow.com/a/48231144
has title: Rotate a matplotlib Path object
type: AnsweredQuestion
answer count: 2
score: 3
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/48231013
favorite count: 0
type: Question
has body: I'm using a matplotlib Path object to create a custom plotting marker as described here. I'd like to rotate the resulting path about its center by an arbitrary angle. Any suggestions on how to do this would be greatly appreciated. Here's the code I'm using to create and plot the custom marker import matplotlib.path import matplotlib.pylab as plt def getCustomMarker(): verts = [( -5 , -15 ), ( -5 , -5 ), ( -15 , -5 ), ( -15 , 5 ), ( -5 , 5 ), ( -5 , 15 ), ( 5 , 15 ), ( 5 , 5 ), ( 15 , 5 ), ( 15 , -5 ), ( 5 , -5 ), ( 5 , -15 ), ( -5 , -15 )] verts = verts codes = [matplotlib.path.Path.MOVETO, matplotlib.path.Path.LINETO, matplotlib.path.Path.LINETO, matplotlib.path.Path.LINETO, matplotlib.path.Path.LINETO, matplotlib.path.Path.LINETO, matplotlib.path.Path.LINETO, matplotlib.path.Path.LINETO, matplotlib.path.Path.LINETO, matplotlib.path.Path.LINETO, matplotlib.path.Path.LINETO, matplotlib.path.Path.LINETO, matplotlib.path.Path.CLOSEPOLY] path = matplotlib.path.Path(verts, codes) return path plt.scatter([0,0],[0,0], marker=getCustomMarker(), s=5000) plt.show() This is what I get: This is the change I'd like to affect:

caffe2
tags question: http://stackoverflow.com/q/48287080
type: Tag
tag name: caffe2

http://stackoverflow.com/a/48218468
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83419183
has comment: http://stackoverflow.com/comment/83419062
has comment: http://stackoverflow.com/comment/83419022
has body: You can try this: import itertools list_a = [0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0] new_data = list(map(lambda x:x[-1], [(a, list(b)) for a, b in itertools.groupby(list_a, key=lambda x:x == 1)])) final_data = map(float, list(itertools.chain.from_iterable([list(map(lambda x:0.0 if x &lt; 0 else x, [1-(0.1*c) for c in range(1, len(a)+1)])) if a[0] == 0 and new_data[i-1][0] == 1 and i &gt; 0 else a for i, a in enumerate(new_data)]))) Output: [0.0, 0.0, 1.0, 0.9, 0.8, 0.7, 1.0, 0.9, 0.8, 1.0, 0.9]
accepted answer of: http://stackoverflow.com/q/48218412
has comment: http://stackoverflow.com/comment/83419638
type: Answer
has comment: http://stackoverflow.com/comment/83419144
has comment: http://stackoverflow.com/comment/83419726
answers question: http://stackoverflow.com/q/48218412
has comment: http://stackoverflow.com/comment/83419041
has comment: http://stackoverflow.com/comment/83419742
has comment: http://stackoverflow.com/comment/83419103
has comment: http://stackoverflow.com/comment/83419518
score: 0
has comment: http://stackoverflow.com/comment/83419671
has comment: http://stackoverflow.com/comment/83418960

http://stackoverflow.com/comment/83601201
has text: Do not use `[list_of_n.count(n) for n in set(list_of_n)]` that is a quadratic algorithm. There are linear algorithms for counting occurrences of items in a list, already implemented for you in `collections.Counter`.
comment on: http://stackoverflow.com/q/48307878
type: Comment
type: QuestionComment
score: 0

memory
tags question: http://stackoverflow.com/q/48222763
tags question: http://stackoverflow.com/q/48304333
tag name: memory
tags question: http://stackoverflow.com/q/48318113
type: Tag
tags question: http://stackoverflow.com/q/48263740
tags question: http://stackoverflow.com/q/48256395
tags question: http://stackoverflow.com/q/48181256
tags question: http://stackoverflow.com/q/48173762
tags question: http://stackoverflow.com/q/48283120
tags question: http://stackoverflow.com/q/48297322

http://stackoverflow.com/comment/83489899
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48253666
has text: @MadhavNakar Well, I'm sorry about your assignment not allowing you to do that. Guess that's too bad.

http://stackoverflow.com/q/48330836
score: 1
tagged with: pandasql
type: Question
answer count: 1
has body: I have the code below where I'm trying to use pandasql to run a sql query with sqldf. I'm doing some division and aggregation. The query runs just fine when I run it in r with sqldf. I'm totally new to pandasql and I'm getting the error below, can anyone see what my issue is and suggest how to fix it? I've also included some sample data. Code: import pandasql from pandasql import sqldf pysqldf = lambda q: sqldf(q, globals()) ExampleDf=pysqldf("select sum(lastSaleAmount-priorSaleAmount)/sum(squareFootage) as AvgPric ,zipcode from data where priorSaleDate between '2010-01-01' and '2011-01-01' group by zipcode order by sum(lastSaleAmount-priorSaleAmount)/sum(squareFootage) desc") Error: File "&lt;ipython-input-100-679165684772&gt;", line 1 ExampleDf=pysqldf("select sum(lastSaleAmount-priorSaleAmount)/sum(squareFootage) as AvgPric ^ SyntaxError: EOL while scanning string literal Sample Data: print(data.iloc[:50]) id address city state zipcode latitude \ 0 39525749 8171 E 84th Ave Denver CO 80022 39.849160 1 184578398 10556 Wheeling St Denver CO 80022 39.888020 2 184430015 3190 Wadsworth Blvd Denver CO 80033 39.761710 3 155129946 3040 Wadsworth Blvd Denver CO 80033 39.760780 4 245107 5615 S Eaton St Denver CO 80123 39.616181 5 3523925 6535 W Sumac Ave Denver CO 80123 39.615136 6 30560679 6673 W Berry Ave Denver CO 80123 39.616350 7 39623928 5640 S Otis St Denver CO 80123 39.615213 8 148975825 5342 S Gray St Denver CO 80123 39.620158 9 184623176 4967 S Wadsworth Blvd Denver CO 80123 39.626770 10 39811456 6700 W Dorado Dr # 11 Denver CO 80123 39.614540 11 39591617 4956 S Perry St Denver CO 80123 39.628740 12 39577604 4776 S Gar Way Denver CO 80123 39.630547 13 153665665 8890 W Tanforan Dr Denver CO 80123 39.630738 14 39868673 5538 W Prentice Cir Denver CO 80123 39.620625 15 184328555 4254 W Monmouth Ave Denver CO 80123 39.629000 16 30554949 6600 W Berry Ave Denver CO 80123 39.616165 17 24157982 6560 W Sumac Ave Denver CO 80123 39.614712 18 51335315 5655 S Fenton St Denver …
downvote count: 0
upvote count: 1
tagged with: python
has title: pandasql EOL error while scanning string literal
accepted answer: http://stackoverflow.com/a/48330878
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48330878

http://stackoverflow.com/comment/83504430
score: 0
type: AnswerComment
has text: Could you please also add to your answer, how to revert back to old dataframe model ?
type: Comment
comment on: http://stackoverflow.com/a/48189755

http://stackoverflow.com/a/48921358
has comment: http://stackoverflow.com/comment/138237262
has comment: http://stackoverflow.com/comment/124228840
upvote count: 2
answers question: http://stackoverflow.com/q/48255299
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/124228850
downvote count: 1
has comment: http://stackoverflow.com/comment/124192356
has comment: http://stackoverflow.com/comment/84886491
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48255299
has body: You have to use QNetworkAccessManager and manually download image from url. Then read bytes from response, create a QPixmap (beacuse it has loadFromData method) and initialize a QIcon from QPixmap. And after that you will be able to set window icon. import sys from PyQt5.QtCore import QUrl from PyQt5.QtGui import QIcon, QPixmap from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout ICON_IMAGE_URL = "https://www.google.ge/images/branding/product/ico/googleg_lodp.ico" class MainWindow(QWidget): def __init__(self): QWidget.__init__(self) self.label = QLabel('Image loading demo') self.vertical_layout = QVBoxLayout() self.vertical_layout.addWidget(self.label) self.setLayout(self.vertical_layout) self.nam = QNetworkAccessManager() self.nam.finished.connect(self.set_window_icon_from_response) self.nam.get(QNetworkRequest(QUrl(ICON_IMAGE_URL))) def set_window_icon_from_response(self, http_response): pixmap = QPixmap() pixmap.loadFromData(http_response.readAll()) icon = QIcon(pixmap) self.setWindowIcon(icon) if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_())

http://stackoverflow.com/comment/83351867
comment on: http://stackoverflow.com/q/48185462
has text: In `df.filter(~mydate.isNotNull()).count()` is `mydate` another dataframe? Or is it a typo? (I mean it should be `df.filter(~df.mydate.isNotNull()).count()` right?)
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83438380
has text: @Stack You can just divide with `len(structure)`
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/48228216
type: Comment

http://stackoverflow.com/comment/88634857
comment on: http://stackoverflow.com/a/50792698
has text: your code build the model structure(i.e. layer count, neuron count of each layer), if your model structure is changed, your backup model can't match the model, it will raise a error. so each structure(python code) will link a backup model.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83529279
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48272740
has text: So you're saying that I can put the output of the difflib into a variable, and use ```[i.replace('\n','') for i in x]``` for that variable?

http://stackoverflow.com/comment/83364147
type: Comment
has text: Ok, I have tested your solution with first dimension set to 512, and per-allocating the array gives a small boost compared to my np.stack solution. Nevertheless, the solution of Divakar is slightly faster.
type: AnswerComment
comment on: http://stackoverflow.com/a/48191558
score: 1

http://stackoverflow.com/comment/83600367
type: Comment
type: AnswerComment
has text: ooh i feel dumb that i didn't notice that
comment on: http://stackoverflow.com/a/48307503
score: 0